Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
problem occured during running a django program
from django.utils.encoding import force_text ImportError: cannot import name 'force_text' from 'django.utils.encoding' (C:\Users\LENOVO\OneDrive\Desktop\internet and intranet\django-ecommerce\venv\lib\site-packages\django\utils\encoding.py) i am trying to run django program -
Error in setting SIGNING_KEY in djangorestframework-simplejwt
It's a bit odd! I have separated the base settings from the local settings. For instance, I moved SECRET_KEY into an other file called local.py as my local settings: SECRET_KEY = env( "DJANGO_SECRET_KEY", default="MY_DEFAULT_SEC_KEY" ) and the following is my simple-jwt settings in base.py which does not contain any variable called SECRET_KEY(since I moved it into local.py): REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ], } SIMPLE_JWT = { "AUTH_HEADER_TYPES": ("Bearer", ), "ACCESS_TOKEN_LIFETIME": timedelta(minutes=30), "REFRESH_TOKEN_LIFETIME": timedelta(days=1), "ROTATE_REFRESH_TOKENS": True, "SIGNING_KEY": env("SIGNING_KEY"), "USER_ID_FIELD": "id", "USER_ID_CLAIM": "user_id", } I want to set a different SIGNING_KEY but I get the following error: File "/usr/local/lib/python3.11/site-packages/rest_framework_simplejwt/settings.py", line 19, in celery_worker-1 | "SIGNING_KEY": settings.SECRET_KEY, celery_worker-1 | ^^^^^^^^^^^^^^^^^^^ celery_worker-1 | File "/usr/local/lib/python3.11/site-packages/django/conf/init.py", line 111, in getattr celery_worker-1 | raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") celery_worker-1 | django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I don't need to set SECRET_KEY according to the documentation when I set a different SIGNING_KEY. However, it says I need to give it a value. What is the problem? -
Django Ajax Request - JSONDecodeError: Expecting value
I am working on a Django project where I have a course enrollment system. I have a button on my HTML page that, when clicked, triggers an Ajax request to submit enrollment data. The button redirects me to a page with a form where a student can fill in data such as name, surname, phone number, email, and language level. However, I am facing an issue where the values from the HTML attributes (data-language-id, data-course-name, data-price) are not getting passed into the Django view. The Django view returns a JSONDecodeError: Expecting value when trying to parse the request body. I intend to save this data into two tables in my database: Student and Enrolment. Any insights or suggestions on how to resolve this issue and successfully save the data into these tables would be greatly appreciated. Thank you! HTML Code: <!-- This is the button triggering the Ajax request --> <div class="block1_1"> <!-- ... other HTML content ... --> <div class="block__button" onclick="submitData(this)" data-language-id="1" data-course-name="Стандарт" data-price="6000"> <a href="{% url 'index3' %}">Записатися</a> </div> </div> JavaScript Code: function submitData(clickedBlock) { var languageId = clickedBlock.getAttribute('data-language-id'); var courseName = clickedBlock.getAttribute('data-course-name'); var price = clickedBlock.getAttribute('data-price'); $.ajax({ url: "/index3/", type: "POST", contentType: "application/json; charset=utf-8", dataType: "json", data: … -
Django TypeError: save() got an unexpected keyword argument 'force_insert'
I get an error when creating a new user via a form on the site, or via python manage.py createsuperuser: TypeError: save() got an unexpected keyword argument 'force_insert' signals.py: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py: from django.db import models from django.contrib.auth.models import User from PIL import Image class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self): super().save() img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) I tried passing args, **kwargs to get def save(self, *args, **kwargs) and super(Profile, self).save(*args, **kwargs). I also tried passing these arguments to signals.py. The error remains, I don't know what to do. If you need more code from any script, I will provide it all Read other threads on this topic, but the solution didn't work for me 😥 -
Incorrect output of parents for a search result in a tree structure
I’m trying to enter parents for the search result so that the user understands in which node the value is located. The output is not correct. How to remove the extra ones???? models.py class Composition(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', db_index=True, verbose_name='Родительская категория') mapping = models.BooleanField(default=False, verbose_name='Отображение в дереве состава') id_drawing = models.ImageField(upload_to='media/image/', blank=True, null=True, default='null', verbose_name='Рисунок') position = models.PositiveIntegerField(verbose_name='Номер позции в родительской категории') designstion = models.CharField(max_length=255, primary_key=True, verbose_name='Обозначение') name = models.CharField(max_length=255, default='null', verbose_name='Наименование') description = models.TextField(blank=True, null=True, default='null', verbose_name='Описание') quantities = models.PositiveIntegerField(blank=True, null=True, default='null', verbose_name='Количество в родительской категории') slug = models.SlugField(verbose_name="Альт. заголовок") objects = TreeManager() @property def drawing_url(self): if self.id_drawing and hasattr(self.id_drawing, 'url'): return self.id_drawing.url class MPTTMeta: order_insertion_by = ['designstion'] class Meta: # unique_together = [['parent', 'slug']] verbose_name = 'Спецификация' verbose_name_plural = 'Спецификация' def get_absolute_url(self): return reverse('manual:catalog_page', args=[str(self.pk), str(self.slug)]) def __str__(self): return "%s (%s)" % (self.name, self.designstion) view.py def get_ancestors(unit): unit.designstion = unit.get_ancestors() return unit def catalog(request): catalog_list = models.Composition.objects.filter(mapping=True) if request.GET.get('q') != None: question = request.GET.get('q') ** seach_catalog =map(get_ancestors, Composition.objects.filter(Q(name__icontains=question)|Q(designstion__icontains=question)))** return render(request, 'catalog.html', { 'catalog_list': catalog_list, 'seach_catalog': seach_catalog, }) else: return render(request, 'catalog.html', { 'catalog_list': catalog_list, }) html {% for unite in seach_catalog %} {{ unite.name}} <div> {{ unite.designstion }}</div> </li> {% endfor %} Output results: … -
__str__ method in model generates large amount of duplicated queries in django admin panel
I have a model Offer which has a ForeginKey to another model Category. And through this Category model I get a Brand associated with this Category and pass it to the Offer on admin page. But it generates a large amount of queries when I use this Brand field in dropdown filter on Offer admin page. models.py class Brand(BaseFields): name = models.CharField() ... def __str__(self): return self.name() class Category(BaseFields): name = models.CharField() brand = models.ForeignKey( Brand, on_delete=models.SET_NULL, null=True, blank=True, ) parents = models.ManyToManyField( 'self', blank=True, verbose_name='Parent_category', related_name='children', symmetrical=False ) def __str__(self): return str(self.brand) + '----' + self.name class Offer(BaseFields): name = models.CharField() category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True, blank=True, related_name='offer', verbose_name='Related_category' ) def __str__(self): return self.name admin.py class OfferAdmin(admin.ModelAdmin): list_select_related = True list_display = ( 'name', 'brand_name', 'category', 'place', 'status' ) list_editable = ('place', 'status') list_filter = ( ('category__brand', RelatedOnlyDropdownFilter), ('category', RelatedOnlyDropdownFilter), 'status' ) fields = [ 'name', 'description', 'tech_info', 'ctru', 'category', 'place', 'status' ] autocomplete_fields = ['category'] actions_on_bottom = True list_per_page = 25 search_fields = ['name'] def get_queryset(self, request): return super().get_queryset(request).select_related('category', 'category__brand') @admin.display(description='Brand', ordering='name') def brand_name(self, obj): return obj.category.brand.name These two blocks are the main problem, as I understand def __str__(self): return str(self.brand) + '----' + self.name list_filter = … -
Including some records in an SQL query increases query time fivefold on Heroku
We use Django with django-guardian for object-based permissions. Recently, we have been experiencing an extreme increase in runtime of a specific query for at least one user with a lot of annotation_texthighlight . Here is the query: SELECT "annotation_texthighlight"."uuid", [omitted for readability] FROM "annotation_texthighlight" INNER JOIN "annotation_annotation" ON ("annotation_texthighlight"."annotation_id" = "annotation_annotation"."uuid") WHERE ( "annotation_texthighlight"."annotation_id" IN (SELECT U0."uuid" FROM "annotation_annotation" U0 WHERE (U0."chapter_id" = '9a481c82-c44b-4ead-94bb-48de0910877b'::uuid AND U0."min_revision_id" IN ('5a301886-e200-441f-ad8e-03c4eb9bd773'::uuid, '6f539d6f-c9eb-41e2-956e-32b4a5950c33'::uuid))) AND "annotation_texthighlight"."uuid" IN (SELECT CAST(U0."object_pk" AS uuid) AS "obj_pk" FROM "guardian_userobjectpermission" U0 INNER JOIN "auth_permission" U2 ON (U0."permission_id" = U2."id") WHERE (U0."user_id" = 1522 AND U2."content_type_id" = 89 AND U2."codename" IN ('view_texthighlight'))) ); This puzzles me quite a bit. Here are the results of my investigation so far: Copying the database from its original Heroku (Postgres 13.4, standard-2, 4GB RAM, 1.2 GB DB size) to local (stock Postgres 13 via standard Docker image) will cut the runtime ~250ms. In total, about 1200 records will be returned. The first 700 (LIMIT 700) will take ~5 seconds. The remaining (OFFSET 700 LIMIT 700) will take ~25 seconds. Removing either of the WHERE filters will reduce runtime <1s. My best guess would be a different configuration on Heroku as compared to the default Postgres … -
Django MySQL OperationalError (1045) - Access Denied for User
I'm encountering an OperationalError (1045) in Django when trying to run migrations with MySQL. The error message is "Access denied for user 'database_userkeem'@'localhost' (using password: YES)". Steps Taken: Checked MySQL user and password using the command line, successfully connected. "mysql -u database_userkeem -p" Verified the correctness of the MySQL user and password in Django's settings.py. " settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_btx', 'USER': 'database_userkeem', 'PASSWORD': '?Bi:88R==usQCB4', 'HOST': 'localhost', 'PORT': '3306', }, } Tried running migrations using Django's management command: "python manage.py migrate" resulting in the OperationalError Considered removing a separate user configuration and making 'keem' the default user. Updated DATABASES in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'database_btx', 'USER': 'keem', 'PASSWORD': '?Bi:88R==usQCB4', 'HOST': 'localhost', 'PORT': '3306', }, A. Any insights into why there might be a discrepancy between successful MySQL command line access and the Django OperationalError? B. Suggestions for resolving the access denied issue when running Django migrations? C. Are there additional steps or configurations I should consider? -
Celery does not see objects in the database
I know that similar questions have already been asked here, but none of the answers I found turned out to be suitable. I hope I get lucky now. So, I have a Django application using Postgres, RabbitMQ and Celery. When I run the components individually, everything works fine. The problem occurs when running through docker-compose. For some reason, celery tasks cannot find the object in the database. The object exists, moreover, it stores the celery task id (for example, for possible subsequent cancellation of the task). Here are the parts of the code relevant to the problem: # docker-compose.yml version: "3.7" services: db: image: postgres:12.4 container_name: "fbrq_db" volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env environment: - POSTGRES_HOST_AUTH_METHOD=trust networks: - default rabbitmq: restart: always container_name: "fbrq_rabbit" image: rabbitmq:3-management-alpine ports: - 5672:5672 - 15672:15672 networks: - default app: restart: always container_name: "fbrq_app" build: . volumes: - .:/code - ./static:/code/static command: gunicorn --bind 0.0.0.0:8000 fbrq_api.wsgi ports: - "8000:8000" networks: - default celery: restart: always container_name: "fbrq_celery" build: . command: celery -A fbrq_api worker -l info env_file: - ./.env depends_on: - app - rabbitmq environment: - CELERY_BROKER_URL=amqp://guest:guest@rabbitmq:5672/ - DJANGO_SETTINGS_MODULE=fbrq_api.settings networks: - default celery-beat: restart: always container_name: "fbrq_celery-beat" build: . command: celery -A fbrq_api beat -l … -
Celery Task does not retry after a certain number of times
I have a celery task with RabbitMQ as the broker. The task calls an API and checks the response, if the response does not meet some conditions, the task retries itself with a 5 seconds countdown. The problem is that my task gets retried for exactly 279 times and after that it gets stuck in "retried" status and does not execute. Here is what my task basically does: @shared_task(name="get-progress", bind=True, max_retries=10 ** 65, acks_late=True, reject_on_worker_lost=True) def get_progress(self, object_id: str): # get progress from third party api and store in status variable if status == "available": # update object in db return else: self.retry(countdown=5) I created another task to test my configuration as follow @shared_task(name="dummy", bind=True, max_retries=10 ** 65, acks_late=True, reject_on_worker_lost=True) def dummy(self): logger.info(f"retry {self.request.retries} of {self.max_retries} with {self.request.id}") self.retry(countdown=1) The dummy task works just fine and gets retried for a ridiculously large number of times. There are no exceptions being raised, I checked if the API times out and that wasn't the case. The number 279 is really confusing me and I guess I'm missing something here. Any help would be appreciated. -
full toolbar in django-ckeditor-5
i cant use full toolbar in django-ckeditor-5 in ckeditor-4 use: CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, } But in version 5, this method does not work please help me please help me please help me please help me please help me thank you -
CKEditor in django displays as a textarea when i save it from form
I have a form with CKEditor and i need to save it to database. When i save it, it somehow save it with textarea like this: <div> <label for="id_body">Body:</label> <div class="django-ckeditor-widget" data-field-id="id_body" style="display: inline-block;"> <textarea name="body" cols="40" rows="10" required id="id_body" data-processed="0" data-config="{&quot;skin&quot;: &quot;moono-lisa&quot;, &quot;toolbar_Basic&quot;: [[&quot;Source&quot;, &quot;-&quot;, &quot;Bold&quot;, &quot;Italic&quot;]], &quot;toolbar_Full&quot;: [[&quot;Styles&quot;, &quot;Format&quot;, &quot;Bold&quot;, &quot;Italic&quot;, &quot;Underline&quot;, &quot;Strike&quot;, &quot;SpellChecker&quot;, &quot;Undo&quot;, &quot;Redo&quot;], [&quot;Link&quot;, &quot;Unlink&quot;, &quot;Anchor&quot;], [&quot;Image&quot;, &quot;Flash&quot;, &quot;Table&quot;, &quot;HorizontalRule&quot;], [&quot;TextColor&quot;, &quot;BGColor&quot;], [&quot;Smiley&quot;, &quot;SpecialChar&quot;], [&quot;Source&quot;]], &quot;toolbar&quot;: &quot;Full&quot;, &quot;height&quot;: 291, &quot;width&quot;: &quot;100%&quot;, &quot;filebrowserWindowWidth&quot;: 940, &quot;filebrowserWindowHeight&quot;: 725, &quot;language&quot;: &quot;en-us&quot;, &quot;versionCheck&quot;: false}" data-external-plugin-resources="[]" data-id="id_body" data-type="ckeditortype">&lt;p&gt;fhdgh&lt;/p&gt; </textarea> </div> </div> But when i just click save from admin panel it all works perfectly form.html: <div class="form-group"> {{form.as_p}} {{form.media}} </div> forms.py class PostForm(forms.Form): body = forms.CharField(widget = CKEditorWidget()) class Meta: model = Document fields = 'body' models.py from django.db import models from ckeditor.fields import RichTextField from simple_history.models import HistoricalRecords class Document(models.Model): class DocumentStatus(models.TextChoices): ACTIVE = 'active', 'Active' ARCHIVED = 'archived', 'Archived' header = models.CharField(max_length = 32) body = RichTextField() category = models.ForeignKey(Category, on_delete = models.CASCADE) timestamp = models.DateTimeField(auto_now_add = True) status = models.CharField(max_length = 10, choices = DocumentStatus.choices, default = DocumentStatus.ACTIVE) history = HistoricalRecords() def __str__(self): return self.header views.py def add_document_view(request): categories = Category.objects.all() languages = get_language_choices() context = {"allCategories":categories, "form":PostForm, … -
TemplateSyntaxError at \stats2
this is my django code def stats2_view(request): monthly_expenses={} months_ = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] # if request.method == 'POST': # year = request.POST.get('selected_year') # if year: expenses = Expense.objects.filter(owner=request.user, date__year=2024) monthly_expenses = calculate_expense_month_summary(expenses) years = range(2010, datetime.datetime.now().year+1) return render(request, 'expense/stats2.html', {'expense_month_data': monthly_expenses,'yr': years,'months':months_}) and, this template <div class="col-md-6"> <h2>Details</h2> <div class="text-md-start center-paragraph"> <h3>For the year 2024 the break down for each month is as follows</h3> {% for month_num, expense in expense_month_data.items %} <p>Total amount spent in {{ months[month_num]}} till now is <span class="fw-bold">{{ expense }}</span></p> {% endfor %} </div> </div> error Im receiving TemplateSyntaxError at /stats2 i want to print month from the index -
Trouble in integrating express.js with Django
i built a login system for a web app using node and express but my friend built a dashboard in Django. Now I am not sure how to integrate both .How do I authenticate the user in dashboard side? can i run both on a single server? I tried creating a Json web token with email and some other details and storing it in session cookie ,which then is authenticated on dashboard side but that isn't working .I am not sure what to do. -
Collapse tree structure in django
I have a tree structure in Django. It is displayed as a menu. To make it compact, you need to design it as an expandable/collapsible list. How to do this? class Composition(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children', db_index=True) mapping = models.BooleanField(default=False) id_drawing = models.ImageField(upload_to='media/image/', blank=True, null=True, default='null') position = models.PositiveIntegerField() designstion = models.CharField(max_length=255, primary_key=True) name = models.CharField(max_length=255, default='null') description = models.TextField(blank=True, null=True, default='null') quantities = models.PositiveIntegerField(blank=True, null=True, default='null') slug = models.SlugField() objects = TreeManager() @property def drawing_url(self): if self.id_drawing and hasattr(self.id_drawing, 'url'): return self.id_drawing.url class MPTTMeta: order_insertion_by = ['designstion'] class Meta: verbose_name = 'Спецификация' verbose_name_plural = 'Спецификация' def __str__(self): return "%s (%s)" % (self.name, self.designstion) {% recursetree catalog_list %} <li > <a href="{{ node.get_absolute_url }}">{{ node.name }}</a> {% if not node.is_leaf_node %} <ul class="children"> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> So far it outputs like this: enter image description here It should be like this: enter image description here -
TemplateSyntaxError at /taskapp/taskapp-board/ Could not parse the remainder: '(status='new')' from 'tasks.filter(status='new')'
i got an error called "TemplateSyntaxError", i created a project that handle tasks in this app i create task-board.html page that handle user's task i create 3 section for it 1 section add new task 2nd in-progress tasks, and 3rd completed task, if i want to start that task move new tasks section to inprogress section with help of drag and drop same gose for inprogress to completed section task-board.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Task Board</title> <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <style> .task-section { border: 1px solid #ccc; margin: 10px; padding: 10px; width: 200px; float: left; } </style> </head> <body> <div class="task-section" id="new-section"> <h3>New</h3> <div class="draggable" id="new"> {% for task in tasks.filter(status='new') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <div class="task-section" id="in-progress-section"> <h3>In Progress</h3> <div class="draggable" id="in_progress"> {% for task in tasks.filter(status='in_progress') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <div class="task-section" id="completed-section"> <h3>Completed</h3> <div class="draggable" id="completed"> {% for task in tasks.filter(status='completed') %} <div class="task" id="task_{{ task.id }}">{{ task.title }}</div> {% endfor %} </div> </div> <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $(function() { $(".draggable").sortable({ connectWith: ".draggable", update: function(event, ui) { var taskId = ui.item.attr("id").split("_")[1]; var … -
Setup HTTP web through WSGI and Websocket through ASGI on the same Heroku app
I've got a quick question for Heroku Pros. How do you handle both websockets(django-channels) and http web dynos together in a Django app? Here's my Procfile setup-web: gunicorn my_proj.wsgi worker: celery -A my_proj.celery_app worker websocket: daphne my_proj.asgi:application --port 8001 --bind 0.0.0.0 -v2 I'm using Gunicorn for regular web stuff and Celery for background tasks, which are all good. But the websocket part isn't kicking in at all. This works fine on local (tested on postman) but after deploying on heroku I try to call this endpoint I get to see NO logs heroku logs -t -d websocket I'm using Django-channels with ASGI, hence Daphne (also tried uvicorn), but it just stalls out. After digging around a bit, I stumbled on the fact that Heroku doesn't play nice with multiple ports. Not sure if I've got that right, but assuming I do, how can I get this working? I could do below as well (which is working fine!) web: daphne logistics_service.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: celery -A logistics_service.celery_app worker But I'd rather not switch everything over to ASGI for the basic web stuff. My question is do I need to use a process manager like Supervisor or maybe create … -
HTMX Syntax Error When Retrieving data Value from Event in Django View
I have a view def tag_delete(request): if request.method == 'POST': tag_name = request.POST.get("tag") tag = Tag.objects.get(name=tag_name) tag.delete() response = HttpResponse(status=204, headers={'HX-Trigger': json.dumps({ "taglistchangeddelete": {"tag": tag_name} })}) return response When the user clicks a button to delete a tag, this view is called. This view works fine. But the problem start because i have a session variable that contains a list of selected tags. If the tag that has been deleted is in this list, it should be removed from there. So, I created another view to handle this deletion: def process_tags_deleted(request, tag): selected_tags = request.session['selected_tags'] if tag in selected_tags: selected_tags.remove(tag) request.session['selected_tags'] = selected_tags #The rendered template will show the user their selected tags response = render(request, 'espace/tags_selected.html', { 'selected_tags': selected_tags, }) return response To call the process_tag_deleted function, I created an HTMX get request within a random div in the template: <div hx-get={% url 'process_tags_deleted' %} hx-vals='{"tag": evt.detail.tag}' hx-target="#tags_selected" hx-headers='{"X-CSRFToken": "{{ csrf_token }}"}' hx-trigger="taglistchangeddelete"> </div> I'm pretty sure that the problem lies in the hx-vals. I can't retrieve the 'tag' value that comes from the event "taglistchangeddelete". It gives a syntax HTMX error in the console: htmx:syntax:error b @ htmx.min.js:1 function b(e) { if (console.error) { console.error(e) #ERROR } else … -
Nginx is showng welcome-page instead of my Django-app
Here is /etc/nginx/sites-available/myapp: server{ listen 80; listen [::]:80; server_name .somedomain.com; location = /favicon.ico{access_log off; log_not_found off;} location /static/ {root /var/www/myapp;} location / {include proxy_params; proxy_pass http://unix:/run/gunicorn.sock;} } Nginx doesn't show my app instead of welcome-page Also made a simlimk to sites-enabled. I'm using Django + gunicorn to handle this app, so using ddns and already set my router port preferences. Gunicorn runs the application normally, but on localhost. Nginx does not want to transfer the application to the domain, although every guide says that it should simply launch it if there are no errors. I didn't change anything in nginx.conf, so it looks like: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; ssl_protocols TLSv1 TLSv1.1 TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; gzip on; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } -
django.contrib.auth user added can't authenticate
New user created by this sign_up can't login. I can see the user successfully created through admin portal. Only super user can login. What is missing here? forms.py from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username','first_name','last_name','email'] labels= {'email': 'Email'} views.py def sign_up(request): if request. Method == "POST": fm=SignUpForm(request.POST) if fm.is_valid(): fm.save() messages.success(request, 'Account Created Successfully !!') else: fm = SignUpForm() return render(request, 'enroll/signup.html', {'form':fm}) def user_login(request): if not request.user.is_authenticated: if request.method == "POST": fm = AuthenticationForm(request=request, data=request.POST) if fm.is_valid(): uname = fm.cleaned_data['username'] upass = fm.cleaned_data['password'] user = authenticate(request, username=uname, password=upass) else: fm = AuthenticationForm() return render(request, 'enroll/userlogin.html', {'form' : fm}) if user is not None: print(user) login(request,user) messages.success(request,'Logged in Successfully !!') return HttpResponseRedirect('/profile/') else: fm=AuthenticationForm() return render(request, 'enroll/userlogin.html', {'form': fm}) else: return HttpResponseRedirect('/profile/') -
How to handle authentication and authorization process if the users data are stored in elasticsearch database?
I am working on a project in which its backend side is implemented using Django framework, and its database is Elastic Search. I have seen several Django projects in which their authentication has been done using JWT(Json Web Token) and related packages. But in my project since all the user data like first name, last name, username and password are stored in an elastic index, I do not know what is the best way to implement a secure authorization and authentication process using tokens which should have time limits. I have searched on net, but could not find relative and helpful results. The only solution which I decided to try was to clone Django-Rest-Simple-JWT repository, and then change all of its models to elastic indices, and change all of their usages. But I think there must be better ways to handle this problem. I will be really grateful for any advice, solution or suggestion. -
Docker is running very slow in ubuntu 18.04 for a simple django hello world
I am just learning dockr generally but specifically for django. I am still very new to docker and all the question on SO does not seem to help me reduce the build time I have tried to dockerize my hello wold app of django, it has taken moe than 3.5 hours for the process of downloading and extacting packages in docker, this seems to be part of a stage 1 of 5 stages in the building process. this is my dockerfile # The first instruction is what image we want to base our container on # We Use an official Python runtime as a parent image FROM python:3.6 # set environment variables #ENV PYTHONDONTWRITEBYTECODE =1 ENV PYTHONBUFFERED = 1 # where your code lives WORKDIR /app ## Allows docker to cache installed dependencies between builds COPY requirements.txt requirements.txt # install dependencies #RUN pip install --upgrade pip # run this command to install all dependencies RUN pip install -r requirements.txt ##old docker file start ## Allows docker to cache installed dependencies between builds #COPY requirements.txt requirements.txt #RUN pip install --no-cache-dir -r requirements.txt # copy whole project to your docker home directory. COPY . . EXPOSE 8000 CMD python3 manage.py runserver Also … -
Substitute auth_user model not authenticating properly (Django)
Hello everyone I started working on a Django app for a class project but I am running into some confusion when trying to authenticate custom users. The app is a social media platform for my school and as per the requirements of the project I must attach a biography and a role (position at the school). I figured the best way to do this is to attach it to the existing auth_user model but upon following almost all the content I could find users wont authenticate. Even when supplied the correct information the user object is still None. To start off lets take a look at my user model which is declared in an app called "landingpage" from django.contrib.auth.models import AbstractUser class User(AbstractUser): bio=models.TextField() role=models.CharField(max_length=32) Then we go to the main app and declare which AUTH_USER_MODEL we want AUTH_USER_MODEL = "landingpage.User" Finally applying the migration commands python manage.py makemigrations python manage.py migrate Then to test it out I have this code. My login system is a popup form so in order to avoid visiting the page I just redirect back to the index which also refreshes the page so I can update content based on the authenticated user. There is … -
What is best way to implement RBAC in Django?
I have this scenario for a software system: A company has many teams. People belong to different teams and have different roles in each team they belong. They have documents stored on a server and they have a web interface to edit those files over web. It is obvious that we want the people to have only the permissions to have specific access (based on their role in a specific team) on their team's files. As an example, consider Mary. Mary belongs to three teams in this company, namely 'ABC', 'DEF', 'GHI'. Mary is the admin of 'ABC', scrum master of 'DEF' and a simple developer in 'GHI'. Now Mary should be able to: do whatever she wants in 'ABC' team view documents related to 'DEF' team edit documents related to 'GHI' team So, I hope you have understood the scenario. The question here is that obviously, default auth app (with its default settings) provided by Django is not that much useful for implementing this scenario, however, I can make make some changes to somehow work around the problem. I can create Django groups like this: ABC_admin ABC_scrummaster ABC_developers And so on. I mean I create a Django group object … -
Pre-populating DateField in Django REST Framework Serializer Not Working
I am developing a web application using Django and Django REST Framework. I have a serializer with a date field that I want to pre-populate with the current date when the form is displayed. The rest framework documentation demonstrate how to use initial to pre-populate a field, but it doesn't seems to be working. Despite following the documentation, the date field of my form displays "yyyy-mm-dd". Environment: django==3.2.18 djangorestframework==3.14.0 Here is my current code: # serializer.py class FormSerializerCurrentStatus(ModelSerializer): date = serializers.DateField(initial=datetime.date.today) class Meta: model = CurrentStatus fields = ('date', 'user', 'currentstatus') # views.py def retrieve(self, request, *args, **kwargs): form_serializer = FormSerializerCurrentStatus() return Response({'serializer': form_serializer}) # html <form action="{% url 'SomeUrl' %}" method="POST"> {% csrf_token %} {% render_form serializer %} <input type="submit" value="Save"> </form> I have also attempted to override the init method of the serializer to set the initial value of the date field. Does anyone could help me understand what my mistake might be? Thank you!