Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't open the Django admin by *.web.app domain in Django+React project in the Google Cloud Run service
First I will introduce my project structure: Frontend: React+ViteJS Backend: Django-ninja for the api stuff Admin Platform: Django original admin framework Custom Domain: Google Firebase host (integrate with google cloud run), for example: the website is https://mysite.web.app Right now I use the Google Cloud Run multicontainer service to deploy the whole project. For the frontend docker Dockerfile: FROM node:20-slim as build WORKDIR /app COPY package*.json ./ RUN npm install COPY . . RUN npm run build # Use Nginx as the production server FROM nginx:alpine COPY nginx.conf /etc/nginx/conf.d/default.conf # Copy the built React app to Nginx's web server directory COPY --from=build /app/dist /usr/share/nginx/html # Expose port 80 for the Nginx server EXPOSE 8000 # Start Nginx when the container runs CMD ["nginx", "-g", "daemon off;"] This is the nginx.conf: server { listen 8000; # listen [::]:80; # server_name localhost; location / { root /usr/share/nginx/html; index index.html index.htm; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } location /admin/ { proxy_pass http://localhost:8080; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; … -
How to enrich page navigator by adding field from first and last objects in Django paginator?
I am building a Django app form managing the digitalisation process of analog film rolls. I would like to add the film_roll.from_year field of the FilmRoll model to my page navigation widget in a Django template. This greatly facilitates navigating to the right page by looking at the year_from range below each page. My view is defined as follows: def index(request): film_roll_list = FilmRoll.objects.order_by( "from_year", "from_month", "title" ).annotate( scan_count=Count("myScanned_VS_NLP", distinct=True), ) paginator = Paginator(film_roll_list, 20) page_number = request.GET.get("page") try: page_obj = paginator.get_page(page_number) except PageNotAnInteger: # If the page parameter is not an integer, show the first page page_obj = paginator.get_page(1) except EmptyPage: # If the page is out of range, show the last page page_obj = paginator.page(paginator.num_pages) film_roll_count = paginator.count context = { "film_roll_list": film_roll_list, "page_obj": page_obj, "film_roll_count": film_roll_count, } return render(request, "filmrolls/index.html", context) Here's the page navigator code in the template: {# Page navigator: start #} {% if page_obj.has_other_pages %} <div class="row"> <div class="btn-group" role="group" aria-label="Item pagination"> {% if page_obj.has_previous %} <a href="?page={{ page_obj.previous_page_number }}" class="btn btn-outline-primary">&laquo;</a> {% endif %} {% for page_number in page_obj.paginator.page_range %} {% if page_obj.number == page_number %} <button class="btn btn-outline-primary active"> <span>{{ page_number }} <span class="sr-only"></span></span> # TODO - add 'year_from' range for the … -
Django session in tests
everyone! I can't figure out how the sessions work in Django. I have a shop, an anonymous user's shopping cart is bound to session_key. The session key is taken from the request object. def _check_session(self, request) -> int | str: session_key = getattr(request.session, ‘session_key’, None) if session_key: return session_key else: request.session.create() return request.session.session_key I'm writing tests, one test adds items to the basket, I take the anonymous user client and make a post request to add, everything is ok. Then in the second test, I take the same anonymous client, make a get request to get the contents of the basket. But in this request the request object has no session_key. Why in the second test, the request object does not contain a session_key? The client is the same. These two tests are written within one TestCase. -
Django constraints: unique together and accept one and only one value
I'm trying to implement a constraint for the following model: class Consumption(models.Model): simcard = models.ForeignKey(SimCard, on_delete=models.CASCADE) start_date = models.DateTimeField() duration_billed = models.FloatField(null=True) volume_billed = models.FloatField(null=True) sms_billed = models.FloatField(null=True) I would like to constraint the user to save one and only one value for duration_billed, volume_billed, sms_billed for a given simcard and start_date. I have the following Meta class: class Meta: constraints = [ UniqueConstraint( fields=['simcard', 'start_date', 'duration_billed'], name='unique_simcard_and_start_date_and_duration_billed' ), UniqueConstraint( fields=['simcard', 'start_date', 'volume_billed'], name='unique_simcard_and_start_date_and_volume_billed' ), UniqueConstraint( fields=['simcard', 'start_date', 'sms_billed'], name='unique_simcard_and_start_date_and_sms_billed' ), ] The problem I face with my constraints in that the DB accept several duration_billed, volume_billed, sms_billed for a given simcard and start_date. The result I try to achieve is if a duration_billed exists for a given simcard and start_date, the user should not be able to import a new duration_billed (even if the value is different from the one stored in DB) for the same simcard and start_date. Same goal for volume_billed and sms_billed. I hope my issue is clear. Any help or advice would be much appreciated 🙏 Many thanks in advance -
“OperationalError: Could not translate host name “db” to address in Dockerized Django App with Datadog”
I have a very complex django project that uses postgresql as database, where I have setup datadog to send traces and events. It works fine locally and I am receiving traces and events in datadog. However, if I try to run my app using docker, it won't send traces and events to datadog. Following is my docker-compose.yml file where datadog integration is borrowed from here. docker-compose.yml services: db: image: ankane/pgvector env_file: - ./docker/env.db volumes: - pgvector_db_data:/var/lib/postgresql/data app: build: context: . dockerfile: ./docker/prod.Dockerfile env_file: - ./docker/env.db - ./.env container_name: scooprank volumes: - static_volume:/opt/code/static - shm:/dev/shm - save_drivers:/opt/code/save_drivers - save_models:/opt/code/save_models command: ./docker/scripts/run-gunicorn depends_on: - db network_mode: host ddagent: image: datadog/docker-dd-agent environment: - DD_BIND_HOST=0.0.0.0 - DD_API_KEY=${DATADOG_API_KEY} - DD_APM_RECEIVER_SOCKET=/tmp/ddagent/trace.sock - DD_DOGSTATSD_NON_LOCAL_TRAFFIC=true ports: - "8127:8126" news_scraper: image: scooprank-app env_file: - ./.env container_name: news_scraper command: python manage.py news_scraper depends_on: - app restart: always volumes: static_volume: shm: save_drivers: save_models: pgvector_db_data: I added network_mode: host as suggested by this answer. I then tried this solution on a simple dummy project having sqlite3 as database and with this docker-compose file, I am receiving traces and events. But if I try to use it in my main project, I can do docker compose build and docker compose up, but when … -
Show dd/mm/yy in django
I have a input type Date field like below. # forms.py widgets = { 'date_of_birth': forms.DateInput(attrs={'type': 'date'}) } I am using below code in HTML Template. <label class="form-label">Date of Birth</label> {{ form.date_of_birth }} I am getting mm/dd/yy format but I would like to get dd/mm/yy format. -
Using Google Cloud SDK in Django Developement and UWSGI
I am trying to access Google Cloud Service in my backend process (views.py). I have successfully run this in developement server. Here is my views.py script : from google.cloud import bigquery @login_required def update_iphone(request): user_profile = UserProfile.objects.get(user=request.user) client = bigquery.Client() if request.method == 'POST': form = IphoneUpdateForm(request.POST) if form.is_valid(): sql = f""" query script """ client.query(sql) else: pass sql = f""" query script """ corporate_list = client.query(sql).to_dataframe() iphone_form = IphoneUpdateForm() return render(request, 'myapp/home.html', {'user_name':user_profile.first_name, 'corporate_list': corporate_list['corporate_name'].to_list(), 'form': iphone_form}) This views.py script runs well in development server. But if try to run it with UWSGI, I am getting error related to the google cloud as following : google.auth.exceptions.DefaultCredentialsError: Your default credentials were not found. To set up Application Default Credentials, see https://cloud.google.com/docs/authentication/external/set-up-adc for more information. My question is why am I getting this error if using UWSGI and not the development server ? how do I deal with this error ? Thank You -
Many one-to-one relationships pointing to the same model Django
I'm designing an application in Django where I have an Item model with numerous attributes for each item. I'm experiencing very poor performance in my application and I'm wondering if there are flaws in my setup that could be causing this issue. I am relatively new to Django, so any pointers would be greatly appreciated. Currently, I have around 200 attribute models, each with optional one-to-one fields linked to an item via a foreign key as follows: Attribute models: class AttrBase(models.Model): prev_value = models.CharField(max_length=250, null=True, blank=True) edited_by = models.ForeignKey( Account, on_delete=models.CASCADE, null=True, blank=True ) edited_on = models.DateTimeField(null=True, blank=True) options = None class Meta: abstract = True class ID(AttrBase): item = models.OneToOneField(Item, on_delete=models.CASCADE) value = models.CharField(max_length=250, null=True, blank=True) name = "ID" tooltip = "..." group = "..." class Height(AttrBase): item = models.OneToOneField(Item, on_delete=models.CASCADE) value = models.IntegerField(null=True, blank=True) name = "Height" tooltip = "..." group = "..." ...more I am also using a generic relationship to link to all of the groups, as follows: class AttributeGroup(models.Model): content_type = models.ForeignKey( ContentType, on_delete=models.CASCADE, limit_choices_to={"app_label": "attributes"}, ) name = models.CharField(max_length=250, null=True, blank=True) description = models.CharField( max_length=1000, default="TODO", null=True, blank=True ) def __str__(self): return str(self.content_type) def save(self, *args, **kwargs): self.name = self.content_type.name super(AttributeGroup, self).save(*args, **kwargs) This … -
Django CSRF cookie not set with 403 error for webhook URL
I am encountering an issue with Django's CSRF protection while trying to handle Stripe webhooks on my local host. I am receiving a 403 Forbidden error with the message "CSRF cookie not set." The error occurs when trying to access the /collect-stripe-webhook/ URL, which is intended to handle incoming webhook requests from Stripe.Also the payments go through and payment is successfull urls.py urlpatterns = [ path('subscribe/', product_list, name='product_list'), path('create-checkout-session/<int:product_id>/', create_checkout_session, name='create_checkout_session'), path('collect-stripe-webhook/', stripe_webhook, name='stripe_webhook'), # Updated path path('success/', TemplateView.as_view(template_name="subscriptions/success.html"), name='success'), path('cancel/', TemplateView.as_view(template_name="subscriptions/cancel.html"), name='cancel'), ] views.py: @csrf_exempt def stripe_webhook(request): """ View to handle Stripe webhooks. """ payload = request.body sig_header = request.META.get('HTTP_STRIPE_SIGNATURE', None) endpoint_secret = settings.STRIPE_WEBHOOK_SECRET if not sig_header: logger.error("No signature header found in the request") return JsonResponse({'status': 'invalid request'}, status=400) try: event = stripe.Webhook.construct_event( payload, sig_header, endpoint_secret ) except ValueError as e: logger.error(f"Invalid payload: {e}") return JsonResponse({'status': 'invalid payload'}, status=400) except stripe.error.SignatureVerificationError as e: logger.error(f"Invalid signature: {e}") return JsonResponse({'status': 'invalid signature'}, status=400) if event['type'] == 'checkout.session.completed': session = event['data']['object'] handle_checkout_session(session) return HttpResponse(status=200) template: <form action="{% url 'subscriptions:create_checkout_session' product.id %}" method="POST"> {% csrf_token %} <button type="submit">Subscribe</button> </form> Error Message: Forbidden (CSRF cookie not set.): /collect-stripe-webhook/ Question: What could be causing this issue with Django's CSRF protection, and how can I resolve … -
How are connections handled by SQLAlchemy internally
Context Hello, I mostly use Django for my main backend monolith. In Django, you do not need to handle db connections on your own, this is abstracted (because Django uses the Active Record pattern instead of the Data mapper pattern used by Sqlalchemy). I have been doing some reading and I feel like I know the basics of the different constructs of Sqlalchemy (like engine, connection, and session). Nonetheless, we have started to scale our FastAPI + Sqlalchemy apps, but I have found this error appearing: sqlalchemy.exc.TimeoutError - anyio/streams/memory.py:92 - QueuePool limit of size 8 overflow 4 reached, connection timed out, timeout 10.00 I would like to understand why that is happening. Current setup Right now we have instances of the web server running, using the following command: python -m uvicorn somemodule.api.fast_api.main:app --host 0.0.0.0 As you can see, I'm not setting the workers flag, so uvicorn is only using 1 worker. On the SQLAlchemy engine, we are using the following options: SQLALCHEMY_ENGINE_OPTIONS = { "pool_pre_ping": True, "pool_size": 16, "max_overflow": 4, "pool_timeout": 10, "pool_recycle": 300, } engine = create_engine(get_db_url(), **SQLALCHEMY_ENGINE_OPTIONS) Questions Q1: does this apply to every worker of uvicorn? My guess is that if I spin two workers in uvicorn, … -
Using Django and reportlab to create a pdf. Report is failing when I try to include a field that is tied to a foreign key
My attempt at making a pdf fails with a server500 error when I attempt to export a field that is created by a foreign key. I believe this to somehow be the problem, as all other fields work as expected. This same field can be similarly exported as a csv. in views.py: def report_pdf(request): # Create a Bytestream buffer buf = io.BytesIO() # Create a canvas c = canvas.Canvas(buf, pagesize=letter, bottomup=0) # Create a text object textob = c.beginText() textob.setTextOrigin(inch, inch) textob.setFont("Helvetica", 14) # Designate the model customers = Customer.objects.all() lines =[] for customer in customers: lines.append(customer.address) lines.append(customer.address2) lines.append(customer.city) lines.append(customer.province3) # Loop for line in lines: textob.textLine(line) # Finsih up c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf, as_attachment=True, filename='customer_list.pdf') and in models.py class Customer(models.Model): address = models.CharField(max_length=100, null=True, blank=True) address2 = models.CharField(max_length=100, null=True, blank=True) city = models.CharField(max_length=50, null=True, blank=True) province3 = models.ForeignKey(Province, null=True, blank=True, on_delete=models.PROTECT) and the foreign model: class Province(models.Model): province = models.CharField(max_length=2) def __str__(self): return(f"{self.province}") I've tried disabling the province3 field, at which point it works. Am I correct that it has to do with the fact that it uses a foreign key? If so, what may be the problem? I have checked the site logs and the apache … -
why my django resgistration view not able to add new users?
I have below DRF APIView, I am building a basic user registration with OTP class RegisterView(APIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): return render(request, 'registration.html') def post(self, request, *args, **kwargs): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): user = serializer.save() # Send verification email with OTP otp = generate_otp() user.otp = otp user.otp_expiry = datetime.now() + timedelta(minutes=5) user.save() send_verification_email(user.email, otp) return Response( { 'message': 'Account created successfully. Please verify your email.', "status": status.HTTP_201_CREATED, } ) return Response( { 'message': serializer.errors, "status": status.HTTP_400_BAD_REQUEST, } ) The above function is calling below two functions def generate_otp(): return str(random.randint(100000, 999999)) def send_verification_email(email, otp): subject = "Verify Your Email Address" template_name = "email_verification.html" context = {"otp": otp} html_content = render_to_string(template_name, context) text_content = strip_tags(html_content) msg = EmailMessage(subject, text_content, to=[email]) msg.content_subtype = "html" msg.send() The register.html as below <form id="register-form"> {% csrf_token %} <div class="form-group"> <label for="email">Email Address:</label> <input type="email" class="form-control" id="email" name="email" required> </div> <div class="form-group"> <label for="password">Password:</label> <input type="password" class="form-control" id="password" name="password" required> </div> <button type="submit">Register</button> </form> <script> document.getElementById('register-form').addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(event.target); const jsonData = {}; for (const [key, value] of formData.entries()) { jsonData[key] = value; } fetch('{% url "register" %}', { method: 'POST', headers: { 'Content-Type': 'application/json' … -
how to resolve the following issue while downloading cs_oracle library for django project
enter image description here I want to connect oracle db to my django project. I tried to install 'cx_oracle' library but it is throwing the attached error. How can I resolve this issue? Is there any other way of connecting oracle db to django project? -
django-simple-captcha Not Displaying Image in Production
I'm encountering a problem with Django-Simple-Captcha in my Django project's production mode (server). The CAPTCHA image is not displaying, while it works correctly in development (local environment). django==3.2.9 django-simple-captcha==0.5.17 -
What is the correct way to query a many to many relationship in Django efficiently?
I probably haven't phrased this question correctly so apologies. Also probably why I cannot find much information when I google it. Anyway I have a Django project that I am using to create an API using Django Rest Framework. For this problem I have 2 models that are relevant. A Product model and an Offer model (slightly pseudocode so ignore any missing fields). class Offer(models.Model): image = models.ImageField(upload_to=upload_to, validators=(validate_image_file_extension,)) discount = models.IntegerField(validators=(MinValueValidator(0), MaxValueValidator(100))) start_date = models.DateField() expiration_date = models.DateField() products = models.ManyToManyField(Product, related_name='offers') customers = models.ManyToManyField(Customer) So as you can see in this model. There's a many to many link to the Product model. Inside the product model is just some standard stuff: class Product(models.Model): name = models.CharField(max_length=256) price = models.FloatField() stock = models.IntegerField() product_photo = models.ImageField(null=True, upload_to=product_photo_path, validators=[validate_image_file_extension]) Okay so now for the actual question. I am trying to add a new feature where it gets the discounted price for a product. If there is multiple offers, it needs to return the highest discount price. It also needs to take into account the customer who sends the request because the offers are not relevant for every customer. This needs to be done on the list endpoint from the API … -
How can I disable Chrome pop-ups like this while running automated Selenium tests in Python?
I am currently writing an automated testing suite for a large Django project for my corporation. Everything was going well until I updated Chrome (v.125.0.6422.142) and the Chromedriver (v.125.0.6422.141). When I ran the tests with the head, I saw that there was a Chrome Tip that popped up from the vertical ellipsis that opens the Chrome menu: Stupid message messing up my tests I checked with a custom GPT (using GPT-4) to see if this was causing potential issues, and had it confirmed (for what it's worth) that this popup indeed would be causing interference in my tests. However, I am unsure of how to get rid of it. I went through Stack OverFlow, GPT, and Github Copilot, and I implemented the following arguments to my setup: def setUpClass(cls): super().setUpClass() if os.environ.get('ENVIRONMENT') == 'LOCAL': # Retrieve the path from an environment variable chromedriver_path = os.environ.get('CHROMEDRIVER_PATH') if not chromedriver_path: raise ValueError("The CHROMEDRIVER_PATH environment variable must be set.") chrome_service = Service(executable_path=chromedriver_path) # Option to run in headless mode if os.environ.get('HEADLESS') == 'True': print("Running in headless mode.") chrome_options = Options() chrome_options.add_argument('--headless') chrome_options.add_argument('--enable-logging') cls.selenium = webdriver.Chrome(service=chrome_service, options=chrome_options) else: chrome_options = Options() chrome_options.add_argument('--disable-first-run-ui') chrome_options.add_argument('--no-first-run') chrome_options.add_argument('--disable-extensions') chrome_options.add_argument('--enable-logging') chrome_options.add_argument('--disable-popup-blocking') chrome_options.add_argument('--disable-notifications') chrome_options.add_argument('--disable-infobars') chrome_options.add_argument('--disable-blink-features=AutomationControlled') cls.selenium = webdriver.Chrome(service=chrome_service, options=chrome_options) cls.selenium.maximize_window() … -
django user login gives error always as the admin with this phone number already exist
I have a custom user model with username field phone_number inherited from AbstractBaseUser and PermissionMixin.I have multiple collge and each college has separate custom admin panel.I have created a admin for each college and i have create a login template to login each college admin. view.py def login_view(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): phone_number = form.cleaned_data['phone_number'] password = form.cleaned_data['password'] user = authenticate(request, username=phone_number, password=password) print(f"phone_number: {phone_number}") print(f"password: {password}") print(f"User: {user}") if user is not None: auth_login(request, user) messages.success(request, "Login successful") return redirect('dashboard') else: messages.error(request, "Login failed. Enter valid credentials and try again.") else: messages.error(request, "Form is invalid. Please check the entered data.") else: form = LoginForm() return render(request, 'accounts/login.html', {'form': form}) models.py class Custom_user(AbstractBaseUser,PermissionsMixin): phone_number=models.CharField(max_length=13,validators=[phone_validator],unique=True) USERNAME_FIELD='phone_number' REQUIRED_FIELDS=[] is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) objects = Custom_user_manager() def __str__(self) -> str: return self.phone_number class Meta: verbose_name = 'Admin' verbose_name_plural = 'Admins' form.py class LoginForm(forms.ModelForm): class Meta: model = Custom_user fields = ['phone_number', 'password'] widgets={ 'password':forms.PasswordInput(), } def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['phone_number'].widget.attrs.update({'class': 'form-control'}) self.fields['password'].widget.attrs.update({'class': 'form-control'}) Whenever i click the login button it gives the error as The admin with phone number already exist -
change selinux policy to allow gunicorn access
How do I create a selinux policy to allow gunicorn to operate with nginx for a django managed web site? I know there's a way to do it, but don't understand selinux' arcane policy definitions --YES, I have read the documents. If I disable selinux with "setenforce 0", then "systemctl start gunicorn" loads gunicorn. If selinux is set to enforcing (setenforce 1), the systemctl command fails. This is definitely a policy issue. So, can anyone describe how to set the policy to allow gunicorn to load? Thanks, Joe White -
Why 'coverage' considers all of my class-based-views as tested?
I'm just learning django testing. When I use 'Coverage' module to check which parts of my code is tested, it considers almost all of class-based-views as tested while I have commented out all of my tests. I investigated this problem and found that in urls.py I have this line: from . import views It seems importing views.py file or just a class from views.py make all classes in views.py run once e.g. the print line in this code will be executed: class AuthorDelete(PermissionRequiredMixin, DeleteView): model = Author success_url = reverse_lazy('authors') permission_required = 'catalog.delete_author' print("----- AuthorDelete -------") And 'Coverage' will mark them as tested. But obviously this class is not tested at all. How can I get real and exact test coverage report? Should I use other tools rather than 'Coverage'? Thanks in advance -
Django blog website rejected in AdSense approval
I applied my www.admoha.com website for adsense but it rejected with policy error so please check my site : www.admoha.com and give me suggestions to fix it. I want to approved my website: www.admoha.com in Google adsense. -
Tips for Django Optimization
i'm looking for tips on things to check next in order to increase the efficiency of my django in production. The loading times vary wildly; sometimes the page are loaded in 200ms, sometimes they require multiple seconds. I've worked extensively on SQL and cache; see the attached image, they take a combined 25ms. Yet the page required almost 10 seconds to load. As techical information, I'm using postgresql (CONN_AGE set to 6), nginx (12 workers on 6 processors), and django-redis-cache. What can I look for next? I've tried to work extensively on SQL and cache, in order to see a consistent reduction on loading times, yet in some occasions the page require multiple seconds to load. -
Java Script for insert html does not work
I load posts when scrolling the page, and for some reason the script for opening a photo of a post or liking a post does not work, I thought for a long time why this was, but I still don’t understand. views.py For the start page (posts that are loaded immediately, and not by scrolling the page), everything is ok. posts.html And if it helps, here's a piece of the script that doesn't work (all of it doesn't work): posts_script.js I checked a lot of things, it seems like all the classes are needed, the data of tags are also normal, that is, everything is there for the script to work, but for some reason it doesn’t want to work, I would be very grateful if you help me. -
How to create a generic relationship without adding dependency between apps in Django?
I have an ecommerce store app that have those apps: core: specific for the ecommerce store app needs. likes: independent reusable app that is supposed to be used with different models from other apps. store: independent reusable app that has the models and views for the ecommerce app. Now I want to add the ability for the user to like a product, so I want to add a like (from likes) to the product (from store), how can I do it without adding explicit dependency (import likes in store) between the two apps? The LikedItem model from likes app: from django.conf import settings from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey class LikedItem(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() The Product model from the store app: class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=6, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey( Collection, on_delete=models.PROTECT, related_name='products') promotions = models.ManyToManyField(Promotion, blank=True) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] I tried implementing this in the core app, I started with creating a CustomProduct model that extends … -
Unexpected Loss of User Authenticated State Between Two Seperate Django Views
I'm having an issue with user authentication using the social-auth-app-django library in my Django project. After the user is successfully authenticated via a social provider (in this case, Google), the user doesn't seem to be authenticated when redirected to the dashboard view. Code # Decorator to check if the user is authenticated and verified def verified_user_required(view_func): print('\nDecorator: verified_user_required') @wraps(view_func) def wrapper(request, *args, kwargs): print('Verified user required') if not request.user.is_authenticated: print('User not authenticated') return redirect('login') nwd_user = get_nwd_user(request.user) if not nwd_user or not nwd_user.is_verified(): print('User not verified') return redirect('verify-email') print('User verified') return view_func(request, *args, kwargs) return wrapper # View function to handle social auth callback @psa('social:complete') def auth_callback(request, backend): print("\nView Auth Callback") # Retrieve the backend and user ID from the session backend_name = request.session.get('auth_backend') user_id = request.session.get('authenticated_user_id') print("Backend from session:", backend_name) print("User ID from session:", user_id) # Ensure the backend is correctly set if not backend_name or not user_id: return redirect('login') # Get the user object try: user = User.objects.get(id=user_id) except User.DoesNotExist: return redirect('login') # Log in the user login(request, user, backend=backend_name) # Debugging: Print the backend and user information print("Backend:", backend) print("Request Backend:", request.backend) print("User:", request.user) # Check if the user is authenticated if request.user.is_authenticated: # Perform any additional … -
Django update_or_create efficiency
Is using Model.objects.update_or_create(field1=x, field2=y, defaults=defaults) slower as compared to doing this: qs = Model.objects.filter(field1=x, field2=y) if qs: qs.update(defaults=defautls) else: defaults.update({'field1': x, 'field2': y}) Model.objects.create(**params)