Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly configure authentication views? (Django)
There are two views index and index1 and my login view is def loginview(request): if request.user.is_authenticated: return redirect('index') else: return redirect('index2') urls.py urlpatterns = [ path('',loginview,name="login"), path('index/',index,name="index"), path('index2/',index2,name="index2"), ] The code works but I want to only access index and index2 after the user is logged on or logged out. When I navigate to localhost:8000/index and localhost:8000/index2, the page directs to the respective pages. How to restrict authorization on these pages? -
objects are not crated through cmd django python
>>> from sabin.models import Task >>> Task.objects.all() <QuerySet []> >>> t=Task(title="dhiraj") error Traceback (most recent call last): File "", line 1, in File "C:\Users\Dhiraj Subedi\ero\lib\site-packages\django\db\models\base.py", line 503, in init raise TypeError ("%s() got an unexpected keyword argument '%s'" % (cls.name, kwarg)) TypeError: Task() got an unexpected keyword argument 'title' models.py file from django.db import models class Task(models.Model): title:models.CharField(max_length=200) completed=models.BooleanField(default=False) created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.title -
Django @ mention user using Django Custom Tags
Hey guys I'm trying to mention a user in the database and have the post return with the username @whatever as a hyperlink in the original post. I seem to be getting an error where I either get the last word of the post only or if I mention just a user I get the url plus the username back as html code the same way I have it in the code. I'm so close to getting but for the life of me can't figure out why it's not returning it correctly. What am I doing wrong? And THANK YOU SO MUCH in advance. I am trying to use the solution that was found here. I get the url with the username but I just want the username plus the original post For example if the post in the database is "hello @faces how are you doing?" I would like to get back the post just as it is but with the user @faces as a hyperlink to the users profile. This is my custom tag from the custom templates that I am using. In the terminal I see that it is finding the user if it's in the database … -
when I run this code and click on signup there is an error
from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth from django.contrib import messages def register(request): if request.method == 'POST': first_name = request.POST['first_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1==password2: if User.object.filter(username=username).exist(): print('username taken') elif User.objects.filter(email=email).exists(): messages.info(request,'email Taken') return redirect('register') else: User = User.objects.create_user(first_name=first_name,username=username,password1=password1,email=email) User.save(); print('user created') return redirect('register') else: print('password not matching') return redirect('register') return redirect('/') else: return render(request,'register.html')[error that I face][1] enter code here enter image description here -
Match Question Mark character in Legacy Path
The following allows me to match surname/Smith and surname.php/surname=Smith but I wish to match surname.php?surname=Smith instead of the latter so as to ensure that people using the old links can still find the info they are after. How should I do this? from django.urls import path, re_path from . import views urlpatterns = [ path('surname/<str:surname>/', views.surname, name="surname"), path('surname.php/surname=<str:surname>',views.surname), ] -
Authentication with google auth , jwt token, django rest framework, nextj
How can I implement authentication system using Django Rest Framework backend and Next js frontend for google oauth (social auth) with jwt token ? -
How to download large file from Cloud Run in Django
I have Django project on Cloud Run. When I download small file from page which has below code. def download_view(request,pk): file_path = f'media/{pk}.mp3' name = f'{pk}.mp3' with open(file_path, 'rb') as f: response = HttpResponse(f.read(), content_type='audio/wav') response['Content-Disposition'] = f'attachment; filename={name}' return response It's works fine. However, when I download a file (50MB). I got this pictures error. Cloud run's log is like this. I couldn't find any log of traceback. 2021-05-06 12:00:35.668 JSTGET500606 B66 msChrome 72 https://***/download/mp3/2500762/ 2021-05-06 11:49:49.037 JSTGET500606 B61 msChrome 72 https://***/download/mp3/2500645/ I'm not sure. Is this error related with download error. 2021-05-06 16:48:32.570 JSTResponse size was too large. Please consider reducing response size. I think this is upload file size error. So this is not related with this subject of download error. When I run Django at local, then download same 50MB file. I can download it. I think this download error related with Cloud run. It's stop after request/response. So I think this error coused by Cloud Run. Which was stoped, when I'm still downloading file. I don't know how to solve this download error. If you have any solution, please help me! -
How to auto create a new row in a table every day or according to date django
modaly.py class User(modals.Modal): name = models.CharField(max_length=30) class Traffic(models.Model): my_user = models.ForeignKey(User, on_delete=models.CASCADE) per_day_user_visit = models.PositiveIntegerField(null=True, blank=True) traffic_date = models.DateField(auto_created=True) id my_user per_day_user_visit traffic_date 1 instance 500 user_visit monday 2 instance 512 user_visit tuesday views.py Auto created a new row, when new day come if newday: Traffic.objects.create(my_user = "1", per_day_user_visit = "512", date=datetime.now()) -
CSRF verification failed in admin panel
I'm deploying my web-site on Apache web-server. Also I have a Single Sign-On authentication with django-remote-auth-ldap library. Everything works directly on the site itself, but when I go to the admin panel and try to change something, an error occurs: 'Forbidden (403) CSRF verification failed. Request aborted'. By the way, in the localhost is working fine. Can you please help me with this thing? I'm actually stuck with this for a week or so. Thank you -
How do I create a multidimensional table in SQL? Or should I use some other DBMS?
I want to use a DB for creating languages (as a hobby), and I went with SQLite. Of course, to save myself some trouble, I decided to write myself a user-friendly interface in the form of a web-app using Django. I already got sa few pages up. Then I stumbled upon this issue that I need to be able to somehow store in my DB that, e.g., a verb has the categories of Mood, Tense, Gender, Person and Number, with Number only relevant for Indicative Mood; Person only relevant for Indicative Mood, Present and Future Tenses; and Gender only relevant for Indicative Mood, Past Tense, Signular Number. Basically, I need to be able to check the values of each category (like Mood, Tense, Gender, Person, Number, so forth) against the values of every other category, and I need this to be as flexible as possible because grammatical geometry of every language is very differnet and I want to be able to reflect that in my DB. I guess what I'm looking for is a multidimensional table, where every dimension is a separate category, but I'm not sure how to do that using SQLite, with the means of Django no less. … -
How i can manage Chat system between my React(front-end) and Django (back-end)
I am working on a chat application, in which I'm gonna use React for the Front-end and Django as the back-end. Note: Both are on different servers. Everything will work through the APIs. I want to know how I can establish a connection between React and Django so I can get real-time messages and display them to the user. Should I use socket.io-client in my React app and Django-channels in my Django app.??? or is there any other way to do this?? And Instagram and other Companies that are using these both stack, how they are doing this stuff??? Please answer ... Kind Regards, Huzaifa -
Error while changing a Char field to Array Field in Django
I am trying to change a existing CharField in a django model (it also allows null and contains null values in db currently) now I am trying to change it to an Array Char Field, but it throws the below error "django.db.utils.IntegrityError: column "tags" contains null values" From tags= models.CharField(max_length=255, blank=True, null=True) To tags = ArrayField(models.CharField(max_length=255, blank=True, null=True)) I have selected option 2 while before running migrate -
Django Redirect: No errors, but no redirect
I POST some data via an HTML form using AJAX to modify data in my database. The data is successfully modified by executing stored procedures on the DB. Final line of the view.py function call is return redirect('Home'). The redirect is successfully executing, but I am not being redirected. I can overcome this by adding window.location.href = 'http://127.0.0.1:8000/ in the success function of the AJAX call. The problem is, I want to use messages.success(request, 'Data Successfully Updated'), which only appears after refreshing the AJAX-originating redirect. Is there a reason why return redirect('Home') is not working here, and is there a way to overcome this? Home is the name of my path in urls.py [06/May/2021 17:23:52] "POST /search/ HTTP/1.1" 302 0 // submitting changes to database [06/May/2021 17:23:55] "GET / HTTP/1.1" 200 4750 // The page I am intending to redirect to Ajax Call function updateCards(){ ajaxUpdCard().done() function ajaxUpdCard() { return $.ajax({ type: 'POST', url: '', data: {csrfmiddlewaretoken: window.CSRF_TOKEN, Action: 'Card', CardID: $('#currentCardID').val(), BCard: $('#sr-bad_card').val(), CNum: $('#sr-card_number').val(), CPin: $('#sr-pin_number').val(), Bal: $('#sr-balance').val()} }) } } views.py if request.method == 'POST' and request.POST['Action'] == 'Card': cardID = request.POST['CardID'] Bcard = int(request.POST['BCard']) CNum = int(request.POST['CNum']) CPin = int(request.POST['CPin']) if request.POST['CPin'] != '' and request.POST['CPin'] … -
string data can't be updated without changing the image in vue js
I have a problem with updating data using vue js as the frontend and django as the backend when updating the data with the data image is changed successfully. but when updating data without an image with an error. i've fire test using postman and managed to update data without changing image. please find a solution this is the method for updating the data ubah() { let datapengajarstaf = new FormData(); datapengajarstaf.append("nama", this.datapengajarstaf.nama); datapengajarstaf.append("nip", this.datapengajarstaf.nip); datapengajarstaf.append("jobs", this.datapengajarstaf.jobs); datapengajarstaf.append("picture", this.gambar); _.each(this.datapengajarstaf, (value, key) => { datapengajarstaf.append(key, value); }); axios .put("http://127.0.0.1:8000/api/Detailpengajarstaff/"+this.id, datapengajarstaf, { headers: { "Content-Type":"multipart/form-data" } } ) .then(response => { this.$router.push("/indexpengajarstaff"); this.$q.notify({ type: "positive", message: `Data berhasil ditambah.` }); }) .catch(err => { if (err.response.status === 422) { this.errors = []; _.each(err.response.data.errors, error => { _.each(error, e => { this.errors.push(e); }); }); } }); } this is for form-data when the data is updated -
Conditionally authenticate users to DRF view
I have a DRF view as such: class DocumentsView(generics.ListCreateAPIView): permission_classes = () authentication_classes = () # I typically enforce authentication with # authentication_classes = (JWTCookieAuthentication,) def list(self, request): pagination_class = None if request.user.is_authenticated: ... return protected data ... else: ... return generic data ... I want to allow both users sending a valid token and those not sending a valid token to both get a response from this endpoint. However, request.user.is_authenticated returns False, even when a valid token is sent (I understand why). How can I try to authenticate the user, but still allow them to proceed even if not presenting a token? Or is better practice to not have the same view to authenticated an unauthenticated users? -
Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]'
I have used django to develop a web app. In frontend, I want to access the object through the loop like in the html template. <label class="radio-inline"> {% for course_for_select in query_results_2 %} <input type="checkbox" name="course_select" value="{{course_for_select}}">&nbsp; {{course_for_select}} {{ query_results_course_id[loop.index0] }} <br> {% endfor %} </label> However, error occurs: Could not parse the remainder: '[loop.index0]' from 'query_results_course_id[loop.index0]' -
Django date format by an user
I'm writing a Django application that requered to give the user the ability to create his own time format, over an API (problay GraphQl). I've figure out the following way, but it seems to be really hard solution for relativlly small problem. class Formatter(models.Model): ... class DateLetter(models.Model): formatter = models.ForeignKey(Formatter, related_name="letters", on_delete=models.CASCADE) index = models.IntegerField(db_index=True) letter = models.CharField(max_length=255, unique=True, choices=LetterChoices.CHOICES, default=LetterChoices.Y) And after that, just going with some sort of loop to get the instance as a date format (%Y-%m-%d) etc. -
Django multiple user roles using AbstractUser without username field
I am trying to build an electronic information system for one teacher and students. Using the tutorial shown here: https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html , in my models.py I have implemented the student and teacher models this way: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) f_name = models.CharField(max_length=20) l_name = models.CharField(max_length=30) parent_tel_numb = models.CharField(max_length=13) parent_f_name = models.CharField(max_length=20) parent_patronimic = models.CharField(max_length=30) parent_l_name = models.CharField(max_length=30) group = models.ForeignKey(Group, to_field='id', on_delete=models.SET_NULL, blank=True, null=True) class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) For my application I would like to exclude the username field both for Teacher and Student models. Instead, I want to use email as username. I have previously tried to do it this way, modifying the User model: class User(AbstractUser): is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) username = None email = models.EmailField(unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] However, after that, when I tried to create a superuser in the terminal, the username field was omitted during the creation of superuser and after submission of email and password, I got an error, saying the username field is absent. How do I deal with this issue? -
Django findstatic gives no error but templates and static files are not loading
when i run python manage.py findstatic --verbosity 2 vendors/jquery/dist/jquery.min.js it is giving me this output. But still it is not loading static elements and css in server. it was working fine in local host. DEBUG = True for now. Found 'vendors/jquery/dist/jquery.min.js' here: /www/wwwroot/default/pmosync/Dev/pmosinc/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static/vendors/jquery/dist/jquery.min.js /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static/vendors/jquery/dist/jquery.min.js Looking in the following locations: /www/wwwroot/default/pmosync/Dev/pmosinc/static/ /www/wwwroot/default/pmosync/Dev/static/ /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/admin/static /www/wwwroot/default/pmosync/Dev/pmoDev_venv/lib/python3.8/site-packages/django/contrib/auth/static -
Add wordlist.txt in exclude query
I am building a BlogApp and I am trying to add wordlist.txt at the place of exclude('wordlist.txt') What i am trying to do :- I build a feature of exclude posts according to words, For Example :- If a post contains word "Bad" then exclude that post like :- from django.db.models import Q posts = Post.objects.exclude(Q(description__contains='bad') & Q(description__contains='bad1')) BUT i am trying to exclude hundreds of words at the same time AND when i add all of them in this way then it will be very lengthy AND i don't want that, So i think I can make a file named wordlist.txt and put all my words that i want to exclude then put the path of wordlist.txt in exclude query so i do not have to write lengthy exlcude words in the query. For example :- posts = Post.objects.exclude(description__contains=wordlist.txt) ( Above example is just to explain, what i am trying to do ) I have no idea how can i do it . Any help would be Appreciated. Thank You in Advance -
Django 'change' can not find existing object
Currentli my django project still using Sqlite as db. I have a model named 'Monitoring'. class Monitoring(models.Model): tebar=models.ForeignKey(Tebar, on_delete=models.CASCADE, related_name='monitoring',) date_created = models.DateTimeField( verbose_name=("Tanggal"), auto_now_add=True, null=True, editable=False,) prevmon=models.ForeignKey('self', on_delete=models.CASCADE, related_name='nextmon', editable=False, blank=True, null=True) dead = models.PositiveIntegerField(verbose_name='Jml. Mati', default=0, null=True) food = models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringfood', verbose_name='Pakan', blank=True, null=True) foodqty=models.PositiveIntegerField(null=True, default=0, verbose_name='Berat Pakan',) suplemen=models.ForeignKey(Bahan, on_delete=models.CASCADE, related_name='monitoringsupl', verbose_name='Suplemen', blank=True, null=True) suplqty=models.PositiveIntegerField(null=True, default=0, verbose_name='juml.Supl.',) feedcost = models.DecimalField(max_digits=10, decimal_places=2, default=0.0, blank=True, null=True) ph = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) weight = models.DecimalField(max_digits=7, decimal_places=2, verbose_name='gram/ekor', default=0.0, null=True) wateradd= models.PositiveIntegerField(verbose_name='Tambah Air', null=True, blank=True, help_text='Penambahan Tinggi Air dalam Cm') class Meta : verbose_name_plural='7. Perlakuan' def __str__(self): return '{}; {}'.format(self.tebar, self.date_created) I add one record, get success. I try to change the record, the web page go to the /admin and under the site name line I got msg: Monitoring with ID “6” doesn’t exist. Perhaps it was deleted? I try to access the db via django console, and that record is there. bino@rtd:~/catatkolam$ pipenv run ./manage.py shell Python 3.9.2 (default, Mar 13 2021, 18:29:25) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from catatkolam.models import * >>> Monitoring.objects.get(id=6) <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> Monitoring.objects.get(id='6') <Monitoring: kolam 1@2021-05-02; 2021-05-06 07:19:53.288664+00:00> >>> I … -
Bulk update with different values in django 1.11
I have been reading the official documentacion of django 1.11 about bulk updating. My problem is that I have only seen how to update the fields for ALL the query objects. What I need is a bulk update but with different values, depending on a condition. Let me write an example. Let's say I have the following model: class A(models.Model): key = models.ForeignKey(SomeOtherModel, db_index=True) value = models.FloatField(blank=True, null=True, default=None) As you can see, the field_definition points to another model. What I want is to mass update the objects of a query of the model A based on that value. Something like this: A.objects.filter(key__id__in=[1,2,3]).update(value_for_id_1="1", ..., value_for_id_n="n") The only thing I have seen so for is this syntax: A.objects.filter(key__id__in=[1,2,3]).update(value="1") Any idea if this is even possible? How can I make this query efficient? -
The best way to get data from another database and refresh it every few seconds in Django
I am wondering what is the best way to get data from another database (on the same server but it is part of different application) and refresh it every few seconds. I want to let user to choose from a select form that contains all the objects with specific status field. I want to use pyodbc (I'm using MySQL for both of databases), run a simple select (E.g. SELECT Index, Name FROM Table WHERE Status = 'OPEN'), create object for every row if it doesn't already exist in Django database: cursor.execute("SELECT Index, Name FROM Table WHERE Status = 'OPEN") for row in cursor: try: order = Order.objects.get(index=row[0]) except Order.DoesNotExist: Order.objects.create(index=row[0], name=row[1]) but my question is- when should i run it? Time it in a loop and do it every few seconds somehow? Or should I just do it every time user requests for a view with select form that contains these objects. What is the correct approach? -
Django / Python : ModuleNotFoundError: No module named 'd'
The project seemed fine till yesterday, but suddenly , when I tried to start the server after some settings changes today, this error pops up everytime: Traceback (most recent call last): File "/PROJECT/manage.py", line 21, in <module> main() File "/PROJECT/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/usr/local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/usr/local/lib/python3.9/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 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'd' the project manage.py file : #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'PROJECT.settings.production') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if __name__ == '__main__': main() Please help me solve this and please do ask if you need more information. Thank you … -
Using a Datepicker with Django and chart.js
Good day, please i am new to django. Can i be shown how to use a datepicker to show my chart.js for the specific date selected by a user? Can i be shown how to install a datepicker for this purpose?Below was my attempt and i have not been able to display any data. Model: class Complainer(models.Model): STATES = ( ('Abia', 'Abia'), ('Abuja', 'Abuja'), ('Adamawa', 'Adamawa'), ('Akwa-Ibom', 'Akwa-Ibom'), ('Anambra', 'Anambra'), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue', 'Benue'), ('Borno', 'Borno'), ('Cross-River', 'Cross-River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ('Nasarawa', 'Nasarawa'), ('Niger', 'Niger'), ('Ogun', 'Ogun'), ('Ondo', 'Ondo'), ('Osun', 'Osun'), ('Oyo', 'Oyo'), ('Plateau', 'Plateau'), ('Rivers', 'Rivers'), ('Sokoto', 'Sokoto'), ('Taraba', 'Taraba'), ('Yobe', 'Yobe'), ('Zamfara', 'Zamfara') ) SECTOR = ( ('Federal Government', 'Federal Government'), ('State Government', 'State Government'), ('Local Government', 'Local Government'), ('Private Company', 'Private Company'), ('Public Company', 'Public Company'), ('Other', 'Other'), ) NATURE = ( ('Delay of Service', 'Delay of Service'), ('Non compliance with Regulation', 'Non compliance with Regulation'), ('Demand for Bribery', 'Demand for Bribery'), ('Vandalism', 'Vandalism'), ('Unrepaired or damaged infrastructure', 'Unrepaired or damaged infrastructure '), ('Insecurity', 'Insecurity'), ('Non Payment of …