Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django redis caching per url
So I am trying to implement moreover learn how to cache Django views per URL. I am able to do so and here is what is happening... I visit a URL for 1st time and Django sets the caches. I get my result from cache and not from querying the database during the second visit if the browser is same. Now the doubt is - if I change my browser from the first visit and second visit, for example, do the first visit from Chrome (it sets the cache) and during the second visit from Mozilla, it again sets the cache. I was expecting it to return the result from the cache. During my research on StackOverflow and checking what it sets as cache, I found there are two important things first being a header and the second being the content. And I think every time a browser is changed the header is new so it sets the cache instead of returning the result from cache. Do let me know if I am wrong. I have a public URL and I was thinking to show data from the cache if a subsequent request is made, irrespective of browser or mobile/laptop/desktop, … -
Trying to view a network pdf file with Django
Please help. I have a project that shows the path of a list of pdf files on the network but it has been impossible to view them after the click. I have tried almost everything without good results. Thanks. -
How can I add a field to a many-to-many relationship in Django?
This is a question about how to add a field to a many-to-many relationship in Django. I have a model LandingPage and a model Product. (Code below). In my project, LandingPages can have many Products listed on them and those same Products can appear on multiple different LandingPages. Product is connected to LandingPage via a ManyToManyField. My Goal: I am trying to figure out how to add a field so that I can set the order (1 through 10) for Products on their associated LandingPages. Reminder, Product instances can appear on multiple LandingPages, so each instance will need to have a different order attribute. Ideally, I'd like to expose this functionality via the built-in Django admin. Right now it shows the relationships table, but not the order field as it does not yet exist. (Screenshots/mockups below). My Code: models.py class LandingPage(models.Model): """Stores a single LandingPage and metadata. """ name = models.CharField(max_length=200, help_text="The name is only used internally. It is not visible to the public.") slug = models.SlugField(default="", editable=False, max_length=150, null=False, verbose_name="Slug", help_text="This is not editable.") # Additional fields that I do not believe are relevant class Product(models.Model): """Stores a single Product and metadata. """ name = models.CharField(max_length=200, help_text="Used internally. Not … -
django.forms.fields.DateTimeField got error: 'list' object has no attribute 'strip', when calling BaseForm._clean_fields()
Handling of a POST request led to calling _clean_fields(self). The form contains a field in type of django.forms.fields.DateTimeField, and it triggered an exception of "AttributeError" saying 'list' object has no attribute 'strip'. It looks like, on step value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) the field got a return as ['', ''], which is a list of empty strings. Later on, step value = field.clean(value) triggered the exception. I'm still new to Django, and this is a project to upgrade from Python2.7+Django1.8 to Python3.7+Django3.1. The older version doesn't have this issue. Any pointers will be highly appreciated. Partial source code of django/forms/forms.py: def _clean_fields(self): for name, field in self.fields.items(): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. if field.disabled: value = self.get_initial_for_field(field, name) else: value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) try: if isinstance(field, FileField): initial = self.get_initial_for_field(field, name) value = field.clean(value, initial) else: value = field.clean(value) self.cleaned_data[name] = value if hasattr(self, 'clean_%s' % name): value = getattr(self, 'clean_%s' % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) -
psql migrate giving error: psycopg2.errors.UndefinedTable: relation "accounts_profile" does not exist
When i run the command python manage.py makemigrations followed by python manage.py migrate I keep getting this error: C:\Users\Rohan\teamproject\epic>python manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying admin.0001_initial...Traceback (most recent call last): File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedTable: relation "accounts_profile" does not exist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_line utility.execute() File "C:\Program Files\Python37\lib\site-packages\django\core\management\__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 371, in execute output = self.handle(*args, **options) File "C:\Program Files\Python37\lib\site-packages\django\core\management\base.py", line 85, in wrapped res = handle_func(*args, **kwargs) File "C:\Program Files\Python37\lib\site-packages\django\core\management\commands\migrate.py", line 245, in handle fake_initial=fake_initial, File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Program Files\Python37\lib\site-packages\django\db\migrations\executor.py", line 229, in apply_migration migration_recorded = True File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 115, in __exit__ self.execute(sql) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\base\schema.py", line 142, in execute cursor.execute(sql, params) File "C:\Program Files\Python37\lib\site-packages\django\db\backends\utils.py", line 98, in … -
Mysql database problem with django and vscode
im working on creating website with tools like vs code, django , mysql(using macos). I was trying connect my database to phpmyadmin with mamp but couldn't. Then i tried connect to mysql workbench and that was working.Think that i broke something because i couldn't run program(had out put like :django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient?`). Finally when tried to install mysqlclient and mysql to my venv i got error like below. Do you have some sugestion to solve this problem? Thanks for help! ERROR: Command errored out with exit status 1: command: /Users/arincatlamaz/Documents/praca-inzynierska/env/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/setup.py'"'"'; __file__='"'"'/private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-record-uph0htiy/install-record.txt --single-version-externally-managed --compile --install-headers /Users/arincatlamaz/Documents/praca-inzynierska/env/include/site/python3.8/mysqlclient cwd: /private/var/folders/f4/yc2ncr0515q7xw3yx9ztjjpm0000gn/T/pip-install-u2k_b6t6/mysqlclient_49a2127f669a431ab48f7a11e2a071cd/ Complete output (118 lines): running install running build running build_py creating build creating build/lib.macosx-10.14.6-x86_64-3.8 creating build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/__init__.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb creating build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.14.6-x86_64-3.8/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.14.6-x86_64-3.8 creating build/temp.macosx-10.14.6-x86_64-3.8/MySQLdb xcrun … -
POST and GET requests to a client API URL using Django REST
I am kind of new to API. I am working on a project where I can send POST and GET requests to different APIs. I just want to know how sort of the class in the view file should look like. For example, I have a class that inherits generics.GenericAPIView. How do I send a get request to a specific URL or how do I save the data using the serializer to the database with post request? class ArticelViewSet(generics.GenericAPIView, mixins.ListModelMixin, mixins.CreateModelMixin): serializer_class = ArticleSerializer_Modelserializers queryset = Article.objects.all() lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request) else: return self.list(request) def post(self, request): return self.create(request) #return the created object -
How to serialize three models with many to many relationships in Django Rest Framework
I have three base models: class User(models.Model): displayName= models.CharField(max_length=128) class Cell(models.Model): title = models.CharField(max_length=128) class List(models.Model): title = models.CharField(max_length=128) And three many-to-many relationships between them: class UserCell(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) cell = models.ForeignKey( Cell, on_delete=models.CASCADE ) value = models.SmallIntegerField() class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'cell'], name='unique_UserCell' ) ] class UserList(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE ) target_list = models.ForeignKey( List, on_delete=models.CASCADE ) last_updated = models.DateTimeField(default=timezone.now) class Meta: constraints = [ models.UniqueConstraint( fields=['user', 'target_list'], name='unique_UserList' ) ] class CellAssignment(models.Model): target_list = models.ForeignKey( List, on_delete=models.CASCADE ) cell = models.ForeignKey( Cell, on_delete=models.CASCADE ) idx = models.SmallIntegerField() class Meta: ordering = ['idx'] constraints = [ models.UniqueConstraint( fields=['target_list', 'idx'], name='unique_cellAssignment' ) ] My view is given a List.id and a User.id and I want to return data in the following format, or something similar: {"List.id": 2, "List.title": "The Big List of Cells", "List.created_date": "2020-10-02T18:14:02Z", "cells": [{"target_list.id": 2, "Cell.id": 6, "CellAssignment.idx": 0, "Cell.title": "The first cell", "UserCell.value": 4}, {"target_list.id": 2, "Cell.id": 12, "CellAssignment.idx": 1, "Cell.title": "This is the second cell and so on", "UserCell.value": 9}, ...]} Is it possible to do this by nesting serializers, or should I query the relationships separately and join the data in the view? Any info … -
Django: Where can i find user login, logout activity for past 1 year
In django, is there any where the login, and logout activity for past 1 year is there any tables which stores these details I am using a web, session based application -
Static files django do not load with nginx and daphne
recently I needed to implement a solution with django-channels in an application that was in production with NGINX and uWSGI. It worked well. So, I had to stop the systemd service that managed uwsgi in order to run and manage Daphne as follows: [Unit] Description=daphne daemon for ubuntu After=network.target [Service] User=ubuntu Group=ubuntu WorkingDirectory=/path/to/my/app/ ExecStart=/path/to/my/app/env/bin/daphne -b 0.0.0.0 -p 8000 myproject.asgi:application [Install] WantedBy=multi-user.target However, when performing modifications to the nginx file, even though the application is running, static files are not being loaded. My nginx file looks like this: upstream channels-backend { server localhost:8000; } server { listen 80; # 8000 server_name my_server_ip; # substitute your machine's IP address or FQDN charset utf-8; client_max_body_size 75M; # adjust to taste location /media { alias /path/to/my/app/media; # your Django project's media files - amend as required } location /static { alias /path/to/my/app/static; # your Django project's static files - amend as required } location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; 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; proxy_set_header X-Forwarded-Host $server_name; } } Note: before that, when I was using uwsgi, I ran the command ./manage.py collectstatic If … -
No module named 'mysite.settings'
I know this question has been asked quite a lot but all the solutions given do not seem to fit for me. I run this in a venv with python 3.6.8 and django 2.2.10 When I run django from cli it works and all functionality is working great so I know it is not django itself that is failing me. Path to wsgi script is "/opt/sites/aws/okta/wsgi.py" Actual wsgi.py: import os, sys sys.path.append('/opt/sites/aws') #path = os.path.dirname(os.path.dirname(os.path.abspath(file))) #sys.path.append(path) print(sys.path) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "okta.settings") from django.core.wsgi import get_wsgi_application application = get_wsgi_application() When running python to see what errors it gives I get ModuleNotFoundError: No module named 'okta.settings' I get the same error when running apache with debug logging. I have quadruple checked the path and the environment variables and they are set right in the wsgi.py script. Please help! Thank You, -Chris -
anonymus user data storing related issue related help in Django
i need help for catching the guest user data. in my Django project for example ... i have a site which have an booking form .and also anyone must be signup for using it . but i like to that any interested user can submit the form before signup and after signup . but who submit the form before signup then he got an signup page after submit the form . and the user complete the signup process and then this user submitted data, can show the user dashboard. more example guest user submit data > Next > login/signup > show the submitted data on dashboard it is an session related issue . but i can not successfully. need help for that . thanks an advance -
Trouble implementing Voting to a Django File Upload project
I'm new to programming and have been following along Vitor Freitas' Django File Upload Project. I was able to complete the project, but now I want to add a vote function to the project that takes one of three choices ['Aye', 'Nay', 'Abstain'] on the uploaded file. I'm just not sure if what I want is possible. After uploading the file using forms.py from django import forms from .models import Leg class LegForm(forms.ModelForm): class Meta: model = Leg fields = ('title', 'ministry', 'pdf', 'cast','votes') widgets = { 'cast': forms.HiddenInput(), 'votes': forms.HiddenInput() }# Hide cast and vote totals options when uploading file for review In views I can call the form and list it Views.py class LegListView(ListView): model = Leg template_name = 'class_leg_list.html' context_object_name = 'legs' class UploadLegView(CreateView): model = Leg fields = ('id','title', 'ministry', 'pdf',) #leave out (cast and votes )fields to hide in upload form success_url = reverse_lazy('class_leg_list') template_name = 'upload_leg.html' Html file: {% extends 'base.html' %} {% block content %} {% block content_header %} <h2>Legislation</h2> {% endblock %} <table class="table mb-0"> <thead> <tr> <th>ID</th> <th>Title</th> <th>Ministry</th> <th>View</th> <th>Cast Vote</th> <!-- <th>Votes</th>--> </tr> </thead> <tbody> {% for leg in legs %} <tr> <td>{{ leg.id }}</td> <td>{{ leg.title }}</td> <td>{{ … -
Is there a way to set an expiration time for a Django cache lock?
I have a Django 3.1.3 server that uses Redis for its cache via django-redis 4.12.1. I know that cache locks can generally be set via the following: with cache.lock('my_cache_lock_key'): # Execute some logic here, such as: cache.set('some_key', 'Hello world', 3000) Generally, the cache lock releases when the with block completes execution. However, I have some custom logic in my code that sometimes does not release the cache lock (which is fine for my own reasons). My question: is there a way to set a timeout value for Django cache locks, much in the same way as you can set timeouts for setting cache values (cache.set('some_key', 'Hello world', 3000))? -
Django field with multiple model option
I have a scenario where I have a model "Thread". There are two fields in it. "Sender" and "receiver". Also there are other models like "Teacher", "Student", "Principal" etc. Now in the "Thread" model, the sender can be a "Student", and receiver can be a "Teacher" OR Vice Versa. What is the solution for that: class Thread(models.Model): sender = models.(???) # can't be a student relation because a sender can be a teacher too receiver = models.(???) # same here. Is there any way that I can dynamically first select the model and then pick an object of that list. I have seen this functionality in Odoo. But is there anything in Django? -
Why list index in Django Template it's not in the output?
I use this in the template {% for num in '0123456789'|make_list %} <li>{{ respuesta.num }}: {{ puntaje.num }} </li> But then, the page only shows something like this : : (and the rest goes on like that) Why it doesn't show the elements from the lists? If I only use {{num}} it prints the actual nums from the for iteration and if I use {{respuesta}} it shows the hole list. This happens without triggering any error message or anything else (and yes, there are elements in the list "respuesta" and "puntaje"). -
(Django App) Django-Microsoft-Auth - Please enter the correct username and password
I have been trying to set up this app, but I am a stuck on step 10 in the usage documentation: Start site and go to /admin and logout if you are logged in. Login as Microsoft/Office 365/Xbox Live user. It will fail. This will automatically create your new user. Login as a Password user with access to change user accounts. Go to Admin -> Users and edit your Microsoft user to have any permissions you want as you normally. Am I supposed to create this user using py .\manage.py createsuperuser? I created a user with that program (Only username and password, no email), but the /admin page says the following when I attempt to log in with these credentials: "Please enter the correct username and password for a staff account. Note that both fields may be case-sensitive" Before I sent the login form, I had the HTTP logs open in Chrome. When I sent the login form, the server responded with 200. I triple checked that my caps-lock key was not the problem, and I changed the HTML so I can see the password I was putting in. Am I missing something? Am I supposed to be using a … -
Limit on Number of cart-products
I'd like to set a limit on the number of products that can be added on a cart. --Case scenario: Assuming delivery-resource scarcity, I don't want users to add more than 5 products at a time. (The quantity of same product can, however, be raised) cart-app/cart.py def add(self, product, quantity=1, override_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if override_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def __iter__(self): products = Product.objects.filter(id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.id)]['product'] = product for item in cart.values(): item['price'] = Decimal(item['price']) item['total_price'] = item['price'] * item['quantity'] yield item I've tried slicing my queries but this doesn't work. Any ideas? -
How to know which group a user belongs to
I am developing an application that allows me to control the users that belong to a certain group, but I find a problem that I don't know how to do correctly, I currently have two groups that are day and night, but I have a problem, and that is that those groups They are validated to know which one they belong to and thus show only information from that group, but if I wanted to add more groups than I have, is there a way to know which group a user belongs to and so on to be able to validate the information that I show in templates, this is my model: class User(AbstractUser): def get_full_name(self): return f'{self.first_name} {self.last_name}' @receiver(post_save, sender=User) def group_user(sender, instance, *args, **kwargs): if instance.groups: if instance.groups == 'diurno': group = Group.objects.get(name='diurno') instance.groups.clear() instance.groups.add(group) else: group = Group.objects.get(name='nocturno') instance.groups.clear() instance.groups.add(group) This is my view: class CarListView(LoginRequiredMixin, ListView): login_url = 'users:login' template_name = 'index.html' paginate_by = 6 def get_queryset(self): group = self.request.user.groups.filter( name='diurno').exists() if group: return Car.objects.annotate(Count('partner')).order_by('-pk') else: user = User.objects.filter(pk=self.request.user.pk).first() return Car.objects.filter(user=user) -
Pycharm CE not hitting breakpoints in my Django project
I have my project properly configured to run manage.py in the right place, with the right settings. I also have debug breakpoints set in a method that I know with certainty is being executed. The breakpoints are not disabled or conditional: When I hit the "Run in debug mode" button, using the above run configuration (I'm sure it's the same one because it's the only one I've configured for this project), this is the console output I get: pydev debugger: process 38083 is connecting Connected to pydev debugger (build 192.5728.105) Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). December 23, 2020 - 19:22:22 Django version 3.1.4, using settings 'FEArena.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. However, when I use a REST client to trigger the above method, the one with breakpoints in it, the breakpoints do not trigger and the debugger doesn't start. I get a 200 OK response in my REST client, but PyCharm does not stop and execute the debugger at any point. I looked at other answers that advised setting "Gevent compatible debugging" (which I don't have, because I'm using Community Edition), and I've tried … -
Django model store information for each user
I am building a competition website where challenges will be released weekly. For each user I want to track if they have completed a challenge but cannot see how this would be done. Currently the challenges are stored as a model and am using the ListView and DetailView to display them. from django.db import models from django.contrib.auth.models import User STATUS = ( (0, 'Draft'), (1, 'Publish'), ) class Challenge(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) release_date = models.DateTimeField() preamble = models.TextField() ciphertext = models.TextField() plaintext = models.TextField() status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-release_date'] def __str__(self): return self.title Thank you in advance to anyone who helps me with this. Oh and a solution will be submitted and then checked with this form. <div class='form'> {% if user.is_authenticated %} <textarea rows="10" name="plaintext" form="submitAnswer" wrap="soft" placeholder="Plaintext.."></textarea> <form method="post" id="submitAnswer"> {% csrf_token %} <input type="submit" value="Submit"> </form> {% else %} <p>Must be logged in to submit answer.</p> {% endif %} </div> -
Exception Value: libFreeCADApp.so: cannot open shared object file: No such file or directory
I can't figure out how to use external library as python module in production. Any help on this issue is much appreciated. I am importing FreeCAD as python module in my django app as follow. views.py import sys sys.path.append('freecad/lib') import FreeCAD import Part And Freecad bin and library files reside at root directory where manage.py file is as shown below. Everything works fine on my local sever. I can import FreeCad and do data processing on CAD files. But things start to break when I deploy app on google cloud engine. After deployment it threw this error. Exception Value: libFreeCADApp.so: cannot open shared object file: No such file or directory I also built docker image of this application to make sure consistent dependencies. But same result local sever finds Freecad library and runs fine, but docker throws this error. ModuleNotFoundError: No module named 'FreeCAD'. -
No Reverse Match in login view Django, html template parsing error
I have an issue with my django application. My base.html template can be parsed in certain views but not in all of them and returns an error code I do not have much experience with django but it seems to be that it can parse the template when the views aren't too far away from each other. I also have a very bad structure, but I have no clue how to properly structure a django website. login file (doesn't work): <!--hovedside/templates/registration/login.html--> {% extends "base.html" %} {% block body %} <h2>Login</h2> <form method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Login"></input> </form> <a href="{% url dashboard %}">Back to dashboard</a> {% endblock body %} dashboard file (works): <!--hovedside/templates/users/dashboard.html--> {% extends "base.html" %} {% block body %} <div class="default-bodycontainer"> <h1>Hello, {{ user.username|default:'Guest' }}!</h1> </div> {% endblock body %} Filestructure for templates: templates/base html templates/registration/login html templates/users/dashboard html urls python file from django.urls import path from django.conf.urls import include, url from . import views app_name = "hovedside" urlpatterns =[ path("", views.index, name="index"), path("dashboard/", views.dashboard, name="dashboard"), #path("accounts/", include("django.contrib.auth.urls")), url(r"^accounts/", include("django.contrib.auth.urls")), ] problematic line from base.html: <link rel="icon" href="{% static 'hovedside/img/favicon.ico' %}"> This is just the first line with static in the html template. [Filestructure][1] Full code … -
My Django & React program crushes with Forbidden 403 Error
I am creating a project following the YouTube tutorial at this link: https://youtu.be/JD-age0BPVo?t=133 I recently did the 6th and 7th video, but accidentally, I started from the 7th and got back to the 6th video. I am currently getting the Forbidden errors when I try to click Create Room button: Forbidden: /api/create-room [23/Dec/2020 13:46:38] "POST /api/create-room HTTP/1.1" 403 58 Interestingly, I have no required login/permission/test. I can't understand what is forbidden. I read other Django 403 Error questions and they usually have authorization steps that gives that error but I don't have it. Since the first line of error has POST in it, I am copying my only pieces of code including POST in them. CreateRoomPage.js: handleRoomButtonPressed() { const requestOptions = { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ votes_to_skip: this.state.votesToSkip, guest_can_pause: this.state.guestCanPause, }), }; fetch("/api/create-room", requestOptions) .then((response) => response.json()) .then((data) => this.props.history.push("/room/" + data.code)); } views.py: class CreateRoomView(APIView): serializer_class = CreateRoomSerializer def post(self, request, format=None): if not self.request.session.exists(self.request.session.session_key): self.request.session.create() serializer = self.serializer_class(data=request.data) if serializer.is_valid(): guest_can_pause = serializer.data.get('guest_can_pause') votes_to_skip = serializer.data.get('votes_to_skip') host = self.request.session.session_key queryset = Room.objects.filter(host=host) if queryset.exists(): room = queryset[0] room.guest_can_pause = guest_can_pause room.votes_to_skip = votes_to_skip room.save(update_fields=['guest_can_pause', 'votes_to_skip']) return Response(RoomSerializer(room).data, status=status.HTTP_200_OK) else: room = Room(host=host, guest_can_pause=guest_can_pause, … -
Django template custom filter does not change size of button
I have a Django template variable and custom filter inside a button stylized with bootstrap 4. <button type="submit" class="btn btn-outline-dark text-left mb-2" disabled> {{ my_variable | my_filter}} </button> If my_filterincreases the length of my_variable, I find that the size of the button is not automatically extended as I assume that its size is processed by Django before the filter is applied. Is there a way around this?