Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update a Cache value without changing original timeout in Django
I am basically creating a cache key at a certain point with a timeout of a week. cache.set("myKey",myValue,timeout=604800) I'd like a way to update this cache value without changing the original timeout value. According to the documentation, if I pass None the value is cached forever, and if I dont pass anything it defaults to what I have in my settings. cache.set("myKey",myValue,timeout=?) So how could I do this? -
Trouble with service account's json stored in Google Secret Manager (Only when deployed)
I've got a problem that I just can't seem to work out. I am running a django project, deploying via GCP App Engine. I have taken all my sensitive key/token data from my settings file and placed them in my Google Secret Manager. That works fine, both locally and deployed. HOWEVER... When I try to do the same from my service account json, the project only runs locally. When I deploy, there is no error in deployment, but the site times out. The error log reads a bunch of: "Process terminated because the request deadline was exceeded. Please ensure that your HTTP server is listening for requests on 0.0.0.0 and on the port defined by the PORT environment variable. (Error code 123)" My app.yaml is configured as: runtime: python39 instance_class: F2 entrypoint: gunicorn -b :$PORT gondolaProject.wsgi:application automatic_scaling: target_cpu_utilization: 0.65 env_variables: DJANGO_SETTINGS_MODULE: "gondolaProject.settings" CLOUD_SQL_CONNECTION_NAME: "placeholder-401815:us-central1:to-be-announced" beta_settings: cloud_sql_instances: "placeholder-401815:us-central1:to-be-announced" Any ideas what might be causing this behavior??? Thanks in advance :) -
I am getting error 405 when running this Django program via drf
This code is for user registration through API, but when I try to test it with Postman, it gives error 405. Can you test the program and tell me where the problem is? I first created an account, then added it to my project settings and URL You can see the rest of the work below views: from rest_framework.response import Response from django.contrib.auth.models import User from .serializers import UserRegisterSerializer class UserRegister(APIView): def post(self, request): ser_data = UserRegisterSerializer(data=request.POST) if ser_data.is_valid(): User.objects.create_user( username=ser_data.validated_data['username'], email=ser_data.validated_data['email'], password=ser_data.validated_data['password'], ) return Response(ser_data.data) return Response(ser_data.errors) serializers: class UserRegisterSerializer(serializers.Serializer): username = serializers.CharField(required=True) email = serializers.EmailField(required=True) password = serializers.CharField(required=True, write_only=True) URLs: from . import views app_name = 'accounts' urlpatterns = [ path('register/', views.UserRegister.as_view()), ]``` and error: [1]: https://i.stack.imgur.com/ckM9c.png -
Django Custom Authentication Not Authenticating Custom User
So I am trying to build a website using Django where there are two separate user bases, one is user and the other is agent. Now I imported User from from django.contrib.auth.models import User and have a separate model for Agent. What I want is for there to be different login urls for users and agents. An agent can be an agent without having to be registered as a user. Now I have tried this code, and what this does is after trying to log in using agent credentials, it logs in and returns the correct html page but doesn't even authenticate if those credentials are right or wrong. Like the agent_login is still logging me in even after providing it with the wrong credentials. Now I want to know what the problem is and how to fix it so that it works properly. My models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phonenumber = models.IntegerField() def __str__(self): return f'{self.user.username} Profile' class Agent(models.Model): name = models.CharField(max_length=100) password = models.CharField(max_length=100) image = models.ImageField(upload_to = 'Images/') bio = models.TextField() instagram = models.URLField(max_length=100) twitter = models.URLField(max_length=100) facebook = models.URLField(max_length=100) linkedin = models.URLField(max_length=100) is_featured = models.BooleanField(default = … -
Django reverse Accessor Clash - Related Name not working
I am receiving an error for 'reverse accessor' clashes when trying to create a models for my Django app. Based on what I have seen, supposedly, assigning a unique 'related name' to the fields solve the issue. However, I have tried this and it still occurs. I have also tried using '%(app_label)s_%(class)s_related' as a related name as well, but this has not worked. I am struggling a bit to understand how this all works - is anyone able to help me out? Will provide code below, thanks class TradeOffersManager(models.Manager): def create_trade_offer(self, sender, reciever, sending_item, recieving_item): trade_offer = self.create(sending_item=sending_item, recieving_item=recieving_item) trade_offer.sender.set(sender) trade_offer.reciever.set(reciever) return trade_offer class TradeOffers(models.Model): sender = models.ManyToManyField(User) sending_item = models.ForeignKey(TradePost, on_delete=models.CASCADE, related_name="sending_item_name") reciever = models.ManyToManyField(User) recieving_item = models.ForeignKey(TradePost, on_delete=models.CASCADE, related_name="recieving_item_name") objects = TradeOffersManager() -
Cannot deploy Django app to App Runner: TypeError: 'staticmethod' object is not callable
I have a Django 5 application that I'm trying to deploy to AWS App Runner. I've followed the instructions on here and also here in order to make a deployment to App Runner using MySQL as the DBMS. I had to downgrade my Django version because App Runner only supports up to Django 4.2.8. I reinstalled every package into my venv in order to get an updated version of the requirements file. Locally, the app works just fine, but whenever I make a deploy to App Runner, I get this error: I've tried looking it up, but I cannot find a reference that helps. What could be going wrong? -
How to add optional filters in Django exta actions
I have a ViewSet with extra action shown below class Parent: queryset = Model.objects.all() serializer_class = ParentSerializer ... ... @action(detail=True, methods=["get", "post"], serializer_class=SomeSerializerclass) def extra(self, request, *args, **kwargs): ... I want to add few optional query parameters to this extra action endpoint like: parent/1/extra/?name=somename and this will filter the data for this name if request.method is GET. Also, this query param can be multiple like: parent/1/extra/?name=somename&?surname=foo How can I achieve this? -
I got an error of Internal server and integrity error how can i solve this
I got an error when i want to fetch value from html page to ajax, and i got null. view.py `def placeorder(request): if not 'userid' in request.session: return redirect('login') if request.method == 'POST': print("hii") neworder = Order() neworder.user_id = request.session['userid'] neworder.fname = request.POST.get('firstname') neworder.lname = request.POST.get('lastname') neworder.address = request.POST.get('address') neworder.city = request.POST.get('city') neworder.state = request.POST.get('state') neworder.country = request.POST.get('country') neworder.zipcode = request.POST.get('code') neworder.phone = request.POST.get('phone') print(neworder.fname) #PAYMENT MODE: # neworder.payment_mode = request.POST.get('payment_mode') neworder.payment_id = request.POST.get('payment_id') cart = Cart.objects.filter(user=request.session['userid']) cart_total_price = 0 for item in cart: cart_total_price = cart_total_price + item.product.Price * item.quantity neworder.totalprice = cart_total_price neworder.save() neworderitems = Cart.objects.filter(user=request.session['userid']) for item in neworderitems: OrderItem.objects.create( order=neworder, product=item.product, price=item.product.Price, quantity=item.quantity ) #Decrease the quantity from order stocks: # orderproduct = Products.objects. Cart.objects.filter(user=request.session['userid']).delete() messages.success(request, "Your order is placed!") return redirect("home")` js file: `$(document).ready(function(response){ $('.paywithrazorpay').click(function (e){ e.preventDefault(); var fname = $("[name='firstname']").val(); var lname = $("[name='lastname']").val(); var address = $("[name='address']").val(); var city = $("[name='city']").val(); var state = $("[name='state']").val(); var country = $("[name='country']").val(); var code = $("[name='code']").val(); var phone = $("[name='phone']").val(); var token = $("[name='csrfmiddlewaretoken']").val(); if(fname == "" || lname == "" || address == "" || city == "" || state == "" || country == "" || code == "" || phone == ""){ // … -
Adding a red star next to the label and deleting this message:This field is required
I want it to appear next to the red star label in the form. However, with these codes, an asterisk appears and the message I mentioned is deleted, but: 1- The symbol like the unordered list symbol is displayed on the top of the label. 2- Fields that are text and Boolean have problems . 3- Based on the field that is text, it is not recognized and I have to put a char field. 4- It comes both next to the label and next to the star field. 5- I want the username to be automatically taken from the user name and cannot be changed. However, if The sixth line of the class is deleted, a drop-down menu will appear and the user can choose a name, and if it is not deleted, the form will not be submitted. (In this context, I tried other codes and it didn't work. They are also commented). views.py: def create_product(request): form = ProductForm(request.POST, request.FILES) if request.method == 'POST': user = request.user if user.is_authenticated: if form.is_valid(): form.save() return redirect('index') else: form = ProductForm() return render(request, 'auctions/create_product.html', {'form': form}) html: {% block body %} <h2>Create New Product</h2> {% if user.is_authenticated %} <form id="cform" method="post" … -
Excluding YouTube links from urlize filter and handling iframe tags in Django template
I'm facing an issue in my Django template where I want to exclude YouTube links from the django urlize filter and ensure that the remaining content, including YouTube videos embedded with iframe tags, is properly displayed. Here's a simplified version of my template and view here's the template <div class="comment-body">{{comment.body|safe|linebreaksbr|urlize}}</div> here is the way i converted the youtube link to iframe: yt_link = re.compile(r'(https?://)?(www\.)?((youtu\.be/)|(youtube\.com/watch/?\?v=))([A-Za-z0-9-_]+)', re.I) yt_embed = '<iframe width="460" height="215" src="https://www.youtube.com/embed/{0}" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>' def convert_ytframe(text): return yt_link.sub(lambda match: yt_embed.format(match.groups()[5]), text) How can I modify my template to exclude YouTube links from the urlize filter How can I ensure that the remaining content, including YouTube videos, is properly displayed and the iframe tags are not affected by the urlize filter -
Having gunicorn binding to the web itself and to pgadmin
When intalling web pgdamin4 on a vps there are things to do besides pip installing. Namely you need to add another location sections in the nginx file location / { proxy_pass http://unix:/tmp/pgadmin4.sock; include proxy_params; } but then you need to bind gunicorn to this address. However, gunicorn is already binding to the web url like this and it works fine: ... ... SOCKFILE=/home/boards/run/gunicorn.sock exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=debug \ --log-file=- and my web is running on supervisor's support, so the question here is how to do that extra binding to that address. namely: gunicorn --bind unix:/tmp/pgadmin4.sock --workers=13 --threads=25 --chdir ~/environments/my_env/lib/python3.10/site-packages/pgadmin pgAdmin:app as nginx is giving me bad gateway 502 error and that is precisely for that, because it can't find the second bind address for the www.myweb.com/pgadmin, however I get no error when going to www.myweb.com -
I'm getting the error "Cannot unpack non-iterable object" in Django app
I've looked through a few topics with questions almost the same as mine but none of them really helped. The thing is that I'm writing a training Django app where I'm storing info about music albums that I like. Currently I'm adding a form via which I want to add albums to the database (instead of the standard form within "/admin/"). So, the models I have are quite simple: from django.db import models class Genre(models.Model): name = models.CharField(max_length=30) class Meta: verbose_name_plural = "genres" def __str__(self): return self.name class Album(models.Model): author = models.CharField(max_length=100) name = models.CharField(max_length=100) release_date = models.IntegerField() cover = models.ImageField(upload_to="media") genres = models.ManyToManyField("Genre", related_name="album") def __str__(self): return self.name As you can see, Album and Genre classes are related to each other via ManyToManyField. The form responsible for adding an album to the database looks like this: from django import forms from .models import Genre CHOICES = Genre.objects.all() class AddAlbumForm(forms.Form): author = forms.CharField(label="Album's author", max_length=100) name = forms.CharField(label="Album's name", max_length=100) release_date = forms.IntegerField(label="Album's release year") genres = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=CHOICES) cover = forms.FileField() All in all, the form is operational, except for the line with "genres" variable (if I comment it, the form works just fine). The related view looks like … -
Move django model field from nested models to the 'main' model
I have 2 django models linked like this: class ModelA(models.Model): id = models.UUIDField(primary_key=True) # some other fields here class ModelB(models.Model): modela_id = models.UUIDField(primary_key=True) unique_field = models.FloatField() order = models.IntegerField(primary_key=True) random_field = models.FloatField() and serializers for these 2 models: class ModelASerializer(serializers.Serializer): id = serializers.CharField(help_text="Measurement ID") # some other fields here b_objects = ModelBSerializer(many=True) classModelBSerializer(serializers.Serializer): id = serializers.CharField(source="order") random_field = serializers.FloatField() unique_field = serializers.FloatField() I want to write an endpoint that will return the list of ModelA entities and all the related ModelB objects to the particular ModelA object. I have this currently, it works just fine: ModelA.objects.prefetch_related("b_objects").all() which returns a list of objects like this one: { "id": "92eb8314-3f26-4bf6-8cc0-83d2935434d9", ### modelA fields here "b_objects": [ { "id": "1", "random_field": 1.0, "unique_field": 0.1 }, { "id": "2", "random_field": 5.0, "unique_field": 0.1 } ] } What I want here is to move "unique_field" from inner level to the level of modelA so that it would return: { "id": "92eb8314-3f26-4bf6-8cc0-83d2935434d9", "unique_field": 0.1 ### modelA fields here "b_objects": [ { "id": "1", "random_field": 1.0 }, { "id": "2", "random_field": 5.0 } ] } It's 100% that all values of unique_field will be equal in all the b_objects within particular modelA objects. I tried to add … -
getting service unavailable and internal server error and JSONDecodeError at /pay/ while integrating phonepe in my django project
enter code heregeettin this error while hitting on pay/ url this is my code please check it once def calculate_sha256_string(input_string): # Create a new SHA-256 hash object sha256 = SHA256.new() # Update hash with the encoded string sha256.update(input_string.encode('utf-8')) # Return the hexadecimal representation of the hash return sha256.hexdigest() def base64_encode(input_dict): # Convert the dictionary to a JSON string json_data = jsons.dumps(input_dict) # Encode the JSON string to bytes data_bytes = json_data.encode('utf-8') # Perform Base64 encoding and return the result as a string return base64.b64encode(data_bytes).decode('utf-8') def pay(request): MAINPAYLOAD = { "merchantId": "PGTESTPAYUAT", "merchantTransactionId": shortuuid.uuid(), "merchantUserId": "MUID123", "amount": 10000, "redirectUrl": "http://127.0.0.1:8000/return-to-me", "redirectMode": "POST", "callbackUrl": "http://127.0.0.1:8000/return-to-me", "mobileNumber": "9999999999", "paymentInstrument": { "type": "PAY_PAGE" } } # SETTING INDEX = "1" ENDPOINT = "/pg/v1/pay" SALTKEY = "099eb0cd-02cf-4e2a-8aca-3e6c6aff0399" base64String = base64_encode(MAINPAYLOAD) mainString = base64String + ENDPOINT + SALTKEY sha256Val = calculate_sha256_string(mainString) checkSum = sha256Val + '###' + INDEX print("Checksum:", checkSum) # Payload Send headers = { 'accept': 'application/json', 'Content-Type': 'application/json', 'X-VERIFY': checkSum } payload = { 'request': base64String } print("Sending request to PhonePe API:") print("URL:", 'https://api-preprod.phonepe.com/apis/pg-sandbox/pg/v1/pay') print("Headers:", headers) print("Payload:", payload) response = requests.post('https://api-preprod.phonepe.com/apis/pg-sandbox/pg/v1/pay', headers=headers, json=payload) print("Raw Response Content:") print(response.text) responseData = response.json() print("Response from PhonePe API:") print(responseData) # Print the raw response content redirect_url = responseData['data']['instrumentResponse']['redirectInfo']['url'] … -
Django: How to dynamically change urlpatterns based on the hostname
In Django it is possible to change the urlpatterns dynamically. For example the i18n module is doing this. https://docs.djangoproject.com/en/5.0/topics/i18n/translation/#translating-url-patterns I want something similar which is changing the pattern depending on the hostname for a view. for exmaple for www.example.com I want: path("articles/", views.articles), www.example.it path("articolo/", views.articles), www.example.de path("artikel/", views.articles), There should be a lookup table for each hostname and a default value if it is not defined. How could I do this? -
Forbidden (403) CSRF verification failed. Request aborted. Origin checking failed -during django admin panel login in google cloud server
I am encountering the following error on the Google Cloud production server when attempting to log in to the admin panel. However, it is functioning correctly on the local server. I have followed the official Google Cloud documentation and added the following code, but the error persists: Django version:4.0I have include this code in setting.py also I've made an attempt to address the issue persisting despite my efforts. -
TypeError: 'Meta.fields' must not contain non-model field names: excursion, user, stars
I am getting TypeError: 'Meta.fields' must not contain non-model field names: excursion, user, stars while doing request to swagger and I think all these because of filters, but I tried to remove it but I still getting the Error Traceback (most recent call last): File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/django/views/decorators/csrf.py", line 56, in wrapper_view return view_func(*args, **kwargs) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 104, in view return self.dispatch(request, *args, **kwargs) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 509, in dispatch response = self.handle_exception(exc) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 480, in raise_uncaught_exception raise exc File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/rest_framework/views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/views.py", line 96, in get schema = generator.get_schema(request, self.public) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/generators.py", line 276, in get_schema paths, prefix = self.get_paths(endpoints, components, request, public) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/generators.py", line 482, in get_paths operation = self.get_operation(view, path, prefix, method, components, request) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/generators.py", line 524, in get_operation operation = view_inspector.get_operation(operation_keys) File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/inspectors/view.py", line 33, in get_operation query = self.get_query_parameters() File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/inspectors/view.py", line 293, in get_query_parameters natural_parameters = self.get_filter_parameters() + self.get_pagination_parameters() File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/inspectors/base.py", line 409, in get_filter_parameters fields += self.probe_inspectors(self.filter_inspectors, 'get_filter_parameters', filter_backend()) or [] File "/Users/macbookpro/PycharmProjects/atlas8-backend/venv/lib/python3.9/site-packages/drf_yasg/inspectors/base.py", line … -
Limit max and min values in django field model
Let's say I have a model class Thing(models.Model): rating = models.FloatField() The rating is not defined by any user but rather calculated by a script, so it will change over and over as the time goes. And I also want it to never drop below 0 and go above 100 (so if it becomes less than 0 then it's 0 and if it goes above 100 then it's 100). Is it possible to set this limitation on model level or do I need to adjust every script that works with this model to take this into account? -
my dockerised django app doesn't run when adding nginx
I'm trying to dockerise my django app and trying to serve it using nginx. I'm not sure what's wrong but the nginx redirected to the correct URL but the django app doesn't load at all. for example if I open URL http://localhost:8000/cas/login/?service=http://localhost:8000/ which served by gunicorn, the app loaded properly. Yet when going to http://localhost:1337/ I would be redirected to https://localhost/cas/login/?service=http://localhost/ and would show unable to connect. I'm not sure what's wrong. Any pointer would be appreciated. docker-compose.yml version: "4.0" services: db: image: mariadb ports: - "3307:3306" environment: MYSQL_DATABASE: 'atshrd_db' MYSQL_ALLOW_EMPTY_PASSWORD: 'true' volumes: - ./data/mysql/dbb:/var/lib/mysql app: build: . volumes: - .:/django ports: - "8000:8000" expose: - "8000" image: app:django container_name: django_container #command: python manage.py runserver 0.0.0.0:8000 command: sh -c "gunicorn --chdir /django/project --reload project.wsgi:application --bind 0.0.0.0:8000" #command: gunicorn --bind 0.0.0.0:8000 --chdir /django/project --reload project.wsgi:application depends_on: - db nginx: build: ./nginx volumes: - ./project/hrd/static:/var/www/static - ./project/hrd/media:/var/www/media ports: - 1337:80 depends_on: - app Dockerfile FROM python:3.9 ENV PYTHONUNBUFFERED 1 WORKDIR /django RUN pip install --upgrade pip COPY requirements.txt requirements.txt COPY /project ./project RUN pip install cmake RUN pip install -r requirements.txt RUN pip install opencv-python-headless RUN pip install mediapipe tensorflow==2.11.0 tensorflow-io-gcs-filesystem==0.27.0 RUN pip install face-recognition RUN pip install django_datatables_view RUN pip install … -
Data is not adding to djnago table
I deleted sqlite file first then created superuser before this I'd 5 tables and now am able to add manually but through form Data is not reaching & getting stored to respective tables. Please anybody help me I tried, and still trying but unable to solve it myself -
JavaScript onclick event listener not triggering after the first click
I'm working on a web page where I have a button with an onclick event listener to switch between dynamically generated elements. The first click works as expected, but after the first click, the event listener doesn't seem to trigger anymore. Here's the relevant part of my JavaScript: document.addEventListener('DOMContentLoaded', function () { // ... (other initialization code) trdmDisplayed = 1; nextbtn = document.querySelector('.nextbtn'); nextbtn.addEventListener('click', function () { console.log(`trdm when the button is first clicked: ${trdmDisplayed}`); currentlyDisplayed = document.querySelector(`.indexdiv .shading-div:nth-child(${trdmDisplayed})`); currentlyDisplayed.style.display = "none"; trdmDisplayed = (trdmDisplayed % 20) + 1; toDisplay = document.querySelector(`.indexdiv .shading-div:nth-child(${trdmDisplayed})`); toDisplay.style.display = "block"; }); }); and here is my html: <div class="movies-container"> {%for movie in movies %} <div class="shading-div" id="trdm-{{movie.id}}"> /* other elements... */ <div> <button class="nextbtn" ><i class="fas fa-arrow-right"></i></button> </div> </div> {%endfor%} </div> Additional clarification: The dynamically generated elements consist of a fixed set of 20 elements. Upon clicking the button for the first time, the first element successfully transitions from element.style.display = "block"; to "none", and the second element transitions from "none" to "block" as intended and everything is logged onto the console. However, upon clicking the button for the second time, no information is logged to the console, suggesting that the event listener is … -
Updated Approach in Optimized page for Django and React SEO
I am learning React and building a website. But I came across the doubt if my approach is good for SEO and user experience. As of now I have my front-end completely built in React and it communicates to the backend through Django REST APIs. I am using JWTs to handle authentication and have built part of the admin panel. But the main pages the users will visit have also been partially built in React. And the more I read the more I am concerned this is not the correct way if I want this page to be visible or rank higher. The landing page has a search bar and after the selection is made users will be redirected to a page where the results will be shown more in detail. Here they can see a profile of the retailers related to the search selected previously, select them and then proceed to payment, sort of like an e-commerce site. Users do not need to be logged in for these pages but could be. The main concern is if having the entire application as a SPA is good or what should be my new setup? From what I read I see … -
how to form validation unique
Please tell me. I created a form in which you can select more than 1 artist for one order. Somehow it was made so that if the user mistakenly selected the same artist several times when saving, the duplication was removed. But how can you make sure that the user knows about this, that is, that it was something like “you selected the same artist several times”? class JrtnPerson(models.Model): rtn = models.ForeignKey(Drtn, verbose_name='Подразделение Ростехнадзора', on_delete=models.CASCADE) name = models.CharField(max_length=200, verbose_name='Имя и Отчество') surname = models.CharField(max_length=200, verbose_name='Фамилия') tel_mob = PhoneNumberField(verbose_name="Номер телефона мобильный", blank=True, null=True) tel_rab = PhoneNumberField(verbose_name="Номер телефона рабочий", blank=True, null=True) email = models.EmailField(max_length=100, verbose_name="Электронная почта", blank=True, null=True) # def str(self): # return '%s %s' % (self.surname, self.name) # def save(self, *args, **kwargs): # if not self.JrtnPerson.objects.filter(surname=self.surname, name=self.name).exists(): # super(self.surname, self.name).save(*args, **kwargs) class Meta: ordering = ('surname',) verbose_name = 'Сотрудник Ростехнадзора' verbose_name_plural = 'Сотрудники Ростехнадзора' unique_together = ('name', 'surname') def save(self, *args, **kwargs): self.full_clean() super(JrtnPerson, self).save(*args, **kwargs) def __str__(self): return '%s %s' % (self.surname, self.name) class JrtnCurator(models.Model): expertise = models.ForeignKey(Cexpertise, verbose_name='Экспертиза', on_delete=models.CASCADE) curator = models.ForeignKey(JrtnPerson, verbose_name='Сотрудник Ростехнадзора', on_delete=models.CASCADE) def __str__(self): return '%s' % self.curator class Meta: ordering = ('curator',) verbose_name = 'Куратор от Ростехнадзора' verbose_name_plural = 'Кураторы от Ростехнадзора' def save(self, *args, … -
How can I shorten Docker Compose + Django CLI commands?
I have a dockerized Django project built using cookie cutter Django. The only way to run the cli commands without the terminal throwing errors is to type this super long prefix docker-compose -f local.yml run django python manage.py + my command. As you can see that is ridiculously long and I don't want to have to type that or remember it every time I want to run a migration. So what can I do to shorten these commands to a simple python manage.py blahblahblah? Do I need to create an alias to shorten it, which I'd rather not have to because I want others to be able to clone the repo and add to the code without also having to type this long command. Any help is appreciated thanks!!! -
why do I get this error "TypeError at /user/Imnew Field 'id' expected a number but got [<User: Imnew>]."?
I keep getting this error and I don't know how to fix it I changed it a few times but it's still giving me TypeError at /user/Imnew Field 'id' expected a number but got [<User: Imnew>]. I searched for answers online as well but to no avail what should I do? if I need to post more code please let me know Thanks in advance views.py class PostListView(ListView): model = post template_name = 'website/welcome.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 4 class UserPostListView(ListView): model = post template_name = 'user_posts.html' context_object_name = 'posts' paginate_by = 4 def get_queryset(self): user = get_list_or_404(User, username=self.kwargs.get('username')) return post.objects.filter(author=user).order_by('-date_posted') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', PostListView.as_view(), name='home'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('posts/', include('posts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('signup', signup, name='signup'), path('profile/',profile, name='profile'), path('', index, name='index'), ] models.py from django.db import models from django.contrib.auth.models import User class post(models.Model): title = models.CharField(max_length=50) body = models.CharField(max_length=1000000) author = models.ForeignKey(User, on_delete=models.CASCADE, default=1) date_posted=models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.title}"