Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: How to make one-to-one relation with auth login and custom profile model?
I've implemented google login to my project, logs in correctly and makes a new row in the database for the user, but does not make a profile. I have one-to-one relation between the user and the profile, how can i add profile for the google logins? I'm getting error UserProfile matching query does not exist. when i try to view my profile on the page. This is the view for the profile page: class ProfileView(views.View): template_name = 'profile/profile.html' def get(self, request, pk): user = UserModel.objects.filter(pk=pk).get() profile = UserProfile.objects.filter(user_id=user.pk).get() context = { 'profile': profile } return render(request, self.template_name, context) the url: path('profile/<int:pk>/', views.ProfileView.as_view(), name='profile-page'), and the template: <li class='text-black text-xl mx-2 py-1.5 rounded-full bg-slate-300 shadow-2xl hover:bg-slate-400'> <a class="px-3 py-1.5" href="{% url 'profile-page' pk=request.user.pk %}"> <i class="fa-solid fa-user"> </i> </a> </li> I can get the error not to show but when i try to edit the profile it cannot do it since it has no relation with the profile model. -
Is it possible to get max id in filtered and limited queryset without fetching?
Suppose I have a table in db with rows like this: ID Foo 19 1 20 1 38 2 44 1 50 2 61 1 I want to get max id (50 in this example) from queryset like this: MyModel.objects.filter(foo=2).values_list('id')[:limit] limit, of course, can be greater than total row number. I can do this by fetching all queryset, convert it to list and use the last item list(MyModel.objects.filter(foo=2).values_list('id')[:limit])[-1] but can I do this in database, without fetching entire queryset? Raw sql solution is welcome too. DB is PostgreSQL. -
Selenium Code works on local machine but breaks when used in celery on heroku
I am developing a site in django where I have a task that uses selenium that takes place using celery, this task runs perfectly fine on my machine, but once hosted to heroku, It still runs but acts differently. -
Form not showing in html for selection
forms.py SHIPPING_CHOICES = ( ('S', 'standard'), ('E', 'express'), ) class Shipping(forms.Form): shipping_option = forms.ChoiceField(widget=forms.RadioSelect, choices=SHIPPING_CHOICES) cost = forms.CharField(required=False) views.py class OrderSummaryView(LoginRequiredMixin, View): def get(self, *args, **kwargs): try: order = Order.objects.get(user=self.request.user, ordered=False) form = Shipping() context = { 'object' : order, 'couponform': CouponForm(), 'DISPLAY_COUPON_FORM': True, } return render(self.request, 'cart.html', context) except ObjectDoesNotExist: messages.info(self.request, "You do not have an active order") return redirect('estores:home') def post(self, *args, **kwargs): form = Shipping(self.request.POST or None) order = Order.objects.get(user=self.request.user, ordered=False) if form.is_valid: shipping_option = form.cleaned_data.get('shipping_option') shipping_cost = form.cleaned_data.get('shipping_cost') if shipping_option == 'S': shipping_cost = 500 elif shipping_option == 'E': shipping_cost = 700 else: shipping_cost = 500 order.ordered = False order.options = shipping_option order.get_total_coupon =+ shipping_cost order.save() html {% for value, name in form.shipping_option.choices %} <div class="card"> <div class="card-header" id="heading-4"> <div class="card-title"> <input id="{{ name }}" type="radio" name="shipping_option" value="{{ value }}" class="button" required> <label for="{{ name }}">{{ name }}</label> </div> </div> </div> i dont know why but i have been trying to it work but it wont work at all. i want to be able to loop the choices available for shipping options. but i was able to do something like that for payment option and it worked. i dont know why but i have been trying … -
WSGI Server for Django + Python-Socketio
I have a Django server, that also has a socketio compenent using python-socketio library. I'm trying to produce a relatively simple but production ready deployment for it on an Amazon EC2 Instance. I've successfully configured the NGINX proxy. I'm curious about the best way to deploy, specifically with regard to WSGI. I've tried using the raw eventlet WSGI server (eventlet.wsgi.server(eventlet.listen(("", 8000)), application)). I then start it with python manage.py runserver. This has worked okay, but I'm unsure about how scalable it is. It seems like the standard stack is Django + Gunicorn + NGINX. Based on python-socketio documentation, this should be possible. I tried django + eventlet + gunicorn, but it seems like gunicorn a) doesn't play nice with eventlet and b) only supports one worker. Gevent + Gunicorn doesn't have this bug, but still only supports one worker. Also, I'm not sure how actively maintained gevent is. So I'm not sure how scalable either Gunicorn + eventlet or Gunicorn + geventlet is as a WSGI server. So I'm not sure if Gunicorn is my best bet, or if it's too limited. So TL;DR a) what scalable stack have you experienced success with for deploying Django + python-socketio and b) … -
Django Model with several OneToOne relationships of same model: implementation strategy
i am looking for a solution to the following problem: i defined the following class: class Parameter(models.Model): name = models.CharField(max_length=40) value = models.FloatField() unit = models.CharField(max_length=20) it describes a parameter for a measurement. now, i have various specific measurement classes and in these classes i want to define a couple of specific parameters as well as custom parameters class SpecificMeasurement1(models.Model): ... some fields here.... specific_parameter_1 = models.OneToOneField( Parameter, on_delete=models.CASCADE, related_name='specific_measurement_1_param_1') specific_parameter_2 = models.OneToOneField( Parameter, on_delete=models.CASCADE, related_name='specific_measurement_1_param_2') now i have several questions: does it make sense to implement the specific parameters like that? in the example above i define the One-To-One relationship in the parent class, which generally is not the best practice? however, i dont have another idea. For the specific parameters, is it possible to fix the name-field in the Parameter-object? e.g. to 'specific_parameter_1' for the specific_parameter_1. how / where would i define any custom-parameters? imagine a user wanted to add some additional parameters to their measurements with custom names. would i include a Generic Relationship in the Parameter class? in that case it can be included in any SpecificMeasurementX class? thanks for your opinions. Kind regards -
Django RestFramework Redirect failing
I am trying to build a csv file using POST and redirecting to GET to download that file. I tried returning a FileResponse/HttpResponse in the post function but the file doesnt download. But when I do a GET, it downloads the file and doesn't allow to take an input. So my solution is this: Do a POST to create the file, redirect to GET and that should download the file. import os import pandas as pd import numpy as np import tensorflow as tf from .apps import ApiConfig from django.shortcuts import render from rest_framework.response import Response from rest_framework.views import APIView # from rest_framework.decorators import api_view from django.http import HttpResponse from django.urls import reverse from django.http import HttpResponsePermanentRedirect from django.shortcuts import redirect # from io import BytesIO as IO # # Create your views here. class PerfPrediction(APIView): def post(self, request): request.session['_old_post'] = request.POST # if request.method == 'POST': data = request.data alt = data['alt'] mach = data['mach'] zxn = data['zxn'] os.environ["CUDA_VISIBLE_DEVICES"] = "-1" model = ApiConfig.model inputs = np.array([[alt, mach, zxn]]).astype(np.float64) cols = ["Thrust (kN)", "TSFC (g/kN.s)", "EGT (K)", "T2 (K)", "T3 (K)", "P2 (kPa)", "P3 (kPa)", "Wf (kg/s)", "St8Tt (K)"] out = pd.DataFrame(model.predict(inputs)).to_csv('out.csv') print("a") return redirect(reverse("save_file"), permanent=True) class Download(APIView): def … -
como configurar mi proyecto en django para crear una pagina de error 404 y otra 500 [closed]
He probado de muchas formas pero no me acaba de funcionar para que me aparezca la página con la template de error 404 y la otra de 500 personalizadas. Por favor ponerme un código que funcione, muchas gracias He probado mucho códigos de personas que han publicado respuestas pero ninguna funciona, puede que ya no se utilicen o no se el porque pero no me funciona. Muchas gracias por todo -
How to display automatically value instead of key in django rest framework for a model attributs which a choice fields?
I have a DRF api with model attributs with choice field like this: STRONG_FOOT = ( ("N", "-"), ("R", "Right"), ("L", "Left"), ("B", "Both") ) class Player(models.Model): ... strong_foot = models.CharField(max_length=2, choices=STRING_FOOT) ... I can chose to display the value instead of the key of the choices like this in my serializers: class JoueurSerializer(serializers.ModelSerializer): ... strong_foot = serializers.CharField(source="get_strong_foot_display") ... class Meta: model = Player fields = "__all__" The issue I have is that I have more than 30 attributs in my models. Is there a way to ask DRF to show automatically the value instead of the key of the choice field in the list view ? Or do I need to do what I did in the serializers for all of my attributs ? -
How should I connect Signals to my Model correctly In Django app?
I tried to connect Signals 'post_save' method to this Order model in my Django app: from django.conf import settings from django.db import models from CFTrade.models import Item class Order(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='order_user') full_name = models.CharField(max_length=50) address1 = models.CharField(max_length=250) address2 = models.CharField(max_length=250) city = models.CharField(max_length=100) phone = models.CharField(max_length=100) post_code = models.CharField(max_length=20) created = models.DateTimeField(auto_now_add=True) edited = models.DateTimeField(auto_now=True) total_paid = models.DecimalField(max_digits=7, decimal_places=2) order_key = models.CharField(max_length=200) billing_status = models.BooleanField(default=False) class Meta: ordering = ('-created',) def __str__(self): return str(self.created) And also Imported the signal receiver module: In my app's apps.py file, from django.apps import AppConfig class OrdersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'orders' def ready(self): import orders.signals In my Model handler I don't receive what I need from model, including billing_status and created ` from django.db.models.signals import post_save from django.dispatch import receiver from orders.models import Order @receiver(post_save, sender=Order) def inventory_handler(sender, instance, created, *args, **kwargs): print('First step') print(args, kwargs)` Here is what I get: First step () {'signal': <django.db.models.signals.ModelSignal object at 0x0000026212438590>, 'update_fields': None, 'raw': False, 'using': 'default'} How should I fix this? -
Can someone help my with this autocomplete django trouble?
I'm having trouble using the django-autocomplete-light package, I followed the tutorial to start an autocomplete field, but although the code is identical mine doesn't seem to work, every time I try I get an ordinary select, can someone help me? My forms.py file: class SubcategoriaFormCadastro(forms.Form): categoria = forms.ModelChoiceField(queryset=Categoria.objects.all(), widget=forms.Select(attrs={'class': 'select', 'data-minimum-input-length': 3, })) nome = forms.CharField(widget=forms.TextInput( attrs={'class': 'input is-primary'}), max_length=100) def clean_nome(self): nome = self.cleaned_data['nome'].upper() categoria = self.cleaned_data['categoria'] checa_nome = Subcategoria.objects.filter( nome=nome, categoria=categoria) if checa_nome.count(): raise ValidationError('Subcategoria já cadastrada') return nome def save(self): if self.is_valid(): subcategoria = Subcategoria( nome=self.cleaned_data['nome'].upper(), categoria=self.cleaned_data['categoria'], ) subcategoria.save() return subcategoria def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'subcategoria-update' self.helper.form_method = 'post' self.helper.form_action = '' My urls.py file: urlpatterns += [ re_path(r'^categoria-autocomplete/$', views.CategoriaAutocomplete.as_view(), name='categoria-autocomplete'), My models.py file: class Subcategoria(models.Model): categoria = models.ManyToManyField(Categoria) nome = models.CharField(max_length=100) class Meta: ordering = ['nome'] def get_absolute_url(self): return reverse( 'subcategoria-detail', args=[str(self.id)]) def __str__(self): return f'{self.nome} ({self.categoria})' My CategoriaAutocomplete block: class CategoriaAutocomplete(LoginRequiredMixin, UserPassesTestMixin, autocomplete.Select2QuerySetView): def test_func(self): return self.request.user.is_staff def get_queryset(self): if not self.request.user.is_authenticated: return Categoria.objects.none() qs = Categoria.objects.distinct().filter() if self.q: qs = qs.filter(nome__istartswith=self.q) return qs It should show a list of existing categories with the option to search for the desired category with a text input, instead I got … -
Authenticate works but login does not. It's stuck on pending
The issue is as explained in the title. I am able to create and authenticate users through forms or the cli but once the user/patient object is passed to the login(request, user) function, the entire application gets stuck and the pages keep loading. Whether I am logging in directly from the sign in page or registering a new member then trying to redirect them based on successful authentication. What could the issue be? (Note, I attempted creating a custom auth backend that also pitfalls into the same issue as the default.) Thanks in advance. This is a snippet of my Patient model along with its manager from the booking app class PatientManager(BaseUserManager): """ Manager for patient profiles """ use_in_migrations = True def _create_user(self, email, password, is_superuser, birth_date, phone_no, **extra_fields): """ Create a new user profile """ if not email: raise ValueError('User must have an email address') email = self.normalize_email(email) user = self.model(email=email, password=password, is_superuser=is_superuser, birth_date=birth_date, phone_no=phone_no, **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') user = self._create_user(email=email, password=password, is_superuser=True, birth_date=date(1990, 1, 1), phone_no="0711111111") return … -
how to use static files in django on production?
I am trying to use django static files on production using railway.app but files not getting served. Pl help. i tried collecting all files with collecstatic commant but still static files not getting served. showing 'not found' error. -
Django FileResponse with Reportlab downloading to the current directory instead of asking user to download
I have a reportlab implementation that generates pdf files for users to view and download to their system but instead, the download is automatically done to my current directly where I am running the Django server from. def dispatch(self, request, *args, **kwargs): buff = io.BytesIO() invoice_name = "new_invoice.pdf" doc = SimpleDocTemplate(invoice_name) flowables = [] flowables.append(all_flowable_data) doc.build(flowables) buff.seek(0) return FileResponse(as_attachment=True, filename=invoice_name) Once I click on the Download Invoice link, it just displays a blank page and when I check the current directory, the file is downloaded there. -
Django MultipleChoiceField callback
I'm kind of new in Django and I'm trying to fill back a listbox with the data previously saved in database. So when I display the HTML page, the choices initially stored in database will be highlighted. The listbox data are saved in this format ['Oranges','Cantaloupes'] but when I call back my form in my HTML page, everything is filled back with the database data except for the listbox. Do I have to add something to retrieve the data stored ? forms.py FRUIT_CHOICES= [ ('Oranges', 'Oranges'), ('Cantaloupes', 'Cantaloupes'), ('Mangoes', 'Mangoes'), ('Honeydews', 'Honeydews'), ] # Create Add Record Form class AddRecordForm(forms.ModelForm): first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"First Name", "class":"form-control"}), label="") last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"Last Name", "class":"form-control"}), label="") email = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"Email", "class":"form-control"}), label="") phone = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"Phone", "class":"form-control"}), label="") address = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"Address", "class":"form-control"}), label="") city = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"City", "class":"form-control"}), label="") state = forms.CharField(required=False, widget=forms.widgets.TextInput(attrs={"placeholder":"State", "class":"form-control"}), label="") zipcode = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={"placeholder":"Zipcode", "class":"form-control"}), label="") regarde = forms.CharField( widget=forms.widgets.Select(choices=FRUIT_CHOICES)) testrever = forms.MultipleChoiceField(choices=FRUIT_CHOICES) class Meta: model = Record exclude = ("user",) models.py class Record(models.Model): created_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.CharField(max_length=100) phone = models.CharField(max_length=15) address = models.CharField(max_length=100) city = models.CharField(max_length=50) state = models.CharField(max_length=50) zipcode = models.CharField(max_length=20) regarde = models.CharField(max_length=50) testrever = … -
New deploy with django and zappa only returns the error "NoneType object has no attribute read"
I've been using Django + zappa + aws perfectly for a few years now. However, when trying to deploy a new project using the latest versions of Django(4.2.1) and zappa(0.56.1) the project deploy only returns: "Error: Warning! Status check on the deployed lambda failed. A GET request to '/' yielded a 500 response code." And using the zappa tail command just returns: "NoneType object has no attribute read" -
django nginx gunicorn media files are not showing
media files are not served while static files served with no problem. here is the setting.py file if django project STATIC_ROOT = BASE_DIR / "staticfiles" STATIC_URL = '/static/' # STATIC_ROOT = 'static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] MEIDA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media/' nginx conf server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/ubuntu/nginx-django/hoshnyetli_project/staticfiles/; } location /media { autoindex on; alias /home/ubuntu/ninx-django/hoshnyetli_project/media/; } location / { include proxy_params; proxy_pass http://unix:/run/hoshniyetli.sock; } } and project dirs are in these order -hoshnyetli_project -... -hoshniyetli -staticfiles -media -... I tried many solutions but couldn't serve media files maybe I did some mistake in project urls.py (i think in deployment mode no need to add static to urlpatterns) -
Am I not deploying Celery correctly?
I deployed DRF with celery on Render (which uses Gunicorn) and celery tasks don't work. Only when I remove .delay() when calling the function, it works. So the email sending function is correct. Tasks are getting created properly (Railway server), but in server logs the print() statement is not shown on a task creation image here Folder structure: |-base |-tasks.py |-manager |-celery.py |-wsgi.py |-settings.py I'm creating a task like this in tasks.py: from celery import shared_task from time import sleep import os, ssl, smtplib from email.message import EmailMessage @shared_task def send_the_email(): sleep(10) email_sender = <my email> email_password = <password, which I generated on two step verification> em = EmailMessage() em['From'] = email_sender em['To'] = <another email of mine> em['Subject'] = 'subject' em.set_content('body') context = ssl.create_default_context() with smtplib.SMTP_SSL('smtp.gmail.com', 465, context=context) as smtp: smtp.login(email_sender, email_password) smtp.sendmail(email_sender, <another email of mine>, em.as_string()) views.py: from base.tasks import send_the_email class index(APIView): permission_classes = [AllowAny] def get(req,self): send_the_email.delay() return Response({'msg': 'hi'}) Any suggestions? -
Scrapy - SQLite3 Foreign Key not created in SQLite
Hi Im new in python and scrape. I am scraping this website to create a database. I have python code that successfully did. I scrap all the data already, but I want to store the ''TagLabel'' in different table. I would like to store all the data in the first table name : property, second table name is : tag 28hse tag code: <div class="tagLabels"> <div class="ui label">1 bedrooms</div> <div class="ui label">Apartment</div> <div class="ui label">Good view</div> <div class="ui label">Sea view</div> <div class="ui label">Elegant</div> my code: import requests from bs4 import BeautifulSoup from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException import datetime import sqlite3 def insertVaribleIntoTable(title, district, estate, grossarea, salesarea, price,url,phone,address,source,content, list_date, up_date,scrape_datetime): try: sqliteConnection = sqlite3.connect('scrap/db.sqlite3') cursor = sqliteConnection.cursor() sqlite_insert_with_param = """INSERT INTO scraping_property (title, district, estate, grossarea, salesarea, price,url,phone,address,source,content, list_date, up_date,scrape_datetime) VALUES (?, ?, ?, ?, ?,?,?, ?, ?, ?, ?, ?,?,?);""" data_tuple = (title, district, estate, grossarea, salesarea, price,url,phone,address,source,content, list_date, up_date,scrape_datetime) cursor.execute(sqlite_insert_with_param, data_tuple) sqliteConnection.commit() print("Python Variables inserted successfully into SqliteDb_developers table") cursor.close() except sqlite3.Error as error: print("Failed to insert Python variable into sqlite table", error) finally: if sqliteConnection: sqliteConnection.close() print("The SQLite connection is closed") def find_nth(haystack, needle, n): start = … -
Python Django "Please correct the errors below." using Django's built-in admin panel
I'm getting this error in my form with no context telling me to correct the errors below. I tried doing several things such as adding blank=True to every optional field that I could insert it into, logging which I found to be ineffective while using native Django forms, and I even tried commenting out various parts of my add_fieldset variable in the UserAdmin class. class UserAdmin(BaseUserAdmin): """Define the admin pages for users""" order = ['id'] ordering = ('email',) list_display = ['email', 'first_name', 'last_name'] fieldsets = ( (None, {'fields': ('email', 'password', 'first_name', 'last_name', 'gender', 'birthday', 'verified_male', 'verified_female_1', 'verified_female_2' )}), ( _('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'verified', 'vetted', ) } ), (_('Important dates'), {'fields': ['last_login']}), ) readonly_fields = ['last_login', 'age'] add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ( 'email', 'password', 'first_name', 'last_name', 'gender', 'birthday', )}), ( _('Permissions'), { 'fields': ( 'is_active', 'is_staff', 'is_superuser', 'verified', 'vetted', ) } ) ) admin.site.register(models.User, UserAdmin) Here is my models.py: class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Create, save, and return a new user""" if not email: raise ValueError('User have must have an email address') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, first_name, last_name, gender, birthday, **extra_fields): """Create and … -
Django website not responding from VPS on external IP
I am trying to use a VPS from google cloud to host my website. I have installed django, pip3, nginx, gunicorn. When I created a new django project, just to be sure, I tried running it once on the development server. But the VPS is not responding to browser requests. I tried diagnosing the problem and here is all what I found: To check firewall, I ran 'sudo ufw status' and it shows 'status:inactive' To check proxy, I ran 'env | grep proxy' and it returned nothing. To check available IPs, I tried 'sudo netstat -tlnp' and it gives this data: Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 9278/nginx: master tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 982/systemd-resolve tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1865/sshd tcp6 0 0 :::80 :::* LISTEN 9278/nginx: master tcp6 0 0 :::22 :::* LISTEN 1865/sshd I also allowed use of ports using 'sudo ufw allow 8000/tcp' and here is the ifconfig data: ens4: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1460 inet 10.182.0.3 netmask 255.255.255.255 broadcast 0.0.0.0 inet6 fe80::4001:aff:feb6:3 prefixlen 64 scopeid 0x20<link> ether 42:01:0a:b6:00:03 txqueuelen 1000 (Ethernet) RX packets 17772 bytes 134810759 (134.8 MB) RX errors … -
Why I am getting CORS with Vue.js/Django/Axios?
I have Vue.js app with Django rest framework integration, using axios. I am not sure if it is my backend or frontend app, that is causing this issue? When I click on Signup button I get following errors in console:- 1)Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/v1/users/' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 2)SignUpView.vue?fdb2:67 "Network Error" xhr.js?1a5c:251 POST http://127.0.0.1:8000/api/v1/users/ net::ERR_FAILED settings.py .... CORS_ALLOWED_ORIGINS = [ "http://localhost:8080", "http://127.0.0.1:8081", "http://127.0.0.1:8000" ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES' : ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES' : ( 'rest_framework.permissions.IsAuthenticated', ), } # Application definition INSTALLED_APPS = [ .... 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'djoser', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] main.js ... axios.defaults.baseURL='http://127.0.0.1:8000' createApp(App).use(store).use(router, axios).mount('#app') SigUpView.js <template> <div class="page-signup"> <div class="columns"> <div class="column is-4 is-offset-4"> <h1 class="title">Sign up</h1> <form @submit.prevent="submitForm"> <div class="field"> <label>E-mail</label> <div class="control"> <input type="email" name="username" class="input" v-model="username"> </div> </div> <div class="field"> <label>Password</label> <div class="control"> <input type="password" name="password" class="input" v-model="password"> </div> </div> <div class="notification is-danger" v-if="errors.length"> <!-- what is v-bind?? --> <p v-for="error in errors" v-bind:key="error"> {{ error }} </p> </div> <div class="control"> <button class="button is-success">Sign up</button> </div> </form> </div> </div> … -
best methods of archiving data of a model in django
Hello everyone, I have a Django model says modelA with 10 million records, our team took a call to not show the first million records as that data would not be of any interest to our customers and data is very old. Now I have two options. Option 1. Don't archive any data, just add created_date param in the search query in such a way that first 1 million records get filtered out while searching against the modelA. Option 2. Archive the first 1 million records of modelA, so that we don't add any date any created_date param in the search query. Can someone tell me please if option is very efficient. Note1: This model has references to other tables, so if I took a call to archive the data, I need to archive the referenced tables as well. -
Django Test can't find in the database the id of the object it created
Context I am building an e-commerce which have several apps such as accounts, products, categories, reviews, etc. The error output I am getting is this: django.db.utils.IntegrityError: insert or update on table "products_product" violates foreign key constraint "products_product_category_id_9b594869_fk_categories_category_id" DETAIL: Key (category_id)=(3) is not present in table "categories_category". By the time Django get to the particular test show that output, the category ID shoul be 4, as three other instances of the Category model were created for previuous test to that. The tests passed only I run them in a particular order. The Code Product Model from django.db import models class Product(models.Model): name = models.CharField(max_length=128) brand = models.CharField(max_length=128) image_url = models.CharField(default='', max_length=512, null=True, blank=True) description = models.CharField(max_length=512) specifications = models.JSONField(null=True, blank=True) price = models.DecimalField(max_digits=10, decimal_places=2) vendor = models.ForeignKey('accounts.User', on_delete=models.PROTECT, related_name='products') category = models.ForeignKey('categories.Category', on_delete=models.PROTECT, related_name='products', blank=True, null=True) available = models.BooleanField(default=True) class Meta: unique_together = ['vendor', 'name'] def __str__(self) -> str: return self.name Tests For The Product Model from django.test import TestCase from products.models import Product from products.tests.helpers import create_product class SetUp(TestCase): def setUp(self): self.product = create_product() return super().setUp() class TesteProduct(SetUp): def test_product(self): self.assertEqual( Product.objects.filter(pk=self.product.pk).exists(), True, ) retrieved_product = Product.objects.get(pk=self.product.pk) self.assertEqual( retrieved_product.name, self.product.name, ) self.assertEqual( retrieved_product.brand, self.product.brand, ) self.assertEqual( retrieved_product.description, self.product.description, ) self.assertEqual( … -
Jinja2 not rendering templates for Django in certain environments
I am using Django with Jinja2. I have an issue where the Jinja2 template engine is not rendering templates on my local machine/Docker setup but the same code does render using Jinja2 on Github Codespaces. The specific error is: TemplateSyntaxError at /val/ Could not parse the remainder: '('valapp:engindex', args=[engagement.id])' from 'url('valapp:engindex', args=[engagement.id])' My template settings in the settings.py file are: TEMPLATES = [ { "BACKEND": "django_jinja.backend.Jinja2", "DIRS": [ os.path.join(BASE_DIR, 'templates') ], "APP_DIRS": True, "OPTIONS": { "environment": 'valuation.jinja2.environment', } }, { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] I also have a jinja2.py file with the following code: from django.contrib.staticfiles.storage import staticfiles_storage from django.urls import reverse from crispy_forms.utils import render_crispy_form import os from jinja2 import Environment, FileSystemLoader custom_template_dir = "/workspaces/valapp/valapp/templates" def environment(**options): env = Environment(**options) env.globals.update({ 'static': staticfiles_storage.url, 'crispy': render_crispy_form, 'url': reverse, }) env.loader = FileSystemLoader(custom_template_dir) return env My requirements.txt file has the following: asgiref==3.6.0 Django==4.1.7 pytz==2022.7.1 sqlparse==0.4.4 crispy-bootstrap4==2022.1 django-crispy-forms==2.0 django-jinja==2.10.2 Jinja2==3.1.2 psycopg2==2.9.5 click==8.1.3 reportlab==3.6.12 The Dockerfile has: FROM python:3.10.11-alpine3.17 WORKDIR /app COPY requirements.txt requirements.txt RUN apk update RUN apk add postgresql-dev gcc python3-dev musl-dev RUN apk add --no-cache freetype-dev RUN pip3 install -r requirements.txt COPY . . CMD …