Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework + Simple JWT - Retrieve saved refresh token from access token?
I am trying to retrieve the pair Access/Refresh token using the access token as the input. Since I'm using the JWT Blacklist, I figured out that I can easily retrieve a list of all refresh tokens by a user id (which I can decode from the access token), but I could not find a way to retrieve the Refresh token that was generated for this specific access token. Any ideas? -
Django-Debug-Toolbar not showing(disallowed MIME type)
i install django-debug-toolbar 3.2.2 and configure it step by step by Installation Django Debug Toolbar my templates is just hello.html <html> <body> <h1>Hello {{ name }}</h1> </body> </html> at the end, when i type python manage.py runserver Django Debug Toolbar not show up. but in concole i see this Loading module from “http://127.0.0.1:8000/static/debug_toolbar/js/toolbar.js” was blocked because of a disallowed MIME type (“text/plain”). python 3.8.8(base on anaconda) Django 3.2.7 windows 10 what's going on? -
Django 3.2 how to redirect 404 to homepage
I did find a number of answers about 404 redirect for Django but mostly are referring to an older version of Django. Here is what I have in Django 3.2.6 DEBUG is set to False to trigger the 404 behaviour urls.py handler404 = views.view_404 views.py def view_404(request, exception=None): return HttpResponseRedirect("/") No error in runserver but a 404 page still returns "Not Found The requested resource was not found on this server.". -
Status disappear if updated while scripts is running (read and write simultaneously doesn't happen)
While this script runs if any product is marked critical then it doesn't get updated instead reset back to not critical so, how to perform read and write operation simultaneously? def get_latest_comment_from_xsite( curs, how_far_back ): print "starting app get latest comment after %0.2f seconds" % ( time.time() - start ) # minutes_back = 24*60 print "Going back %0.2f minutes" % (how_far_back) sql = """ WITH ORDERED AS ( SELECT eh.equipmentname, to_date(eh.time,'YYYYMMDD HH24MISS\"000\"') AS \"TIME\", NVL(eh.workordernumber,eh.workrequestnumber ) AS \"WORKORDERNUMBER\", eh.username, DBMS_LOB.SUBSTR(ec.detaildescription,1700,1) AS \"COMMENTTEXT\", ROW_NUMBER() OVER (PARTITION BY eh.equipmentname ORDER BY eh.equipmentname ASC) AS rn FROM FwEqpHistory eh, FwEqpComment ec WHERE ec.sysId (+) = eh.eqpComment AND ec.detaildescription NOT LIKE 'Marked as critical%' AND ec.detaildescription NOT LIKE 'Removed from critical%' AND eh.time > TO_CHAR(sysdate - {0}*((1.0/24.0)/60.0),'YYYYMMDD HH24MISS')||'000' ORDER BY 1, 2 desc) SELECT * FROM ORDERED WHERE rn = 1""".format(how_far_back) print sql curs.execute(str(sql)) comments = curs.fetchall() print "Collected app Data after %0.2f seconds" % ( time.time() - start ) for row in comments: tool_id, comment_time, wo_number, user_id, comment_text, row_num = row print tool_id + ' ' + str( comment_time) + ' ' + user_id + ' ' + comment_text try: status = CurrentStatus.objects.get(table_name = tool_id) if ( status.title_updated_at == None or status.title_updated_at < … -
How to deploy react-django project with a react app inside the django api?
I have a django app with two django apps inside it, one is an api and other is a frontend app which has a react app made inside it. How do I deploy it to heroku? If I specify a buildpack that includes nodejs, the package.json is not in the root directory [it's inside the child django app]. I tired just copying out the child django app and pasting it in root directory. But it gives this error: Field 'browser' doesn't contain a valid alias configuration -
How delete column in database [Django]
hi i'm working on a project with django but i'm having some problem in deleting 2 columns from the table. I deleted the columns in question in the initial.py and models.py files. Then when I execute the command "python manage.py makemigrations" the terminal replies in this way: File "C: \ Users \ Marco \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ site-packages \ django \ urls \ conf.py", line 34, in include urlconf_module = import_module (urlconf_module) File "C: \ Users \ Marco \ AppData \ Local \ Programs \ Python \ Python39 \ lib \ importlib \ __ init__.py", line 127, in import_module return _bootstrap._gcd_import (name [level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C: \ Users \ Marco \ Desktop \ REAL4 \ ecomapp \ urls.py", line 2, in <module> from .views import * File "C: \ Users \ Marco \ Desktop \ REAL4 \ ecomapp \ views.py", line 12, in <module> from .forms import * … -
GIS - Can i have multple geo_fields (point, polygon, line) in 1 model and then serialize with DRF?
If I have 1 model with 3 different geo_fields in (point, poly and line), can I serialize all of these with django-rest-framework-gis? My model: class Job(BaseModel): name = models.CharField(max_length=64) desc = models.CharField(max_length=64) loc_poly = models.PolygonField(blank=True) loc_polyline = models.LineStringField(blank=True) loc_point = models.PointField(blank=True) user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True) Can I serialize by doing something like: class JobSerializer(GeoFeatureModelSerializer): class Meta: model = Job geo_field = ("loc_point", "loc_polyline", "loc_poly") fields = ('__all__',) Basically can I have geo_field to be multiple geo fields? Or is this only 1? -
Django cms not updating the page type
I am trying to create the Page Type and use it in the pages, and I can create it and use it in the pages at the time of creating the pages. But after the creation of the Page, I cant update the Page Type. -
Celery task and python function debug together
I have a Test class in the SampleFIle.py file that looks like this: Class Test: def m1(): import ipdb; ipdb.set_trace(); # Some logic In the same file I have a celery task that looks like this: @shared_task() def m1_task(): from celery.contrib import rdb rdb.set_trace() # some logic But The rdb break after the function returns. It doesn't go and checks what m1() contains. How can I debug both celery tasks and related functions for a better understanding of coding flow? -
I need has_perm() example for AbstractBaseUser in django
I have a Custom User Model, and I need to give permissions to users with certain roles (fields in user model) but I couldn't find any examples on the internet, so I'm asking for examples from anybody who has done this before. Here's my Abstract user model for reference: class User(AbstractBaseUser, PermissionsMixin): class RoleChoices(models.TextChoices): admin = 'Admin', _('Admin') cashier = 'Cashier', _('Cashier') waiter = 'Waiter', _('Waiter') courier = 'Courier', _('Courier') customer = 'Customer', _('Customer') username = models.CharField(_('username'), unique=True, max_length=100) name = models.CharField(_('name'), max_length=100) surname = models.CharField(_('surname'), max_length=100) phone_number = models.CharField(_('phone_number'), max_length=100, null=True, default='Invalid Phone Number') role = models.CharField(max_length=50, choices=RoleChoices.choices, default=RoleChoices.customer) active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'surname'] class Meta: ordering = ['date_joined', ] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return self.active objects = CustomUserManager() Thanks in advance, and Please excuse any grammatical errors. -
Error Apollo Client local resolver handling has been disabled and 400 Bad Request
I use GraphQl to access and set JWT token into Authorization Header, but it issues 2 errors, i have done every thing but I cannot resolve and fix it. const client = new ApolloClient({ uri: "http://localhost:8000/graphql/", fetchOptions : { credentials: "include" }, request: operation => { const token = localStorage.getItem('authToken') || ""; operation.setContext({ headers: { Authorization: `JWT ${token}` } }); }, clientState : { defaults: { isLoggedIn: !!localStorage.getItem('authToken') } } }); Dev tools warning that: Found @client directives in a query but no ApolloClient resolvers were specified. This means ApolloClient local resolver handling has been disabled, and @client directives will be passed through to your link chain. POST http://localhost:8000/graphql/ 400 (Bad Request) -
Why {{ form }} represents a form instance in template file?
According to django official doc, All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its <label> and <input> elements appropriately. Where is the form instance named/defined as form for template context in django source code? and How can I change the name to something else {{ my_form }} for example ? -
Django - Get urls of all images that reference a Post?
I have this model where a Post can have many Photos. I'm trying to retrieve all posts, including ImageField url attribute (according to Django docs FileField and ImageField have a url attribute). So I'd like to ideally return all the urls of the images associated with the post (ideally in order of created). model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) class Photo(AbstractBaseModel): created = models.DateTimeField('Created at', auto_now_add=True) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=directory_path) view.py def get(self, request): data = Post.objects.order_by('created').values('body', 'goal_id__description', 'created', 'creator_id__username', replies=Count('replypost'), cheers=Count('cheerpost'), image_urls='photo__image_url') return Response(list(data), status=status.HTTP_200_OK) -
how to use django Serializer to update an instance
in Django PUT method, I want to update an instance: sv= SV.objects.get(pk=pk) serializer = SVSerializer(sv, data=request.data) if serializer.is_valid(): Here, in request.data, I just want to pass some of the variable of SV. But as some fields missing, the is_vaild will be false. What I want is, just update the fields in request.data, for the other ones, keep the value in sv. How could I do that? -
Django filter model based on max date
I have a model Drugs with following entries : id location num date country 1 UC ABC 2021-03-26 ZAF 2 UC DEF 2021-03-26 ZAF # line to retrieve with filter 3 UC ABC 2021-09-06 ZAF # line to retrieve with filter I want to select record based on max date for a combinaison loc - num - date for example, in the test case above, I want to only return the laste 2 records as id 3 is more recent than id 1 -
Model form data not showing up in database. Form not saving data
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly. ps. I've connected my database, ran migrations and created a superuser as well but still nothing. models.py from django.db import models Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' views.py from django.shortcuts import redirect, render from django.http import HttpResponse from .forms import AppsForm from .models import Appear def AppS(request): if request == 'POST': form = AppsForm(request.POST) if form.is_valid(): Apps = form.save(Commit=False) Apps.save() … -
Rendering multiple views and documents based on user settings
I am currently creating a settings menu to figure out what "type" of trial balance a user would like to pull and whether they would want to preview it , print it to pdf or print it to excel My code looks like this... Views.py: def home(request): return render(request , 'main/home.html') def KyletrbSettings(request): if request.GET.get('Excel'): return redirect('main/pdf-trialbalance.html') if request.GET.get('PDF'): return redirect('main/pdf-trialbalance.html') if request.GET.get('Preview'): return redirect('main/Kyletrb.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Debit"] = row[2] rdict["Credit"] = row[3] xAll_l.append(rdict) creditTotal = ' Select ROUND(SUM(Credit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(creditTotal); xCreditTotal = cursor.fetchone() debitTotal = ' Select ROUND(SUM(Debit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(debitTotal); xDebitTotal = cursor.fetchone() return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all … -
Django - how to match URL pattern regex with additional parameters?
I have the following endpoint at my urls.py url(r'^stream/(?P<pk>[0-9a-f-]+)$', App_Views.stream, name='stream'), That would mean that the endpoint would look like this on call: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156 Now I'm adding some extra parameters to the URL before calling it, so that it looks like this: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156?st=zD3H0cHJrbcUAHZPNbPGyg&e=1630915404 Now to my actual question, how does the regex at urls.py has to look like in order to accept the second URL example? Already dealing with this since 2 days and was not able to find a solution. Thanks in advance -
How to retrieve the .count in a django template through ManyToManyField
I have some models, which are connected via manytomany or foreignkey. I would like to get a .count value for tutor.students.lessons.type and display the number of lessons online or class based. I have tried to pass in tuttype= tutorObj.students.get(type="CLASS") through the views which does not get the required result and have been trying out {{tutorobj.students.type.ONLINE.get}} {{tutorobj.students.get(type=ONLINE)}} in the templates with no luck also models.py class Tutor(models.Model): name = models.CharField(max_length=200, null=True, blank=True) students = models.ManyToManyField('Student', blank=True) lessons = models.ManyToManyField('Lesson', blank=True) lesson_reviews = models.ManyToManyField('LessonNote', blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) def __str__(self): return self.name class Student(models.Model): GENDER_CHOICES = ( ('M', 'Male',), ('F', 'Female',) ) TYPE_CHOICES = ( ('CLASS', 'Class',), ('ONLINE', 'Online',) ) YEAR_CHOICES = ( ('K1', 'Kindergarten 1',), ('K2', 'Kindergarten 2',), ('K3', 'Kindergarten 3',), ('P1', 'Primary 1',), ('P2', 'Primary 2',), ('P3', 'Primary 3',), ('P4', 'Primary 4',), ('P5', 'Primary 5',), ('P6', 'Primary 6',), ('M1', 'Mathayom 1',), ('M2', 'Mathayom 2',), ('M3', 'Mathayom 3',), ('M4', 'Mathayom 4',), ('M5', 'Mathayom 5',), ('M6', 'Mathayom 6',), ('C', 'College',), ('U', 'University',), ('A', 'Adult',), ) taught_by = models.ForeignKey(Tutor, on_delete=models.SET_NULL, null=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) school_year = models.CharField(max_length=2, choices=YEAR_CHOICES, null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True, blank=True) hours_weekly = … -
How to connect Google Sheets with PostgreSQL database in a server?
So I have a server with a Django backend using PostgreSQL, but now I need to connect the database to this Google sheet to add on to the current database. How do I do this? I did some research and installed the KIPbees addon in Google Sheets. However, I do not know what the hostname for the database should be. -
how does django class based view cycle go around?
got request a worker initialize a class based view instance returns a response and destroies the view instance or view instance is initialized when server starts up workers wait in queue to get response and returns a response from view instance view instance lives forever I suddenly came to realize that i've been using Django for several years and still don't know how it works so.. which one is it? Thanks -
Django - How to properly receive multi-image upload via POST?
I have this view.py and models.py files below that supposed to support uploading multiple images. I have tests that work and do generate images, but the images are attached to the POST request as a ByteIO format. I'd like this endpoint to receive a POST request from a React Native front-end containing an image and I don't know if it'll be in ByteIO format. I tried sending an image in byte format by doing with open('./media/test.png', 'rb') as f: image = f.read() But it turns the QueryDict that is request.data into an immutable dict for some reason. As you can see below that's an issue as I do change it. Is the way I've implemented it correct for receiving multiple image uploads from React Native? view.py class PostView(APIView): def post(self, request): post_body = request.data['body'] hash_tags_list = extract_hashtags(post_body) hash_tags = [HashTag.objects.get_or_create( hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags serializer = PostSerializer(data=request.data) if serializer.is_valid(): try: post_obj = serializer.save() if 'images' in request.FILES.keys(): for img in request.FILES.getlist('images'): Photo.objects.create(post_id=post_obj, image=img) except django.db.utils.InternalError as e: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = … -
How to upload image/media file from React to Django API?
I am able to save the data without the image field. I am new to react so don't know pretty much about this type of problems. What is the problem with the image field?? this isn't showing me any error just my image data is not saving. I am sharing all my code it will be really helpful if you guys help me out. #models.py class Test(models.Model): full_name = models.TextField(max_length=200, blank=True, null=True) image = models.ImageField(null=True, blank=True) address = models.TextField(max_length=200, blank=True, null=True) def __str__(self): return str(self.id) #views.py @api_view(['POST']) def add(request): data = request.data test = Test.objects.create( full_name = data['full_name'], address = data['address'], ) serializer = TestSerializer(test, many=False) return Response(serializer.data) #this is screen for react page import React from 'react'; class Test extends React.Component{ constructor(){ super(); this.state={ full_name:'', image: '', address:'' } this.changeHandler=this.changeHandler.bind(this); this.submitForm=this.submitForm.bind(this); } // Input Change Handler changeHandler(event){ this.setState({ [event.target.name]:event.target.value }); } // Submit Form submitForm(){ fetch('http://127.0.0.1:8000/api/orders/test',{ method:'POST', body:JSON.stringify(this.state), headers:{ 'Content-type': 'application/json; charset=UTF-8', }, }) .then(response=>response.json()) .then((data)=>console.log(data)); this.setState({ full_name:'', image: '', address:'' }); } render(){ return ( <table className="table table-bordered"> <tbody> <tr> <th>Full Name</th> <td> <input value={this.state.full_name} name="full_name" onChange={this.changeHandler} type="text" className="form-control" /> </td> </tr> <tr> <th>Voucher</th> <td> <input value={this.state.image} name="image" onChange={this.changeHandler} type="file" className="form-control" /> </td> </tr> <tr> <th>Address</th> <td> <input … -
why the user is not logged in after registration in django
views.py ( after registration it is not logged in , can anyone help me to solve why this is happening there after successfully creating user but not logged in by user. User creates table in data base successfully and register consider all the required added def login_view(request): if request.method == "POST": # Attempt to sign user in email = request.POST["email"] password = request.POST["password"] user = authenticate(request, username=email, password=password) # Check if authentication successful if user is not None: login(request, user) return redirect('home') else: return render(request, "login.html", { "message": "Invalid email or password." }) else: return render(request, "login.html") models.py ( consider all required install or added ) class User(AbstractUser): G = [ ('Female', 'Female'), ('Male', 'Male'), ('Others', 'Others'), ] address = models.TextField(max_length=50 ,default='' ,null=True,blank=True) phone = models.CharField(max_length=15 ) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) Gender = models.CharField(max_length=150,choices=G ,default='',null=True,blank=True) def __str__(self): return self.email def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return User.objects.get(email=email) except: return False def isExists(self): if User.objects.filter(email = self.email): return True return False is_staff = models.BooleanField(('Staff status'),default=True,) is_active = models.BooleanField(('Active'),default=True,) login.html ( where user can logged but not working ) <div class="loginContainer"> {% if message %} <div><i>{{ message }}</i></div> {% endif %} <div class="login__form"> <h2>Login</h2> <form action="{% url 'login' … -
django.db.utils.ProgrammingError: relation "Industry" does not exist // LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR
enter image description here enter image description here django.db.utils.ProgrammingError: relation "Industry" does not exist LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR...