Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the error in my syntax of javascript in django website?
See i am making a basic e commerce website in django for my django practice and i dont know javascipt really well. Can you please find problem in my javascript. Code in my checkout page's checkout.js checkout.js Error coming in this part image My views.py checkout function views.py Please help me out -
config sendgrid and django
hello despite my trying I can not configure sendgrid here is the code thank you for your help SENDGRID_API_KEY = 'password' EMAIL_BACKEND = 'sendgrid_backend.SendgridBackend' EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_HOST_USER='API Key ID' EMAIL_HOST_PASSWORD=SENDGRID_API_KEY EMAIL_PORT = 587 EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'Python ecommerce <API Key ID>' BASE_URL = 'sitename' DEFAUT_FROM_EMAIL='API Key ID' MANAGERS = ( ('mohamed aymen hssen', "API Key ID"), ) ADMINS = MANAGERS error HTTP Error 401: Unauthorized -
python How to force download generated pdf?
I am using `xhtml2pdf` library in a django project to generate pdf file from html, and I would like to know how to force download the generated pdf to the server. If you need more information, please comment below. Thank you in advance. -
Post a JSON object on conditional input -- Django Restframework
Iam working on Django Restframework. I want to POST into an API to create an object. The problem is the condition I want to make, is itself in the POST data. For example, I have 5 fields: Name Lastname Email is_member membership_id I want to create a membership_id, if the user sends "is_member== True" while data posts. Problem: The data does get posted but the "membership_id" is blank. And no errors received. I could conclude that the reason is the "if/else" condition is triggered before all the fields are set. I tried to give the "if/else" condition when the function starts Inside the object which save the entry ie user_object. But nothing works Iam until here def create_user(request): if request.method == "POST": firstname = request.POST.get('firstname') lastname = request.POST.get('lastname') email = request.POST.get('email') is_member = request.POST.get('is_member') # default is = False category = request.POST.get('category') timestamp = int(datetime.now(tz=timezone.utc).timestamp()*1000) if is_member == True: membership_id = hashString(str(timestamp)) else: membership_id = "" try: user_object = MasterUser( firstname = firstname, lastname = lastname, email = email, is_member = is_member, membership_id = membership_id ) user_object.save() return HttpResponse('User successfully created') Is it possible or do I have to look out for some different apporach. Any ideas are welcomed! Thanks. -
Test failed for Date of Birth
I am a beginner in python-django coding. Currently I'm at the challenge part of https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Testing. My tests are going well except for def test_form_date_of_death_initially_set_to_expected_date(self). The error is AssertionError: datetime.date(1900, 1, 1) != datetime.date(2020, 6, 11) From what I understand the 1900,1,1 is the date that return to me after the function is done checking. But the problem is I have no idea how this date is coming out. I check thru my files and I cant see any codes setting it as 1900, 1, 1. So is this a default date if it is not set? If it is default by nature, how come i set test author date of death, it is still coming out 1900, 1, 1. Appreciate if anyone could help me. Thanks class AuthorCreateTest(TestCase): def setUp(self): # Create a user test_user1 = User.objects.create_user(username='testuser1', password='1X<ISRUkw+tuK') test_user2 = User.objects.create_user(username='testuser2', password='2HJ1vRV0Z&3iD') test_user1.save() test_user2.save() # Give test_user2 permission to renew books. permission = Permission.objects.get(name='Set book as returned') test_user2.user_permissions.add(permission) test_user2.save() # Create a book test_author = Author.objects.create(first_name='John', last_name='Smith', date_of_death='2006-06-11') def test_redirect_if_not_logged_in(self): response = self.client.get(reverse('author-create')) self.assertRedirects(response, '/accounts/login/?next=/catalog/author/create/') def test_forbidden_if_logged_in_but_not_correct_permission(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 403) def test_logged_in_with_permission(self): login = self.client.login(username='testuser2', password='2HJ1vRV0Z&3iD') response = self.client.get(reverse('author-create')) self.assertEqual(response.status_code, 200) def test_uses_correct_template(self): login … -
trying to override allauth templates on a Django 3.2 app recognized in python 3.9
I'm working with ALLAUTH on Django 3.2. Most solutions I found are for Django 1, so I'm hoping to find something more up-to-date here. I have the module/app installed, but I'm having problems overriding the templates with my own. In settings.py: INSTALLED_APPS = [ ... 'Landing.apps.LandingConfig', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ BASE_DIR / 'templates' ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ # Already defined Django-related contexts here # `allauth` needs this from django 'django.template.context_processors.request', ], }, }, ] AUTHENTICATION_BACKENDS = [ # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', ] Research Urls #The Project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('', include('Landing.urls')), path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), ] Landing/urls.py #app-level urls from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name='home'), path('login/', views.LoginView.as_view(), name='account_login'), path('signup/', views.SignupView.as_view(), name='account_signup') ] Home.html <...> <body> <H1>This is the homepage</H1> <p><a href="{% url 'account_login' %}">login</a></p> <p><a href="{% url 'account_signup' %}">Create Account</a></p> </body> <...> Note: account_login and account_signup are both in Landing urls and Landing Views Landing Views … -
Design decision for deleting Django fields
I have a preexisting Postgres Database connected with the Django app. I want to delete a field in one of my Django models. I have 2 ways to do this: Manually delete the field from the auto generated files created during the previous migrations which django created -> Drop the column manually in the preexisting database -> Run migration again with the new migrations. Run makemigrations again which will cause django to create another migration file to drop the aforesaid field -> Migrate the preexisting database with the new migrations. Could anyone advice me what is the best practice to remove the field? Cheers, Fellow StackOverflower -
How to reposition form button in a Django template
I have a Django template that renders a form. The code is: {% block body %} <h3> Create Listing </h3> <table> <form action="{%url 'create' %}" method="POST"> {% csrf_token %} {{ form.as_table }} <input type="submit" value="Create Listing" class="btn btn-primary"> </form> </table> {% endblock %} Note: I'm using <table> to left justify the input boxes (otherwise the form looks messy on the screen). The blue "Create Listing" button is currently appearing above the input boxes. How do I move this button such that it's positioned below the input boxes? Thanks in advance! -
I have a confusion about creating the user profile when the user is newly registered
views.py def login_view(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username,password=password) if user is not None: login(request,user) return redirect('homepage') else: messages.error(request,'No current user!') else: form = AuthenticationForm() context = {'form':form} return render(request,'login.html',context) def logout_view(request): logout(request) return redirect('login') @login_required def profile(request): Profile.objects.get_or_create(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfileForm(request.POST,request.FILES,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request,'Profile updated successfully!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileForm(instance=request.user.profile) context = { ## 'user':request.user, 'u_form':u_form, 'p_form':p_form, } return render(request,'profile.html',context) signals.py @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() models.py class Profile(models.Model): name = models.OneToOneField(User,on_delete=models.CASCADE) mobile = models.IntegerField(null=True) address = models.CharField(max_length=350,null=True) image = models.ImageField(upload_to='profile_pics', default='default.png',null=True) def __str__(self): return str(self.name.username)+'\'s Profile' forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['mobile', 'address', 'image'] I am facing an issue that the user profile could not get created or updated although I used the signals for the profile model. When I login a registered user, the error message told me that User has no profile so in order to automatically … -
ValueError at /new_post/ The 'image' attribute has no file associated with it
In my django blog site if I want to add a new post there is an option of post it with or without an image. If I make a post with the image then it works fine, but if I make a post without any image it shows this error: ValueError at /new_post/ The 'image' attribute has no file associated with it. my codes are given below models.py: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=300) content = models.TextField() image = models.ImageField(upload_to='post_image', blank=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return f'{self.author}\'s Post' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.width > 300 or img.height > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) def get_absolute_url(self): return reverse('post_detail', kwargs={'pk': self.pk}) views.py: class PostCreateView(CreateView): model = Post fields = ['title', 'content', 'image'] success_url = '/' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['title'] = 'New Post' return context def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) home.html: {% if post.image %} <img class="card-img-right flex-auto d-none d-md-block" style="width:200px;height:200px;" src="{{ post.image.url }}" alt="{{ post.title }}"> {% endif %} -
Django email address not showing in admin
I'm trying to create a simple email and name collector , everything looks fine but I can only see the name option in the admin site the email option is not there admin page model Here is my code Forms.py from django import forms from sonus import models from django import forms class NameForm(forms.Form): your_name = forms.CharField(label="Your Name",max_length=20) your_email = forms.EmailField(label="Email",max_length=100) Here Goes my Views.py def get_name(request): person = Person() if request.method=="POST": form = NameForm(request.POST) if form.is_valid(): person.name = form.cleaned_data['your_name'] person.email = form.cleaned_data['your_email'] person.save() return HttpResponseRedirect(reverse('index')) else: form = NameForm() return render(request,'form.html',{ 'form': form }) My Admin.py from django.contrib import admin from django.contrib.admin.decorators import display from django.contrib.auth.admin import UserAdmin from .models import Details, Person,list from sonus import models # Register your models here. admin.site.register(Person) -
How to subtract datefield from datetimefield in django
I'm using Django, the model for field A is DateField and the model for field B is models.DateTimeField(auto_now_add=True) . I want to get the day difference by subtracting field A from field B. I tried as below because the properties of the two fields are different, but the result is output as datetime.timedelta(0) . Please tell me how to solve it. I've been thinking about it for a few days. Help... Feedback.objects.filter(Q(date__gte='2020-01-01')) .annotate(days_diff=ExpressionWrapper(F('create_date') - F('date'), output_field=DurationField()))\ .values('days_diff', 'id') -
checkbox to allow the staging frontend to connect with backend on localhost:8000 or staging backend
I have hosted the frontend and backend on staging server, sometimes I need to test the frontend with my local changes in the backend, so basically, I need a checkbox that allows the frontend to connect to localhost:8000 instead of staging server for the backend? That way, I will have no need to run the front-end locally just to change the endpoint. the frontend is written in React and the backend is written in Django. anyone who can help me with this thing? thanks in advance -
Problems with filtering data in Django
I am making a post, and the question is that i need to filter a list with the users who have published the most posts. I had tried, but only managed to filter the total posts, and have had trouble with that. The fields in Models.py from User: from django.contrib.auth.models import AbstractUser class Usuario(AbstractUser): email = models.EmailField(unique=True) creation_time = models.TimeField(auto_now_add=True) description = models.TextField() avatar = models.ImageField(blank=True, null=True, upload_to='autores/', default='img/default.jpg') social = models.URLField(blank=True, null=True) slug = models.CharField(max_length=60, unique=True, blank=True) is_author = models.BooleanField(default=False) meanwhile in models.py from Blog: class Post(ModeloBase): title = models.CharField('Titulo del Post', max_length=200, unique=True) slug = models.SlugField(max_length=200, blank=True, unique=True) description = models.TextField('Descripcion') author = models.ForeignKey(Usuario, on_delete= models.CASCADE) category= models.ForeignKey(Category, on_delete= models.CASCADE) content= RichTextField() referential_img = models.ImageField('Imagen Referencial', upload_to='imagenes/', max_length=255) published= models.BooleanField('Publicado / No Publicado', default=False) publication_date = models.DateField('Fecha de Publicacion') like = models.ManyToManyField(Usuario, blank=True, related_name='likes') dislike = models.ManyToManyField(Usuario, blank=True, related_name='dislikes') class Meta: verbose_name = 'Post' verbose_name_plural = 'Posts' def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) Looking in the django documentation, i tried to do the filtering but it didn't work for me. I don't know what my mistake was, so i hope someone could help me. for example, so i have my … -
Problems with accessing a Model in the Admin website
I have created Profile model, which works fine in the admin website in Django, obviously, I try creating a very complex model but I keep getting error, anyway decided to streamline the process and I created a very simple model. models.py from django.db import models from django.conf import settings #from django_countries.fields import CountryField #from phone_field import PhoneField class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) email = models.EmailField(blank=True,null=True) role = models.TextField(blank=True) location = models.TextField(blank=True) photo = models.ImageField(upload_to='users/%Y/%m/%d', blank=True) def __str__(self): return f'Profile for user {self.user.username}' class Client(models.Model): firstname = models.CharField(blank=True, max_length=30) def __str__(self): return f'{self.firstname}' I ran python manage.py makemigrations and python manage.py migrate and the code works fine, I have also ensured that all previous migrations are deleted, so I successfully created a 0001_initial.py file in migrations. I decided to include my new model in the admin.py file so I can interact with the model from Django's user interface from django.contrib import admin from .models import Profile, Client @admin.register(Profile) class ProfileAdmin(admin.ModelAdmin): list_display = ['user', 'photo','role'] @admin.register(Client) class Client(admin.ModelAdmin): list_display = ['firstname'] #list_display = ['firstname', 'lastname','position','country','email','phone'] And this is where the problem starts, I can successfully see that the Clients model is create din the admin section, but when I click the … -
Use django-compressor on form assets (media) in Django
According to the Django Doc on Form Assets. You can add static files (.css and .js) to your forms and widgets via the Media meta-class. However, I am trying to add .scss and .ts files instead. Those files would obviously be compressed by django-compressor. Everything is working fine with the normal static files in *project*/static/style/stylesheet.scss and in my apps' static directories, but how would I compress the files specified in the Media class ? I don't know if that's possible using django-compressor or if there is another way to achieve what I am trying to do. I could not find any documentation on this problem on the django-compressor doc. I tried to directly add the .scss file directly in the Media meta-class as such: class Media: css = {'all': ('accounts/style/accounts.scss',)} However, django tells me that the stylesheet is not of type text/css. That would mean that overriding the media system for this would be an option to render with text/scss instead and try to compress the file... Nonetheless, that approach seems a bit overkill. I would appreciate any help! -
Testing DRF GenericViewSet with parameters in url_path
I'm trying to test DRF endpoint with unittest. View under the test: class HwView(mixins.ListModelMixin, viewsets.GenericViewSet): @action(detail=False, methods=['get'], url_path='switch_state/(?P<switch_id>\d+)') def switch_state(self, request, switch_id): print(f'sw: {switch_id}') results = {"state": 'ok'} return Response(results) Entry in the url.py from rest_framework import routers router = routers.DefaultRouter() router.register(r'hw', hw_views.HwView, basename='HwModel') And the test code from rest_framework.test import APIRequestFactory, APITestCase class TestCommandProcessor(APITestCase): def setUp(self): pass def test_switch_state(self): factory = APIRequestFactory() request = factory.get( '/api/hw/switch_state/3', ) view = HwView.as_view({'get': 'switch_state'}, basename='HwModel') response = view(request) self.assertIn('state', response.data) self.assertEqual('ok', response.data['state']) As I run the test I'm getting the error: TypeError: switch_state() missing 1 required positional argument: 'switch_id' Any other methods in this view (GET without parameters, POST with parameters) work fine with the same testing approach. Can you help me find out why my view can't parse parameters in the URL? Or any advice on how can I rewrite my test to successfully test my code. -
django print value of checked box from HTML form
I have a HTML form that is displaying a table with data. I added checkboxes to the form and now want to take baby steps to print the value of the checked box, when the button named "test_btn" on my HTML form is clicked. However, based on the lack of console logs, I know that I am not entering the get_checked_items function. Any ideas would be greatly appreciated. Here is my HTML Form named show.html <body> <div class="container"> <form method="POST" action=#> {% csrf_token %} <table class="table table-striped"> <thead> <tr> <th>Shipment ID</th> <th>Load Number</th> <th>Booked By</th> <th>Pickup City</th> <th>Pickup State</th> <th>Pickup Date</th> <th>Pickup Time</th> <th>Destination City</th> <th>Destination State</th> <th>Trailer Number</th> <th>Seal Number</th> <th>Primary Driver</th> </tr> </thead> <tbody> {% for ship in shipment %} <tr> <td><input type="checkbox" name="checks" id="{{ship.id}}" value="{{ship.id}}" />{{ship.id}}</td> <td>{{ship.load_number}}</td> <td>{{ship.booked_by}}</td> <td>{{ship.pickup_city}}</td> <td>{{ship.pickup_state}}</td> <td>{{ship.pickup_date}}</td> <td>{{ship.pickup_time}}</td> <td>{{ship.destination_city}}</td> <td>{{ship.destination_state}}</td> <td>{{ship.trailer_number}}</td> <td>{{ship.seal_number}}</td> <td>{{ship.primary_driver}}</td> </tr> {% endfor %} </tbody> </table> <div class="form-group"> <button><a href="/showform">Enter New Shipment</a></button> <div class="form-group"> <button><a href="/updatedata">Update Data</a></button> </div> <input type ="submit" class="btn" value="TESTING" name="test_btn"> </form> Here is my views.py file. I have a couple of print statements in there just to give me some more visibility as to which functions I'm actually entering. from django.shortcuts import render,redirect from django.http import … -
How to validate a formset in django
I am using formset to input my data into the database but for some reason it just doesn't validate, whenever I test in the terminal and call the .is_valid() It just returns false no matter what I try. Here's the code in my views.py and forms.py . Any help will be much appreciated! # Advanced Subjects (Advanced Biology) def form_5_entry_biology_view(self, request): current_teacher = User.objects.get(email=request.user.email) logged_school = current_teacher.school_number students_involved = User.objects.get(school_number=logged_school).teacher.all() data = {'student_name': students_involved} formset_data = AdvancedStudents.objects.filter(class_studying='Form V', combination='PCB') student_formset = formset_factory(AdvancedBiologyForm, extra=0) initial = [] for element in formset_data: initial.append({'student_name': element}) formset = student_formset(request.POST or None, initial=initial) print(formset.is_valid()) context = {'students': students_involved, 'formset': formset, 'class_of_students': 'Form V', 'subject_name': 'Advanced Biology'} return render(request, 'analyzer/marks_entry/marks_entry_page.html', context) And here is my forms.py class AdvancedBiologyForm(forms.ModelForm): student_name = forms.CharField() class Meta: model = ResultsALevel fields = ('student_name', 'advanced_biology_1', 'advanced_biology_2', 'advanced_biology_3',) -
how know id form.model while editing Djando
i have to check if a name is already in use but to do it i have to exclude item i'm going to edit class EditItemForm(forms.ModelForm): name = forms.CharField( max_length=80, min_length=3, required=True ) def clean_name(self): # Get the name name = self.cleaned_data.get('name') if Item.objects.filter(name=name).exclude(id=id).exists(): raise forms.ValidationError('This name is already in use.') class Meta: model = Item fields = ('type', 'name', ) class Item(models.Model): type = models.IntegerField(choices=TYPE, blank=False, default=NO_CAT) name = models.CharField(max_length=250 ) def __str__(self): #metodo righiesto return self.name how i can retrive current item id/pk to exlude it? -
How can I autocomplete Forms in Django with Foreign Keys?
My intention is that the form takes the available book with its respective foreing key but I cannot with the 'book_id' field of loans. I have managed to take the user crazy but not the book # Model class Prestamos (models.Model): libro_id = models.ForeignKey(Libros, on_delete=models.CASCADE) usuario_id = models.ForeignKey(Usuarios, on_delete=models.CASCADE) cantidad_dias = models.SmallIntegerField('Cantidad de dias a prestar', default= 5) fecha_prestamo = models.DateField('Fecha de prestamo', auto_now=False, auto_now_add=True) fecha_vencimiento = models.DateField('Fecha de vencimiento de la reserva', auto_now=False, auto_now_add=False, null = True, blank = True) estado = models.BooleanField(default=True, verbose_name= 'Prestado') # Form class PrestamoForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in iter (self.fields): self.fields['cantidad_dias'].widget.attrs['readonly'] = False class Meta: model = Prestamos fields = [ 'cantidad_dias'] exclude = ['libro_id', 'usuario_id','fecha_prestamo','fecha_vencimiento', 'estado'] def clean_libro(self): libro = self.cleaned_data['libro_id'] if libro.cantidad < 1: raise ValidationError('No se puede prestar este libro, no hay unidades disponibles') return libro # View class RegistrarPrestamo(CreateView): model = Prestamos template_name = 'libro/prestar_libro.html' success_url = reverse_lazy('libros:disp_libro') form_class = PrestamoForm def form_valid(self, form): form.instance.usuario_id = self.request.user libro= Libros.objects.get(pk=int(id)) form.instance.libro_id = libro return super (RegistrarPrestamo, self).form_valid(form) #Url path('libro/prestar-libro/', login_required(RegistrarPrestamo.as_view()), name = 'prestar_libro') int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method' -
Running a Django REST-API on AWS - apache server does nothing
I have built a functional API with the django rest_framework, but as the runserver command is not suitable for production I am trying to get the AWS Apache to run the server as documented all over the place (e.g. : https://aws.amazon.com/getting-started/hands-on/deploy-python-application/ , https://dzone.com/articles/deploy-django-application , etc etc). Essentially, it's an image translation application that takes an image via a POST request and returns a modified image in the Response. Fairly simple, just one major endpoint. When I start or restart apache after running through all those configuration steps, i get a response saying "Restarted Apache" as expected. However, nothing is accessible! I can't run a POST command as I could with built-in server ./manage.py runserver 0.0.0.0:8000 So what's going on here? When I run with the built-in django server there are several parts of the start-up process that I can see and I get responses as expected, but with Apache? Nothing. -
CORS fetch issue HeaderDisallowedByPreflightResponse
I have an app running locally (Django app serving a React frontend, localhost:5000) and I have an external Django service on localhost:8888. Both work fine separately. The app needs to perform a GET to the service, but fails with: CORS error: HeaderDisallowedByPreflightResponse. The OPTIONS goes through OK, but this one fails. If I try performing the same request through Postman, it works fine. I've tried many header versions in my fetch, and this is what I ended up with, still not working: fetch(`${baseUrl}/programs`, { method: 'GET', mode: 'cors', headers: { 'X-API-Key': 'testing', 'Access-Control-Request-Method': 'GET', 'Access-Control-Allow-Origin': 'localhost:5000', // tried "*", as well 'Access-Control-Expose-Headers': 'X-API-Key, Content-Type, Access-Control-Request-Method, Access-Control-Allow-Origin', 'Access-Control-Allow-Methods': 'OPTIONS, GET, POST', 'Access-Control-Allow-Headers': 'X-API-Key, Content-Type, Access-Control-Request-Method, Access-Control-Allow-Origin', 'Content-Type': 'text/plain', 'Access-Control-Allow-Credentials': true, }, }).then((re) => { console.log(re); }) .catch(err => console.log(err)); Initially I started with just method, mode and headers X-API-Key, Access-Control-Allow-Origin and worked my way up from there. The external Django service has installed django-cors-headers and allowed all origins in the settings file so I'm not sure if this is the service's issue or frontend's. Any ideas what to try? -
Python Django Post Queue
Hi I have a Django Project. In my project, I want to queue all incoming post requests and show the sequence number. First in, first out. How can I go about this? Because I have created a project where many people can submit requests at the same time. When I receive a request like this at the same time, the server may crash or delays may occur.For this, I thought about queuing and giving sequence numbers to users, but I couldn't find much source about it. For example, 10 requests came all of a sudden, the server calls the functions on the backend and the sequence number 10 appears. Then the user who made the first request gets a response and the sequence number drops to 9. -
Django 2.0.7 Exception Type: OperationalError
enter code here Environment: enter code here Request Method: POST enter code here Request URL: http://127.0.0.1:8000/admin/products/product/add/ enter code here Django Version: 2.0.7 enter code here Python Version: 3.8.6 enter code here Installed Applications: enter code here ['django.contrib.admin', enter code here 'django.contrib.auth', enter code here 'django.contrib.contenttypes', enter code here 'django.contrib.sessions', enter code here 'django.contrib.messages', enter code here 'django.contrib.staticfiles', enter code here 'products',] enter code here Installed Middleware: enter code here ['django.middleware.security.SecurityMiddleware', enter code here 'django.contrib.sessions.middleware.SessionMiddleware', enter code here 'django.middleware.common.CommonMiddleware', enter code here 'django.middleware.csrf.CsrfViewMiddleware', enter code here 'django.contrib.auth.middleware.AuthenticationMiddleware', enter code here 'django.contrib.messages.middleware.MessageMiddleware', enter code here 'django.middleware.clickjacking.XFrameOptionsMiddleware'] enter code here Exception Type: OperationalError at /admin/products/product/add/ enter code here Exception Value: no such table: main.auth_user__old I'm getting this error on django adminstration site when i click on the save button. These are the errors, Exception Type: OperationalError at /admin/products/product/add/ and Exception Value: no such table: main.auth_user__old