Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to send query params for tests?
I am trying to make some tests in which asks for ads of a particular type for instance: http://127.0.0.1:8000/ads/?type=normal should return the normal ads and http://127.0.0.1:8000/ads/?type=premium should return the premium ads the tests ask for the ads like this response = self.client.get(reverse("ads")) self.client is for the site. Reverse() was the function i have been using for the other tests so i thought it would work as fine. i was looking for a way i could send the parameters but there is nothing on the internet as far as i'm concerned and i have been struggling with this for hours. ┻━┻ ︵ヽ(`Д´)ノ︵ ┻━┻ If you need any more info i could bring you i tried using: reverse("ads", kwargs={"type": "normal"}) reverse("ads", QUERY_PARAMS={"type": "normal"}) reverse("ads", QUERY_KWARGS={"type": "normal"}) reverse("ads", {"type": "normal"}) these are all things i found online However, nothing worked thanks for reading -
How to render a Django Serializer Template with React Js?
I've set up my api for a basic model in my Django project. I've defined my post and get methods and everything is working correctly. Now, I'm wondering how I can render my Django model using react js. Essentially, I'm wondering how I can use react js to assign my django model values that were inserted using reactjs instead of django. For example, if my django model's fields are "name" and "id", how can I assign these fields using reactjs instead of the basic Django page(I've inserted my current page below)? Do we need to use axios or jquery to make these transitions? Thanks. -
How can I register model created by django-simple-history on admin site?
So, I got a model Question that has a history saved in the model HistoricalQuestion by the django-simple-history package, how do I register it to django admin site? Other model registering is straightforward admin.site.register(models.Event) But I am not sure how to get it for that package models. -
React + Django communication
I'm working on a data mining web app, you should be able to upload a csv file, apply an algorithm and get results in the browser and a pdf with information (graphs and models for prediction principally) this is my first time using React and Django, so my question is, how to send the csv file from react to django, handle the data and return it to react? Thanks!! I've seen a lot of tutorials, but every tutorial use the sqlite data base and the POST method for store data and I only want to process the data inside the csv, because the files will never be the same. -
Django dumpdata/loaddata – Key is not present in table
I'm trying to dump my postgres data and load it locally, but I'm ending up with an error These are my two models: class User(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, primary_key=True ) dob = models.DateField(null=True, blank=True) This is the code I'm executing for the data dump: call_command('dumpdata', indent=4, exclude=['contenttypes', 'auth.Permission', 'sessions', 'admin.logentry']) However, when trying to load it, I get the following error: django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "profiles_profile" violates foreign key constraint "profiles_profile_user_id_a3e81f91_fk_accounts_user_id" DETAIL: Key (user_id)=(1) is not present in table "accounts_user". What I noticed when trying to read the fixture is that there are no pks for the user, and no references from the profile: { "model": "accounts.user", "fields": { "password": "xyz", "last_login": "2022-11-27T17:28:45.854Z", "is_superuser": true, "username": "JohnDoe", "first_name": "John", "last_name": "Doe", "is_staff": true, "is_active": true, "date_joined": "2020-09-02T16:28:13.329Z", "groups": [], "user_permissions": [] } }, { "model": "profiles.profile", "pk": 1, "fields": { "dob": "1980-06-20", } }, Is that normal? Note that I also tried using natural-foreign and natural-primary-keys like this: call_command('dumpdata', indent=4, exclude=['contenttypes', 'auth.Permission', 'sessions', 'admin.logentry']) but without any effect. What am I doing wrong? Thanks! -
how to group by category in Django
I have a list of project tasks that show on a Django site. But how in the template can I force it to split the projects this way? What I want to do is have section headings: **PROJECT 1** Task 1 Task 2 Task 3 **PROJECT 2** Task 1 Task 2 -
How can I change URL for upladed files?
I have a problem with a path for opening files. I files are saved on s3 amazon, and url for it is https://certsstorenordic.s3.eu-west-3.amazonaws.com/certificate/2022/11/28/Coffee_Maker_64753-001-003_SN_13-09-4222.pdf. However when i am trying to open it from my website it opens as http://127.0.0.1:8000/certificate/2022/11/28/Ceiling_Light_PN_4041-70_SN_31907.pdf. How to change the beginning of url for uploaded files? My MEDIA_URL in settings.py doesn't work. My urls.py: urlpatterns = [] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Settings.py: WS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.eu-west-3.amazonaws.com' STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'static' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/' MEDIA_ROOT = BASE_DIR / 'media' models.py: certificate = models. FileField(upload_to='certificate/%Y/%m/%d/', blank=True, null=True) html: {% for i in response %} <tr> <td>{{i.component.description}}</td> <td><a href="{{ i.certificate }}">Download</a></td> </tr> {% endfor %} -
Calling a DRF View from another View
I have a User Model Viewset that adds users to my Django Rest Framework application (VueJS -> DRF -> PostGres). I have another ModelViewSet for an activity log that has entries when users get credit for doing training, etc. I ran into an issue where I realized that a user that has done nothing, skews the metrics. To combat this, I just want to insert an Activity into the ActivityLog upon user creation. How can I call a ModelViewSet to post a new activity from the the new user post? I read several questions that seemed similar but I am not understanding well enough to translate to my issue. I just want to take the ID created from the new user creation and pass that with some data to the ActivityLogViewset. If I override perform_create() in the UserViewset, how would I call and pass the data to the other endpoint? Thanks. BCBB -
how to fix error UNIQUE constraint failed: auth_user.username
i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username ` i was trying to use sending email modual from django in order to send sign up email for each user when sign up im facing this error :UNIQUE constraint failed: auth_user.username` # this is my views.py from django.shortcuts import render ,redirect from django.contrib.auth import login from django.contrib.auth.decorators import login_required from . import forms # Create your views here. def home(request): return render(request,'home.html') @login_required def customer_page(request): return render(request,'home.html') @login_required def courier_page(request): return render(request,'home.html') def sign_up(request): form = forms.SignUPForm() if request.method=='POST': form=forms.SignUPForm(request.POST) if form.is_valid(): email=form.cleaned_data.get('email').lower() user= form.save(commit=False) user.useranme = email user.save() login(request,user,backend='django.contrib.auth.backends.ModelBackend') return redirect('/') return render(request,'sign_up.html',{ 'form':form }) ` now i have created signals.py to use email forms ` # my signals.py file from email.base64mime import body_decode from django.db.models.signals import post_save from django.dispatch import receiver from django.core.mail import send_mail from django.conf import settings from django.contrib.auth.models import User from django.template.loader import render_to_string from django.core import mail connection = mail.get_connection() @receiver(post_save,sender=User) def send_welcome_email(sender,instance,created,**kwarg): if created and instance.email: connection.open() body=render_to_string( 'welcome_email_template.html', { 'name':instance.get_full_name() } ) email2 = mail.EmailMessage( 'Welcome to fast Parcle', body, … -
Django RestFramework POST nested request
I'm having a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it. This is my models.py file. class Supplier(models.Model): name = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.name class Transaction(models.Model): date = models.CharField(max_length=255, blank=True, null=True) income = models.IntegerField(blank=True,null=True) expense = models.IntegerField(blank=True,null=True) card = models.CharField(max_length=255, blank=True, null=True) currency = models.CharField(max_length=255, blank=True, null=True) supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) category = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.date + ' ' + str(self.expense) + ' ' + self.card + ' ' + str(self.supplier) This is my serializers.py file class SupplierSerializer(serializers.ModelSerializer): class Meta: model = Supplier fields = ['id', 'name'] class TransactionSerializer(serializers.ModelSerializer): supplier = SupplierSerializer() class Meta: model = Transaction fields = ['id', 'date', 'income', 'expense', 'card', 'currency', 'supplier', 'category'] read_only_fields = ['id'] def create(self, validated_data): supplier_data = validated_data.pop('supplier') supplier = Supplier.objects.create(**supplier_data) transaction = Transaction.objects.create(supplier=supplier, **validated_data) return transaction This is my views.py file @api_view(['POST', 'GET']) def transaction(request): if request.method == 'POST': transaction_serializer = TransactionSerializer(data=request.data) print(transaction_serializer) if transaction_serializer.is_valid(): transaction_serializer.save() return Response(transaction_serializer.data, status=status.HTTP_201_CREATED) if request.method == 'GET': transactions = Transaction.objects.all() serializer = TransactionSerializer(transactions, many = True) return JsonResponse(serializer.data, safe=False) I'm trying to make this POST Request: { "date": "12/10/2022", "income": 41241, "expense": null, "card": "Credit card", "currency": … -
Serving static HTML etc and Django from root '/' using nginx
I have nginx set up to successfully serve a Django website. I'd like to have it also serve a directory of HTML files, images, etc. If a URL doesn't match a file in there, the request should go to Django. Currently I have this (with irrelevant settings removed, e.g. SSL, logging, etc): upstream myproject_server { server unix:/webapps/myproject/run/gunicorn.sock fail_timeout=0; } server { server_name example.com; rewrite ^/favicon.ico$ /static/myproject/favicons/favicon.ico last; rewrite ^/robots.txt$ /static/myproject/robots.txt last; location /static/ { # Django's static files alias /webapps/myproject/code/myproject/static_collected/; } location / { if (!-f $request_filename) { proxy_pass http://myproject_server; break; } } } If I have a directory of miscellaneous files like this at /webapps/myproject/code/myproject/static_html/: static_html/ test.html directory/ foo.html bar.png another/ hello.pdf etc... What do I need to add to my nginx.conf so that those files are efficiently served at /test.html, /directory/foo.html, etc? -
How do I get the client IP address of a websocket connection in Django Channels?
I need to get the client IP address of a websocket connection for some extra functionality I would like to implement. I have an existing deployed Django server running an Nginx-Gunicorn-Uvicorn Worker-Redis configuration. As one might expect, during development, whilst running a local server, everything works as expected. However, when deployed, I receive the error NoneType object is not subscriptable when attempting to access the client IP address of the websocket via self.scope["client"][0]. Here are the configurations and code: NGINX Config: upstream uvicorn { server unix:/run/gunicorn.sock; } server { listen 80; server_name <ip address> <hostname>; location = /favicon.ico { access_log off; log_not_found off; } location / { include proxy_params; proxy_set_header Connection ""; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_pass http://uvicorn; proxy_headers_hash_max_size 512; proxy_headers_hash_bucket_size 128; } location /ws/ { proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "Upgrade"; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_redirect off; proxy_pass http://uvicorn; } location /static/ { root /var/www/serverfiles/; autoindex off; } location /media { alias /mnt/apps; } } Gunicorn Config: NOTE: ExecStart has been formatted for readability, it is one line in the actual config [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=django Group=www-data WorkingDirectory=/srv/server Environment=DJANGO_SECRET_KEY= Environment=GITEA_SECRET_KEY= Environment=MSSQL_DATABASE_PASSWORD= ExecStart=/bin/bash -c " source venv/bin/activate; exec /srv/server/venv/bin/gunicorn --workers 3 --bind unix:/run/gunicorn.sock … -
Django view in array
I have 2 tables (posts, upvoted) that I am working within and am looking to see if a post has been upvoted already and if it has, replace the upvote arrow with a filled arrow. In my view, I am already sending over the Upvote object to my template and am trying to check if the post.id exists within the upvoted table. I tried the code below but it didn't work. How would I do it? {% if post.id in upvote.post_id.all %} -
Upload multiple images to a post in Django View Error(Cannot resolve keyword 'post' into field.)
My Model : class Gallary (models.Model): ProgramTitle = models.CharField(max_length=200, blank = False) Thum = models.ImageField(upload_to='Gallary/Thumb/',default = "", blank = False, null=False) VideoLink = models.CharField(max_length=200, blank = True,default = "") updated_on = models.DateTimeField(auto_now = True) created_on = models.DateTimeField(auto_now_add =True) status = models.IntegerField(choices=STATUS, default = 1) total_views=models.IntegerField(default=0) class Meta: verbose_name = 'Add Gallary Content' verbose_name_plural = 'Add Gallary Content' #for compress images if Thum.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.Thum) # set self.image to new_image self.Thum = new_image # save super().save(*args, **kwargs) def __str__(self): return self.ProgramTitle class GallaryDetails (models.Model): Gallary = models.ForeignKey(Gallary, default = None, on_delete = models.CASCADE) G_Images = models.ImageField(upload_to='Gallary/Images/',default = "", blank = False, null=False) #for compress images if G_Images.blank == False : def save(self, *args, **kwargs): # call the compress function new_image = compress(self.G_Images) # set self.image to new_image self.G_Images = new_image # save super().save(*args, **kwargs) def __str__(self): return self.Gallary.ProgramTitle My View def gallery(request): gallary = Gallary.objects.all() context = { 'gallary': gallary.order_by('-created_on') } return render(request, 'gallery.html',context) def album_details(request, post_id): post = get_object_or_404(Gallary,pk=post_id) photos = GallaryDetails.objects.filter(post=post) context = { 'post':post, 'photos': photos } return render(request, 'album_details.html',context) Gallary View <div class="our_gallery pt-60 ptb-80"> <div class="container"> <div class="row"> {% for post in gallary … -
Jinja elif not working even though condition is true
The fourth elif statement is the one causing me the issue. I have swapped the third elif statement with the fourth and every time the fourth is in third place it works. {% block content%} {% load static %} <link rel="stylesheet" href="{% static 'css/home_page.css' %}"> <link rel="stylesheet" href="{% static 'css/home_w_d_cs.css' %}"> {% if first_hour_d == 'clear sky' and time_of_day == True %} <!-- day == True means day --> <div class="side-hour-icon"> <img src="{% static 'images/sunny-black.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'clear sky' and time_of_day == False %} <!-- day == False means night --> <div class="side-hour-icon"> <img src="{% static 'images/clear-night-black.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'overcast clouds' or 'broken clouds' %} <div class="side-hour-icon"> <img src="{% static 'images/cloudy2.png' %}" alt="" width="55" height="50"> </div> {% elif first_hour_d == 'few clouds' or 'scattered clouds' %} <div class="side-hour-icon"> <img src="{% static 'images/few-clouds-black.png' %}" alt="" width="55" height="50"> </div> {% endif %} {% endblock %} I want to have a few elif statements, maybe 10 or 12. Is this possible? -
Django update_or_create defaults with a query object
I'm using Django 3.2 and I'm trying to call update_or_create like in the snippet below: from django.db import models result = model.objects.update_or_create( field1="value1", field2="value2", defaults={ "field3": "value3", "field4": ~models.Q(field3="value3"), }, ) field4 is a boolean. The problem is the returning value in field4 after the method is called isn't a boolean, but a query object: result[0].field4 <Q: (NOT (AND: ('field3', 'value3')))> However if I refresh the object, the content is correct: result[0].refresh_from_db() result[0].field4 False I'm sure the field was updated because before I ran the snippet, there was an instance with the same values for field1 and field2 but with the opposite value in field4 (True). My question is: is there a way for update_or_create return a boolean value for field4 without querying the instance again from the DB? I checked StackOverflow before for similar questions, this was the closest one I found but it still doesn't answer my question. -
User Registration alsongside simple-JWT with DRF
I am creating a social media type app(twitter clone). I was using allauth for signup and signin which was working perfectly with endpoints /accounts/login and accounts/signup with their default view. But now I was implementing simple-JWT for authentication. I was following this blog post. The guy is using dj-rest-auth with JWT. Login and logout are mounted with endpoints /dj-rest-auth/login/ and dj-rest-auth/logout/ respectively. Now what about the registration? In the blog it is mentioned: Notice that this list includes allauth social accounts; this is actually so that the registration endpoint of dj-rest-auth can work. But I am unable to figure out the endpoint of the same. So I decided to create my own registration url with following codes: views.py class UserRegister(APIView): def post(self,request): serializer = UserSerializer(data = request.data) if serializer.is_valid(): serializer.save() return Response({"User":serializer.data}) return Response({"errors":serializer.errors}) serializers.py class UserSerializer(serializers.Serializer): email = serializers.EmailField(max_length=50, min_length=6) username = serializers.CharField(max_length=50, min_length=6) password = serializers.CharField(max_length=150, write_only=True) class Meta: model = User fields = ['fname','lname','email','username','password'] def validate(self, args): email = args.get('email', None) username = args.get('username', None) if User.objects.filter(email=email).exists(): raise serializers.ValidationError({"email":"email already exists"}) if User.objects.filter(username=username).exists(): raise serializers.ValidationError({"username":"username already exists"}) return super().validate(args) def create(self, validated_data): return User.objects.create_user(**validated_data) But on launching the respective endpoint I am getting a response: { "detail": … -
Deploying Django App Using Google Cloud Run - gcloud builds submit error
I've followed the tutorial for deploying Django on Cloud Run (https://codelabs.developers.google.com/codelabs/cloud-run-django), and I followed the exact instructions up to "Build your application image" on Step 7: "Configure, build and run migration steps". When running the command: gcloud builds submit --pack image=gcr.io/${PROJECT_ID}/myimage [builder] × python setup.py egg_info did not run successfully. [builder] │ exit code: 1 [builder] ╰─> [25 lines of output] [builder] /layers/google.python.runtime/python/lib/python3.11/site-packages/setuptools/config/setupcfg.py:508: SetuptoolsDeprecationWarning: The license_file parameter is deprecated, use license_files instead. [builder] warnings.warn(msg, warning_class) [builder] running egg_info [builder] creating /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info [builder] writing /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/PKG-INFO [builder] writing dependency_links to /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/dependency_links.txt [builder] writing top-level names to /tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/top_level.txt [builder] writing manifest file '/tmp/pip-pip-egg-info-xoozdk2u/psycopg2_binary.egg-info/SOURCES.txt' [builder] [builder] Error: pg_config executable not found. [builder] [builder] pg_config is required to build psycopg2 from source. Please add the directory [builder] containing pg_config to the $PATH or specify the full executable path with the [builder] option: [builder] [builder] python setup.py build_ext --pg-config /path/to/pg_config build ... [builder] [builder] or with the pg_config option in 'setup.cfg'. [builder] [builder] If you prefer to avoid building psycopg2 from source, please install the PyPI [builder] 'psycopg2-binary' package instead. [builder] [builder] For further information please check the 'doc/src/install.rst' file (also at [builder] <https://www.psycopg.org/docs/install.html>). [builder] [builder] [end of output] [builder] [builder] note: This error originates from … -
test router in DRF
hello im trying to test a router and i cant seem to find the url this is inside test function def test_send(self): token1 = Token.objects.get(user=self.user1) response = self.client.post( reverse('send-create'), data=json.dumps({ "receiver": self.user2, "subject": "my first message", "msg": "hello this is my first" }), content_type='application/json', **{'HTTP_AUTHORIZATION': f'Bearer {token1}'} ) this is router router.register('send', views.SendMessagesView, basename='send_message') and this is the view class SendMessagesView(viewsets.ModelViewSet): serializer_class = SendMessageSerializer permission_classes = [permissions.IsAuthenticated] http_method_names = ['post'] def create(self, data): msg = Message.objects.create( sender=self.request.user, receiver=User.objects.get(id=data.data['receiver']), subject=data.data['subject'], msg=data.data['msg'], creation_date=datetime.date.today() ) msg.save() serializer = MessageSerializer(msg) return Response(serializer.data). the error i get is : django.urls.exceptions.NoReverseMatch: Reverse for 'send-create' not found. 'send-create' is not a valid view function or pattern name. please if anyone can help me undertand what am i doing wrong test router in django rest framework -
How do I prescroll an element in django
I have a scrollable element that I would like to be pre-scrolled by 320px on loading the page in my django calendar project. Can I achieve that without using javascript? -
Python backend and javascript front end
I am new to the full stack development and have a question on what frameworks I should use for my project. my project description: my projet recived a csv file from user and uses to make network using networkx and pyvis python libraries. Then we get the network data from pyvis and use vis.js javascript library to display the network to the user. there can be different views for the same dataset and if a user moves things in displayed graph the new layout is saved for them. My main problem is choosing a frame work that allows bidirectional data flow between python and js. can anyone give me some insights? I am thinking about django and flask but not sure how useful they are by themselves -
How Filter Specific Result
Here Is My Space Model Which Include Plantes Details enter image description here Here Is My Moon Model Class Which Include Moons Details and Forgein Key Of Space Model So I Can Set Moon According To Its Planet enter image description here 1st How Can I Filter Object In View So I can Get Moon According To Related Planet Example: Jupiter Is Moon Name Is Eurpo - Eart Moon 2nd- Every Planet Has Different Numbers Of Moon So I also Want To Every Moon Related to that planets enter image description here I Just Stuck In Filtertion How To Get Specific information From two Differnt Models -
How to filter multiple checkboxes in django to check greater value
views.py if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status_new_records = request.POST.get("new_records", None) print(check_box_status_new_records) check_box_status_error_records = request.POST.get("error_records", None) print(check_box_status_error_records) drop_down_status = request.POST.get("field",None) print(drop_down_status) global get_records_by_date if (check_box_status_new_records is None) and (check_box_status_error_records is None): get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) else: get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)).filter(new_records__gt=0,error_records__gt=0) print(get_records_by_date) home.html <form action="" method="post"> {% csrf_token %} <label for="from_date">From Date:</label> <input type="date" id="from_date" name="from_date"> <label for="to_date">To Date:</label> <input type="date" id="to_date" name="to_date"> <input type="submit">&nbsp <input type="checkbox" name="new_records" value="new_records" checked> <label for="new_records"> New Records</label> <input type="checkbox" name="error_records" value="error_records" checked> <label for="error_records"> Error Records</label><br><br> <label for="field">Choose your field:</label> <select name="field" id="field"> <option value="">--Please choose an option--</option> <option value="started">Started</option> <option value="completed">Completed</option> </select> </form> I need to filter both new_records and error_records greater than 0. But my filter function get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)).filter(new_records__gt=0,error_records__gt=0) is not working. Is there any solution to filter both check boxes -
How do I amend a form template in Django?
Im using a custom/extended ModelMultipleChoiceField and ModelChoiceIterator as per the answer to another question here https://stackoverflow.com/a/73660104/20600906 It works perfectly but Im trying to amend the template used to generate the groups to apply some custom styling - but after poking around everywhere I cant find anything to overwrite. I have gone through all the template files in '\venv\Lib\site-packages\django\forms\templates\django\forms' and cannot find anything relating to the behaviour Im seeing on screen. The 'groups' are wrapped in tags which is fine, but id like to find the file specifying this so I can overwrite with some bootstrap classes. I've traced back through the class inheritance and the first widget specifiying a template is this one: class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False Checking these files doesn't help as they don't appear to be the ones in use. Not sure where i'm going wrong? -
Displaying user orders in user's profile Django
I'm new in Python and hope that someone can help me. I realise that this is probably not a unique question, but please be sympathetic. I'm working on web-application (it's a bookstore). I make a cart and the proccess of forming an order. Now I'm trying to make a usr profile but unfortunately, I don't know how to display all user orders and make it possible to cahnge orders (change quantity of books for exmpl.) and how to make changable user profile information. I realised the following logic: User creates the cart and then create the order. After order creation cart also is in database. To summarise the above, main questions are: How to add all information from user cart (that was formed into the order) to user's profile? How to make user's data and order's/cart's data possible to change in the user's profile? How to display several user's orders in separate rows in HTML table (cause in my template all orders are in one row)? Cart models: User = get_user_model() class Cart(models.Model): customer = models.ForeignKey( User, null=True, blank=True, related_name="Customer", verbose_name="Customer", on_delete=models.PROTECT ) @property def total_price_cart(self): goods = self.goods.all() total_price_cart = 0 for good in goods: total_price_cart += good.total_price return …