Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dropdown dependent problems with saving in the form part
I have a problem with dropdown dependent. in the frontend it works perfectly and filters me optimally but in the backend I have problems saving. Choose a valid option. The choice made does not appear among those available. This error is due to the fact that in form.py I cannot find 'gruppo_single' in self.data because it was excluded from the form to be dynamically passed from the view during the post. Can anyone help me with this problem? my models class Gruppi(models.Model): nome_gruppo = models.CharField(max_length=100) class Esercizi(models.Model): nome_esercizio = models.CharField(max_length=100) gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'gruppo') class Schede(models.Model): nome_scheda = models.CharField(max_length=100) data_inizio = models.DateField() data_fine = models.DateField() utente = models.ForeignKey(User, on_delete = models.CASCADE,related_name = 'utente') class DatiGruppi(models.Model): giorni_settimana_scelta = [ ("LUNEDI","Lunedì"), ("MARTEDI","Martedì"), ("MERCOLEDI","Mercoledì"), ("GIOVEDI","Giovedì"), ("VENERDI","Venerdì"), ("SABATO","Sabato"), ("DOMENICA","Domenica") ] giorni_settimana = MultiSelectField(choices = giorni_settimana_scelta,default = '-') dati_gruppo = models.ForeignKey(Gruppi,on_delete = models.CASCADE, related_name = 'dati_gruppo') gruppi_scheda = models.ForeignKey(Schede,on_delete = models.CASCADE, related_name = 'gruppi_scheda') class DatiEsercizi(models.Model): serie = models.IntegerField() ripetizione = models.IntegerField() peso = models.DecimalField(max_digits = 4,decimal_places = 1,blank = True,null = True) dati_esercizio = models.ForeignKey(Esercizi,on_delete = models.CASCADE,related_name = 'dati_esercizio') gruppo_single = models.ForeignKey(DatiGruppi, on_delete = models.CASCADE, related_name = 'gruppo_single') view for creating groups and exercises def creazione(request, nome): scheda = get_object_or_404(Schede, … -
Access control and input (json) validation in Django ajax views?
With a regular view we use decorators (e.g. login_required/user_passes_test/etc.) to do access control for a view and forms to validate user input. Is there anything similar for ajax views that take json as input (and output)? Doing it manually isawfully verbose.. def my_ajax_view(request): if not request.is_ajax(): return http.HttpResponseForbidden('cannot use this view directly') if request.user.is_anonymous(): return http.HttpResponseForbidden('must login') if not request.user.has_perm('can_foo'): return http.HttpResponseForbidden('no foo permission') try: data = json.loads(request.body) except json.decoder.JSONDecodeError: return http.HttpResponseForbidden('invalid input') # validate {"a": [list of int]} if not isinstance(data, dict): ..error if not 'a' in data.keys(): ..error if not isinstance(data['a'], list): ..error if not all(isinstance(val, int) for val in data['a']): ..error return http.JsonResponse({"length": len(data['a'])}) -
how to get selected item in <li> to views in django
please help !!! I have a code which get the data from db and display it in dropdown menu, the problem is : i can't get the selected item to insert it in an other table the html : <div class="template-demo" > <div class="mdc-select demo-width-class" data-mdc-auto-init="MDCSelect" > <i class="mdc-select__dropdown-icon"></i> <div class="mdc-select__selected-text"></div> <div class="mdc-select__menu mdc-menu-surface demo-width-class" > <ul class="mdc-list"> <li class="mdc-list-item mdc-list-item--selected" data-value="" aria-selected="true"> </li> {% for TypeFrais in typefrais %} <li class="mdc-list-item" > <input type="hidden" name="type_field"> {{TypeFrais.FRT_NAME}} </li> {% endfor%} </ul> </div> <span class="mdc-floating-label">Type de frais</span> <div class="mdc-line-ripple"> </div> </div> </div> views.py if request.method == 'POST': #iden = request.POST['id_field'] designation = request.POST['des_field'] date = request.POST['date_field'] montant = request.POST['montant_field'] type = request.POST['typefield'] GES_FRAIS = Frais(FR_TYPE_id=type,FR_DESIGNATION=designation,FR_MONTANT=montant,FR_DATE=date,FR_CODE=78) GES_FRAIS.save() return render(request, 'gesfrais.html',context) the error is : MultiValueDictKeyError at /dashboard/gesfrais/ 'typefield' -
models.AutoField not working for tables under new schemas
I am trying to save the file upload information in a table under a new schema, not 'public' in PostgreSQL database. I used id = models.AutoField(db_column="id", primary_key=True) in my model class definition because I want the id of each row to be automatically incremented. However, I get the error as shown in the screenshot below after uploading the image. The Autofield worked when I saved the data in a table under 'public' schema, but it doesn't work for a table under the separate schema. I couldn't find any solution to fix this problem. Any suggestion would be appreciated. -
how to fix Comodo SSL certificate on Django app not trusted?
I have a comodo positive SSL certificate. put it on my server and started my server using this: python manage.py runserver_plus --cert-file /my/cert --key-file /my/key 0.0.0.0:443 but it is not trusted in browsers yet. shows this: I passed my files that have same name with my domain to runserver_plus. I think maybe i used wrong files. now i want to know what is my problem? -
Django Celery. How do I run task at exact time?
How can I write a code that will run a task for example "everyday (or every 24 hours)at 3:20 a.m."? The main problem is "3:20" part, how do I make cron task at this exact time? -
Use of select_related in simple query in django
I have a model in Django in which a field has a fk relationship with the teacher model. I have came across select_related in django and want to use it in my view. However, I am not sure whether to use it in my query or not. My models: class Teacher(models.Model): name = models.OneToOneField(max_length=255, default="", blank=True) address = models.CharField(max_length=255, default="", blank=True) college_name = models.CharField(max_length=255, default="", blank=True) class OnlineClass(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) My view: def get(self, request,*args, **kwargs): teacher = self.request.user.teacher classes = Class.objects.filter(teacher=teacher) #confusion is here.............. serializer_class = self.get_serializer_class() serializer = serializer_class(classes,many=True) return Response(serializer.data,status=status.HTTP_200_OK) I have commented on the line or the section of the problem. So I wanted to list all the classes of that teacher. Here I have used filter. But can we use select_related here?? What I understood is if I want to show another fields of teacher model as well, for eg name or college_name, then I have to use it. Otherwise the way I have done it is correct. Also, select_related is only used for get api not for post api, is that correct?? -
Django process running tasks instead of Celery
I'm running an app with Celery+redis for asynchronous tasks. I managed to get Celery see the list of tasks. However my tasks aren't executed by Celery workers but by Django process instead. I tried invoking the tasks with .delay() and .apply_async() without success (actually in these cases the call to the task gets blocked indefinitely and nothing is shown in the logs). I might be missing something very basic but cannot see where. Relevant settings follow: settings.py CELERY_REDIS_DB = os.environ.get("REDIS_DB_CELERY", 0) CELERY_REDIS_HOST = os.getenv("REDIS_HOSTNAME", "redis") CELERY_REDIS_PORT = 6379 CELERY_RESULT_BACKEND = BROKER_URL = ( f'redis://{CELERY_REDIS_HOST}:{CELERY_REDIS_PORT}/{CELERY_REDIS_DB}' ) CELERY_TIMEZONE = TIME_ZONE CELERY_RESULT_EXPIRES = 5 * 60 * 60 celery.py from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'maat.settings') app = Celery('maat') # Using a string here means the worker don't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() tasks.py @shared_task def remove_task( environment=None, payload=None, **kwargs, ): LOGGER.info('Received task, now removing') ... views.py class MyClass( LoginRequiredMixin, PermissionRequiredMixin, SingleObjectMixin, APIView ): return_403 = True model = models.Environment slug_field = 'name' slug_url_kwarg = 'environment' def delete(self, request, environment): tasks.remove_task(environment=environment, payload=request.data) … -
How to pass broker_url from Django settings.py to a Celery service
I have Celery running as a service on Ubuntu 20.04 with RabbitMQ as a broker. Celery repeatedly restarts because it cannot access the RabbitMQ url (RABBITMQ_BROKER), a variable held in a settings.py outside of the Django root directory. The same happens if I try to initiate celery via command line. I have confirmed that the variable is accessible from within Django from a views.py print statement. If I place the RABBITMQ_BROKER variable inside the settings.py within the Django root celery works. My question is, how do I get celery to recognise the variable RABBITMQ_BROKER when it is placed in the ? My celery.py file: import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'backoffice.settings') app = Celery('mydjangoproject') default_config = 'mydjangoproject.celery_config' app.config_from_object(default_config) app.autodiscover_tasks() My celery_config.py file: from django.conf import settings broker_url = settings.RABBITMQ_BROKER etc... The settings.py in /etc/opt/mydjangoproject/ (non relevant stuff deleted): from mydangoproject.settings import * RABBITMQ_BROKER = 'amqp://rabbitadmin:somepassword@somepassword@webserver:5672/mydangoproject' etc... My /etc/systemd/system/celery.service file: [Unit] Description=Celery Service After=network.target [Service] Type=forking User=DJANGO_USER Group=DJANGO_USER EnvironmentFile=/etc/conf.d/celery WorkingDirectory=/opt/mydjangoproject ExecStart=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi start $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --loglevel="${CELERYD_LOG_LEVEL}"' ExecReload=/bin/sh -c '${CELERY_BIN} -A $CELERY_APP multi restart $CELERYD_NODES \ --pidfile=${CELERYD_PID_FILE} --logfile=${CELERYD_LOG_FILE} \ --loglevel="${CELERYD_LOG_LEVEL}" $CELERYD_OPTS' Restart=always [Install] WantedBy=multi-user.target … -
Duplicate Entry on Django
I seem to get duplicate entry or Integrity error when trying to create or update my entries . I have tried using objects.get_or_create() and objects.update_or_create(). Creating seems to work well when there is no record yet but somehow updating is just throwing some duplicate entry error. here is my views.py: def evaluate(request): r = [] i = [] a = [] s = [] e = [] c = [] for id in range(1,43): score = float(request.POST.get(f'{id}')) question = RIASEC_Test.objects.get(pk=id) if question.category == 'R': r.append(score) if question.category == 'I': i.append(score) if question.category == 'A': a.append(score) if question.category == 'S': s.append(score) if question.category == 'E': e.append(score) if question.category == 'C': c.append(score) r = (sum(r)/7) * 100 i = (sum(i)/7) * 100 a = (sum(a)/7) * 100 s = (sum(s)/7) * 100 e = (sum(e)/7) * 100 c = (sum(c)/7) * 100 name=request.user try: User=Riasec_result.objects.get(user=request.user) Riasec_result.objects.update(user=User,reality=r, investigative=i, artistic=a, social=s,enterprising=e, conventional=c) except ObjectDoesNotExist: result=Riasec_result.objects.create(user=name,reality=r, investigative=i, artistic=a, social=s,enterprising=e, conventional=c) result.save() # if (Riasec_result.objects.get(user=name)): # Riasec_result.objects.update(user=name, reality=r, investigative=i, artistic=a, social=s, enterprising=e, # conventional=c) # else: # result = Riasec_result.objects.create(user=name, reality=r, investigative=i, artistic=a, social=s, # enterprising=e, conventional=c) # result.save() return HttpResponseRedirect(reverse('riasec:home')) and this is my models.py: class Riasec_result (models.Model): class Meta: verbose_name = _('RIASEC Result') verbose_name_plural … -
htmx swapping element but the style not included
I'm learning to use htmx with Django, so I just built a simple Twitter app with a form and the tweet body. when you submit the form, the new tweet appears on top. post_list.html {% block post %} {% include 'snippets/post_list_tweet_box.html' %} <div class="infinite-container"> <div id="post-content"> {% include 'snippets/post_list_body.html' %} </div> <div class="d-flex d-none position-fixed" style="top:35vh;left:46vw;"> <button class="btn btn-primary loading" style="display: none;"> <span class="spinner-border spinner-border-sm"></span> Loading tweet... </button> </div> {% if post_list.has_next %} <a class="infinite-more-link" href="?page={{ post_list.next_page_number }}"></a> {% endif %} </div> {% endblock post %} post_list_body.html <style> ... </style> {% for post in post_list %} <div class="tweet-wrap infinite-item"> ... </div> {% endfor %} my view : class PostListView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' def get(self, request, *args, **kwargs): print("GET-HOME") posts = Post.objects.filter( author__userfollow__followers__in=[request.user.id] #Fix later ) form = PostForm(request.POST, request.FILES) share_form = ShareForm() posts = Post.objects.all().order_by('-created_on') post_list = [] for post in posts: comment = Comment.objects.filter(post=post).count() user = UserProfile.objects.get(account=post.author) is_like = False if request.user in post.likes.all(): is_like = True post_list.append((post,comment,user,is_like)) page = request.GET.get('page', 1) paginator = Paginator(post_list,10) try: post_pagination = paginator.page(page) except PageNotAnInteger: post_pagination = paginator.page(1) except EmptyPage: post_pagination = paginator.page(paginator.num_pages) context = { 'post_list': post_pagination, 'shareform': share_form, 'form': form, } return render(request, 'post/post_list.html', context) def post(self, … -
Fixtures Dumpdata Unable to serialize database: 'charmap' codec can't encode characters in position 3979-3980
I am trying to dump local-level data into the production-level database. However, Before I could, I got a headache running the dumpdata command for hours: Whenever I run the command python manage.py dumpdata <app_name>.<app_model> --format json --indent 4 --exclude auth.permission --exclude contenttypes > data.json , This only dumps a portion of model data to data.json, but not all the model instances. click here to see what data.json looks like. I don't know why I always get this kind of data. click here for traceback. In models.py from django.db import models import readtime from EHub.models import * from django.utils.translation import gettext_lazy as _ from django.utils.text import slugify from django.contrib.auth.models import User from django.urls import reverse from mptt.models import MPTTModel, TreeForeignKey from taggit.managers import TaggableManager from ckeditor_uploader.fields import RichTextUploadingField def article_image_directory_path(): return 'Articles/' class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return str(self.name) class IpModel(models.Model): ip=models.CharField(max_length=100,null=True) timestamp = models.DateTimeField(auto_now_add = True) def __str__(self): return str(self.ip) class Article(models.Model): options=( ('draft','Draft'), ('published','Published'), ) def get_absolute_url(self): return reverse('MArticles:article_detail',kwargs={'pk':self.id,'slug':self.slug}) visibilitymode=( ('private','Private'), ('public','Public'), ) class CustomManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(visibility = 'public' ,status = 'published') contenttype=models.CharField(default="Article", max_length=50) visibility = models.CharField(max_length=20 ,choices=visibilitymode, default="public", help_text="<p style='color:#b1b1b1;'>Private -> Only You can see this article.</p><p style='color:#b1b1b1;'>Public -> Anyone on the internet can … -
How to deploy label studio on Azure VM?
I want to deploy label studio annotation package to my azure VM. It is based on Django. I know how to deploy Django apps. But I was curious to know if there is any possible way to deploy it more efficiently. I am hesitant to try docker right now because I have one more Django app deployed on the same VM using Apache, and I fear using docker might break it. -
How to deal with nested serializer fields in Djnago rest framework?
I have nested serializer (AmountSerializer). I need field meal_name in one ViewSet. But when this field is nested i don't need it to be seen in endpoint(in MealSerializer). How to exclude field from nested serializer when is it actually nested? serializers.py: class AmountSerializer(serializers.ModelSerializer): ingredient_name= serializers.ReadOnlyField(source='ingredient_name.name') -->#meal_name = serializers.ReadOnlyField(source='meal.name') class Meta: model = IngredientAmount fields = ('ingredient_name','amount','meal_name') class MealSerializer(serializers.ModelSerializer): type_name= serializers.ReadOnlyField(source='type.name') ingredients = serializers.SlugRelatedField(read_only=True, slug_field='name', many=True) amount = AmountSerializer(read_only=True, many=True,source='meal_id') class Meta: model = Meal fields = ('id', 'name', 'type_name', 'recipe', 'photo', 'ingredients','amount') -
Django Admin one field required related on other field
I am using Django admin to save models my model is like bellow: class PurchaseItem(models.Model): product=models.ForeignKey("products.Product",on_delete=models.CASCADE,blank=True,null=True) product_attribute=models.ForeignKey("products.ProductAttribute",on_delete=models.CASCADE,blank=True,null=True) The goal is to save only one of the foreign keys for example : If the product is not null then the product attribute needs to be null Same thing for the product_attribute if its not null then the product must be null Note: product and product_attribute cannot be null at the same time . how to achieve this using the Django admin. -
Django App to read QR code URL and display image on website
I am creating a django that displays different images on a website when their respective QR codes are scanned. Its my first time working with Django and I am unsure how to update the index page to display the image when the QR code is scanned. I would like to add a URL route that should make the image visible when the QR code is scanned but I am unsure how to carry out that logic in django. views.py def index(request: HttpRequest) -> HttpResponse: return render(request, "index.html") # template = loader.get_template('index.html') # return HttpResponse(template.render({}, request)) urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ # path('admin/', admin.site.urls), path("", views.index, name="index") ] index.html {%extends 'base.html' %} {% load static %} {% block title %} Home {% endblock %} {% block content %} <div class="grid-container"> <figure class="gallery__item gallery__item--1"> <img id="image1" src="{% static 'theme/assets/img/Freesample.svg' %}" class="gallery__img" alt="Image 1"> </figure> </div> {% endblock %} scripts.js function setImageVisible(id, visible){ var img = document.getElementById(id); img.style.visibility = (visible ? 'visible' : 'hidden'); } -
append the char field in django models
I have a simple choice field in my model which saves present or absent of a student for his/her attendance. However, what I felt is, it will create different object for just a status of his/her attendance. Is there any way to just append present or abset to the same field to save the resource of the database?? My models look like this: class OnlineClass(models.Model): teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE) course = models.ForeignKey(Subject,on_delete=models.CASCADE) faculty = models.CharField(max_lenthg=255) students_in_class = models.ManyToManyField(Student) STATUS = ( ('present','present'), ('absent','absent'), ) class Attendance(TimeStampAbstractModel): classes = models.ForeignKey(OnlineClass) student = models.ForeignKey(Student) status = models.CharField(choices=STATUS, max_length=10, blank=True) By using this model, there will be different object of attendance for each student of each course which will be consuming huge resources. Instead what I want is just append present or absent for each day of attendance to the status field just like django-taggit. So that when I call get api, I will be getting like a list of attendances.Is it possible?? -
wanted call store procedure from another store procedure and returning output on HTML page with python django
I have totally 3 store procedures 1)notification_services(email_template_id,execute_date,record_no) passing this parameter I got output having 'script_coloum' which contain another store procedure. 2)sp_get_email_services_project_assigned 3)sp_get_email_services_project_rejected these 2 and 3 store procedure selection depends upon notification_services(email_template_id) if email_template_id=1 call sp_get_email_services_project_assigned if email_template_id=2 call sp_get_email_services_project_rejected According this result should be display on HTML page ############################################################################################## from typing import List from django.db.backends.utils import CursorDebugWrapper from django.http.response import HttpResponse from django.shortcuts import render import os from django.db import connection from rest_framework import generics from demo_sp.serializers import StoredProcedureSerializer #from mysql.connector import MySQLConnection,Error #from python_mysql_dbconfig import read_db_config # def show_details(request):#email_template_id #wk # return render (request,'sp_app/html_template.html')#{'id':email_template_id} #from django.http import HttpResponse def common(self,script=[],request=[]):#self, request=None, print("IN common Function") #assigned if script==[]: #user_name = self.request.GET.get('user_name') print(115) with connection.cursor() as cursor: print(116) cursor.callproc('sp_get_email_services_project_assigned',['user_name','project_name','city_name','toll_free_no','help_desk_email']) #result=cursor.fetchall() data=StoredProcedureSerializer(cursor).data if type(data)==dict and not data: data=[] print("uuuuuuuuuuu=",data) #return data return render(request,'sp_app/html_template.html',{"data":data}) #reject if script=='116': with connection.cursor() as cursor: cursor.callproc('sp_get_email_services_project_rejected') data=StoredProcedureSerializer(cursor).data result=cursor.fetchall() return result #return render(request,'sp_app/html_template.html',{'result':result}) #<-------------------------------------------------------------------------------------------> class gettemplate(generics.ListCreateAPIView): print(1) def get(self, request, *args, **kwargs): print(2) email_template_id = self.request.GET.get('email_template_id') print(email_template_id) execute_date =self.request.GET.get('execute_date') print(execute_date) record_no =self.request.GET.get('record_no') print(record_no) if not email_template_id : raise Exception("Please enter valid template ID") if not execute_date : raise Exception("Please enter valid execute_date") if not record_no : raise Exception("Please enter valid record_no") with connection.cursor() as cursor: cursor.callproc('notification_services',[email_template_id,execute_date,record_no]) data=StoredProcedureSerializer(cursor).data … -
How can I reduce the deep learning model inference inside Django server
I have a Pytorch vision model which takes <4 seconds for performing inference on a image on CPU when calling as a standalone python program or calling from Django as a subprocess, but when the same inference method is called from Django server inside view.py methods, the time for performing inference is >50 seconds. How can I solve this issue. Tried the following inside Django view import sys import subprocess sys.path.append('/home/ubuntu/project/driver/') def process_pool(file_path): return main.process(file_path) def predict(request): file_path = get_path(request) cmd = '/home/ubuntu/project/driver/main.py' print(subprocess.check_output(['python',cmd])) # Method 1 Using python subprocess - Takes 4 seconds to infer the output pr = multiprocessing.Pool() result = pr.map(process_pool,[file_path]) # Method 2 Using multiprocessing - Takes more than 50 seconds to infer the output process_pool(file_path) # Method 3 - Without multiprocessing - Takes more than 50 sec to infer the output The project main.py contains def process(file_path): """ run deep learning code """ return predict(file_path) if __name__ == '__main__': process('/home/ubuntu/a.jpg') -
Django: 'WSGIRequest' object has no attribute 'Post'
Im kinda new to Django and already stuck at some simple POST-problem. Heres the HTML within profile.html: <form action="{% url 'profile' %}" method="post"> {% csrf_token %} <input type="text" placeholder="Weight", name="weight"> <input type="text" placeholder="Reps", name="reps"> <input type="submit"> </form> And heres the correspoding view: def profile(request): if request.method == "GET": return render(request, "userprofile/profile.html") elif request.method == "POST": print(request.Post) return render(request, "userprofile/profile.html") Basically, all I want to do for now, is to print the POST-data dictionary into the Terminal. However, I get the following error: AttributeError at /profile/ 'WSGIRequest' object has no attribute 'Post'. What am I missing? Thanks so much for any help! -
How do I fix no module found error in Django?
I'm reading the Django docs and I'm going through the first project called "mysite" and it has an app called polls This is my file structure : \pythonproject \mysite \mysite \polls \migrations __init.py__ admin.py apps.py models.py tests.py urls.py views.py __init__.py db.sqlite3 manage.py I am in this location : polls\urls.py and I want to import "polls\views.py" So I type in this : from mysite.polls import views And I get the error when I ran: python manage.py test This is the error : No module found "mysite.polls" The error refers to the second line of code in polls\urls.py I am using pycharm and my Django version is "3.2.8" My python version is "3.10" -
why is the form works in "is_valid" but doesn't update objects?
I'm trying to update this field, when I do "forms.is_valid" and print anything into it like print("updated") as you can see below, this print works fine which means that "is_valid()" produce a "True" value, however, nothing is updated in a database then. anyone can help please: views.py def review_membership(request, id=None): roles = str(User.objects.get(email=request.user).roles.get()) membership = MemberShip.objects.get(id=id) user_admin = User.objects.get(roles__id='Admin') forms = MemberShipForm() disable_field = True if request.user.email == membership.ambassador.email: disable_field = False if membership.status == "Pending": if roles == "SubAmbassador": if restrict_see_report(request) == True: field_disabled(forms) if request.method == "POST": if "update" in request.POST: forms = MemberShipForm(request.POST) # print(User.objects.get(email=membership.ambassador)) if forms.is_valid(): forms.instance = request.user print('updated') forms.save() messages.success(request, 'This field has updated') return redirect('index:review_membership', membership.id) forms.py class MemberShipForm(forms.ModelForm): name = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Name', 'class': 'form-control'})) price = forms.IntegerField(widget=forms.NumberInput(attrs={'value': 0, 'class': 'form-control'})) description = forms.CharField(widget=forms.Textarea(attrs={'placeholder': 'type a description here...', 'class': 'form-control'})) class Meta: model = MemberShip fields = ['name', 'price', 'description'] models.py class MemberShip(models.Model): name = models.CharField(max_length=20, blank=False) description = models.TextField(blank=False, null=True) price = models.PositiveIntegerField(default=0) ambassador = models.ForeignKey(User, on_delete=models.CASCADE, null=True) sub_ambassador = models.ForeignKey(SubAmbassador, on_delete=models.CASCADE, null=True, blank=True) status = models.CharField(max_length=20, choices=MEMBERSHIP_STATUS, default='Inactive') def __str__(self): return self.ambassador.email def get_status(self): return self.status -
django-rest-framework-social-oauth2: error 400 - redirect_uri_mismatch
I've been trying to add google login to my django app following this tutorial: https://github.com/RealmTeam/django-rest-framework-social-oauth2 By following exactly the instructions, everything works fine in local. However, when I try to replicate the same on the server, I get the following error on the redirect page of the login: Error 400: redirect_uri_mismatch redirect_uri: http://localhost:8000/auth/complete/google-oauth2/ What is strange to me is, in my google developer console, I have set up the correct redirect url in my app, as follows: https://mydjangoapp.com/auth/complete/google-oauth2/ And I have also put 'mydjangoapp.com' under 'Authorised JavaScript origins'. So my question is, why google keeps telling me that the redirect url is http://localhost:8000/auth/complete/google-oauth2/ which is not the one I have set up in the console? Perhaps there is something obvious that I'm missing here. Thank you! -
Charts not being displayed in django app when using Chart.js 3.6 version
I have a Django application which has charts. They were implement in Chart.js 2.9 version. When I upgraded to Chart.js 3.6 version, I am unable to view the charts. I have check those charts in a standalone HTML page. They work fine there. -
Error 32 when Twitter sign in with Django AllAuth and post tweet with Tweepy
I'm using Django AllAuth for twitter login, and it's working perfectly and saving the token and token secret to the Social Account Tokens table. I'm then trying to use Tweepy to send a tweet on the user's behalf (yes, the scope allows that). But when I try to send the tweet, I get tweepy.error.TweepError: [{'code': 32, 'message': 'Could not authenticate you.'}] Here's the auth code: def auth_tweepy(user): twitter_auth_keys = settings.TWITTER_AUTH_KEYS auth = tweepy.OAuthHandler( twitter_auth_keys['consumer_key'], twitter_auth_keys['consumer_secret'] ) user_auth = SocialToken.objects.get(account__user=user, account__provider='twitter') auth.set_access_token( user_auth.token, user_auth.token_secret ) return tweepy.API(auth) def send_tweet(tweet_content): api = auth_tweepy(user) try: api.update_status(tweet_content) except tweepy.TweepError as error: if error.api_code == 187: print('duplicate message') I dont think the tokens are expired bc I JUST logged in. Any ideas what might cause the 32 error in this case?