Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pdf file created throw following error, file response has no read attribute
I am trying to save pdf file inside directory , pdf file is properly created but it does not contains data and throw error. def file_pdf_to_merge(id): flow_obj=flow_obj_for_display(id) buffer = io.BytesIO() doc = SimpleDocTemplate(buffer) doc.build(flow_obj) buffer.seek(0) file_nm=file_name_only(id) response= FileResponse(buffer,as_attachment=True,filename=file_nm) fs=FileSystemStorage() if fs.exists(file_nm): fs.delete(file_nm) fs.save(file_nm,response) code throws following error. I think due to this error pdf file created is also corrupt or not properly decoded. 'FileResponse' object has no attribute 'read' thanks -
When I Submit Form I Got This Errors Field 'id' expected a number but got Why i got this errors ? What's wrong in my code :(
views---------- def update(request): if request.method == 'POST': aa = Add_Ep(request.POST) print("this is id:") Title = Add_Ep.Ep_Title print(Add_Ep) aa.save() return redirect('/') else: aa = Add_Ep() Form class add_ep(ModelForm): class Meta: model = Add_Ep fields = "__all__" Error: Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['UTwwWtdY9Vy0L6BzYL5jK9SPRqBFsJaBpGwxIOtqdD5kDQC7CRiyPSDxC0rbUo4g'], 'Ep_Title': ['title'], 'CreatorsNote': ['this is creaters note555'], 'series': ['2']}>. -
Django Many-To-One Relationship add data to Many side
I have two models like below. I'm using Django restframework. class Family(models.Model): name= models.CharField(max_length=100) class Parishioner(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) family = models.ForeignKey(Family, on_delete=models.CASCADE) There are my ViewSets class FamilyViewSet(viewsets.ModelViewSet): queryset = Family.objects.all() serializer_class = FamilySerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) class ParishionerViewSet(viewsets.ModelViewSet): queryset = Parishioner.objects.all() serializer_class = serializers.ParishionerSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) These are my Serializers class FamilySerializer(serializers.ModelSerializer): class Meta: model = Family fields = ('id', 'name') read_only_fields = ('id',) class ParishionerSerializer(serializers.ModelSerializer): class Meta: model = Parishioner fields = ('id', 'first_name', 'last_name', 'family') read_only_fields = ('id',) depth = 1 So basically Parishioner can have one Family. Family has multiple members(Parishioners) Currently I have to go to all Parishioners and select the Family. is it possible to add a field called members to Family model, where members would be an Array of Parishioners ? or is there any other way to handle this ? -
How to correctly 1.Implementing slugs in Django? 2. Instantiate subject in Django? 3. Extend base.html in Django?
I am using django to create a blog where all posts are shown on the home page as well as on pages depending on their subject. While the basics as shown work, I am having great difficulty with the following three issues: For each subject page I would like the url to include ~/subject_slug/ Currently I am getting ~/subject/subject_slug When I eliminate subject/ from urls.py (line 8), I get the desired ~/subject_slug only. HOWEVER, the individual posts cannot now be accessed. Error: Subject.DoesNotExist: Subject matching query does not exist. Line 21 in views.py is pointed to. There I have tried to include either Subject, or subject, in the bracket before subject_slug=subject_slug. Unfortunately that shows: UnboundLocalError: local variable 'subject' referenced before assignment. Attempts with adding subject to the post_detail view have also not worked. For each post I would like the url to include ~/subject_slug/slug/ Therefore I added str:subject_slug/ to urls.py line 10. This throws the error: NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'post_detail' with arguments '('a-slightly-longer-post',)' not found. 1 pattern(s) tried: ['(?P<subject_slug>[^/]+)/(?P[^/]+)/$']. This part of base.html is repeated on each page: DR SMART.INFO the web site for the analytical rugby fan However this part only shows on index.html <p> <ul> {% for … -
How can I implement two kinds of login with Django?
How can I implement two kinds of logins with Django? For example, 1, Employee login - Employee page 2, Supervisor login - Supervisor page. -
annotate group by in django
I'm trying to perform a query in django that is equivalent to this: SELECT SUM(quantity * price) from Sales GROUP BY date. My django query looks like this: Sales.objects.values('date').annotate(total_sum=Sum('price * quantity')) The above one throws error: Cannot resolve keyword 'price * quantity' into field Then I came up with another query after checking this https://stackoverflow.com/a/18220269/12113049 Sales.objects.values('date').annotate(total_sum=Sum('price', field='price*quantity')) Unfortunately, this is not helping me much. It gives me SUM(price) GROUP BY date instead of SUM(quantity*price) GROUP BY date. How do I query this in django? -
IntegrityError not thrown during create within transaction.atomic()
I want to create a Car with an FK to an Engine. I also want to save a record to an audit table that Car has been created; I'm including the Engine's id within that audit record. I'm using the Django Rest Framework. Here's my serializer code for "create": @transaction.atomic def create(self, validated_data): try: with transaction.atomic(): car = Car.objects.create(**validated_data) except Exception as e: raise serializers.ValidationError("my message") a_function_that_creates_an_audit_record() The problem is that, if engine_id=0 in validated_data and there is no Engine object with an id of 0, no Exception is thrown, and the except ... doesn't get triggered. Execution continues to a_function_that_creates_an_audit_record(), where I do something like car.engine.id and there I do get an IntegrityError saying that an Engine with an id of 0 doesn't exist. What am doing wrong? Is there something I'm missing? -
Django test if SMTPRecipientsRefused error is raised
I'm writing tests in Django for some functions but one of them causes me problem to test. Here is the part of the function: try: set_password_form = PasswordResetForm({'email': newuser.email}) if set_password_form.is_valid(): set_password_form.save( request=request, email_template_name='authentication/password_reset/password_reset_html_email.html', html_email_template_name='authentication/password_reset/password_set_email.html', subject_template_name='authentication/password_reset/password_set_subject.txt' ) messages.success(request, "The user {} has been created. A mail has been sent foir setting the password".format( newuser.fullname())) return redirect('authentication:users') except SMTPRecipientsRefused: form.add_error('email', 'This email address does not exist') messages.error(request, "Some data are not valid") I would like to test that the exception is raised when giving a wrong email but I have absolutely no clue how to do that according to the fact that Django doesn't try to send the mail in the tests. -
django mysql and Big Sur
Some trouble after Big Sur update I use Django 2.1.15 and Python 3.8 according to posts and documentation I installed the connector brew install mysql-connector-c and pip install mysql-python after I install mysql brew install mysql and the client pip install mysqlclient try to run django and i get: django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 54") This is my setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'BATABASE', 'USER': 'sa', 'PASSWORD': 'password', 'HOST': '192.168.1.10', 'PORT': '1433', -
Django : Not able to handle Multiple post request on the same page / FormHi
i have a code which should handle multiple post request on the same page . it has two button in html page inside a single form . It is taking the post value from first button but not the second . no idea why when i include the second button and click on first it says the second button not found . Can anyone please help me solve this issue . index.html <input type="submit" style="background-color:#FFFF66;color:black;width:150px; height:40px;" name="ServerDetails" value="ServerDetails"/> <br><br> <input type="submit" style="background-color:#FFFF66;color:black;width:150px; height:40px;" name="GenerateFile" value="GenerateFile"/> views.py if request.method == 'POST': if request.POST['ServerDetails']: print("Inside Server Details") if request.POST['GenerateFile']: filename = request.POST['patchconfigofpg3'] print(filename) models.py class course(models.Model): patchconfigofpg3 = models.CharField(max_length=100) so when i click on first button it is throwing me the below error : -
Error: invalid input syntax for type numeric: "21/4/2020 01:52:56.2751+00" But there is no type numeric
I have this error in PostGreSQL running a simple select query: select * from public.jaap_rent ERROR: invalid input syntax for type numeric: "21/4/2020 01:27:26.357908+00" The thing is, in this view, there are no numeric column. There are 3 timestamp with timezone columns, which is where the problem come from. Selecting any other column is completely normal. This is how the timestamp columns defined: to_timestamp(( CASE WHEN ((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text) ~~ '%E9'::text) THEN ((((replace((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text), 'E9'::text, ''::text))::double precision * ('1000000000'::numeric)::double precision))::integer)::numeric WHEN (((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric > ('100000000000'::bigint)::numeric) THEN (((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric / (1000)::numeric) ELSE ((vf_scraper_scraperdata.data ->> 'first_scrape_date'::text))::numeric END)::double precision) AS first_scrape_date I updated the table using an old Django system. However, another view without being updated also had this issue that we've never previously experienced. I don't have a lot of experience with SQL so after some looking I still don't know where to start to solve this issue. -
How to implement django rest api with phone otp based authentication
I am tried and succeed send otps and verifies otps. How to create custom user model for Django phone otp based authentication after entering otp how to check particular phone number with that otp, after verification how to create jwt token using phone number.... please reply if any knows as early as possible. -
How to use if else in django template
I have a part of the registration form that I wish to hide from third party viewers. Basically, it can only be seen on registration and the user of the account. I thought this is the correct syntax but it gavve me a TemplateSyntaxError Could not parse the remainder: '(request.user.is_authenticated' from '(request.user.is_authenticated' {% if (request.user.is_authenticated and request.user.account_type == 1) or not request.user.is_authenticated %} -
I want to serve a Django website from a Raspberry pi, setup as an access point in a standalone network (not connected to the internet)
I am working on a project to serve a django website from a raspberry pi thatis set up as an access point in a standalone network(not connected to the internet) just a minimum pi setup,am able to set it up as a wifi access point, but the challenge now is deploying the django website and serving it over the wifi access point to any connected device. am hoping somone could guid me through this orpoint me to any link with a guide to solve this -
Django Ordering First Column Groupings by Max Value in Second Column Per Group
Given a Model in Django with fields/values as shown: Group Votes A 5 B 2 B 7 A 3 it's easy to use class Meta: ordering = ['group', '-votes'] to return Group Votes A 5 A 3 B 7 B 2 How could this be modified so that the Group is also ordered by the max Votes value within each Group as shown: Group Votes B 7 B 2 A 5 A 3 -
Alternative Widget for Django Admin Choice Field Select with Many Entries?
I have a model with many country fields and each is a choice field wit list of countries. The issue is that there's a lot of countries! So each choice field adds a lot of size and rendering time to the page to generate a select dropdown in django admin. (E.g. Making 5 of these read only brought down response time from 10s to 4s!) I want to see if there's any alternatives known for handling choice field inputs. Since we use ISO-2 for countries, I want to avoid operators having to input values directly as they would not know them. Ideally I was hoping for some sort of search or select pop-up similar to what happens with raw_id_fields. That way a select list is only generated when needed, but so far havent found -
How to POST reverse relation using django rest framework?
I have a model set up with foreign keys referencing back to the model: models.py (There are more fields in A, but are irrelevant) class A(models.Model): name = models.CharField(max_length=60) class B(models.Model): other_name = models.CharField(max_length=60) a = models.ForeignKey("A", on_delete=models.CASCADE) And I have serializers set for both models. serializers.py class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = '__all__' class ASerializer(serializers.ModelSerializer): b_set = BSerializer(many=True) class Meta: model = A fields = ['name', 'b_set'] And a view for the model: views.py class AList(generics.ListCreateAPIView): queryset = A.objects.all() serializer_class = ASerializer I am able to issue a get request and receive both the A models and their associated B models. I can issue a post with just an A instance, but I can't issue a post with an A instance and a B instance at the same time. Is there a way to do this with one post request? -
IntegrityError :UNIQUE constraint failed: theatre_audience.ticketId
I am trying to create a Django application to assign seats for the audience in a theatre(for live performances). Whenever I try to add a new audience, I cannot add more than one audience. It gives UNIQUE constraint failed error. Here, in my code, I am trying to create a ticketId using the UUID field. But, it is not getting saved for more than one audience. my model from django.db import models import uuid # Create your models here. class Audience(models.Model): name = models.CharField(max_length=200, null=True) ticketId = models.UUIDField( primary_key = True, default = uuid.uuid4(), editable = False ) seatNo = models.IntegerField(default=0) my application def occupy(request, pname): arr = [i for i in range(1,Total_seats+1)] inst = Audience() inst.name = pname num = Audience.objects.values_list('seatNo') print(num) for i in num: v = i[0] arr.remove(i[0]) print(arr) if(len(arr)<1): msg="All seats are occupied" context={"msg":msg} return render(request,"theatre/ERROR.html",context) else: seatn = random.choice(arr) inst.seatNo = seatn inst.save() temp = Audience.objects.get(seatNo = seatn) context = {"temp":temp} return render(request, "theatre/show.html", context) I am getting error in the following line The above exception (UNIQUE constraint failed: theatre_audience.ticketId) was the direct cause of the following exception: inst.save() -
Access a variable defined in a function into another function while using flask
I am basically developing this query based website on flask where you can give tower and flat for someone and you get his details like his name and all. class DataForm(FlaskForm): tower = StringField('Tower eg. CC2', validators=[DataRequired(), Length(min=3, max=3)]) flat = StringField('Flat eg. 0001', validators=[DataRequired(), Length(min=1, max=4)]) submit = SubmitField('Submit') data = { 'CC10001':"['Granth', '1111']", 'CC10002':"['Bagadia','1112']", } @app.route("/data", methods=['GET', 'POST']) def data(): form = DataForm() code = f"{form.tower.data}{form.flat.data}" message = data[code] return render_template('data.html', title='Request Data', form=form) @app.route("/data_output", methods=['GET', 'POST']) def data_output(): name = message[0] I want to redirect the data_output page and print out the details from the data dictionary on receiving the code from user but don't know how to can someone guide me with it. If not by this method maybe some other manner Thank You -
How to run and test a django cloned project from github in visual studio code?
I have cloned a random project and trying to run it in my local system. I am using visual studio code editor. After opening the extracted folder in editor, I have clicked on run. At this point in time, a new chrome browser is getting opened and its showing that the server is down. I tried setting up a virtual environment and by using the command - "python manage.py runserver" . Even though I am unable to test that project. Could I get some insights to get rid of this issue as early as possible please? -
from django to django rest framework : e-commerce with react
i have completed an e-commerce project with pure django and want to transform it to Django Rest Framework with React, i just want to know if the use of Sessions to create a cart would still be the same or is there something else or a different aproach to keep cart functionality, i have been looking at some github projects to see how it can be done ,and just got me confused, if someone can clear that out for me, much much apreciated, thank you, -
Is Heroku handling Django template files differently than my local Django?
I have successfully deployed my Django application onto Heroku. Some pages work perfectly and exhibit successful loading of static files and templates, but others don't. In Python debug, my error points to a Django package file (defaulttags.py) TypeError at /[path] sequence item 1: expected str instance, int found Request Method:GET Request URL:[url] Django Version:3.1.4 Exception Type:TypeError Exception Value:sequence item 1: expected str instance, int found Exception Location:/app/.heroku/python/lib/python3.9/site-packages/django/template/defaulttags.py, line 218, in render Python Executable:/app/.heroku/python/bin/python Python Version:3.9.0 Python Path:['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Defaulttags.py unexpectedly clashes with a custom tag I'm using. Error during template rendering In template /app/testpage/templates/cite_snippet.html, error at line 6 sequence item 1: expected str instance, int found 1{% load static %} 2{% load custom_filter %} 3 4 5{%nospaces%} 6 {% for link in links %} 7 <a href="#footnote\_{% getglobal count %}" >[{% getglobal count %}]</a><a name="ref\_{% getglobal count %}"></a> 8 {% incrementglobal count %} 9 {% endfor %} 10{%endnospaces%} The traceback to defaulttags.py shows the problem: /app/.heroku/python/lib/python3.9/site-packages/django/template/defaulttags.py, line 218, in render 218. return mark_safe(''.join(nodelist)) Local vars ... nodelist [' \n <a href="#footnote_', 2, '" >[', 2, ']</a><a name="ref_', 2, '"></a> \n ', '', '\n '] So it seems like defaulttags.py uses .join on "nodelist" (a list made … -
How to access response.user from Django Form
Hi I am trying to access the user id that access to my form in order to give him the choice to select options from the db. this is my form code: from django import forms from .models import Viajes class solicitudesFacturas(forms.Form): razon_social = forms.CharField(max_length=200) ruc = forms.IntegerField() viajes_selected = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=listaviajes) def __init__(self, *args, **kwargs): self.user = kwargs.pop('user', None) super(solicitudesFacturas, self).__init__(*args, **kwargs) def getuser(self): user = self.cleaned_data.get('id') print(user.id) listaviajes = [] listaviajes2 = Viajes.objects.filter(id=user.id) for viajes in listaviajes2: elemento = [viajes.ride_ID, str( "Desde: " + viajes.pickup_zone + " - hasta: " + viajes.dropoff_zone + " - monto: " + str( viajes.billable_amount) + " - el: " + str(viajes.ride_date))] listaviajes.append(elemento) print(listaviajes) return listaviajes The problem is that I don't know how to use listaviajes for viajes_selected and when I put viajes_selected in getuser, it doesn´t appear in the form. Please I hope you could help me. This is my view.py code: @login_required(login_url='/login') def crear_solicitud(response): if response.method == "POST": form = solicitudesFacturas(response.POST, user=response.user) if form.is_valid(): razon_social = form.cleaned_data["razon_social"] ruc = form.cleaned_data["ruc"] viajes_selected = form.cleaned_data["viajes_selected"] print(razon_social) print(ruc) print(viajes_selected) print("id usuario: "+str(response.user.id)) usuario = User.objects.get(id=response.user.id) print(usuario) solicitud = Solicitudes(razon_social=razon_social, ruc=ruc, status="Solicitado", id=usuario) solicitud.save() solicitud_id = str(solicitud.id_solicitud) for viaje in viajes_selected: ride = Viajes.objects.get(ride_ID=viaje) … -
How to improve Django-PostgreSQL search performance and increase HTML rendering or AJAX response speed?
I am working on a full text search application in django with postgreSQL where the database has about 50k rows currently. I am using SearchRank and TrigramSimilarity and have already implemented SearchVectorField and GIN indexes, but still the search results takes around 5-10 seconds to display on the screen depending on the search complexity. I am using jquery ajax call to send the search query from UI to django views.py and after performing the search, filter and order operations, I am rendering a different HTML along with result query set using DTL. The execution time taken inside the views.py function is around 0.5 seconds but the total time taken during the ajax call and response is about 5-6 seconds. Please see my code below: VIEWS.PY start_time = time.time() search_query = SearchQuery(query) rank = SearchRank('search_vector', search_query, weights=[0.2, 0.4, 0.6, 0.8]) trigram = (TrigramSimilarity('report_name', query_trigram) + TrigramSimilarity('tool', query_trigram) + TrigramSimilarity('owner', query_trigram) result_set = BI_Report.objects.annotate(rank=rank, trigram=trigram, total=rank+trigram).order_by('-total').filter(Q(trigram__gt=0.2) | Q(rank__gt=0.1))[:50] time_taken = time.time() - start_time) return render(request, 'display.html', {"result_set": result_set, 'query':query}) time_taken = 0.45 seconds GIN indexes are present on both SearchVectorField and other database fields and it's showing Bitmap heap scan when running SQL inside postgres. In my code, on using .explain() I … -
which is the better design of database for article Like function?
I'm using Django to develop a news website.Now I'm developing the like function in news detail page, this function is like that at the bottom of the news, there is a like button, once you click it the amount of like will add 1. Now I have 2 choices to design the table of the database in django we call it model.I'm not sure which design is better. First:just use one News model class News(models.Model): ...code.. is_up = models.BooleanField(default=True) up_count = models.IntegerField(default=0) Once is_up ,up_count will add 1. Sceond:use 2 models,News model and a separate Like model class News(models.Model): ...code.. up_count = models.IntegerField(default=0) class Like(models.Model): """ 点赞表 """ nid = models.AutoField(primary_key=True) user = models.ForeignKey('UserInfo', null=True, on_delete=models.CASCADE) news = models.ForeignKey("News", null=True, on_delete=models.CASCADE) is_up = models.BooleanField(default=True) class Meta: unique_together = [ ('news', 'user'), ] Any friend can tell which design is better ?