Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle django.db.utils.IntegrityError for asynchronous POSTs? (Can you except an IntegrityError?)
I have a model with a @BEFORE_CREATE signal hook like thus: from django.lifecycle.hooks import BEFORE_CREATE class Item(models.Model): title = models.CharField() slug = models.JSONField(unique=True) @hook(BEFORE_CREATE) def populate_slug(self): # Create a slug from the title # If the slug already exists, append "-{n}" # to make sure it is unique slug[0] = slugify(self.title) n = 2 while List.objects.filter(slug=slug).exists(): slug[0] = f"{slug[0]-{n}" n += 1 self.slug = slug This works fine in my tests when the Items are created synchronously one-after-another: i1 = Item.objects.create(title="Hello") i2 = Item.objects.create(title="Hello") self.assertEqual(i1.slug, ["hello"]) self.assertEqual(i2.slug, ["hello-2"]) However, on my actual frontend, I'm creating these objects asynchronously and at the same time: const item1 = axios.post(POST_ITEMS_URL, {title: "Hello"}) const item2 = axios.post(POST_ITEMS_URL, {title: "Hello"}) Promise.all([item1, item2]); Which gives me this error: web_1 | django.db.utils.IntegrityError: duplicate key value violates unique constraint "app_item_slug_key" web_1 | DETAIL: Key (slug)=(["hello"]) already exists. An easy fix (I think) would be to change my @hook to be AFTER_CREATE but I would like to avoid the additional write on all objects if possible. Is it possible to put an except IntegrityError somewhere? If so, where? Or how else can I overcome this problem? I'm using PostGRE if that matters. -
Explain relay and find_global_id in django graphql
i was reading django project in schema they define interface as a relay and also explain use of find_global_id class Meta: model = Books interfaces = (relay.Node, ) class Arguments: ad_id = graphene.ID() in mutate function ad_id = from_global_id(ad_id)[1] what will store ad_id ? -
Django rest framework and frontend
I want to use Django Rest Framework to create RESTAPI to integrate with the payment gateway API like stripe. For the frontend part I can only see project using React for the frontend. Cant i use Django as a frontend? Looking for suggestions if i really just need to use React or Vue. Or is it possible to use django as frontend as well. Looking for your suggestions. Thank you. -
How to get relate model without nested in Django rest framework?
How to get a json with relate model but without nested in Django rest framework? Code : Models, Session and Athlete, Athlete models has foreign key relationship with Session class Session(models.Model): Id = models.AutoField(primary_key=True) SessionNo = models.SmallIntegerField() WinTeam = models.SmallIntegerField(null=True) class Athlete(models.Model): Id = models.AutoField(primary_key=True) Name = models.CharField(max_length=6) Age = models.SmallIntegerField() Session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='athletes') Status = models.SmallIntegerField() Serializers class SessionSerializer(serializers.ModelSerializer): class Meta: model = Session fields = '__all__' class AthleteSerializer(serializers.ModelSerializer): Session = SessionSerializer(read_only=True) class Meta: model = Athlete fields = ('Age', 'Status', 'Session') And views: def all_athletes(request): """ Get all athletes list """ queryset = Athlete.objects.all().select_related() serializer = AthleteSerializer(instance=queryset, many=True) return Response(serializer.data) And the API result is : [ { "Age": 38, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } }, { "Age": 26, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } }, { "Age": 35, "Status": 2, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null } } ] It works to get relate model, but I want relate models show without nested, how to do to fit my expectation ? I expect the API result: [ { "Age": 38, "Status": 1, "Session": { "Id": 13, "SessionNo": 1, "WinTeam": null }, { … -
Django ownership assignment to modify or delete entries
First post here. I followed the project code in the Python Crash Course book, so if the code looks similiar that is why. In my django project, I want all the users to be able to view everything on the website. However, I want to have only the users who entered information in the entries to be able to edit and delete said entries. I know I need to assign ownership, but I'm having difficulty assigning it. currently I have a default setting enabled. For some reason if I take out the default it messes everything up. urls.py """Defines URL patterns for research_topic_database.""" # research_topic_database from django.urls import path from . import views app_name = 'research_topic_database' urlpatterns = [ # Home page path('', views.index, name='index'), # Page that shows all the research category topics. path('topics/', views.topics, name='topics'), # Detail page for a single research entry submission. path('topics/<int:topic_id>/', views.topic, name='topic'), # Page for adding a new research entry submission. path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), # Page for editing an entry. path('edit_entry/<int:entry_id>/', views.edit_entry, name='edit_entry'), ] models.py class Topic(models.Model): """A research category for topic submissions to fall under.""" category = models.CharField(max_length=19, choices=CATEGORY_CHOICES, blank=True) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" … -
Can't make live updated django site?
I have been updating code on my django site, but for some reason I cannot make it alive again. Now I get Internal Server Error... Apache/2.4.41 (Ubuntu) Server at something. When I put back old code, it works perfectly. At this update is not that big update, few small stuff. Any idea what I might messed up? -
How to process multiple variables of url parameter at once in django
Currently, the function is applied by passing only one argument to the url parameter, but considering the case of selecting multiple checkboxes, I am curious how to handle it when multiple arguments are received at once. Please help. urls.py path('student/add_teacher/<int:id>/', views.add_teacher) views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Register date</th> <th>Select</th> </tr> </thead> <tbody> {% for student in student %} <tr class="text-black tr-hover table-link text-center student" student-id="{{ student.id }}"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.register_date }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_detail.js $(function () { $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("업데이트하시겠습니까?"); if (updateTeacher) { window.location.href = 'student/add_teacher/' + studentID + '/'; } }); }); -
constraint validation invalid django
I try validate form but it go to the database and return the constraint validation error. form.py from django import forms from . models import Semana class FormularioSemana(forms.ModelForm): class Meta: model = Semana exclude = ['username'] #fields = '__all__' widgets = {'lunes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'lunes_fin': forms.TimeInput(attrs={'type': 'time'}), 'martes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'martes_fin': forms.TimeInput(attrs={'type': 'time'}), 'miercoles_inicio': forms.TimeInput(attrs={'type': 'time'}), 'miercoles_fin': forms.TimeInput(attrs={'type': 'time'}), 'jueves_inicio': forms.TimeInput(attrs={'type': 'time'}), 'jueves_fin': forms.TimeInput(attrs={'type': 'time'}), 'viernes_inicio': forms.TimeInput(attrs={'type': 'time'}), 'viernes_fin': forms.TimeInput(attrs={'type': 'time'}), 'sabado_inicio': forms.TimeInput(attrs={'type': 'time'}), 'sabado_fin': forms.TimeInput(attrs={'type': 'time'}), 'domingo_inicio': forms.TimeInput(attrs={'type': 'time'}), 'domingo_fin': forms.TimeInput(attrs={'type': 'time'}), } def __init__(self, username, *args, **kwargs): super(FormularioSemana, self).__init__(*args, **kwargs) # Set the instance's solicitante to the passed user. With this, you no longer have to do it in your views.py as well self.instance.username = username if not username.is_staff: # note that I moved the queryset filtering inside the if statement to avoid logical errors when user.is_staff is True self.fields['nombre'].queryset = nombre.stem.filter(username = request.user) def clean(self, *args, **kwargs): super().clean(*args, **kwargs) # Get the values nombre = self.cleaned_data['nombre'] username = self.instance.username # Find the duplicates duplicates = Semana.stem.filter( nombre=nombre, username=username ) if self.instance.pk: duplicates = duplicates.exclude(pk=self.instance.pk) if duplicates.exists(): raise forms.ValidationError('El nombre de la semana existe!') I think the problem is here but i dont see them views.py def index(request): … -
How to stop the Post request, if there is already the same data is in the Model
I am trying to stop the instance if the data matches in the DB. But i tried and failed again and again. My Code: models.py class Doctor(models.Model): """ Manages data of consulting doctors working in the Hospital """ user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=40) contact = models.IntegerField() department = models.CharField(max_length=50) active = models.BooleanField(default=False) def __str__(self): return f"{self.user} ({self.department})" class Patient(models.Model): """ Manages data of patient """ user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=40) contact = models.IntegerField() symptoms = models.CharField(max_length=50) active = models.BooleanField(default=False) def __str__(self): return f"{self.user} ({self.symptoms})" class Appointment(models.Model): """ Manages the appointment details """ patient_name = models.ForeignKey(Patient, on_delete=models.CASCADE, related_name='doctor') doctor_name = models.ForeignKey(Doctor, on_delete=models.CASCADE, related_name='patient') appointment_date = models.DateTimeField() active = models.BooleanField(default=False) def __str__(self): return str(self.patient_name) + " has appointment with " + str(self.doctor_name) serializers.py from rest_framework import serializers from api.models import Patient, Doctor, Appointment class AppointmentSerializer(serializers.ModelSerializer): """ Appointment serializer class """ class Meta: model = Appointment fields = "__all__" class DoctorSerializer(serializers.ModelSerializer): """ Doctor serializer class """ user = serializers.StringRelatedField(read_only=True) patient = AppointmentSerializer(many=True, read_only=True) class Meta: model = Doctor fields = "__all__" class PatientSerializer(serializers.ModelSerializer): """ Patient serializer class """ user = serializers.StringRelatedField(read_only=True) doctor = AppointmentSerializer(many=True, read_only=True) class Meta: model = Patient fields = "__all__" views.py from django.shortcuts import render from … -
Django template not displaying React component
I have installed all the packages I need, And I believe my webpack is setup correctly. I can run the server and the dev script with no errors at all. If I was to put anything in the HTML(e.g. text) file, it shows. But no react components on it. Webpack.config const path = require("path"); const webpack = require("webpack"); module.exports = { entry: "./src/index.js", output: { path: path.resolve(__dirname, "./static/frontend"), filename: "[name].js", }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", }, }, ], }, optimization: { minimize: true, }, plugins: [ new webpack.DefinePlugin({ "process.env": { NODE_ENV: JSON.stringify("development"), }, }), ], }; HTML <body> {% load static %} <div id="main"> <div id="app"> </div> </div> <script src="{% static 'frontend/main.js' %}"></script> </body> React import React, { Component } from "react"; import ReactDOM from 'react-dom'; export default class App extends Component(){ constructor(props){ super(props); } render(){ return <h1> Site Placeholder </h1> } } ReactDOM.render(<App />, document.getElementById('app')); The index.js just has an import: import App from "./components/App"; Views simply renders the index.html def index(request, *args, **kwargs): return render(request, 'frontend/index.html') I am not getting any errors anywhere, but my html is blank. In chrome inspect, I can see that there is the main.js … -
Django and HTML Dropdown : Populate Parent / Child field with Selected any one of the Child Attributes
I have 3 models which are being used for Dropdown, and user can select value from any of dropdown. When user select the parent the child dropdown auto-filters (this is working), however need a functionality where, when a user select a child, parent dropdown will also get filter. While doing research I came across with such functionality on site "https://www.hertzcarsales.com/nashville.htm?utm_source=google&utm_medium=organic&utm_campaign=GoogleLocalListing". Due to security reason cannot share actual models. however can refer to the site. User can select Vehicle Make, and the model + Body Style will auto filter, and when user selects just Body Style, then Make & Model will be filtered accordingly. For example, in below screenshot I just selected Body Style as Truck, and all Make & Model are auto-filtered. Please suggest or point me how this can be doable, just a pointer or small suggestion would help. I did tried using JavaScript, but unable to do reverse dropdown filter. -
Validate user name in django by jquery and javascript
Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username Is this is correct way to check? i am using javascript here user name from User model in django i have setup urls.py for validate_username function delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, ms || 0); }; } $('#id_username').on('focus', function(){ if ( $(this).val() == '' ){ $(this).attr('oldValue',''); } else { $(this).attr('oldValue',$(this).val()); } }); $('#id_username').keyup(delay(function () { var currValue = $(this).val(); var oldValue = $(this).attr('oldValue'); if (currValue == oldValue){ // Not sending ... } else{ // create an AJAX call $.ajax({ data: … -
gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> Bad Gateway - error 504
I am getting this error from my django application running on ubuntu version 20.04. I have tried all the solution I have seen online, including here on StackOverflow but none of them seems to have solved problem. Here is the error: [2021-09-27 21:32:14 +0000] [607] [INFO] Worker exiting (pid: 607) Sep 27 21:32:14 server.varsell.com gunicorn[608]: [2021-09-27 21:32:14 +0000] [608] [ERROR] Exception in worker process Sep 27 21:32:14 server.varsell.com gunicorn[608]: Traceback (most recent call last): Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker Sep 27 21:32:14 server.varsell.com gunicorn[608]: worker.init_process() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/workers/base.py", line 134, in init_proce> Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.load_wsgi() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.wsgi = self.app.wsgi() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi Sep 27 21:32:14 server.varsell.com gunicorn[608]: self.callable = self.load() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 58, in load Sep 27 21:32:14 server.varsell.com gunicorn[608]: return self.load_wsgiapp() Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp Sep 27 21:32:14 server.varsell.com gunicorn[608]: return util.import_app(self.app_uri) Sep 27 21:32:14 server.varsell.com gunicorn[608]: File "/root/projects/varsell/varsell/lib/python3.8/site-packages/gunicorn/util.py", line 359, in import_app Sep 27 21:32:14 server.varsell.com gunicorn[608]: mod = … -
How to convert post to Json - Django
I'm trying to convert data from a post to Json formed. But I still haven't had success. I tried to do in this format Unfortunately I couldn't think of anything. Could anyone help? if post: import re pattDet = re.compile('^([a-zA-Z_]\w+.)\[([0-9_\-][\w\-]*)\]\[([a-zA-Z_\-][\w\-]*)\]$') pattProd = re.compile('^([a-zA-Z_]\w+.)\[([0-9_\-][\w\-]*)\]\[([0-9_\-][\w\-]*)\]\[([a-zA-Z_\-][\w\-]*)\]$') pprint.pprint(post) det = [] prodtem = [] count = 0 for post_name, value in post.items(): try: det_count = int(pattDet.match(post_name).group(2)) if pattDet.match(post_name).group(1) == 'det': det[pattDet.match(post_name).group(3)] = value except: pass try: if pattProd.match(post_name).group(1) == 'prod': if count == int(pattProd.match(post_name).group(3)): prodtem.insert(count, {pattProd.match(post_name).group(4): value}) else: count += 1 except Exception as e: print(e) pass result.append({ 'det': det, 'prod': prodtem }) -
How to use a request.session stored value within a DetailView as the initial data to a ModelForm input field?
I'm a beginner at Django and I'm currently developing my first project. I'm using DetailView to display information from an object and in this same template there's a button that redirects to a ModelForm template. I've already gotten how to prepopulate the user field with form.save(commit=False) and a date field by simply setting a default on models. But I'm having trouble setting a ForeignKey field up. I've already tried different methods and variations of them but none worked. The one below is the last one I've tried. I've already studied and tried to make it work but I'm not sure how to use django sessions to pass the '''Book.id''' or anything that could possibly replace it from the DetailView to the ModelForm field. There were times I've gotten an error saying certain object was not JSON serializable then I've tried to make it work importing serializing modules and it didn't work as well. I also have doubts if I'm using the best method to achieve what I want using the DetailView class. Obs.: the input field is there with the options to pick. My intention is to set the initial value with previous page object. views.py class BookView(DetailView): model = … -
Django model where u can specify either a specific date, year, year range or unknown
the idea is that the field could take the following inputs 1926; 01/04/1997; 1937-1940,unknown is this even possible? how about django admin would it be possible to integrate? -
RuntimeError: Model class apps.concert.models.Band doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am attempting to import models from my concert app into an uploader app. However, when I do so, I get this error. RuntimeError: Model class apps.concert.models.Band doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. I have tried a number of solutions listed on StackOverflow but none of them work. I'll include my file setups here and would love help finding a solution. I'm banging my head against the wall trying to figure this out since I've not had this issue in the past. settings.base INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'rest_framework_simplejwt', 'storages', 'user', 'concert', 'uploader', ] apps.concert.models from django.db import models from django.db.models import ( CharField, TextField, ForeignKey, BooleanField, DateField, FileField, IntegerField, CASCADE ) import uuid import pdb def user_directory_path(instance, filename): random_file_name = "".join([str(uuid.uuid4().hex[:6]), filename]) return "concerts/{0}/{1}/{2}/{3}/{4}/{5}".format(instance.concert.date.year, instance.concert.date.month, instance.concert.date.day, instance.concert.venue, instance.concert.pk, random_file_name) class Band(models.Model): name = TextField() def __str__(self): return self.name class Concert(models.Model): venue = TextField() date = DateField() city = CharField(null=True, blank=True, max_length=100) state = CharField(null=True, blank=True, max_length=100) country = TextField() band = ForeignKey(Band, on_delete=CASCADE, related_name='concert') # user = ForeignKey(User, on_delete==CASCADE, related_name='user') def __str__(self): return self.venue class Song(models.Model): title = TextField() concert = ForeignKey(Concert, on_delete=CASCADE, related_name='song') # user = … -
How to do multiple pages with Django
I got some flash cards My flash cards I want to increase them, but they should not all append on one page, I want to have a page layout below. Like this: Like this: How should I do? -
How to setup django-sslserver with openssl?
I have installed OpenSSL64 successfully on my windows machine. I have a django project that I want to use SSL on. I've found github repo called "django-sslserver". I've set it up. The issue I am having is, when launching the django project through this command ($ python manage.py runsslserver myipaddress:portnumber), the https doesn't work and the browser shows that a certificate while it does exist, it is however not secure and its given by "localhost". So I figured I just need to get the proper certificate. My question is, how do I create the proper crt and key through openssl? I need to execute this command ; $ python manage.py runsslserver --certificate /path/to/certificate.crt --key /path/to/key.key -
Django filter object by ManyToMany and only return those ManyToMany relationships that match
class Category(models.Model): .... class User(models.Model): ..... category = models.ForeignKey( Category, on_delete=models.SET_NULL, null=True) group = models.ManyToManyField( Group, through="UserGroup") class Group(models.Model: .... class UserGroup(models.Model): ...... user = models.ForeignKey( User, on_delete=models.CASCADE) Group = models.ForeignKey( Group, on_delete=models.CASCADE) ..... I want to be able to return the Groups that contains a User with a certain category which I can do with... queryset = Group.objects.all() category = Category.objects.get(pk=category_id) queryset = queryset.filter(user__category_id=category_id) But this still returns all the Users associated to that Group even if the User.category does not equal the given category_id. How do I filter those many to many relationships also to return the Group where Users have that category and ONLY those Users within the Group? -
Hi i am getting user is AnonymousUser even i am passing valid token
hi i am using djangorestframework-simplejwt==4.4.0 and creating token using it but django give me AnonymousUser when i am trying to pass this token in side Authorization Bearer my restframework setting is : 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ) } from datetime import timedelta ... SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=50), 'REFRESH_TOKEN_LIFETIME': timedelta(days=60), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } view code is given below where i am trying to use it class PostProductsReviewsView(CreateAPIView): # permission_classes=[IsAuthenticated] serializer_class = ReviewsSerializer def get(self,request): print(request.user) user_id=request.user.id try: user=User.objects.get(id=user_id) except: return Response({"error":"user is not authenticated"},status=status.HTTP_401_UNAUTHORIZED) data=request.data stars=data.get('stars') title=data.get('title') review_content=data.get('review_content') review_content=data.get('product') quesry_data={ 'stars':stars, 'title':title, 'review_content':review_content, 'user':user, 'is_active':True } # data['user']=user serializer=ReviewsSerializer(data=quesry_data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) please help me when i copy and test on jwt.io this token contain all details but show invalid signature please help me -
Django Paginator not working after first page
I am doing a search that returns different model information. I want to have pagination on the results, and I have tried to do it with my get_context function (to figure out search parameters) and then a Paginator call. It returns the first page, but the next links in the template do not work. I get an error: UnboundLocalError at /search/ local variable 'my_object_list' referenced before assignment. My Search_Results_View looks like this: class SearchResultsView(LoginRequiredMixin,ListView): model = Program template_name = 'search_results.html' def get_context_data(self, **kwargs): context = super(SearchResultsView, self).get_context_data(**kwargs) # all_program_results = None segment_results = None segment_program_results = None segment_program_list = None segment_ids = None q_words = [] query = self.request.GET.get('q') start_date = self.request.GET.get('start_date') end_date = self.request.GET.get('end_date') svc_choices = self.request.GET.getlist('service_choices') print("Query = %s" % query) print("Start Date = %s " % start_date) print("End Date = %s " % end_date) print("SVC_CHOICES = %s" % svc_choices) for choices in svc_choices: print("Service choices = %s " % choices) if start_date and end_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__range=[start_date,end_date]).order_by('id') else: if start_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__gte=start_date).order_by('id') else: if end_date: all_program_results = Program.objects.filter(service__in=svc_choices,air_date__lte=end_date).order_by('id') else: all_program_results = Program.objects.filter(service__in=svc_choices).order_by('id') # We have gotten every program that applies if not query: print(" ALL programresults_count = %s" % all_program_results.count()) else: if re.match('^[0-9]+$',query): #user entered Program … -
Django + Vue deployment pythonanywhere.com
I am new to vue and cannot figure out how to get my Django/Vue app deployed on pythonanywhere.com. For the backend I am using cookiecutter which I have deployed as normal using [this guide][1] . This is working and I can view the API endpoints. I have been having difficulty connecting up the vue part, this is probably due to being new to JS frameworks so I am not entirely sure how they run in production. From [this post][2] I know I need to serve my Vue files as static files but I dont know how to do this. I have tried to build my vue project on my local machine which creates a dist folder, I added the contents of this folder to my django static folder and ran collectstatic command but this has not worked for me. Does anyone have experience with Vue and Django on pythonanywhere that could point me in the right direction? Any ideas of how to get this working? Thanks, John -
(Bad Gateway) ERROR 502 Nginx, Gunicorn, Django DRF, Vue.js
I have deployed ecommerce made with Django and Vue.js on a VPS. Everything is working fine, but when I try to use POST method, Error 502 appears in console and nothing happens. The API is able to show products from Django Admin, but I can't post anything from the frontend. It always gives me this Error 502 problem. I have been trying to solve this for a few day already and still don't get what is wrong. Hope you can help. Thank you! upstream perulab_app_server { server unix:/webapps/perulab/venv/run/gunicorn.sock fail_timeout=0; } server { listen 8000; listen [::]:8000; server_name 172.16.7.52; client_max_body_size 40M; location / { root /webapps/perulab/web-frontend/dist; try_files $uri /index.html; index index.html index.htm; } location /static/ { root /webapps/perulab/web-backend; } location /media/ { root /webapps/perulab/web-backend; } location /api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://perulab_app_server/api/; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; } location /admin/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-NginX-Proxy true; proxy_pass http://perulab_app_server/admin/; proxy_ssl_session_reuse off; proxy_set_header Host $http_host; proxy_redirect off; } } When I try to run gunicorn --bind 172.16.7.52:8000 core.wsgi this is what appears: [2021-09-27 14:55:59 -0500] [230558] [INFO] Starting gunicorn 20.1.0 [2021-09-27 14:55:59 -0500] [230558] [ERROR] Connection in use: ('172.16.7.52', 8000) … -
Is it good practice to use HTML forms to display data?
I am planning on using the form-control classes from Bootstrap to display data. I have an inclusion template tag that generates a "form" from objects in the DB. Is this a good practice? Or should I be investing my time in searching for a better way to display data?