Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to add background in Django2.0 using html or css
I want to add an image inside my django homepage, but I always cannot get the correct location of the image file I want(yellow high light) The picture below are the thing I type so far: https://i.stack.imgur.com/ecyQu.png also in the same file {% load static %} body { background-image: url('{% static "/bitcoin.jpg" %}'); } Do I need static whenever I want to insert image in Django2.0? also, I see some people open separate static file and some ppl put image inside the templete. I am confused where I should put? How can put the background image inside the html?? thank you so your answering!!!! update ** this is what I have so far enter image description here -
Receive data from Django front end form
what I am trying to do: I am trying to get data from Django frontend table, and post it back to frontend. I am not using modelForm, I thought I don't need save the data to database. My code: in views.py: def panelThree(request): startDate = '' endDate = '' byOtherField = '' if request.method == 'POST': form = QueryForm(request.POST) if form.is_valid(): startDate = request.POST.get('date') endDate = request.POST.get('date1') byOtherField = request.POST.get('date2') else: form = QueryForm() # if not byOtherField: dataTable = Production.objects.order_by('-id') return render(request, 'frontend/panelThree.html', { 'form': form, 'dataTable': dataTable, 'startDate':startDate }) frontend_form: <form method="post"> {% csrf_token %} <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col-md-4"> <label > TextField1 </label> <input class="form-control" id="date" name="date" placeholder="MM/DD/YYYY" type="text"/> <p> >> Start Date </p> </div> <div class="col-md-4"> <label class="control-label " for="date1"> TextField2 </label> <input class="form-control" id="date1" name="date1" placeholder="MM/DD/YYYY" type="text"/> <p> >> End Date </p> </div> <div class="col-md-4"> <label class="control-label " > Or </label> <label class="control-label " for="date2"> TextField3 </label> <input class="form-control" id="date2" name="date2" placeholder="MM/DD/YYYY" type="text"/> <p> >> By Other Field </p> </div> </div> </div> <div class="col-md-4"> <div class="button-box"> <button class="btn btn-primary " name="submit" type="submit"> Search </button> </div> </div> </div> </form> My error: there is no error, but I just cannot get value from the … -
Django not matching unicode in url
I have a problem with django 2.0, where a url that contains a unicode slug isn't matched, I searched for a solution but I didn't find one for my case, here's a simplified version of my code: // models.py class Level(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(max_length=100, allow_unicode=True) in my urls file I have those patterns: // urls.py urlpatterns = [ path('', views.index, name='index'), path('level/<slug:level_slug>', views.level, name='level')] Now if I go, say to http://127.0.0.1:8000/game/level/deuxième I get this error: Request Method: GET Request URL: http://127.0.0.1:8000/game/level/deuxi%C3%A8me Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: game/ [name='index'] game/level/<slug:level_slug> [name='level'] admin/ accounts/ The current path, game/level/deuxième, didn't match any of these. but if I change the item's slug to deuxieme without the unicode character, it works fine, does anyone know the solution to this problem? thanks! -
Filters of Django REST Framework inside GET function?
Is there a way of using the Django REST filters inside a GET function I created? It works when I use this: class ContactListView(generics.ListAPIView): queryset = Profile.objects.all() serializer_class = UserContactListSerializer filter_backends = (filters.SearchFilter,) search_fields = ('name', 'last_name',) But I want it to work in the GET function I created: def get(self, request, pk, format=None): contacts = Profile.objects.get(pk=pk) serializer = UserContactListSerializer(contacts) filter_backends = (filters.SearchFilter,) search_fields = ('name', 'last_name',) return Response(serializer.data) -
Django Storing Serialized JSON data
Using the Django REST framework I have been serializing data for Invoices with the purpose of using the JSON for a search. In order to have the JSON in the correct format, I have had to serialize foreign key models (Customers, Products, etc) with their own serializers, and this process (as more and more invoices are created) has begun to take an unacceptably long time. My thought to fix this was to store all serialized invoices in the database, and when an invoice is created, serialize that new invoice and add it to the database. When an existing invoice is edited, update the JSON in the database with the new information. As of now, every time my view is loaded, ALL of the invoices are serialized, where as here we would serialize on when there is an add/edit/delete. What would be the best way to go about doing this? I found Django has a JSONField so maybe I could create a new model to hold this JSON data? If so should I store all of the serialized invoices in one field? Or have foreign keys of each invoices JSON data that point to that new model? Maybe there's a better … -
Amazon ELB + Django HTTPS issues
Hi have been searching on a lot of questions on SO but none of the solutions seem to work for my case. So basically i have an Classical Elastic Load Balancer passing requests to my Nginx containers that proxy pass to my gunicorn containers. Nginx config: server { listen 80; listen [::]:80; ... if ($http_x_forwarded_proto = 'http') { return 301 https://$server_name$request_uri; } location / { .. proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; .. } In my Django Settings i have : SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = False The thing is, when a request is made to an endpoint, if i print(request.META.get('HTTP_X_FORWARDED_PROTO')) i get http instead of https. This causes my DRF auto generated doc links to be generated in http instead of https. Is there something wrong with my configurations? How can i force https behind an elb? -
Django migrate attempts to connect to non-default database
According to the Django documentation: The migrate management command operates on one database at a time. By default, it operates on the default database, but by providing the --database option, you can tell it to synchronize a different database. My Django application has the following database configuration in my local development environment: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydatabase', 'USER': 'myuser', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', }, 'external_db': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'myexternaldb', 'USER': 'myexternaluser', 'PASSWORD': 'myexternalpassword', 'HOST': '10.10.10.10', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } I only have one table in the "external_db" database, and I treat it as read-only (in fact, the user only has read permissions). When I try to migrate a table in my default database, I get the following error: _mysql_exceptions.OperationalError: (2003, "Can't connect to MySQL server on '10.10.10.10' (10060)") Why is the migrate operation trying to connect to this external database when the documentation expressly indicates that it only works on the default database by default? Is this a Django bug? -
Django error message: ["'on' value must be either True or False."]
I'm currently having this error message on django: ["'on' value must be either True or False."] views.py from django.shortcuts import render, redirect from .models import Comment from .forms import sign def index(request): return render(request, 'submits/index.html') def sign_list(request): if request.method == 'POST': form = sign(request.POST) if form.is_valid(): new_contact = Comment(email=request.POST['email'], message=request.POST['message'], checkbox=request.POST['checkbox']) new_contact.save() return redirect('index') else: form = sign() context = {'form' : form} return render(request, 'submits/sign.html', context) forms.py from django import forms from .models import Comment class sign(forms.Form): email = forms.CharField(max_length=500, widget=forms.TextInput(attrs={ 'type' : 'email', 'class' : 'form-control', 'placeholder' : 'Enter your email', 'aria-describedby' : 'emailHelp'})) message = forms.CharField(widget=forms.Textarea(attrs={ 'class' : 'form-control', 'rows' : '3', 'placeholder' : 'Write your proposal'})) checkbox = forms.BooleanField(required=False, initial=True) checkbox_attributes={'class': 'form-check'} models.py from django.db import models # Create your models here. class Comment(models.Model): email = models.CharField(max_length=500) message = models.TextField() checkbox = models.BooleanField() def __str__(self): return 'e-mail: {}, ID: {}'.format(self.email, self.id) I really can't understand how to fix this error -
How would you create a 'manual' django migration?
I've discovered that I can set defaults for columns on a postgres database in a django project using migrations.RunSQL('some sql'). I'm currently doing this by adding a column, makemigrations, then removing the column, makemigrations, and then manually modifying the migration file that is produced. I tried copying an old migration file and then removing the old code so just the new sql could be run and got some strange errors. CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0067_auto_20180509_2327, 0068_auto_20180514_0707 in csmu). To fix them run 'python manage.py makemigrations --merge' How would you create a 'manual' django migration? -
DjanoRestFramework App Cannot Find Module Named 'graphene_django'
I used the Django Rest Framework cookiecutter available here to scaffold a project. I've made no changes aside from setting up a virtualenv, installing requirements, and running pip install graphene_django. However, when I add graphene_django to the INSTALLED_APPS I receive the following error when attempting to run the server: ModuleNotFoundError: No module named graphene_django Any ideas why? Traceback: Traceback (most recent call last): File "manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 347, in execute django.setup() File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 90, in create module = import_module(entry) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 953, in _find_and_load_unlocked Pip Freeze: aniso8601==3.0.0 appnope==0.1.0 backcall==0.1.0 blessings==1.6.1 boto3==1.7.19 botocore==1.10.19 certifi==2018.4.16 chardet==3.0.4 click==6.7 coverage==4.5.1 decorator==4.3.0 dj-database-url==0.5.0 Django==2.0.5 django-configurations==2.0 django-filter==1.1.0 django-model-utils==3.1.2 django-nose==1.4.5 django-oauth-toolkit==1.1.2 django-storages==1.6.6 django-unique-upload==0.2.1 djangorestframework==3.8.2 docutils==0.14 factory-boy==2.11.1 Faker==0.8.14 flake8==3.5.0 graphene==2.1 graphene-django==2.0.0 graphql-core==2.0 graphql-relay==0.4.5 gunicorn==19.8.1 idna==2.6 ipdb==0.11 ipython==6.4.0 ipython-genutils==0.2.0 iso8601==0.1.12 jedi==0.12.0 Jinja2==2.10 jmespath==0.9.3 livereload==2.5.2 Markdown==2.6.11 MarkupSafe==1.0 mccabe==0.6.1 mkdocs==0.17.3 mock==2.0.0 newrelic==3.2.0.91 nose==1.3.7 nose-progressive==1.5.1 oauthlib==2.0.7 parso==0.2.0 pbr==4.0.2 pexpect==4.5.0 pickleshare==0.7.4 promise==2.1 prompt-toolkit==1.0.15 psycopg2-binary==2.7.4 ptyprocess==0.5.2 pycodestyle==2.3.1 pyflakes==1.6.0 … -
Django keep language when redirecting
I'm trying to internationalize. The only way to change the language is by changing the url for example, change from example.com/en/... to example.com/es/... If I do that the language changes, but when I go to another page when I click a button or a link the language goes back to the original. How can I keep the language I selected by changing the url? Thanks. -
Error when installing mysqlclient
I'm trying to install mysqlclient to connect to my database with django, but get the following error: (venv) dhcp-ccc-12919:project user$ pip3 install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/6f/86/bad31f1c1bb0cc99e88ca2adb7cb5c71f7a6540c1bb001480513de76a931/mysqlclient-1.3.12.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/var/folders/l4/0f1p1xlj3hlbxr6rzgqzrxmh0000gn/T/pip-install-lo7y8khq/mysqlclient/setup.py", line 17, in <module> metadata, options = get_config() File "/private/var/folders/l4/0f1p1xlj3hlbxr6rzgqzrxmh0000gn/T/pip-install-lo7y8khq/mysqlclient/setup_posix.py", line 54, in get_config libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/l4/0f1p1xlj3hlbxr6rzgqzrxmh0000gn/T/pip-install-lo7y8khq/mysqlclient/setup_posix.py", line 54, in <listcomp> libraries = [dequote(i[2:]) for i in libs if i.startswith('-l')] File "/private/var/folders/l4/0f1p1xlj3hlbxr6rzgqzrxmh0000gn/T/pip-install-lo7y8khq/mysqlclient/setup_posix.py", line 12, in dequote if s[0] in "\"'" and s[0] == s[-1]: IndexError: string index out of range ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/l4/0f1p1xlj3hlbxr6rzgqzrxmh0000gn/T/pip-install-lo7y8khq/mysqlclient/ I have the following in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'todo', 'USER': 'root', 'PASSWORD': 'password' } } -
How to use slug in URL with generic view?
How can I view a single article by it's headline like so: news/article_name? I managed to make it work with numbers (<int:pk> in urls then access it in template using {% url 'article' article.id %}) so news/1 actually worked. Instead of using numbers I want to use headlines and can't figure out how. models.py class Article(models.Model): headline = models.CharField(max_length=200) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) content = models.TextField() def __str__(self): return self.headline urls.py path('<slug:headline>/', views.DetailView.as_view(), name='article'), views.py class ArticleView(generic.DetailView): model = Article template_name = 'news/index.html' context_object_name = 'article' local_context = {**context, **{'show_comments':False}} somewhere in article template <p><a href="{% url 'article' %}">Read more</a></p> -
MultiValueDictKeyError at /optin/amend-user-optins/1/ "u'form-0-id'"
I have this UpdateView which when I GET it works fine and when I POST it saves the formset data but then errors opening the template. This is the view: class UpdateUserOptinView(LoginRequiredMixin, UpdateView): form_class = UserForm model = USER_MODEL template_name = 'optin/optin_form.html' def get_context_data(self, **kwargs): data = super(UpdateUserOptinView, self).get_context_data(**kwargs) # ensure we have an option for each Category categories = Category.objects.all() for category in categories: opt, created = UserOptin.objects.get_or_create(user=USER_MODEL.objects.get(pk=self.kwargs['pk']), category=category) if created: opt.save() qs = UserOptin.objects.filter(user=USER_MODEL.objects.get(pk=self.kwargs['pk'])) # create the formset if self.request.POST: data['formset'] = UserOptinFormSet(self.request.POST) else: data['formset'] = UserOptinFormSet(queryset=qs) return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] if formset.is_valid(): formset.save() return super(UpdateUserOptinView, self).form_valid(form) Traceback: File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 215. response = response.render() File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/response.py" in render 107. self.content = self.rendered_content File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/response.py" in rendered_content 84. content = template.render(context, self._request) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/backends/django.py" in render 66. return self.template.render(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/base.py" in render 207. return self._render(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/base.py" in render 990. bit = node.render_annotated(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/base.py" in render_annotated 957. return self.render(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/loader_tags.py" in render 177. return compiled_parent._render(context) File "/home/henry/Documents/Sites/Development/pickem/env/local/lib/python2.7/site-packages/django/template/base.py" in _render 199. return self.nodelist.render(context) File … -
Cursor (SQL) - break the connection after deployment of website to remote server
after deployment my webiste (Django + NGINX + uwsgi) I have problem with SQL connections. When I run wscgi for first time, after quit earlier instance, the site loads properly via web-browser (SQL connection is estabilished, and query are executed, I get a result). After go to next site (next query should be executed), I receiving errors like below: [pid: 26143|app: 0|req: 1/1] 2001:470:70:f5f::2 () {58 vars in 1057 bytes} [Sun May 13 19:03:54 2018] GET /index/ => generated 270 bytes in 712 msecs (HTTP/1.0 200) 4 headers in 123 bytes (1 switches on core 0) [pid: 26143|app: 0|req: 2/2] 2001:470:70:f5f::2 () {56 vars in 1044 bytes} [Sun May 13 19:04:07 2018] GET /accounts/login/ => generated 634 bytes in 41 msecs (HTTP/1.0 200) 7 headers in 380 bytes (1 switches on core 0) [pid: 26143|app: 0|req: 3/3] 2001:470:70:f5f::2 () {60 vars in 1170 bytes} [Sun May 13 19:04:17 2018] POST /accounts/login/ => generated 0 bytes in 2570 msecs (HTTP/1.0 302) 9 headers in 531 bytes (1 switches on core 0) Internal Server Error: /index/ Traceback (most recent call last): File "/root/Env/pyrat/lib/python3.5/site-packages/django/db/backends/utils.py", line 83, in _execute return self.cursor.execute(sql) psycopg2.InterfaceError: cursor already closed The above exception was the direct cause of the … -
Django-filters RangeField Form Validation Error Message Missing
I'm using django-filters to create a form like this: f = MyFilter(request.POST, queryset=Offers.objects.all()) return render(request, 'search.html', {'filter_form': f.form}) That's how my MyFilter looks like: class MyFilter(django_filters.FilterSet): class Meta: model = Offers fields = { 'zipcode': ['exact']} strict = django_filters.STRICTNESS.RAISE_VALIDATION_ERROR chairs = django_filters.NumericRangeFilter(lookup_expr='range',) Now, if I cause a validation error for zipcode, by entering a letter instead of a number, the error gets auto-magically displayed in the form, in the correct place. If I do the same thing with the first chairs field, no error is displayed. The error is present but does not get shown. This is what f.form.errors looks like: {'chairs': [ValidationError(['Enter a number.'])]} My idea what causes the error is: There is no html field chairs in the html form. Because it's a range, there are two of them: chairs_0 and chairs_1. How can I make the error to appear (in the right place)? Interesting enough, in f.form.fields, there is only one field called chairs. I do not understand how it magically becomes two html fields and vice versa. Thank you very much! -
Django - calling attribute from queryset with a string
i'm trying to loop over different querysets while not repeating myself too much and have encountered a problem using the queryset class. This is not necessarily completely a Django-problem. What I'm trying to do is to use my keylist, which corresponds to a django model's column names, to create a list of the data from those column names, what i want to do is something like this: if needthisdata==1: needdata=['column1', 'column2', 'column3'] else: needdata=['column1', 'column4', 'column7'] entry=djangomodel.get.all().filter(identifier='id') dictitems=[] for n in range(0, len(needdata)): if n==0: dictitems=[entry.needdata[n]] else: dictitems.append(entry.needdata[n]) Which ofcourse doesn't work since the queryset doesn't have a needdata attribute, is there some way to call an attribute for a class with a string in this way? -
Django post_save signal not triggering from data migration
I am using post_save signal to trigger the creation of profile data for User instance. The problem is if I create a User object from data migration then the post_save signal isn't triggering. However, If I create User instance via shell or UserCreationForm, everything seems to be working as normal. -
django file style.css cannot be found
My css is failing. no css commands initialize in my templates page. django shows no errors in it but in the apache logs I see that the stlye.css cannot be found, even with a static path. [wsgi:error] [pid 25372] [remote 73.135.97.117:47050] Not Found: /home/robin/www/trader/templates/trader/style.css but the file is very much there. I tried permission 644 and 777 to the style.css file root@localhost:/home/robin/www/trader# ls -l /home/robin/www/trader/templates/trader total 12 -rw-r--r-- 1 www-data www-data 2905 May 13 14:26 index.html -rwxrwxrwx 1 www-data www-data 155 May 13 12:46 style.css My apache directive looks normal <VirtualHost *:80> ServerName coinz.com ServerAdmin webmaster@coinz.com DocumentRoot /home/robin/www/ ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined WSGIDaemonProcess trader python-path=/home/robin/www/trader/:/usr/lib/python3/dist-packages/ WSGIProcessGroup trader WSGIScriptAlias / /home/robin/www/trader/trader/wsgi.py <Directory /home/robin/www/trader/> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> settings.py root@localhost:/home/robin/www/trader# cat trader/settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'xxx' DEBUG = True ALLOWED_HOSTS = ['coinz.com'] # Application definition INSTALLED_APPS = [ 'trader', 'buy', 'sell', 'manager', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'trader.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/robin/www/trader/templates/'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'trader.wsgi.application' DATABASES = { 'default': { … -
Send a message from a celery background task to the browser with Django Channels
I have a long running task running on Celery. When it is done, I want to send a message to the browser that will simply instruct it to refresh the page. To do that, I want to use channels V2. It's not clear from the docs how to achieve that. This is what I have in my background task, but I'm not sure how to set up the Consumer @shared_task def my_task(): time.sleep(5) Channel('my-background-task').send({"refresh": True}) -
Namespacing Hyperlinked Serializers in Django REST Framework
I'm currently doing the tutorial on Relationships and hyperlinked API's. However I've come across a strange problem that I can't seem to fix. My serializers.HyperlinkedIdentityField and serializers.HyperlinkedRelatedField doesnt seem to detect the namespace I'm using. My serializers look like this class SnippetSerializer(serializers.HyperlinkedModelSerializer): owner = serializers.ReadOnlyField(source='owner.username') highlight = serializers.HyperlinkedIdentityField(view_name='snippets:snippet-highlight', format='html') class Meta: model = Snippet fields = ('url', 'id', 'highlight', 'owner', 'title', 'code', 'linenos', 'language', 'style') class UserSerializer(serializers.HyperlinkedModelSerializer): snippets = serializers.HyperlinkedRelatedField(many=True, view_name='snippets:snippet-detail', read_only=True) class Meta: model = User fields = ('url', 'id', 'username', 'snippets') Which is pretty much the same as the tutorial except I am adding view_name='snippets:snippet-detail' in the serializer field. I am creating my namespace as suggested by the Django documentation, by adding app_name = 'snippets' above my urlpatterns. This is the error I'm getting ImproperlyConfigured at /snippets/ Could not resolve URL for hyperlinked relationship using view name "snippet-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. As you see, I have approached the problem the same way other people have but without resolving the issue. Anyone have an idea about what I could try next? -
Deleting object from a view in Django
I have a page that shows a list of objects and I want to add a button beside each one to enable the user to delete it. I've found a few questions about similar scenarios online but for some reason I keep getting errors when I try to replicate the solutions. Here is the delete function in views.py: def delete_dish(request, pk): query = Dish.objects.get_object_or_404(pk) supermenu = query['supermenu'].pk query.delete() return redirect('foodmenu:menu', supermenu) Here is the form in the HTML template: <li> {{ dish.name }} - {{ dish.description }} <form action="{% url 'foodmenu:delete_dish' dish.id %}" method="POST"> {% csrf_token %} <button type="submit">X</button> </form> </li> And here is the urls.py: app_name = 'foodmenu' urlpatterns = [ ... path('dish/delete/<int:dish.id>', views.delete_dish, name="delete_dish") ] When I click the button, the browser goes to ./dish/delete/1 (1 being the pk of the object), but Django returns a 404 error. -
django rest framework DefaultRouter error
I wrote a program to learn django rest framework, but the program I wrote is not executed correctly. I have been looking for it for a long time. I can't find the error. I need someone to help me check the problem from another perspective. Thank you. models.py from django.db import models class Subsystem(models.Model): name = models.CharField(max_length=36) class Menu(models.Model): subsystem = models.ForeignKey(Subsystem, on_delete=models.CASCADE) name = models.CharField(max_length=36) serializers.py from rest_framework.serializers import ModelSerializer from subsystem.models import Subsystem, Menu class SubsystemSerializer(ModelSerializer): class Meta: model = Subsystem fields = ('name', ) class MenuSerializer(ModelSerializer): class Meta: model = Menu fields = ('name', 'subsystem') views.py from rest_framework.viewsets import ModelViewSet from subsystem.models import Subsystem, Menu from subsystem.api.serializers import SubsystemSerializer, MenuSerializer class SubsystemViewSet(ModelViewSet): queryset = Subsystem.objects.all() serializer_class = SubsystemSerializer(queryset) class MenuViewSet(ModelViewSet): queryset = Menu.objects.all() serializer_class = MenuSerializer I started trying to run python manage.py runserver but it can't run error: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x06125FA8> Traceback (most recent call last): File "D:\env\python\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\env\python\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check(display_num_errors=True) File "D:\env\python\lib\site-packages\django\core\management\base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "D:\env\python\lib\site-packages\django\core\management\base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "D:\env\python\lib\site-packages\django\core\checks\registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "D:\env\python\lib\site-packages\django\core\checks\urls.py", line 13, … -
Django order queryset by OnetoOneField
I have a two models UserProfile and User. The UserProfile model has a onetoone filed with the user. I figured out how to order the UserProfile by a variable it contains. However, I do not know how to order the items in UserProfile by their related User models class User(AbstractBaseUser): full_name = models.CharField(max_length=255, blank=True, null=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) lunch_price = models.DecimalField(max_digits=6, decimal_places=2, blank=True, null=True) I can run this query just fine: from myapp.models import UserProfiles print(UserProfile.objects.all().order_by('lunch_price') I thought i'd run something like this to order by full_name, but it doesn't work from myapp.models import UserProfiles print(UserProfile.objects.all().order_by('user.full_name') How do I make that jump to the user model? -
Django whitenoise drawback
There are many article describing the pros of using whitenoise instead of other configuration for serving static files. But the information about it's cons is kind of hard to find Is there any cons or drawbacks of using whitenoise for serving static files? If the question is to broad, I'm now using NGINX for serving my static files (I also use it and gunicorn for serving my Django Application) and I found its also quite easy to configure it