Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What could be the problem of django run error
My Django project used to work well the day before but it was not working when I run the next day. The following is the error I am getting. I didn't change anything and yet it did not work. When I run my project, the following error occurs. The project name is 'carpooling' and the the database user is 'Jigme'. I think the last line points the error towards the database which I didn't change anything. Please help me. Your help will be appreciated. Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 219, in ensure_connection self.connect() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\mysql\base.py", line 234, in get_new_connection return Database.connect(**conn_params) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (1044, "Access denied for user 'jigme'@'%' to database 'carpooling'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\threading.py", line 950, in _bootstrap_inner … -
Djnago - Make query based on information provided from a user on front end. Not all filters will be used every time. How to achieve this?
I have a problem. I am building an app where user in a form can select some filtering options. Not all options will be used every time. I don't know how to build proper django query. At first I tried this approach: if mileage: if mileage_less_more == 'mileage_less_than': cars = cars.objects.filter(price__lte=mileage) if mileage_less_more == 'mileage_more_than': cars = cars.objects.filter(price__gte=mileage) if production_year: if production_year_less_more == 'production_year_less_than': cars = cars.objects.filter(production_year__lte=production_year) if production_year_less_more == 'production_year_more_than': cars = cars.objects.filter(production_year__gte=production_year) if production_year_less_more == 'production_year_exact': cars = cars.objects.filter(production_year=production_year) I assumed that it would work like any other variable in python and even if one of the above filters won't be used (mileage will be None for example) then it just won't execute. But this kind of approach is not supported by django as I learned. Then I tried many weird things with f strings but it also didn't work. Then I tried with this approach: if mileage: if mileage_less_more == 'mileage_less_than': mileage_qs = Car.objects.filter(price__lte=mileage) if mileage_less_more == 'mileage_more_than': mileage_qs = Car.objects.filter(price__gte=mileage) else: mileage_qs = Car.objects.all() if production_year: if production_year_less_more == 'production_year_less_than': production_year_qs = Car.objects.filter(production_year__lte=production_year) if production_year_less_more == 'production_year_more_than': production_year_qs = Car.objects.filter(production_year__gte=production_year) if production_year_less_more == 'production_year_exact': production_year_qs = Car.objects.filter(production_year=production_year) else: production_year_qs = Car.objects.all() cars_final = Car.objects.all().intersection( mileage_qs, production_year_qs) … -
Load a large json file 3.7GB into dataframe and convert to csv file using ijson
I have a large json data file with 3.7gb. Iam going to load the json file to dataframe and delete unused columns than convert it to csv and load to sql. ram is 40gb I try to load data but it fails because of out of memory data_phone=[] with open('data.json', 'r', encoding="UTF-8") as f: numbers = ijson.items(f, 't',multiple_values=True) for num in numbers : data_phone.append(num) It shows errors Out of memory I try another way data_phone=[] data_name=[] with open("Vietnam_Facebook_Scrape.json", encoding="UTF-8") as json_file: cursor = 0 for line_number, line in enumerate(json_file): print ("Processing line", line_number + 1,"at cursor index:", cursor) line_as_file = io.StringIO(line) # Use a new parser for each line json_parser = ijson.parse(line_as_file) for prefix, event, value in json_parser: if prefix =="t": data_phone.append(value) if prefix =="id": data_name.append(value) cursor += len(line) it still error : out of memory Thanks for reading -
Value Error "The parameter 'item' must be an integer or a string" while converting pyFTS example to Django app
I want to convert the example from pyFTS to Django application, but it is not work even the code is same. Sample code: https://colab.research.google.com/drive/1S1QSZfO3YPVr022nwqJC5bEJvrXbqS_A from pyFTS.data import Enrollments from pyFTS.partitioners import Grid from pyFTS.models import chen train = Enrollments.get_data() test = Enrollments.get_data() partitioner = Grid.GridPartitioner(data=train,npart=10) model = chen.ConventionalFTS(partitioner=partitioner) model.fit(train) print(model) forecasts = model.predict(test) my code: from django.shortcuts import render from django.http import JsonResponse from pyFTS.data import Enrollments from pyFTS.partitioners import Grid from pyFTS.models import chen import warnings def index(request): warnings.filterwarnings('ignore') train = Enrollments.get_data() test = Enrollments.get_data() df = Enrollments.get_dataframe() fs = Grid.GridPartitioner(data=train, npart=10) model = chen.ConventionalFTS(partitioner=fs) model.fit(train) # ==========>>> error here forecasts = model.predict(test) data = {'message': 'Hello world'} return JsonResponse(data) The error is: The parameter 'item' must be an integer or a string and the value informed was 0 of type <class 'numpy.intc'>! My Pipfile is: [[source]] url = "https://pypi.org/simple" verify_ssl = true name = "pypi" [packages] django = "*" djangorestframework = "*" django-cors-headers = "*" pyFTS = "*" gunicorn = "*" whitenoise = "*" pandas = "*" scipy = "*" matplotlib = "*" dill = "*" [dev-packages] [requires] python_version = "3.8" screenshot: How to solve this? I have not found any solution. -
How to do a class based delete view that allows DELETE method in django 3.1?
In Django 3.1, the typical DeleteView accepts GET and POST. See https://docs.djangoproject.com/en/3.1/ref/class-based-views/generic-editing/#deleteview and I reproduce below: A view that displays a confirmation page and deletes an existing object. The given object will only be deleted if the request method is POST. If this view is fetched via GET, it will display a confirmation page that should contain a form that POSTs to the same URL. How do I do a DELETEView that's class based view and also accepts DELETE method? -
registration form not getting saved in the database
this is my models.py for the registration session choice = ( ('2020-2021', '2020-2021'), ('2021-2022', '2021-2022'), ('2022-2023', '2022-2023'), ) registrationSession=models.CharField(max_length=15,choices=choice,blank=False) this is my views.py registrationSession=request.POST['RegistrationSession'] stu=Student(registrationSession=registrationSession) stu.save() this is my template <div class="component"> <label for="RegistrationSession">Registration Session <span style="color:red;">*</span> </label> <select class="col-form-label " style="width:760px;" name="RegistrationSession" id="RegistrationSession"> <option>2020-21</option> <option>2021-22</option> <option>2022-23</option> </select> </div> -
Django CACHEOPS different timeout for different querysets
I'm using Django CACHEOPS. cacheops' README In settings.py how can I config different timeouts for different querysets? (cache the get queryset for 10 seconds and cache queryset fetches for 60 seconds) Something like this: (This obviously has duplication key error) CACHEOPS = { 'blog.Article': {'ops': 'fetch', 'timeout': 60}, 'blog.Article': {'ops': 'get', 'timeout': 10}, } My goal is: I want to cache each article detail page longer than the article list page. -
Display list of HTML in one field of list_display in django admin
I want to display all colors with HTML on django admin page. I can do it with one color instance but when I have a product with multiple colors it will display a string and won't render it with HTML format. # models.py class Color(models.Model): product = models.ForeignKey( Product, related_name='colors', on_delete=models.CASCADE) color = ColorField(default='#FFFFFF') # ... def colored_name(self): return mark_safe( '<span style="color: %s;">%s</span>' % (self.color, self.color) ) # admin.py class ProductAdmin(admin.ModelAdmin): inlines = [ImageInline, ColorInline] list_display = [ 'title', 'price', 'active', 'colors' ] def colors(self, obj): result = list() for color in obj.colors.all(): result.append(color.colored_name()) return result -
Django Passing Parameters to Formset
Create a method for the Form form.py --- def create_certificate_form(id_certificate): class CertificateAdditionalFieldForm(forms.ModelForm): class Meta: model = CertificateAdditionalField fields = [ 'certificate_title', 'no', 'component_activities', 'text', ] def __init__(self, *args, **kwargs): super(CertificateAdditionalFieldForm, self).__init__(*args, **kwargs) self.fields['certificate_title'].queryset = CertificateAdditionalTitle.objects.filter( is_deleted=False,certificate_id=id_certificate) self.fields['certificate_title'].required = True return CertificateAdditionalFieldForm view.py -- def createCertificateField(request, certificate_pk): template_name = "contract/final/experience_certificate_TitleAndOtherField.html" certificate = ExperienceCertificate.objects.get(pk=certificate_pk) title = CertificateAdditionalTitle.objects.filter(certificate_id=certificate_pk) CertificateAdditionalFieldForm = create_certificate_form(certificate_pk) CertificateAdditionalFieldFormset = formset_factory( CertificateAdditionalFieldForm,extra=1 ) if request.method == 'GET': formset = CertificateAdditionalFieldFormset() elif request.method == 'POST': formset = CertificateAdditionalFieldFormset(data=request.POST) if formset.is_valid(): try: with transaction.atomic(): for form in formset: set_save = form.save(commit=False) set_save.created_user = request.user set_save.save() messages.success(request, "Filed Successfully Add") logger.debug(f"Filed Successfully Add {formset}") return redirect('experience_certificate', pk=certificate.pk) except IntegrityError: print("Cant save") data = { 'formset': formset, 'title': title, } return render(request, template_name, data) -
jQuery/Django retrieving file
I have seen many answers to questions like this, but none has solved my problem... I want to produce a pdf in the backend and then download it to the user. So I have a basic blank page with a button. For that button there is a jQuery function: $.post("{% url 'printReport' %}", { 'params' : JSON.stringify({ 'reportcode' : 'HelloWorld', }) }, function(data, status) { $("#testZone").text(data) }); On the server side, I produce the pdf and save it locally in the server folder. This goes perfect. Then, in the views file I have this: def printRreport(request): if request.method=="POST": res = producePdf(request) #works fine! the PDF is birght an shiny, saved on the server response = HttpResponse(res.data,content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="report.pdf"' #setting response headers return response where res.data is actually open(pdf_path,'r').read() this is 70% fine, because the browser actually receives the pdf data inside the request response (I can see it on the dev console). It's 30% wrong because this does not give me a download dialog and does not allow me to save a pdf file on the client side. What is wrong here? In my case I opted by using a POST method, I know it's debatable, but I … -
DJango call management command asynchronously
I have a DJango app and where users upload many images. What I want is to trigger a management command using the call_command function from management once a new object is created but the problem is I want to do it asynchronously. I don't want to keep the user waiting for the management command to finish. Yes I am aware about third party services like Celery but I want to keep it simple. I also know that I can schedule a cron job but the thing is I want the change to reflect instantly. Is there any other way to do so? -
Django- Is it possible to make a fill-in form on a website with an autoreply with data from a selfmade database?
I want to build a website with a function within where people can fill in a form. And when they admit their answer, they get a few examples of products that fit in their wishes. Is this possible in Django? -
Redeploy or edit a dynamic website after publishing
I made a dynamic website using django and i already hosted it on aws. I should always add new blog posts to my website, which does not have a login page to create them, so i created them through the code on my local machine. How i can edit the hosted website to add these new blog posts ? -
Django - Filtering queryset many times while using the same name?
in django docs I found this solution for filtering multiple time the same query in many lines: q1 = Entry.objects.filter(headline__startswith="What") q2 = q1.exclude(pub_date__gte=datetime.date.today()) q3 = q1.filter(pub_date__gte=datetime.date.today()) But I need to make it on one variable name. I created it like this thinking that it will work similar to python variables: q1 = Entry.objects.filter(headline__startswith="What") q1 = q1.exclude(pub_date__gte=datetime.date.today()) q1 = q1.filter(pub_date__gte=datetime.date.today()) But apparently it is not, I am doing something wrong. How can I achieve this while using one variable? -
unable to fide one specific template
when i got /contact in my website it shows this error i am created my models, views, forms.pyforms all root project which is website and I did not create any other application error views.py settings.py -
Django "if form.is_valid()" returns None
Im new to using Django and I am trying to have a file uploaded from a form, to then be handled after a POST request. However in my views function if form.is_valid() returns None and I am unable to retrieve the request.FILES['file']. Does anyone know what the issue is? Thanks views.py function: def success(request): if request.method == 'GET': return render(request, 'send_receive_files/success.html', {'form': UploadFileForm}) else: form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['file']) return redirect('/') else: return HttpResponse('invalid') forms.py: from django import forms class UploadFileForm(forms.Form): title = forms.CharField(max_length=50) filer = forms.FileField() form template: {% block content %} {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static 'css/dashboard.css' %}"> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,300;1,100&display=swap" rel="stylesheet"> <title>Dashboard</title> </head> <header> <a id="header-link" href="/"> <h1 id="heading">File Share</h1> <div id="cont"> <a id ="login" class="header-buttons" href="/login">Logout</a> </div> </a> </header> <body> <center> <div id="send-container"> <form method="post" action="/dashboard/upload/"> {% csrf_token %} {% if error %} <p id="error">{{error}}</p> {% endif %} <input name="username-send" type="text" placeholder="Recipient's username" id="username" required> <input name="file-send" type="file" id="file" required> <p> <input type="submit" value="Send"> </p> </form> </div> </center> </body> </html> {% endblock %} -
Azure Django React Web App - Operational Error 1045
I deployed my django react web app on azure with a MySQL server being the database engine, but once I go to the django admin page to sign in, I'm getting this error I have 20.151.49.29 as one of my outbound IP addresses. Does anyone know why it's denying access? Also, my other web pages that are linked from the landing page are showing up as blank. -
comments in django not get stored in backend
I don't know why my comments are not get stored in backend .. it showing no error but I think it is logical error. Can somebody help me to find out the error ... it will be great help!! Thank you 1.Views.py from django.shortcuts import render, get_object_or_404, redirect from datasecurity.models import Post, BlogComment from django.urls import reverse from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib import messages from django.contrib.auth.models import User # Create your views here. @login_required def likes(request, pk): post=get_object_or_404(Post, pk=pk) post.likes.add(request.user) return HttpResponseRedirect(reverse('datasecurity:datasecurity')) def datasecurity(request): allPosts= Post.objects.all() context={'allPosts': allPosts} return render(request, 'datasecurity/data.html',context=context) def blogHome(request, slug): post=Post.objects.filter(slug=slug).first() comments= BlogComment.objects.filter(post=post) context={'post':post, 'comments': comments, 'user': request.user} return render(request, "datasecurity/blogHome.html", context) def postComment(request): if request.method == "POST": comment=request.POST.get('comment') user=request.user postSno =request.POST.get('postSno') post= Post.objects.get(sno=postSno) comment=BlogComment(comment= comment, user=user, post=post) comment.save() return HttpResponseRedirect(reverse('datasecurity:blogHome')) 2.urls.py from django.conf.urls import url from . import views app_name = 'datasecurity' urlpatterns = [ url(r'^$', views.datasecurity, name="datasecurity"), url(r'^datasecurity/(?P<slug>[^/]+)', views.blogHome, name='blogHome'), url(r'^likes/(?P<pk>\d+)/', views.likes, name = "likes"), url(r'^datasecurity/postComment', views.postComment, name="postComment"), ] 3.models.py from django.db import models from ckeditor.fields import RichTextField from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class Post(models.Model): sno=models.AutoField(primary_key=True) title=models.CharField(max_length=255) author=models.CharField(max_length=14) slug=models.CharField(max_length=130) timeStamp=models.DateTimeField(blank=True) content=RichTextField(blank=True, null=True) img = models.ImageField(blank=True, null=True, upload_to="dataimage/") likes = models.ManyToManyField(User) @property … -
Can I create a pool of token in DRF
Can I create a pool of token in Django RestFrame ? I want to create a pool of token, where I will have 'n' number of token. Later on I want to assign token to a user. How should I proceed ? -
How run django with pm2?
I have a django project on ubuntu 18.04 I wanna start and stop it with pm2. I've created a django_project.yml file with the following contents: apps: - cwd: 'directory_that_manage.py_exists_in_it' script: './manage.py runserver' args: 'server --binding 0.0.0.0' interpreter: 'python3' name : 'django_project' instances: 1 watch : false exec_mode: fork_mode then, I run it with the following command: pm2 start django_project.yml --interpreter ../.env/bin/python3 it starts, but after stop it and start it again, it gets the following errors. what is the problem? please help me. thanks -
Can we create Token in DRF without creating Superuser
Can we create Token in Django RestFramework without creating Superuser. I want to create a token pool, where I will have 'n' numbers of token, lateron on hitting a url a token from token pool will be assign to the user. Is this possible ? Is it possible to create a pool of DRF token ? And later on assign a token from pool to a user on hitting url? -
Why is my query not working for room.slug
Currently, I am trying there are 4 categories, each categories have 4 rooms. I am trying to write the view to enter that particular room but somehow even though I can render the page, what i query doesn't work.Why is this so? function-based views.py def room_view(request, category_slug, room_slug): context = {} category = get_object_or_404(Category, slug=category_slug) rooms = Room.objects.filter(typeofcategory=category) room = Room.objects.filter(slug=room_slug) context['room'] = room return render(request, "room.html", context) template {{ room_slug }} urls.py path('<slug:category_slug>/<slug:room_slug>/', room_view , name= "room"), models.py class Category(models.Model): type_of_category = models.CharField(max_length=80, null=False, blank=False, choices=type_of_category_CHOICES, default=True, unique=True) slug = models.SlugField(blank=True, unique=True) class Room(models.Model): typeofcategory = models.ForeignKey(Category, related_name='typeofcategory', on_delete=models.CASCADE) slug = models.SlugField(blank=True) -
Django IntegrityError when editing a value referenced by a foreign key
I have an app with two (relevant) models, in what is essentially a CRM: class StudentTutorRelationshipProfile(models.Model): pupil_name = models.CharField(max_length=100, unique=True) parent_name = models.CharField(max_length=100) ... class TimeSheet(models.Model): user = models.ForeignKey( User, on_delete=models.PROTECT, limit_choices_to={"is_tutor": True} ) student = models.ForeignKey( StudentTutorRelationshipProfile, on_delete=models.CASCADE, to_field="pupil_name" ) ... Now someone has misspelled a pupil's name and would like to change it pupil_name in StudentTutorRelationshipProfile but because there are already TimeSheet records with the Students misspelled name, Django raises an error (from psychog): ForeignKeyViolation: update or delete on table "invoicing_studenttutorrelationshipprofile" violates foreign key constraint "invoicing_timesheet_student_id_07889dc0_fk_invoicing" on table "invoicing_timesheet" DETAIL: Key (pupil_name)=(Student Name) is still referenced from table "invoicing_timesheet". File "django/db/backends/base/base.py", line 243, in _commit return self.connection.commit() IntegrityError: update or delete on table "invoicing_studenttutorrelationshipprofile" violates foreign key constraint "invoicing_timesheet_student_id_07889dc0_fk_invoicing" on table "invoicing_timesheet" DETAIL: Key (pupil_name)=(Student Name) is still referenced from table "invoicing_timesheet". What is a nice way of changing this data? I don't mind changing the historic timesheets too or leaving them as is (but can't delete them), what ever is easier / less likley to lead to problems. (And yes the fact that I rely on unique name and surname combinations is not ideal, but won't fix that for now unless the change for the IntegrityError also … -
why Django loss it's dependencies
I made a few django+react websites before. But, they work very fine for a while and later after I run few git commits and many other changes the Django backend start showing errors like " there is no module named Django" or "there is no module named django-allauth" despite I installed all of them before and the website was working very well. Could that be because of the environment? what if I used docker could it help to prevent such things? or it may be a problem with code only? -
How inject data from ('another') model in admin?
I have User model: class PublisherProfile(models.Model): publisher_id = models.AutoField(primary_key=True) user_profile = models.OneToOneField(Profile, on_delete=models.SET_NULL, null=True, verbose_name=_("user profile")) In admin I registered this model: @admin.register(PublisherProfile) class PublisherProfileAdmin(admin.ModelAdmin): list_display = ( "publisher_id", "user_profile", ) In another model I have: class PublisherOffer(models.Model): offer_owner = models.ForeignKey('user.PublisherProfile', on_delete=models.CASCADE, verbose_name=_("offer owner"), ) title = models.CharField(_('Offer title'), help_text=_('Title of the offer.'), max_length=250, blank=False, null=False) How can I inject all PublisherOffer to PublisherProfileAdmin?