i am newer and study django.when i install django_comments , i need add to add a new url and view for django_comments, but it don't work.
comments folder structure:
__init__.py __pycache__/ forms.py migrations/ models.py templates/ urls.py views.py
__init__.py:
def get_model():
from comments.models import CommentModel
return CommentModel
def get_form():
from comments.forms import CommentForm
return CommentForm
and forms.py and models.py is fine work.but when i add urls.py, views.py and add the urls to main urls file. it don't work.
urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('delete/<int:comment_id>/', views.delete_own_comment, 'delete_own_comment'),
]
views.py
from .models import CommentModel
#login_required
def delete_own_comment(request, comment_id):
comment = get_object_or_404(CommentModel, id=comment_id, site__pk=settings.SITE_ID)
if comment.user == request.user:
comment.is_removed = True
comment.save()
but when i add path('mycomments/', include('comments.urls')) to main urls.py, it run strange errors. can anyone help me???
It's not
django-admin startapp myapp
It's
python manage.py startapp myapp
Provided that you created before a project with
django-admin startproject myproject
Related
I know this has been asked multiply times before, but I still don't get it.
How can I create a href-link in one Django app that sends the user to a 2nd app?
This is my setup:
myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
app1/
migrations/
templates/
app1/
app1.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
app2/
migrations/
templates/
app2/
app2.html
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls'), name='app1'),
path('app2/', include('app2.urls'), name='app2'),
]
myproject/settings.py
INSTALLED_APPS = [
'app1.apps.App1Config',
'app2.apps.App2Config',
'django.contrib.admin',
...
]
app1/urls.py (analogous for app2)
from django.urls import path
from . import views
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py (analogous for app2)
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
app1/templates/app1/app1.html (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # doesn't work
Go to App2 # doesn't work
Go to App2 # doesn't work
My problem is that this sends me to the address 127.0.0.1:8000/app1/app2/ which gives me a 404 error. However, I can access app2 via 127.0.0.1:8000/app2/ without a problem.
Edit:
Thanks everyone for your feedback. After going through your suggestions, I made the following changes:
myproject/urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app1/', include('app1.urls', namespace='app1')), # ADDED NAMESPACE
path('app2/', include('app2.urls', namespace='app2')), # ADDED NAMESPACE
]
myproject/settings.py: no changes
app1/urls.py: (analogous for app2)
from django.urls import path
from . import views
app_name = 'app1' # THIS WAS MISSING
urlpatterns = [
path('', views.app1, name='app1'),
]
app1/views.py: no changes
app1/templates/app1/app1.html: (analogous for app2)
<p>This is the template of app1.</p>
Go to App2 # AS SUGGESTED BY seif
Now it works.
in your template and views try not to hardcode the url of href instead use the {%url ''%}
which will be {%url 'namespace:urlname'%}
<p>This is the template of app1.</p>
Go to App2
this give you flexibility to change the path in your urls and not to worry about changing it at all your templates and views you can read more here https://docs.djangoproject.com/en/3.1/topics/http/urls/#reverse-resolution-of-urls
your href link doesn't go to the .html file in templates, templates are just for UI, and barely have a say in how you project gets routed, infact it depends on you to configure. instead it should go to the url specified in your url file,
so say your bases url is
path('app1/', include('app1.urls'), name='app1')
for one of your app it will be
App 1
if you have other links under app1 url file, it will then be
A link under App 1
example.com here, could be localhost:8000 or just localhost with any port, depending on the port your django project runs one.
then as for this,
from django.template import loader
from django.http import HttpResponse
def app1(request):
template = loader.get_template('app1/app1.html')
return HttpResponse(template.render())
I will suggest you do something like this instead
from django.shortcuts import render
from django.http import HttpResponse, HttpRequest
def app1(request,slug=None):
return render(request,'app1/app1.html',{})
#path to the template folder, under templates, depends on your configuration though
Kindly read more on templates configuration and routing in Django,but this should give a jumpstart.
Cheers
When you input "127.0.0.1:8000/app1/app2/", django will recieve "app1/app2/" and work like below(not accurate):
1.compare app1/ to every element in urlpatterns of myproject/urls.py
so, app1/ will be found.
2.compare app2/ to every element in urlpatterns of app1.urls
there's nothing will be found, because there is only a "" in urlpatterns of app1.urls.
so you get a 404 page.
if you input "127.0.0.1:8000/app2/", in step 2, "" equals to "",
fuction views.app2 executes, and you get a correct page.
I suggest you read the django's tutorials in official site.
https://docs.djangoproject.com/en/3.1/intro/tutorial01/
I have created a new app "grn" in my django project and tried to import the models from another app named "packsapp" in the same project like this:
Models.py
from ..packsapp.models import *
But I got the following error:
ValueError: attempted relative import beyond top-level package
Here's the structure of the app:
yantra_packs
grn
--migrations
__init__.py
admin.py
apps.py
models.py
tests.py
views.py
media
packsapp
--migrations
templates
templatetags
views1
__init__.py
apps.py
decorators.py
forms.py
models.py
urls.py
views.py
How can I import the models of the packsapp in the grn ??
The root directory of a Django project is not a Python package or module. So relative imports across Django apps will not work. Use an absolute import instead:
from packsapp.models import *
from employee import views
does not work!...the server is giving a page not found (404) response
here is the project structure:
employee
migrations folder
....other files
views.py
hrdjango
__init__.py
settings.py
urls.py
I feel like the urls can't access my views
this is the views.py
from .models import Employee
# Create your views here.
def emp(request):
if request.method == "POST":
form = EmployeeForm(request.POST)
if form.is_valid():
try:
form.save()
return redirect('/show')
except:
pass
else:
form = EmployeeForm()
return render(request,'index.html',{'form':form})
def show(request):
employees = Employee.objects.all()
return render(request,"show.html",{'employees':employees})
def edit(request, id):
employee = Employee.objects.get(id=id)
return render(request,'edit.html', {'employee':employee})
def update(request, id):
employee = Employee.objects.get(id=id)
form = EmployeeForm(request.POST, instance = employee)
if form.is_valid():
form.save()
return redirect("/show")
from django.contrib import admin
from django.urls import path
from employee import views
urlpatterns = [
path('admin/', admin.site.urls),
path('emp', views.emp),
path('show',views.show),
path('edit/<int:id>', views.edit),
path('update/<int:id>', views.update),
path('delete/<int:id>', views.destroy),
]
urls.py
I am having unresolved import 'employee'message
Is this the project urls.py or the app-level urls.py? If this is your app level urls.py, then the import should be from . import views. If it is the project-level urls.py, then post up your file structure so we can see if the import structure is wrong.
I think the better solution would be to use separate urls.py file for separate apps and then include them to your root urls.
create a urls.py in your app.
in your root urls.py
from django.urls import path,include
urlpatterns = [
...,
...,
path('employee/', include('employee.urls')),
]
I would like to keep my views and forms separate, just like you can with models. Are you able to make a directory of views and forms, and if so, what goes in the init.py files for each.
Update:
I made my folders, but I keep getting errors. Here's all my code info:
myproject structure (abbreviated):
myproject/
myproject/
name/
forms/
__init__.py
name_form.py
models/
__init__.py
name_model.py
urls.py
views/
__init__.py
name_view.py
models/init.py
from .name_model import Name
models/name_model.py
from django.db import models
from django.urls import reverse
class Name(models.Model):
...
forms/__init__.py and views/__init__.py are blank files.
urls.py
from django.urls import path
from name.views import name_view
app_name = 'name'
urlpatterns = [
path('', views.name_view, name='name-view'),
]
forms/name_form.py
from django.forms import ModelForm, TextInput
from name.models import Name
class NameForm(ModelForm):
class Meta:
model = Name
views/name_view.py
from django.shortcuts import render, redirect
from name.forms import NameForm
def name_view(request):
...
I run python3 manage.py makemigrations in the terminal and get:
/myproject/name/views/name_view.py", line 4, in <module>
from name.forms import NameForm
ImportError: cannot import name 'NameForm'
Thinking you can't make a ModelForm without a model, I run python3 manage.py migrate and get the same error.
I created a project to isolate this issue. Without the folders it worked, unless I messed up my original code trying to get this to work.
Just make a folder for your views and a folder for your forms wherever you want them to be and put an empty __init__.py file into each folder. The purpose of the __init__.py file is to tell python to treat the folder as a module. Then make your views.py file and your forms.py file in their respective directories and now you can do...
from myproject.path.to.views import MyView
from myproject.path.to.forms import MyForm
...as if it were any other module. Which it is.
Django's documentation provides an easy way of installing admin app.
It assumes the structure of files as follows:
mysite/
manage.py
mysite/
settings.py #adding `admin` under `INSTALLED_APPS`
__init__.py
urls.py #adding urls
wsgi.py
myapp/
__init__.py
admin.py #creating this file
models.py
views.py
My question is how to get the admin interface to work if my structure is as follows:
mysite/
manage.py
settings.py
__init__.py
urls.py
myapp/
__init__.py
forms.py
models.py
views.py
What will be the various changes that I will have to incorporate to get the admin interface working. [my other apps are working].
I have read and read the documentation several times.
I'm using Django 1.4.
EDIT#1
I'm getting this error on running localhost:8000/admin/:
error at /admin/
unknown specifier: ?P[
Whole error here.
My urls.py file has the lines [as in the docs]:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^admin/(.*)', include(admin.site.urls)),
)
My admin.py file in the myapp folder has the code:
import models
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(models.Article, PostAdmin)
This is how you're supposed to include the admin urls:
url(r'^admin/', include(admin.site.urls)),
The documentation shows this.
The error that you're getting is coming straight from the re python module, complaining about this part of a url:
?P[
The URLs you've posted in your comment beneath show this:
url(r'^(?P[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
Try changing that url by giving the match group a name:
url(r'^(?P<slug>[-a-zA-Z0-9]+)/?$', 'myapp.views.getPost')
And in your getPost view, include a slug argument.