Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Download multiple files as zip in Django shows memory error
I am trying to download multiple files as a zip in Django. It works well when file sizes are small. If the file size is more than 1GB, it's showing memory error: Traceback (most recent call last): x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write x-xxx-xx: shutil.copyfileobj(src, dest, 1024*8) x-xxx-xx: File "/usr/lib64/python3.7/shutil.py", line 82, in copyfileobj x-xxx-xx: fdst.write(buf) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1131, in write x-xxx-xx: self._fileobj.write(data) x-xxx-xx: MemoryError x-xxx-xx: During handling of the above exception, another exception occurred: x-xxx-xx: Traceback (most recent call last): x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner x-xxx-xx: response = get_response(request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response x-xxx-xx: response = self.process_exception_by_middleware(e, request) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response x-xxx-xx: response = wrapped_callback(request, *callback_args, **callback_kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/utils/decorators.py", line 130, in _wrapped_view x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func x-xxx-xx: response = view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 231, in inner x-xxx-xx: return view(request, *args, **kwargs) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/views/decorators/cache.py", line 31, in _cache_controlled x-xxx-xx: response = viewfunc(request, *args, **kw) x-xxx-xx: File "/var/app/venv/staging-LQM1lest/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view x-xxx-xx: return view_func(request, *args, **kwargs) x-xxx-xx: File "/var/app/current/fileupload/views.py", line 519, in downloadScanView x-xxx-xx: zf.write(tmp.name, zip_path) x-xxx-xx: File "/usr/lib64/python3.7/zipfile.py", line 1764, in write … -
ignore fields on update view
I have a very large form that I have an update view for. The issue is when the users submits an update it says some fields are required such as author and post date. I don't want users to change these fields. The fields are manually rendered How can I ignore these fields in the update view. I have tried to set the requirements to false def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['author'].required = False self.fields['date_posted'].required = False But this throws a null value in column "author" of relation "blog_post" violates not-null constraint Alot of posts said to add null=True but these fields cannot be null view: class PostUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Post form_class = PostFormUpdate def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False form: class PostFormUpdate(ModelForm): class Meta: model = Post fields = '__all__' -
ImportError : cannot import name 'ugettext_lazy'
I'm trying to install suit, I entered this command : pip install https://github.com/darklow/django-suit/tarball/v2 and wrote this code : from suit.apps import DjangoSuitConfig class SuitConfig(DjangoSuitConfig) : layout = 'horizontal' And added it : INSTALLED_APPS = [ 'products.apps.SuitConfig', .....] But when I added this last code I had this error : InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'suit.templatetags.suit_menu': cannot import name 'ugettext_lazy' from 'django.utils.translation' (C:\Users\hp\environments\env3\lib\site-packages\django\utils\translation_init_.py) note : django 4.01 -
Stripe 'card-element' isn't visible (Python/Django)
this is my first time using this site to ask a question. I'd appreciate the help, I have to turn in this bit of the project today as part of my course :( I'm following this tutorial: https://www.youtube.com/watch?v=ncsCnC3Ynlw (chapter: stripe elements) When I visit my checkout page, the card element isn't showing up. I am at the stage around 3:45:00, and when looking at the checkout, the div for the card element is just a thin, empty bar. Could anyone help me find where I made a mistake? I think it might be the connection between the script and the template or just the script itself, but I'm losing my mind trying to figure out what I've done wrong. My views.py: def BasketView(request): carrinho = Carrinho(request) total = str(carrinho.gettotal()) total = total.replace('.', '') total = int(total) stripe.api_key='sk_test_[...]' intent = stripe.PaymentIntent.create( amount=total, currency='brl', metadata={'integration_check': 'accept_a_payment', 'userid': request.user.id} ) return render(request, 'pedido/pedido_novo.html', {'client_secret': intent.client_secret}) My html template: {% load static %} {% block title %}Livraria Aquaflora | Novo Pedido{% endblock %} {% block adtscripts %} <script src="https://js.stripe.com/v3/"></script> <script src="https://unpkg.com/imask@6.0.7/dist/imask.js"></script> <script src="{% static 'js/orderform.js' %}"></script> <script src="{% static 'js/payment.js' %}" data-rel-js></script> {% endblock %} {% block conteudo %} <div class="container-fluid"> <div class="row no-gutter"> … -
How to get all objects with certain interval of time in django
I want to get all objects which has time to live next 5 seconds with django python ORM. I'm trying in a following way and I don't know why that is not working or what i'm doing wrong... def ttl_expire_list(self): query = self.filter(is_remove=False,ttl__range=[timezone.now() + timedelta(seconds=5), timezone.now()]).order_by("-ttl") # query = self.filter(is_remove=False).order_by("-ttl") return query' -
Django how to find if the object is referenced by ForeignKey from another class in model.py
I have two classes shown below, I wanted to add a function to File to check if the file is referenced by any data inside the Project class (similar how "was published recently" is done here: https://docs.djangoproject.com/en/4.0/_images/admin12t.png ). class File(models.Model): def __str__(self): return self.name file = models.FileField(upload_to='uploads/') class Project(models.Model): def __str__(self): return self.name project = models.ForeignKey(Project, on_delete=models.CASCADE) -
Index not being used for django desc
I have a django model with the following indexes: class Meta: indexes = [ models.Index(fields=['-current']), models.Index(fields=['current']), ] These were added and I ran the migration and saw the results: companies/migrations/0294_auto_20220110_1155.py - Create index companies_c_current_f2c815_idx on field(s) -current of model company - Create index companies_c_current_c8bcb7_idx on field(s) current of model company I've found that running a django-rest-framework query with ordering=current is ~5x faster than with ordering=-current. Using PSQL explain I get the following: # explain select * from company order by current desc nulls last limit 100; QUERY PLAN -------------------------------------------------------------------------------------------------------- Limit (cost=41028.75..41040.42 rows=100 width=1223) -> Gather Merge (cost=41028.75..68747.19 rows=237570 width=1223) Workers Planned: 2 -> Sort (cost=40028.73..40325.69 rows=118785 width=1223) Sort Key: current DESC NULLS LAST -> Parallel Seq Scan on companies_company (cost=0.00..35488.85 rows=118785 width=1223) (6 rows) # explain select * from company order by current asc nulls last limit 100; QUERY PLAN ------------------------------------------------------------------------------------------------------------------------------------ Limit (cost=0.42..49.79 rows=100 width=1223) -> Index Scan Backward using companies_c_current_f2c815_idx on companies_company (cost=0.42..140727.06 rows=285084 width=1223) (2 rows) It seems clear from the above that the asc is using the index while the desc is not, which explains the time difference. My question is: why not? Is there a different way the index needs to be added to make sure … -
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name
NoReverseMatch at /search/ Reverse for 'entry' not found. 'entry' is not a valid view function or pattern name. I´m trying to make an search engine for my website in django, via views.py, but Django always says that there's an exception in views.py Views.py def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) def entries(request, entry): if entry not in util.list_entries(): raise Http404 content = util.get_entry(entry) return render(request,"encyclopedia/entry.html", {"title": entry, "content": Markdown().convert(content)}, ) def search(request): query = request.GET.get("q", "") if query is None or query == "": return render( request, "encyclopedia/search.html", {"found_entries": "", "query": query}, ) entries = util.list_entries() found_entries = [ valid_entry for valid_entry in entries if query.lower() in valid_entry.lower() ] if len(found_entries) == 1: return redirect("entry", found_entries[0]) return render( request, "encyclopedia/search.html", {"found_entries": found_entries, "query": query}, ) But Django says: "if len(found_entries) == 1: return redirect("entry", found_entries[0]) have an "NoReverseMatch" error" Urls.py from django.urls import path from . import views, util urlpatterns = [ path("", views.index, name="index"), path("entries/<str:entry>", views.entries, name="entries/{{ entry }}"), path("search/", views.search, name="search"), ] handler404 = 'encyclopedia.views.error_404_view' Layout.html {% load static %} <!DOCTYPE html> <html lang="en"> <body> <div class="row"> <div class="sidebar col-lg-2 col-md-3"> <h2>Wiki</h2> <form action="{% url 'search' %}"> <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <div> <a … -
How could i redirect a user to a specific primary key
Good evening everyone, I am writing a forum where there are different rooms, in each room a user can leave a comment and also update it as needed. After updating the comment, i want to redirect the user to the same room where this comment was. I tried: 1.Reverse + HTTPResponseRedirect def room(request, pk): room = Room.objects.get(id=pk) room_messages = room.message_set.all().order_by('created') participants = room.participants.all() if request.method == 'POST': message = Message.objects.create( user=request.user, room=room, body=request.POST.get('body') ) room.participants.add(request.user) return redirect('room', pk=room.id) context = {'room': room, 'room_messages': room_messages, 'participants': participants,} return render(request, 'base/room.html', context) @login_required(login_url='login') def updateMessage(request, pk): message = Message.objects.get(id=pk) form = MessageForm(instance=message) if request.user != message.user: return HttpResponse('Unable to edit message') if request.method == 'POST': form = MessageForm(request.POST, instance=message) if form.is_valid(): form.save() return HttpResponseRedirect( reverse( "room", kwargs={ "pk": "13" } ) ) return render(request, 'base/message_form.html',{'obj':message, 'form': form}) but it's working out to return the user only when I manually write the id of the room in which the comment is. Is there a way to bind the id of the comment and the id of the room? I tried to search for similar material and looked for similar projects on github repos, but I can't figure out how to do it, the … -
NGINX serve static files - django project has no styling
I managed to deploy my Django app but I can not pass the static files with Nginx. I have followed all the instructions for deploying to production. When I inspect the page all I see is empty static folder Can anyone spot the mistake? Thanks a lot nginx.conf 10 upstream app_upstream { 9 server app:8080; 8 } 7 6 server { 5 listen 80; 4 listen 443; 1 server_name #######; 2 3 location /static/ { 4 alias /static/; 5 } 6 7 location /media/ { 8 alias /media/; 9 } 10 11 location / { 12 proxy_set_header Host $host; 13 proxy_pass http://app_upstream; 14 } 15 } settings.py 14 13 STATIC_URL = '/static/' 12 STATIC_ROOT = '/static/' docker-compose.yml .... 12 app: 13 build: . 14 ports: 15 - 8000:8000 16 - 8080:8080 17 env_file: 18 - db_${RTE}.env 19 volumes: 20 - .:/app/ 21 - static:/static/ 22 - media:/media/ 23 depends_on: 24 - db 25 26 nginx: 27 build: nginx/ 28 ports: 29 - 443:443 30 - 80:80 31 volumes: 32 - ./nginx/${RTE}/conf.d/:/etc/nginx/conf.d/ 34 - static:/static/ 35 - media:/media/ 36 depends_on: 37 - app 38 39 volumes: 40 static: ... Error message when I docker-compose: nginx_1 | 2022/01/10 16:26:17 [error] 10#10: *8 … -
How to resolve an Import error when using markdownx with Django?
I'm attempting to use markdownx in my code and keep getting an error when running migrations/runserver as shown in extract below: https://i.imgur.com/lzWkM9r.png I've done some searching and everything I have found lists the steps as: pip install django-markdownx Reference in urls.py & settings use in code - models/views py update migrations & run my code currently: settings.py https://i.imgur.com/74n6rPn.png main urls.py (cookbook is app name) https://i.imgur.com/fXIez51.png app/models.py https://i.imgur.com/cJVwBuq.png package versions https://i.imgur.com/t7n5ukS.png The link I have been referencing as a tutorial is: https://dev.to/vladyslavnua/how-to-build-a-django-web-app-from-scratch-tutorial-5bp0 If I comment out the path line relating to the markdownx in main urls.py all works except for a missing import error embedded in page and in server console ' "POST /markdownx/markdownify/ HTTP/1.1" 404 3590 Not Found: /markdownx/markdownify/' I've not used markdownx previously so not sure how to resolve; any help greatly appreciated. Thanks -
Register button won't disappear when user logs in(django, html, css, bootstrap)
Why is this code showing the register button regardless of whether or not a user is logged in? (this is for Django with bootstrap) ''' {% if user.is_authenticated %} <li class="nav-item"> <span class="navbar-text"}">Study hard, {{ user.username }}.</span> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:logout' %}">Log out</a> </li> {% else %} <li class="nav-item"> <a class="nav-link" href="{% url 'users:register' %}">Register</a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'users:login' %}">Log in</a></li>''' -
Django displays source code instead of web page
I am new to django. Any help will be appreciated. It displays source code instead of web page. To be specific the base page (base.html). What I want is to use the data from patient details and doctors detail as they are from different groups. I think that the problem is when i pass my dictionary. Views.py def booking(request): if not request.user.is_active: messages.success( request, ("In order to book an appointment you must login first")) return redirect('login') doctor_details = Doctor.objects.all() f = {'doctor_details': doctor_details} g = request.user.groups.all()[0].name if g == 'Patient': patient_details = Patient.objects.all().filter(EmailAddress=request.user) d = {'patient_details': patient_details} return render(request, 'booking.html', f, d) Html {% extends 'base.html' %} {% block content %} {% load static %} <div class="loginContainer"> <div class="img"> <img src="{% static 'image/booking.svg' %}"> </div> <div class="login-content"> {% for d in patient_details %} <form method="POST" id="signupForm"> {% for f in doctors_details %} {% csrf_token %} <h2 class="title">Booking form</h2> <div class="input-div one"> <div class="i"> <ion-icon name="person-circle"></ion-icon> </div> <div class="div"> <h5>Patient ID: PID - {{d.id}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="person"></ion-icon> </div> <div class="div"> <h5>Name: {{d.FirstName}} {{d.LastName}}</h5> </div> </div> <div class="input-div one"> <div class="i"> <ion-icon name="business"></ion-icon> </div> <div class="div"> <h5>Department</h5> <input type="text" class="input" name="age" required> </div> </div> <div class="input-div … -
Save multiple objects in Django DRF ViewSet create
I have a model in Django which stores some basic information. class Inventory(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), name = models.CharField(max_length=100, unique=True) nickname = models.CharField(max_length=100, blank=True, null=True) manufacturer = models.ForeignKey(InventoryManufacturer, on_delete=models.PROTECT) comment = models.TextField(max_length=500, blank=True, null=True) link = models.URLField(max_length=100, blank=True, null=True) class Meta: unique_together = ('manufacturer', 'manufacturer_part_no') I have another table which stores images for this model: class InventoryImages(models.Model): created_at = models.DateTimeField(auto_now_add=True) added_by = models.ForeignKey(User, on_delete=models.SET("anonymous"), blank=True, null=True) file = ImageField(blank=True, default='', upload_to='inventory/images/%Y/%m/') primary = models.BooleanField(default=False) order = models.IntegerField(blank=True, null=True) item = models.ForeignKey(Inventory, on_delete=models.CASCADE, blank=True, null=True, related_name='images') What is the right way to handle a scenario where a user can fill out a form (where you can set the Inventory model fields) and also upload multiple images. What I did now that the user can upload images everytime on this form, the image gets uploaded but the item Foreign Key stays null. When the user submits the form, the ForeignKey is set for each uploaded image. The scenario when a image gets discarded (no form submission) is handled. This is what I did now: def create(self, request, *args, **kwargs): # Create Inventory item serializer = CreateInventoryItemSerializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(added_by=self.request.user, updated_by=self.request.user) # Save properties inventory_id = serializer.data['id'] # Add id … -
Django - convert datetime string to timezone aware datetime object
So I have a a list of dates and times as a string "2022-01-23 21:30” that I need to import into my Django Application My Django server UTC, however the strings are intended to be UTC+2. So if I import it directly, Django would assume it’s UTC and then the timestamp would saved as 2022-01-23 21:30 (UTC), where in reality it should be converted to 2022-01-23 19:30 (UTC). Is there a specific way I should format it before saving the object in a Django DateTimeField so it will become timezone aware? Thanks in advance. -
formset function update view does not save the forms because the id is missing
I have a view to update 6 of my formset only that the click of the send button gives me the error that the id of each form is missing ... how do you fix it? When I have to create formset there are never problems with the id... Can anyone tell me where I'm wrong? I leave my code below view @login_required def PianoSingleUpdateView(request, id): piano = models.Piano.objects.get(single_piano__id = id) piano_sett = models.PianoSingleDay.objects.get(id = id) dato = models.PianoDay.objects.filter( piano_day = piano_sett) DatiFormSet = modelformset_factory(models.PianoDay, extra = 0, fields=('id', 'kcal', 'carboidrati', 'proteine', 'grassi')) if request.method == 'POST': dati_formset = DatiFormSet(request.POST, request.FILES, queryset = dato) if dati_formset.is_valid(): for dato in dati_formset: dato.save() return redirect('gestione-piano', id = piano.id) else: dati_formset = DatiFormSet(queryset = dato) context = {'piano': piano, 'piano_sett': piano_sett, 'dati_formset': dati_formset} return render(request, 'crud/update/update_piano_giornaliero.html', context) models class Piano(models.Model): nome_piano = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente_piano = models.ForeignKey( User, on_delete = models.CASCADE, related_name = 'utente_piano' ) def __str__(self): return self.nome_piano class PianoSingleDay(models.Model): giorni_settimana_scelta = [ ("1","Lunedì"), ("2","Martedì"), ("3","Mercoledì"), ("4","Giovedì"), ("5","Venerdì"), ("6","Sabato"), ("7","Domenica") ] giorni_settimana = models.CharField( choices = giorni_settimana_scelta, max_length = 300 ) single_piano = models.ForeignKey( Piano, on_delete = models.CASCADE, related_name = 'single_piano' ) def __str__(self): return self.giorni_settimana class … -
CSRF cookie is not set in Django after API call
I have a small Django web app that allows you to log in with a platform using their API. The user is able to log in, but the callback from the log in returns this error: Forbidden (CSRF cookie not set.): /account/platforms/apicallback/ on my server output. I believe that the callback does route to the correct url in my web app, but when it gets to the view associated with it, the CSRF cookie error arises. My request code is below: params = { "app_name": "My App", "scope": scope, "user_id": request.user.id, "return_url": redirect_uri, "callback_url": "https://www.myapp.co.uk/account/platforms/apicallback", "state": {"platform":"api"} } query_string = urlencode(params) url = "%s%s?%s" % (auth_url, query_string) return redirect(url) Here is the urls.py file that contains the callback url: urlpatterns = [ path(r'apicallback/', views.apicallback, name='apicallback'), ] Here is the views.py file with the view for the callback url: @login_required def apicallback(request): consumer_key = request.GET.get('consumer_key') consumer_secret = request.GET.get('consumer_secret') I have got two APIs already working with my web app that both use OAuth2.0, and I haven't come into this issue before. Any ideas on how to fix it without disabling CSRF cookies. Thank you -
Parse File While Upload in Django
May I know how to parse XML tags from XML files while upload in django ? I wanted to make sure below things :- Once I upload file from GUI i wanted to parse data from it and store somewhere in models in django and then land file in media storage directory -
Can not use POST method with Django 4 Rest Framework
I'm having an issue with a new django 4 app not processing or not allowing POST method. I used to bypass this in Django version 3 by adding a trailing slash "/" to the end of url in Postman API Tester like http://127.0.0.1:8000/api/didipay/ instead of http://127.0.0.1:8000/api/didipay . But now in my Django 4 API I completed the url with the slash but POST method is still not processing the data. It gives me a "500 internal server error" and I don't understand where it is coming from. The GET method is rather giving an empty array which is normal because I've not inserted any data yet in the database. I'm using venv, Django 4 Rest framework, serializer, viewSet and these is my models and API urls configurations: //Serialize.py from rest_framework.decorators import permission_classes from didipay_app.models import Didipay_app from rest_framework import viewsets, permissions from .serializers import Didipay_appSerializer class Didipay_appViewSet(viewsets.ModelViewSet): queryset = Didipay_app.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = Didipay_appSerializer // Project folder's urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('didipay_app.urls')), ] // App folder's urls.py from rest_framework import routers, urlpatterns from .api import Didipay_appViewSet router = routers.DefaultRouter() router.register('api/didipay', Didipay_appViewSet, 'didipay') urlpatterns = router.urls The … -
Python Paramiko "exec_command" does not execute - Django
I am facing an issue with the Python Paramiko library in my Django Application This is a function I have written to create an SFTP connection: def createSFTPConnection(request,temp_pwd): ssh=paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) user = User.objects.get(username=request.user) ssh.connect(hostname=temp_host,username=user.username,password=temp_pwd,port=22) sftp_client=ssh.open_sftp() return ssh,user,sftp_client This just returns me the variable for ssh, the username, and sftp_client Then I execute a command on the remote server using this code - ssh,user,sftp_client=createSFTPConnection(request,temp_pwd) # passes the password on that server for the user for creating the connection cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" # executing a shell script by passing it 2 variables stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call print("stderr: ", stderr.readlines()) print("pwd: ", stdout.readlines()) Now, this code works fine and executes the script "temp.sh" on the remote server, but it takes a lot of time as I am returning stdin, stdout and stderr and printing them on the console But, since I don't want that I removed the readlines() calls from there making my code look like this - cmd_to_execute="(cd "+temporary_path+"; sh temp.sh"+" "+var1+" "+var2+")" stdin, stdout, stderr = ssh.exec_command(cmd_to_execute) # actual call But for some reason, this code just doesn't execute on the remote server after removing the readlines() calls Thus, making me think that exec_command … -
From where Django takes the paramenters for "field_names" and "values" in the "from_db" method?
Model class has a method from_db which accepts 3 parameters: @classmethod def from_db(cls, db, field_names, values): Where the arguments that Django passes as field_names, values come from? I need to use them in a different custom method. Thanks in advance for suggestions or solutions. -
Django Form.errors can not display in templates
Django form validation. I'm trying to submit the data form but form.errors can not display in the templates. views def registerUser(request): page = 'register' form = CustomUserCreationForm() if request.method == 'POST': form = CustomUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() messages.success(request, 'User account was created!') login(request, user) return redirect('edit-account') else: messages.success( request, 'An error has occurred during registration') context = {'page': page, 'form': form} return render(request, 'users/login_register.html', context) template form <form method="POST" action="{% url 'register' %}" class="form auth__form"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} <!-- {% if field.help_text %} <small>{{field.help_text}}</small> {% endif %} --> {% for error in field.errors %} <p style="color: red;">{{error}}</p> {% endfor %} </div> {% endfor %} <div class="auth__actions"> <input class="btn btn--sub btn--lg" type="submit" value="Sign In" /> </div> </form> I have not been able to understand why the error message can not display. any help is apriciated. -
Django Models Multiple Field Saving
I'm trying to create an object in my Order model. My js return a list of multiple values for Model database however I can not save multiple values that I received from ajax as a list. I see it's an array in js and a list in django but it's not happening. I've tried ManyToManyField instead of ForeignKey for my Order model model field, but that did not work too. Is there any way to save multiple values (list) that are already objects in my other models? models.py from django.db import models class Car(models.Model): name = models.CharField(max_length=80) country = models.CharField(max_length=100) def __str__(self): return str(self.name) class Model(models.Model): name = models.CharField(max_length=50) car = models.ForeignKey(Car, on_delete=models.CASCADE) def __str__(self): return f"{self.car}-{self.name}" class Order(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) model = models.ForeignKey(Model, on_delete=models.CASCADE) def __str__(self): return str(self.pk) views.py def create_order(request): if request.method == 'POST': print("***", request.POST) my_car_id = request.POST.get('car') my_model_id = request.POST.getlist('model[]') print("***", my_car_id, my_model_id) print("***", type(my_car_id), type(my_model_id)) car_obj = models.Car.objects.get(id=my_car_id) model_obj = models.Model.objects.get(id=my_model_id) print("obj", car_obj, model_obj) models.Order.objects.create(car=car_obj, model=model_obj) return JsonResponse({'created':True}) return JsonResponse({'created':False}) html <form id="car-form"> {% csrf_token %} <div class="row"> <div class="col"> <label for="cars-data-box">Choose a car</label> <select style="width: 15rem;" class="form-control" id="cars-data-box"> <option value="---">---</option> </select> </div> <div class="col"> <label for="models-data-box">Choose a model</label> <select multiple style="width: 15rem;" … -
Python Django Static not showing
I tried many solutions available in stock overflow too but non of it solved my problems.Django is my very first framework right after learning HTML,CSS,python(basics) I don't know what I am doing wrong please help me fix it here is my code Here is my folder structure: [folder structure][1] Here is my settings,URL,HTML code STATICFILES_DIR=[ os.path.join(BASE_DIR,"static") #BASE_DIR/'static' ] from django.urls import path from . import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns=[ path('', views.home, name='home'), path('customer',views.customer,name='customer'), path('products',views.products,name='products') ] urlpatterns += staticfiles_urlpatterns() {% load static %} <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Dash Board</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <link type="text/css" rel="stylesheet" href="{% static 'css/main.css' %}"> </head> <body> {% include "navbar.html" %} {% block content%} {% endblock %} <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.10.2/dist/umd/popper.min.js" integrity="sha384-7+zCNj/IqJ95wo16oMtfsKbZ9ccEh31eOz1HGyDuCQ6wgnyJNSYdrPa03rtR1zdB" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.min.js" integrity="sha384-QJHtvGhmr9XOIpI6YVutG+2QOK9T+ZnN4kzFN1RtK3zEFEIsxhlmWl5/YESvpZ13" crossorigin="anonymous"></script> </body> </html>``` [1]: https://i.stack.imgur.com/65Z9x.png -
Django & React - 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*'
The error I get on the react console is Access to XMLHttpRequest at 'http://127.0.0.1/api/analyse/' from origin 'http://localhost' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here are my Django settings ALLOWED_HOSTS = ['localhost', 'http://localhost', '127.0.0.1'] CORS_ALLOWED_ORIGINS = ['http://localhost', 'localhost', 'http://127.0.0.1' ] CORS_ORIGIN_WHITELIST = ['localhost', 'http://localhost', 'http://127.0.0.1'] CSRF_TRUSTED_ORIGINS = [ 'localhost', 'http://localhost', '127.0.0.1'] INSTALLED_APPS = ['corsheaders',] MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware',] The axios.post is axios.post(ip_address, formData, { headers: { 'accept': 'application/json', 'content-type': 'multipart/form-data' }, This seems to be a common problem and many others had it before but not sure what did I do wrong. Can someone please help?