Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - DROP and CREATE DB - No changes detected
I'm moving my project from Sqlite3 to MySQL database. I've connected new MySQL database to Django and run manage.py migrate. There were some errors but tables were created so I decided to DROP the database and recreate it. The problem is that even when I DROP the database DROP DATABASE mydb; And then create it CREATE DATABASE mydb; And deleted migrations Django's manage.py makemigrations says no changes detected which is very weird since it should track changes inside recreated database which is empty. Do you know what to do and why it behaves this way? mysql> DROP DATABASE keywords_search; Query OK, 13 rows affected (0,19 sec) mysql> SHOW DATABASES; +--------------------+ | Database | +--------------------+ | information_schema | | mysql | | performance_schema | | sys | +--------------------+ 4 rows in set (0,00 sec) mysql> CREATE DATABASE keywords_search; Query OK, 1 row affected (0,00 sec) mysql> use keywords_search; Database changed mysql> show tables; Empty set (0,00 sec) mysql> -
DRF: creating new object in a model with 'ManyToMany' field and 'through' table
I have the following Django models: class Product(models.Model): name = models.CharField(max_length=250, unique=True) quantity = models.IntegerField(default=0) class Order(models.Model): products = models.ManyToManyField( Product, through='PositionInOrder' ) discount = models.CharField(max_length=50, blank=True) total_sum = models.DecimalField(max_digits=11, decimal_places=2, default=0) class PositionInOrder(models.Model): sale = models.ForeignKey(Order) product = models.ForeignKey(Product) quantity = models.PositiveIntegerField() price = models.PositiveIntegerField() And the following serializers: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = '__all__' class PositionInOrderSerializer(serializers.HyperlinkedModelSerializer): sale = serializers.ReadOnlyField() product = serializers.ReadOnlyField() class Meta: model = PositionInOrder fields = "__all__" class OrderSerializer(serializers.ModelSerializer): products = PositionInOrderSerializer(many=True) def create(self, validated_data): products = validated_data.pop('products') order = Order.objects.create(**validated_data) return order class Meta: model = Order fields = '__all__' I want to create new Order. Send post query which contains this json: { "products": [{"id": 2606, "name": "Some name", "quantity": 140, "price": 250}], "discount": "15", "total_sum": 500 } And in the create() method of a class OrderSerialization I obtain that products=: [OrderedDict([('quantity', 140), ('price', 250)])] and there are no information about product_id and product_name. How can I get them? -
how to list files in digitalocean server with django?
I make cloud panel projects with django but i have a problem. i am click to manage button after this page show: https://s18.postimg.org/lj7qwc8p5/Ekran_G_r_nt_s_2018-02-21_19-22-33.png I make connect to paramiko. Paramiko is right work but this is not connect yet. so we will make first with connect paramiko after then, later on the directory make verification on server. This code piece is wrong: from django.shortcuts import render from explorer.models import Servers from django.http import HttpResponse import paramiko import logging import csv paramiko.util.log_to_file("filename.log") # Create your views here. def listfiles(path,ssh,server,sftp): cmd = "cd "+path lf = "ls -p | grep -v /" f = open('dumps/' + server + 'traverse.sh','w+') f.write('#!/bin/bash\n') f.close() f = open('dumps/'+ server + 'traverse.sh','a+') f.write(cmd + "\n") f.write(lf) f.close() sftp.put('dumps/' + server +'traverse.sh ','traverse.sh') ssh.exec_command("chmod 777 traverse.sh") stdin,stdout,stderr = ssh.exec_command("./traverse.sh") data = stdout.read() ssh.exec_command("rm -rf traverse.sh") return data.split() line 37 = lf = "ls -p | grep -v /" manage.py inside: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "cloudpanel.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv) How to be solution my problem? Do not look for my bad english. -
Dynamic get_absolute_url using url query parameters
Big picture: I'd like my reverse method in get_absolute_url (see below) to return a url with a query parameter appended to it at the end, e.g. <url>?foo=bar. Further, I'd like bar to be specified by the POST request that triggered the call to get_absolute_url, either as an input to the form (but not a field represented by the model, something temporary) or as a url query parameter. I am easily able to access bar in my view using either method, but I can't seem to figure out how to access it in my model. The motivation here is that my detail page splits up the fields from my model into different tabs using javascript (think https://www.w3schools.com/howto/howto_js_tabs.asp). When the user is updating the model, they choose which tab they want to update, and then the update template only renders the fields from the model which are related to that tab. More importantly, after the user submits the update, I want the detail page to know to open the specific tab that the user just edited. (I understand how this works if the field is a part of the model; in get_absolute_url with parameters, the solution is pretty straightforward and involves using … -
Why CRUD Operations Using Ajax and Json for Django powered app is so slow ?
I am performing operations on remote legacy MySQL database having about 7000 records.Currently, it's taking around 1.5 minutes for the Update / Delete / Create operation. Should I use Rest? OR some other some other API. Any suggestions will be appreciated! Here is the code: plugin.js $(document).ready(function(){ var ShowForm = function(){ var btn = $(this); $.ajax({ url: btn.attr("data-url"), type: 'get', dataType:'json', beforeSend: function(){ $('#modal-book').modal('show'); }, success: function(data){ $('#modal-book .modal-content').html(data.html_form); } }); }; var SaveForm = function(){ var form = $(this); $.ajax({ url: form.attr('data-url'), data: form.serialize(), type: form.attr('method'), dataType: 'json', success: function(data){ if(data.form_is_valid){ $('#book-table tbody').html(data.book_list); $('#modal-book').modal('hide'); } else { $('#modal-book .modal-content').html(data.html_form) } } }) return false; } // create $(".show-form").click(ShowForm); $("#modal-book").on("submit",".create-form",SaveForm); //update $('#book-table').on("click",".show-form-update",ShowForm); $('#modal-book').on("submit",".update-form",SaveForm) //delete $('#book-table').on("click",".show-form-delete",ShowForm); $('#modal-book').on("submit",".delete-form",SaveForm) }); Views.py @login_required() def book_list(request): books = AvailstaticCopy.objects.all().order_by('-row_date') page = request.GET.get('page', 1) paginator = Paginator(books, 144) try: books = paginator.page(page) except PageNotAnInteger: books = paginator.page(1) except EmptyPage: books = paginator.page(paginator.num_pages) context = { 'books': books } return render(request, 'books/book_list.html',context) @login_required() def save_all(request,form,template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True books = AvailstaticCopy.objects.all() data['book_list'] = render_to_string('books/book_list_2.html', {'books':books}) else: data['form_is_valid'] = False context = { 'form':form } data['html_form'] = render_to_string(template_name,context,request=request) return JsonResponse(data) @login_required() def book_create(request): if request.method == 'POST': form … -
DRF How to serialize models inheritance ? (read/write)
I have some models class RootModel(models.Model): # Some fields class ElementModel(models.Model): root = models.ForeignKey(RootModel, related_name='elements', on_delete=models.CASCADE) class TextModel(ElementModel): text = models.TextField() class BooleanModel(ElementModel): value = models.BooleanField() a viewset class RootViewSet(viewsets.ModelViewSet): queryset = RootModel.objects.all() serializer_class = RootSerializer and serializers class TextSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() class Meta: model = TextModel fields = '__all__' def get_type(self, obj): return 'TEXT' class BooleanSerializer(serializers.ModelSerializer): type = serializers.SerializerMethodField() class Meta: model = BooleanModel fields = '__all__' def get_type(self, obj): return 'BOOL' class RootSerializer(WritableNestedModelSerializer): elements = ... class Meta: model = RootModel fields = '__all__' WritableNestedModelSerializer comes from drf_writable_nested extension. I want to GET/POST/PUT a root containing all data example with GET (same data for POST/PUT) { elements: [ { type: "TEXT", text: "my awesome text" }, { type: "BOOL", value: true } ], ... root fields ... } What is the best way for elements field in RootSerializer ? I also want to have information with OPTIONS method Thanks -
Impossible to install gettext for windows 10
I have followed all the steps shared in all stackoverflow and other questions out there to install gettext for windows (10), but still, I get the error: "Can't find msguniq, make sure you have gettext tools installed" when using internationalization in django. I have tried to download the files directly and added them to the PATH, and even an installer that had already compiled everything and added to the path automatically, but it still doesn't work, and I don't know what else to do... Help please! Thank you for your time. -
Django - validate model before saving to DB
in Django 1.10 - I want to create multiple objects by importing. Before creating them I want to validate fields to make sure as much as I can that creation will pass successfully and collect as much data as I can about invalidate fields. For example, to find out whether a char field is too long. I can use 'if' statement for each field but it's not robust. I thought of using the model Serializer. The problem is that there are models to create that uses other models that also should be created. So when trying to validate the model that depends on the other one - it fails since it's not existed yet. For example: class FirstModel(BaseModel): title = models.CharField(max_length=200) identifier = models.CharField(max_length=15) class SecondModel(BaseModel): identifier = models.CharField(max_length=15) firstModel = models.ForeignKey(FirstModel, related_name='first_model') Any idea how to validate the data? -
How to filter objects from template?
I have 2 models Category and Spending where Category is one of the Spending fields. User can create custom categories and add spending on the webpage. The question is, how to filter spendings by categories in Template? I have: {% for category in categories %} {% for spending in spendings %} 'I want this FOR have only spendings from this category.' I know how to filter objects with Object.objects.filter() but I am not sure it applies here, because categories are dynamic here -
Error running WSGI application
I'm trying to host my app on pythonanywhere. I'm getting this error. Error log 2018-02-21 16:19:19,137: Error running WSGI application 2018-02-21 16:19:19,138: django.core.exceptions.ImproperlyConfigured: The app module <module 'resumemaker_app' (namespace)> has multiple filesystem locations (['/home/Audhoot/django-resumemaker/resumemaker/resumemaker_app', './resumemaker_app']); you must configure this app with an AppConfig subclass with a 'path' class attribute. 2018-02-21 16:19:19,138: File "/var/www/audhoot_pythonanywhere_com_wsgi.py", line 57, in <module> 2018-02-21 16:19:19,138: django.setup() 2018-02-21 16:19:19,138: 2018-02-21 16:19:19,139: File "/home/Audhoot/.virtualenvs/MyDjangoEnv/lib/python3.6/site-packages/django/__init__.py", line 24, in setup 2018-02-21 16:19:19,139: apps.populate(settings.INSTALLED_APPS) 2018-02-21 16:19:19,139: 2018-02-21 16:19:19,139: File "/home/Audhoot/.virtualenvs/MyDjangoEnv/lib/python3.6/site-packages/django/apps/registry.py", line 89, in populate 2018-02-21 16:19:19,139: app_config = AppConfig.create(entry) 2018-02-21 16:19:19,139: 2018-02-21 16:19:19,140: File "/home/Audhoot/.virtualenvs/MyDjangoEnv/lib/python3.6/site-packages/django/apps/config.py", line 110, in create 2018-02-21 16:19:19,140: return cls(entry, module) 2018-02-21 16:19:19,140: 2018-02-21 16:19:19,140: File "/home/Audhoot/.virtualenvs/MyDjangoEnv/lib/python3.6/site-packages/django/apps/config.py", line 40, in __init__ 2018-02-21 16:19:19,140: self.path = self._path_from_module(app_module) 2018-02-21 16:19:19,141: 2018-02-21 16:19:19,141: File "/home/Audhoot/.virtualenvs/MyDjangoEnv/lib/python3.6/site-packages/django/apps/config.py", line 73, in _path_from_module 2018-02-21 16:19:19,141: "with a 'path' class attribute." % (module, paths)) WSGI configuration: `import os import sys path = "" if path not in sys.path: sys.path.append(path) os.chdir(path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "resumemaker.settings") import django django.setup() from django.core.wsgi import get_wsgi_application application = get_wsgi_application()` -
Unknown column in field list, django slug error
I tried to set up a second slug for my models, but this time, I got an error like: (1062, "Duplicate entry '' for key 'slug'") But then I faked migrations and when I tried to load the page I got into another error: (1054, "Unknown column 'courses_faculty.slug' in 'field list'") What can be the cause of this. I read other similar questions and I made the slug non-unique, but that's not helping.. # model class Faculty(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=140, unique=False, default=None, null=True, blank=True) class Meta: verbose_name_plural = 'Faculties' def __str__(self): return self.name # urls path('courses/<slug:slug>/', views.faculties, name='faculties') # view def faculties(request, slug): query = Faculty.objects.get(slug=slug) context = { 'courses': Course.objects.all(), 'faculties': query, 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), } return render(request, 'courses/faculties.html', context) -
Send Bootstrap Tab's ID to View.py via Django
I am trying to send tabs id to the the server from Django template. I want to send the selected tab's ID after submit the page. Is there any way to do that? Here is my tab list: <ul class="nav nav-tabs" role="tablist"˛id="myTab"> <li><a href="#Section1" role="tab" id="MyFirstTab" data-toggle="tab"><i class="fa fa-sun-o"></i>MyFirstTab</a></li> <li><a href="#Section2" role="tab" id="MySecondTab"data-toggle="tab"><i class="fa fa-cloud"></i>MySeconfTab</a></li> </ul> -
Celery, calling delay with countdown
I'm trying to understand how celery works In my django application in tasks.py file I have created one task: @celery.shared_task(default_retry_delay=2 * 60, max_retries=2) def my_task(param1, param2): # There are some operations I call this task by using this code: my_task.delay(param1, param2) Inside of this my_task there is one condition where this task should be started again but after one minute delay I have found that there are some kind of ETA and countdown for tasks, but their examples are only with apply_async Is it possible to use some kind countdown for delay? -
ImportError: No module named 'filebrowser'
I have just installed django-filebrowser on my django site hosted on pythonanywhere and using python 3.5 and django 1.11.7. I followed the instructions in the docs to set it up. The apps are installed in settings.py, and I have used manage.py collecstatic to collect those files in the currect location (I am using whitenoise to serve static files through an Amazon CDN). My urls.py declarations are as follows: url(r'^filebrowser/', include('filebrowser.urls')), url(r'^grappelli/', include('grappelli.urls')), url(r'^admin/', admin.site.urls), I also used site.urls, but was informed that 'site' is undefined. The error I receive on the present settings is: ImportError: No module named 'filebrowser.urls' -
How can I output formset as a result of submition of another form?
I am trying to output formset as a result of another form submission on the same page. This formset contains forms that should be submitted too. Here is my func view: def manage_articles(request): dyn_form = type('DynForm', (forms.BaseForm,), {'base_fields': {'title': forms.CharField(), 'name': forms.CharField()}}) form = ArticleForm() formset = formset_factory(dyn_form, extra=4) if request.method == 'POST': form = ArticleForm(request.POST) formset = formset(request.POST, request.FILES) if formset.is_valid(): print('Formset sent') if form.is_valid(): return render(request, 'test_form.html', {'formset': formset, 'form':form}) else: return render(request, 'test_form.html', {'form':form, 'formset': ''}) Here is my basic form: class ArticleForm(forms.Form): author = forms.CharField() How can I do that? -
Hidden Input with django-encrypted-fields
Is there a way to make the input field in Django Admin a HiddenInput field when using django-encrypted-fields? I've tried using widget=forms.HiddenInput but then this error TypeError: __init__() got an unexpected keyword argument 'widget' For now I've excluded it from the admin but was hoping there was a way to do this that I couldn't find. I'm using django 1.11 with python 3.6. models.py from django.db import models from encrypted_fields import EncryptedCharField class Environment(models.Model): name = models.CharField(max_length=120, unique=True, null=False, blank=False) creds = EncryptedCharField(max_length=120, null=False, blank=False) admin.py from django import forms from django.contrib import admin from encrypted_fields import EncryptedCharField from .models import Environment class EnvironmentAdmin(admin.ModelAdmin): save_as=True #creds = EncryptedCharField(widget=forms.HiddenInput) exclude = ('creds',) admin.site.register(Environment, EnvironmentAdmin) -
ISS Webservice encoding on XML to SQL Server
I have a ISS + asp.net webservice, witch I receive a XML via post. This post calls a stored procedure on SQL Server, passing the XML as parameter. But all the accents of the XML are turned into "?", like this: <FIRST_NAME>Jos?</FIRST_NAME> Should be: <FIRST_NAME>José</FIRST_NAME> But the xml sent from a django app is correct. I've already tried utf-8 and utf-16 on the XML header, nothing changed. The procedure parameter in face is a NVARCHAR(MAX), as the webservice turns < and > in html char, so I have to do this: @DATASET NVARCHAR(MAX) SET @DATASET = REPLACE(REPLACE(@DATASET, '&lt;', '<'), '&gt;','>') DECLARE @DATASET_XML XML = @DATASET If the XML comes with the <, this would be not necessary. Where should I focus my debug? ISS maybe be doing this? Or is something on the django app or the SQL server? -
Setting up Django Channels
I have been trying to integrate Django channels into my existing Django application. Here's my routing.py: from channels.routing import route channel_routing = [ route('websocket.receive', 'chat.consumers.ws_echo', path=r'^/chat/$'), ] Here's my consumers.py: def ws_echo(message): message.reply_channel.send({ 'text': message.content['text'], }) I am trying to create a socket by doing this: ws = new WebSocket('ws://' + window.location.host + '/chat/'); ws.onmessage = function(message) { alert(message.data); }; ws.onopen = function() { ws.send('Hello, world'); }; When I run this code, I get the following error in my console: WebSocket connection to 'ws://localhost:8000/chat/' failed: Error during WebSocket handshake: Unexpected response code: 404 On my server, I get the following error: HTTP GET /chat/ 404 Based on the error, I think that Django is giving a http connection rather than a ws connection. Any help on this issue is greatly appreciated. -
Django migrations, resolving merging problems
As I was changing my models.py and migrating, I got an error message saying: python manage.py makemigrations project_profile CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0033_auto_20180217_0912, 0036_auto_20180217_0927 in project_profile). To fix them run 'python manage.py makemigrations --merge' So, when I tried to follow the instructions, I got another error that one of my tables that the merged migration is now depending on do not exist anymore (I renamed it). Interestingly enough, this renaming took place during the merge operation. So, really Django should have known about it in the first place. To resolve the situation, I deleted prior migrations up to and including the migrations that was not applied, the one that caused all the headache. I tried to makemigrations and migrate again. But, Django now throws another error saying some of the models it wants to create in the database already exist. Obviously, I do not want to delete those tables and loose all that information to appease Django. So, I had to resort to some hacking solutions and actually change those tables manually and do a fake migration in order to stop Django from complaining. Having said all of that, I feel like there … -
django admin nested inlines with mptt children
I'm trying to figure out if it's possible to create a ModelAdmin with multiple nested inlines like: Contract Mainproduct Subproduct1 Subproduct2 SubSubproduct And I'm also trying to solve the models with mptt. My models are looking like this: class Contract(models.Model): contractnumber = models.CharField(max_length=25) field2 = models.CharField(max_length=25) field3 = models.CharField(max_length=25) field4 = models.CharField(max_length=25) def __str__(self): return self.field1 class Meta: verbose_name = 'Contract' verbose_name_plural = 'Contracts' class Mainproduct(MPTTModel): pr_c_contractnumber = models.ForeignKey(Contract) pr_name = models.Charfield(max_length=50) productdetails = models.Textfield(max_length=5000) pr_sernr = models.CharField(max_length=50) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', db_index=True, on_delete=models.SET_NULL) def __str__(self): return self.pr_c_contractnumber, self.pr_name class MPTTMeta: order_insertation_by = ['pr_sernr'] class Meta: verbose_name = 'Product' verbose_name_plural = 'Products' My admin.py file is looking like this: class ProductModelInlineForm(forms.ModelForm): parent = TreeNodeChoiceField(queryset=Product.objects.all()) class ProductModelInline(admin.TabularInline): model = Product form = ProductModelInlineForm extra = 1 class ProductAdmin(admin.ModelAdmin): inlines = [ProductModelInline, ] class ProductInline(admin.TabularInline): model = Product extra = 1 class ContractAdmin(admin.ModelAdmin): inlines = [ProductInline, ] Is there a way to create these nested inlines? Am I missing something important? -
Searching literature regarding the lack of security patching in web frameworks
I'm currently in my final year of my master in Computer Science. I'm working on a security master thesis where the goal is to automatically patch a web framework whenever a security patch is released. There is a lot of frameworks that already have this feature, however my approach is a little bit different where I'm going to detect the critical impact areas of such an update. My question is if there is anyone out there that have stumbled opun some good articles or studies of this topic? What is the practice that the industry is using when it comes to patching their systems when a new security vulnerability is exploited? I'm working with Django as my web framework, however any research on other frameworks are much appreciated! -
Django ProgrammingError claims there is no unique constraint for a table that has an unique constraint.
I have a model, which contains a foreignkey to MtAssignment, which is in another app. Class BinaryQuestionReply(Models.Model): mturk_assignment = models.ForeignKey( 'mturk.MtAssignment', null=True, blank=True, related_name='+', on_delete=models.SET_NULL ) class MtAssignment(Models.Model): id = models.CharField(max_length=128, primary_key=True, unique=True) When running makemigrations and migrations, Django will return the following error: django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table "mturk_mtassignment" See the full stack trace: Traceback (most recent call last): File "manage.py", line 18, in <module> execute_from_command_line(sys.argv) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 111, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 148, in apply_migration state = migration.apply(state, schema_editor) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 87, in __exit__ self.execute(sql) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 107, in execute cursor.execute(sql, params) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 81, in execute return super(CursorDebugWrapper, self).execute(sql, params) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 66, in execute return self.cursor.execute(sql, params) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/utils.py", line 97, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/data_nfs/opensurfaces2/venv/local/lib/python2.7/site-packages/django/db/backends/utils.py", line 66, in execute return self.cursor.execute(sql, params) django.db.utils.ProgrammingError: there is no unique constraint matching given keys for referenced table … -
How to stop redirection from local host to https
I have a website using Django. There is always a redirection from our website as https. The problem that on localhost it cause a problem. The error is : **An error occurred during a connection to 127.0.0.1:8000. SSL received a record that exceeded the maximum permissible length. Error code: SSL_ERROR_RX_RECORD_TOO_LONG** How to solve this problem? Please, I need your help. This problem doesn't exist before. I couldn't find the solution till now. The nginx configuration is: server { listen 80; listen [::]:80; server_name www.website.com; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_max_body_size 6m; if ($scheme = http) { return 301 https://website.com$request_uri; } location /static { alias /home/website/staticfiles; autoindex on; expires max; gzip on; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; } location /media { alias /home/website/media; autoindex on; expires max; } location / { proxy_pass http://127.0.0.1:8000/; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } server { listen 443 ssl; listen [::]:443 ssl; server_name IP website.com; ssl_certificate /home/website/website.com.crt; ssl_certificate_key /home/website/website.com.key; ssl_protocols TLSv1 TLSv1.1 TLSv1.2; ssl_prefer_server_ciphers on; ssl_ciphers ''; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; client_max_body_size 6m; location /static { alias /home/website/staticfiles; autoindex on; expires max; gzip on; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; } location /media … -
How to reference Users model to my app models and Provide a foreign key
I am using Django-Cookiecutter which uses Django-Allauth to handle all the authentication and there is one App installed called user which handles everything related to users like sign-up, sign-out etc. I am sharing the models.py file for users @python_2_unicode_compatible class User(AbstractUser): # First Name and Last Name do not cover name patterns # around the globe. name = models.CharField(_('Name of User'), blank=True, max_length=255) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) Now that I have added my new App say Course and my models.py is class Course(models.Model): name = models.CharField(max_length=30) description = models.CharField(max_length=100) def __str__(self): return self.name def get_absolute_url(self): return reverse("details:assess", kwargs={"id": self.id}) I have also defined my views.py as @login_required def course_list(request): queryset = queryset = Course.objects.all() print("query set value is", queryset) context = { "object_list" :queryset, } return render(request, "course_details/Course_details.html", context) Is there any way I can reference(Foreign key) User App to my Course App so that each user has their own Course assigned to it. one of the possible ways is to filter objects on the basis of the user and pass it to the template I can't figure it out that how to map users and course in order to get the list of … -
Is it possible to disable a field in Django admin?
I give you my example right now because it's too hard to explain it, well, I don't know XD. I have an object named Step like this : class Step(models.Model): # Intitulé de la question title = models.CharField(max_length=300) # Appartenance belonging = models.ForeignKey('Survey', blank=True, null=True) # Renvoi à lui-même pour arborescence parent = models.ForeignKey('self', blank=True, null=True) # Ordre de la réponse order = models.PositiveIntegerField(default=0) # Complément d'information add_info = models.TextField(blank=True, verbose_name="Additional informations") def __str__(self): return (self.title) def children(self): return Step.objects.filter(parent=self, belonging=self.belonging).order_by('order', 'title') def render_step(self): template = get_template('app_questionnaire/_step.html') return template.render({'step': self}) I have one Step without parent and only one. I just wonder if it's possible to disable the EMPTY parent field in the Django admin after adding a Step ? I would like to add others Step with a parent but not another Step without a parent. I don't know if you know what I mean :) Thank you in advance !