Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Having trouble printing form credentials
Hey guys im pretty new to django and having a trouble when I try to print the posted credentials on my form. Here is what my html looks like <form method="post" style="font-family: Roboto, sans-serif;font-size: 36px"> {% csrf_token %} <div class="form-group"><input class="form-control" type="text" name="adsoyad" placeholder="Adınız ve Soyadınız" required=""></div> <div class="form-group"><select class="form-control" name="sehir" required=""> <optgroup label="Yaşadığınız Şehir"> <option value="12">Aydın</option> <option value="13">Balıkesir</option> <option value="14">Bilecik</option> <option value="15">Bursa</option> <option value="16">Edirne</option> <option value="17">Eskişehir</option> <option value="18">İstanbul</option> <option value="19">İzmir</option> <option value="20">İzmit</option> <option value="21">Kırklareli</option> <option value="22">Kocaeli</option> <option value="23">Kütahya</option> <option value="24">Manisa</option> <option value="25">Sakarya</option> <option value="26">Tekirdağ</option> <option value="27">Uşak</option> <option value="28">Yalova</option> <option value="29">Çanakkale</option> </optgroup> </select></div> <div class="form-group"><input class="form-control" type="tel" placeholder="Telefon Numaranız" name="telefon" required="" minlength="9" maxlength="10""> </div> <div class="form-group"><select class="form-control" name="medenidurum" required=""> <optgroup label="Medeni Durumunuz"> <option value="12" selected="">Evli</option> <option value="13">Bekar</option> <option value="14">Dul</option> </optgroup> </select></div> <div class="form-group"><input class="form-control" type="text" name="meslek" placeholder="Mesleğiniz" required="" minlength="0" maxlength="30"></div> <div class="form-group"><input class="form-control" type="number" name="dogumyili" placeholder="Doğum Yılınız" min="0" max="2020" required=""> </div> <div class="form-group"> <button class="btn btn-primary" type="submit" style="background: rgb(235,235,235);"> GÖNDER </button> </div> </form> and my views.py is here def index(request): if request.method == 'POST': adsoyad = request.POST['adsoyad'] telefon = request.POST['telefon'] sehir = request.POST['sehir'] medenidurum = request.POST['medenidurum'] meslek = request.POST['meslek'] dogumyili = request.POST['dogumyili'] print(adsoyad, telefon, sehir, medenidurum, meslek, dogumyili) return render(request, 'index.html') The sehir and medenidurum field is not working when … -
Docker django connect non docker postgresql
I have django project and trying to dockerize the project. Everything is working very well but the problem with postgresql. I have installed my postgresql in my local machine, so postgresql host is localhost and my django app running in my local machine docker. I dont want to install postgresql with docker, it's already installed without docker. so i tried to connect this with following infomrmatin: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydbname', 'USER': 'postgres', 'PASSWORD': 'secret', 'HOST': 'localhost', 'PORT': '5432', } } and it is not working, it's firing error. Can anyone help me what can i do in this case? I dont want to install postgres by docker, the datbase should be in my direct local machine. and this is my dockerFile FROM python:3.8.1-slim-buster RUN useradd wagtail EXPOSE 8000 ENV PYTHONUNBUFFERED=1 \ PORT=8000 # Install system packages required by Wagtail and Django. RUN apt-get update --yes --quiet && apt-get install --yes --quiet --no-install-recommends \ build-essential \ libpq-dev \ libmariadbclient-dev \ libjpeg62-turbo-dev \ zlib1g-dev \ libwebp-dev \ && rm -rf /var/lib/apt/lists/* RUN pip install "gunicorn==20.0.4" # Install the project requirements. COPY requirements.txt / RUN pip install -r /requirements.txt WORKDIR /app RUN chown wagtail:wagtail /app COPY --chown=wagtail:wagtail . … -
TypeError: UserProfile() got an unexpected keyword argument 'user'
Error TypeError at /spotify/authorize/ UserProfile() got an unexpected keyword argument 'user' Aim is to create a UserProfile as soon as a user is created models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE), liked_songs = models.ForeignKey("Song", on_delete= models.CASCADE, default=None) class Meta: db_table = "UserProfile" def create_profile(sender, **kwargs): if kwargs["created"]: user_profile = UserProfile.objects.create(user=kwargs["instance"]) post_save.connect(create_profile, sender=User) class Album(models.Model): Album_name = models.CharField(max_length=40) class Meta: db_table= "Album" class Song(models.Model): track_name = models.CharField(max_length=250) artiste_name= models.CharField( max_length=200, default=None ) album = models.ForeignKey(Album, on_delete= models.CASCADE) class Meta: db_table="Song" def __str__(self): return self.track_name -
DRF - overrige Serializer.update to update related set
I'm trying to override update method of ModelSerializer so I can update the related set of objects while updating the instance. The problem is that validated_data doesn't include ids of these objects even when I'm passing there to the serializer. def update(self, instance, validated_data): subcontracts = validated_data.pop('subcontracts') # THERE ARE NO IDS HERE contract = super().update(instance,validated_data) instance.subcontracts.exclude(id__in=[x.get('id',None) for x in subcontracts if x is not None]).delete() for subcontract in subcontracts: _id = subcontract.get('id',None) if _id: sc = SubContract.objects.get(id=_id) else: sc = SubContract() for attr, value in subcontract.items(): setattr(sc, attr, value) sc.contract = instance sc.save() return contract Basically, what I want to do: {id:4, some_data..., subcontracts:[{id:1,description:'xxx'},{id:2,description:'yyy'}]} This data would (except updating the instance) delete related subcontracts not having id 1 or 2 and update the rest. Do you know what to do? -
when i use objecs.values('xx') i am losing my related fields
Firstly, sorry for couldn't find right title for my problem. I prapered a queryset in views.py. It is grouping the countries and summing the cities population. There is no problem and i can show the sum of population and grouped country as {% for query in queryset %}<li>{{query.countryname__name}} : {{query.country_population}}</li>{% endfor %} But how can i add location of country which i defined on my models.py? Or other related county fields? Because when i use City.objects.values('countryname__name') i am losing my data and can not reach any field as City.objects.all() :( Models.py class Seasons(models.Model): season = models.CharField(max_length=50) def __str__(self): return self.season class Country(models.Model): name = models.CharField(max_length=30) location = models.CharField(max_length=50) flag_def = models.CharField(max_length=50, null = True, blank = True) season_country = models.ManyToManyField("Seasons") def __str__(self): return self.name class City(models.Model): name = models.CharField(max_length=30) countryname = models.ForeignKey(Country, on_delete=models.CASCADE) population = models.PositiveIntegerField() def __str__(self): return self.name views.py def index(request): queryset = City.objects.values('countryname__name').annotate(country_population=Sum('population')) content = { "queryset" : queryset } return render(request,"index.html", content) template.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Population</h1> {% for query in queryset %} <li>{{query.countryname__name}} : {{query.country_population}} {{query.countryname__name.location}} </li> {% endfor %} </body> </html> display: Population Brazil : 7700000 (in here i would like to display … -
ManyToMany field query returns empty set but not empty
I have a many-to-many field that when queried is returning an empty QuerySet but is definitely not empty. I can see this from the admin page. I can see in admin that there is an Application object in Vacancy(id=1). Plus when I query the job for an Application, it returns Vacancy(id=1). I have included my shell script below. models.py class Vacancy(models.Model): CATEGORY_CHOICES = [ ('ADMINISTRATION', 'Administration'), ('CONSULTING', 'Consulting'), ('ENGINEERING', 'Engineering'), ('FINANCE', 'Finance'), ('RETAIL', 'Retail'), ('SALES', 'Sales'), ] employer = models.ForeignKey('Employer', on_delete=models.CASCADE) job_title = models.CharField(max_length=35, default=None) main_duties = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) person_spec = models.TextField(default=None, validators=[ MinLengthValidator(650), MaxLengthValidator(2000) ]) salary = models.PositiveIntegerField(default=None, validators=[ MinValueValidator(20000), MaxValueValidator(99000) ]) city = models.CharField(choices=CITY_CHOICES, max_length=11, default=None) category = models.CharField(choices=CATEGORY_CHOICES, max_length=15, default=None) max_applications = models.PositiveSmallIntegerField(blank=True, null=True) deadline = models.DateField(blank=True, null=True) applications = models.ManyToManyField('Application', blank=True) active = models.BooleanField(default=True) class Meta: verbose_name_plural = 'vacancies' class Application(models.Model): STAGES = [ ('pre-selection', 'PRE-SELECTION'), ('shortlisted', 'SHORTLISTED'), ('rejected pre-interview', 'REJECTED PRE-INTERVIEW'), ('rejected post-interview', 'REJECTED POST-INTERVIEW'), ('successful', 'SUCCESSFUL') ] candidate = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) job = models.ForeignKey('Vacancy', on_delete=models.CASCADE) cv = models.CharField(max_length=35, default=None) cover_letter = models.TextField(default=None, validators=[ MinLengthValidator(0), MaxLengthValidator(2000) ]) submitted = models.DateTimeField(auto_now_add=True) stage = models.CharField(choices=STAGES, max_length=25, default='pre-selection') manage.py shell >>> from recruit.models import * >>> RA = Vacancy.objects.get(id=1) >>> RA <Vacancy: 1 Research Administrator> … -
Using the URLconf defined in lec3.urls, Django tried these URL patterns, in this order: admin/ hello/ The empty path didn't match any of these
these are my main codes i wrote to create wepapp but i get this 404 error so pleas help my hello urls.py from django.urls import path from hello import views urlpatterns = [ path("", views.index, name="index") ] my urls.py from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include("hello.urls")), ] my views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def index(request): return HttpResponse("hello, orld") -
Stream OpenCV Video Stream in HTML webpage Django Python
I am using Django Framework. Can anyone advise how should I modify the views.py to enable Video Stream at HTML webpage ? Can anyone advise how to write the HTML webpage ? Views.py def camera(request): id = 0 cap = cv2.VideoCapture(0) font = cv2.FONT_HERSHEY_PLAIN while id == 0: _, frame = cap.read() decodedObjects = pyzbar.decode(frame) for obj in decodedObjects: #print("Data", obj.data) id = str(obj.data) id = id[2:-1] print(type(id)) print(id) cv2.putText(frame, str(obj.data), (50, 50), font, 2, (255, 0, 0), 3) cv2.imshow("Frame", frame) key = cv2.waitKey(1) if id != 0: cv2.destroyAllWindows() return redirect('product_detail', id) return render(request, 'infos/index.html') -
can we deploye django project on heroku, which we used mongodb as our DATABASES
I added MongoDB as a database like belove ... DATABASES = { 'default': { 'ENGINE': 'djongo', "NAME": 'smartFuelApp', } } ''' -
Calculate with agregates and save on table field on django
How to calculate the total of invoice using sum annotate or agregate instead of forloop and save the value on field invoice.total class Invoice(models.Model): date = models.DateField(default=timezone.now) client = models.ForeignKey('Client',on_delete=models.PROTECT) total = models.DecimalField(default=0, max_digits=20, decimal_places=2) def totalsubtotals(self): items = self.invoiceitem_set.all() total = 0 for item in items: total += item.subtotal return total def save(self, *args, **kwargs): self.total = self.totalsubtotals() super(Invoice, self).save(*args, **kwargs) class InvoiceItem(models.Model): invoice = models.ForeignKey('Invoice', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.PROTECT) price = models.DecimalField(max_digits=20, decimal_places=2) quantity = models.DecimalField(max_digits=20, decimal_places=2) subtotal = models.DecimalField(default=0, max_digits=20, decimal_places=2) def save(self, *args, **kwargs): self.subtotal = self.price * self.quantity super(InvoiceItem, self).save(*args, **kwargs) -
Django Allauth form login and google login
I have a problem. I would be glad if you help. There are two registration options on my site. Register with google and form. If there is a record with a form in my database, that record cannot login with google. Can you help me on the subject? -
How To Optimize Loop In Python Django
How To Loop All Users In Less Time From Firebase AUTH finallist = [] for users in auth.list_users().iterate_all(): finallist.append(users) I'm using this code to fetch all users in single request but it takes lot of time to fetch all the user list now I don't have idea to fetch all users in less time Please suggest me How I can fetch all the data from firebase AUTH in right way. #firebase #python #django Thanks -
django call view fuction from javascript onclick
I am trying to make a form where I can have buttons that assign an integer value to a field. If I use a url path that goes to the view then it refreshes the form and I lose all of the other data that has been entered so I am trying to use a javascript onclick event that could call the function. If there is a better way of doing it then please let me know. Template would be something like this: {% block head %} <script> function fieldBtnFunc() { $.get('view/', function () { alert("field updated!"); }); } </script> {% endblock head %} {% block content %} <form method="POST" action=""> {% csrf_token %} //main form {{ form.as_p }} <p>fields:</p> //this is the list of selected buttons //if clicked it should call function that sets field value to 0 {% if form_two.field.value == 1 %} <button onclick="fieldBtnFunc()" class="field_btn_selected" type="button">Field Label</button> {% endif %} //this is the list of unselected buttons //if clicked it should call function that sets field value to 1 {% if form_two.field.value == 0 %} <button onclick="fieldBtnFunc()" class="field_btn" type="button">Field Label</button> {% endif %} <input class="submit_btn" type="submit" value="Submit"> </form> {% block content %} View should look something like … -
Plotting Image with Plotly in Django
Hi community maybe you can help me. The last couple of days I was trying to find a solution to plot an image in Django with plotly because I need a 2nd trace with a scatter on top of it and additional a slider wo move around. But first things first. In order to plot an image from an URL I've put in the following in views.py in my Django app views.py from skimage import io def slide_plot(centroid=1): #steps = Ypixels.objects.filter(centroid__in=[centroid]).order_by('step').values_list('step', falt=True).distinct() #CentroidCount.objects.filter(centroid__in=[centroid]).order_by('id_observation').values_list('id_observation', flat=True).distinct() url = 'https://www.cs.technik.fhnw.ch/iris/sji_png/images/20140910_112825_3860259453/20140910_112825_3860259453_1400_1176.jpg' img_array = io.imread(url) layout = go.Layout( title='Appearances for Centroids', xaxis=dict( title='Step', ), paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', yaxis={ 'title':'occurences' }, images=dict( 'source':url ), ) data = [] fig = go.Figure(data=data, layout=layout) plot_test = plot(fig, include_plotlyjs=False, output_type='div') return plot_test once this is resolved I can move to the next step creating the scatter trace. Any help would be appreciated -
Django Creating Two Objects If Don't Exist
I have a django app and I need in one view function to get two objects: token and plan or create them if they don't exist, here the code I'm currently using: def get_or_create_token_and_plan(user): try: token = Token.objects.get(user=user) except ObjectDoesNotExist as e: token = Token.objects.create(user=user) try: plan = Plan.objects.create(user=user) except ObjectDoesNotExist as e: plan = Plan.objects.get(user=user) return token, plan def profile(request): user = User.objects.get(username=request.user) token, plan = get_or_create_token_and_plan(user) context = {'token':token, 'plan':plan} return render(request, 'profile.html', context) I'm trying to figure out a way of improving get_or_create_token_and_plan() function, knowing that token and plan objects will be, in theory, created initially at the same time. Except for exceptions, if I merge both try, except structures into a single one will work, like here: def get_or_create_token_and_plan(user): try: token = Token.objects.get(user=user) plan = Plan.objects.create(user=user) except ObjectDoesNotExist as e: token = Token.objects.create(user=user) plan = Plan.objects.get(user=user) return token, plan The main issue with this is that if token already exists and plan doesn't, the I will get an IntegrityError when creating it again for the same user, but as said, in theory this won't happend because both token and plan will be created only in this function, so my question is, should I change get_or_create_token_and_plan in … -
Django -AttributeError: 'str' object has no attribute 'objects'
I am a beginner in Python, I got an error -AttributeError: 'str' object has no attribute 'objects'. insert=feedback.objects.create(prid_id=pid,urid_id=uid,feedback=feedback,aboutproduct=aboutproduct,aboutshop=aboutcompany,shopid_id=sid) insert.save() -
Different Local Storage items for different Django user
I am making an E-commerce site with Django (Python Framework). But I'm Facing an issue that is : I am using Javascript local Storage for the items in cart I am logged in with my account username is for example : user1 I added 5 Titan watches in my cart And then I logged with some account username is for example : user2 (on the same device) I can see the same 5 Titan watches in my cart If I change my cart and add 4 mobiles and login with my previous account (user1) I can see the 4 mobiles and and not the Titan Watch And If I login with some other device then I see that my cart is totally empty That is happening Because on different devices the local Storage is different and if the same device and I am logging in with different accounts then the local Storage is same for user 1 and user 2 how should I set the local storage depending on the authenticated user and save the data and if I login with different device and login my account I should see my data and If I am not logged and then … -
how do i solve an 404 error in Django for images
I am stuck on this 404 error When I try to find what the error is using inspection I get this My settings code: STATIC_URL = '/static/' MEDIA_URL = '/images/' STATICFILES_DIR =[ os.path.join(BASE_DIR, 'static') ] How i refer to my image in the html file <img src="{% static 'images/logo.png' %}" alt="Image"> My urls file: urlpatterns = [ path('admin/', admin.site.urls), path('', include('amitians.urls')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) I have a static folder inside which i have an images folder On my inspection page the file type is shown as text/html though its clearly a .png. Not sure if its related but here and my error as shown in the command prompt geos like this: Quit the server with CTRL-BREAK. [12/Dec/2020 13:44:45] "GET / HTTP/1.1" 200 2616 [12/Dec/2020 13:44:45] "GET /static/images/logo.png HTTP/1.1" 404 1772 I've tried many solutions on stackoverflow but cant seem to get it working I've tried using my image file directly in the statics folder too. Would be GLAD if someone cud help out! -
django-allauth no records in db for emailconfirmation but verification works
I've been doing some tests with django allauth, but in production with debug flags off, I'm not able to view any email confirmation records in my db (postgresql) while verification still works correctly... My understanding is that any verification emails sent is recorded in the account_emailconfirmation table in the django's database (I use postgres). I can see these records in the db and in the admin console (as model view) in local testing (with debug on), but in production, both the records and the entry for EmailConfirmation in the admin console itself is missing. Have I messed up my migration settings? What could have caused this? -
Django send form request with csrf protection not sending form data
I have the following code in the client side: <form class="tab-pane fade in show active" id="panel7" role="tabpanel" action="/user?action=login" method="post"> <div class="modal-body mb-1"> <div class="md-form form-sm mb-2"> <input type="text" id="userName" class="form-control form-control-sm validate" placeholder="user name" required> </div> <div class="md-form form-sm mb-2"> <input type="password" id="password" class="form-control form-control-sm validate" placeholder="password" required> </div> {% csrf_token %} </div> <!--Footer--> <div class="modal-footer"> <button class="btn btn-info">Log in <i class="fas fa-sign-in ml-1"></i></button> <button type="button" class="btn btn-outline-info waves-effect ml-auto" data-dismiss="modal">Close</button> </div> </form> whenever I put the {% csrf_token %} tag inside the form, I can't see the full request payload back in the server: {'csrfmiddlewaretoken': '5aSfhBLgNYP0O43ds6E15mRRMMwkrNPG8lSzpb47GfsilPxQCFK31ODXr3tgNaKm', 'action': 'login'} I would like to receive: {'csrfmiddlewaretoken': '5aSfhBLgNYP0O43ds6E15mRRMMwkrNPG8lSzpb47GfsilPxQCFK31ODXr3tgNaKm', 'action': 'login', "userName", "password": "1231fadqa"} the username and password are not being received in the server side. -
JWT Token - Authentication were not provided in react native
I am finding it really difficult to get authentication on my project, I developed a backend with django and use JWT for token, it works well on the backend as when i use Postman, I get the token, when i request for any API view through Postman i put the Token in Authorization Type: Bearer. and its works well. but in react native, its not working, it keeps showing "Authentication credentials were not provided." in react-native debugger when i try to inspect an API, Please help. this is my API client in react where i get the endpoint: import { create } from "apisauce"; import cache from "../utility/cache"; import authStorage from "../auth/storage"; const apiClient = create({ baseURL: "http://127.0.0.1:8000/api", }); apiClient.addAsyncRequestTransform(async (request) => { const authToken = await authStorage.getToken(); if (!authToken) return; request.headers["Authorization"] = "Bearer " + authToken; // request.headers["x-auth-token"] = authToken; }); const get = apiClient.get; apiClient.get = async (url, params, axiosConfig) => { const response = await get(url, params, axiosConfig); if (response.ok) { cache.store(url, response.data); return response; } const data = await cache.get(url); return data ? { ok: true, data } : response; }; export default apiClient; If you need any page. i will gladly provide. -
can't compare offset-naive and offset-aware datetimes
I Need To compare the Booking datetime, Book the room when no one booked the Room While I'm Trying to Compare Two dates I got Below Error can't compare offset-naive and offset-aware datetimes Here Is my Check availability function import datetime from booking.models import Booking from mainapp.models import Room def check_avaliblity(room,Check_in,Check_out): avaliblity_list=[] #It will return binch of True and False booking_list=Booking.objects.filter(room=room)#It will check bookings of specific room ex:101 for booking in booking_list: if booking.Check_in>Check_out or booking.Check_out<Check_in: #booking.check_in and booking.check_out is existing booking avaliblity_list.append(True) else: avaliblity_list.append(False) #If any of list in avaliblity_list is get False The Booking cannot happend return all(avaliblity_list) This is My Booking Model class Booking(models.Model): """Django data model Booking""" user=models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) room=models.ForeignKey(Room,on_delete=models.CASCADE) Check_in = models.DateTimeField(datetime.datetime.strptime(str(datetime.datetime.now()),'%Y-%m-%d %H:%M:%S.%f').strftime("%Y-%m-%d %H:%M")) Check_out = models.DateTimeField(datetime.datetime.strptime(str(datetime.datetime.now()),'%Y-%m-%d %H:%M:%S.%f').strftime("%Y-%m-%d %H:%M")) class Meta: verbose_name = 'Booking' verbose_name_plural = 'Bookings' def __str__(self): return f'{self.user} booked {self.room} from {self.Check_in} to {self.Check_out}' And Finally Views.py if request.method=='POST': #This is from booking page get_roomType=Room_Type.objects.get(roomtype=request.POST['type']) roomid=get_roomType.id getout=request.POST['check_out'] check_out=datetime.datetime.strptime(getout,'%m/%d/%Y %H:%M %p').strftime('%Y-%m-%d %H:%M:%S+00:00') getin=request.POST['check_in'] check_in=datetime.datetime.strptime(getin,'%m/%d/%Y %H:%M %p').strftime('%Y-%m-%d %H:%M:%S+00:00') check_in=datetime.datetime.strptime(check_in,'%Y-%m-%d %H:%M:%S+00:00') check_out=(datetime.datetime.strptime(check_out,'%Y-%m-%d %H:%M:%S+00:00')) print(type(check_out)) #This can set the values id to roomtype id room_list=Room.objects.filter(room_type_id=get_roomType) user_book=request.user avalible_rooms=[] for room in room_list: if avalablity.check_avaliblity(room,check_in,check_out): avalible_rooms.append(room) if len(avalible_rooms)>0: room=avalible_rooms book_room=Booking.objects.create( user=user_book, room=room, Check_in=check_in, Check_out=check_out ) book_room.save() return HttpResponse(book_room) else: … -
How to render Model field in Django, either it contains text or image?
In models.py, question field contains text and question_img filed contains image. Questions may be text or image. If question filed contains text, question_img field should be empty and if question_img filed contains image, question filed should be empty. So, how to render text question or image question based on condition? If question field is empty then it should render question_img from Database vice-versa. models.py: class Questions(models.Model): paper = models.CharField(max_length=10, default='None') qs_no = models.IntegerField(default=None) question = models.TextField(max_length=500) question_img = models.ImageField(null=True, blank=True) option_a = models.CharField(max_length=100) option_b = models.CharField(max_length=100) option_c = models.CharField(max_length=100) option_d = models.CharField(max_length=100) ans = models.CharField(max_length=50) forms.py: class QuestionsForm(forms.ModelForm): paper = forms.CharField(widget=forms.Select(choices = PAPER_CHOICES)) class Meta: model=Questions fields=[ 'paper', 'qs_no', 'question', 'question_img', 'option_a', 'option_b', 'option_c', 'option_d', 'ans', ] views.py: def questions(request): if not request.user.is_superuser: return render(request, 'login.html') else: if request.method == 'POST': form = QuestionsForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('questions') else: return HttpResponseRedirect('questions') else: form = QuestionsForm() return render(request, 'questions.html', {'form':form}) def render_questions(request): print(f'user in render_questions is {request.user.username}', flush=True) if not request.user.is_authenticated: return render(request, 'login.html') else: global exam_session exam_session = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(10)) print(f"session id in render ques is {exam_session}", flush=True) questions = Questions.objects.all() ques = [] qs_no = 1 for q in questions: que = {} … -
Django Password Reset Request View not working
I have been trying to figure out what could be wrong with this Code but I can't seem to find it The email isn't sending the supplied email address @csrf_protect def password_reset_request(request): if request.method == 'POST': password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): email = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(Q(email=email)) if associated_users.exists(): for user in associated_users: current_site = get_current_site(request) mail_subject = 'Password Reset.' message = render_to_string('users/password_reset_mail.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': default_token_generator.make_token(user) } ) to_email = user.email email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return render(request, 'users/password_reset_sent.html') password_reset_form = PasswordResetForm() return render(request, 'users/password_reset_request.html', {'password_reset_form': password_reset_form}) -
ieldError: Unsupported lookup for AutoField or join on the field not permitted
Good day, I am trying to build a system that creates an order and allows a user to add pieces. Here are the two models: class Order(models.Model): order_slug = models.SlugField(unique=True, blank=True) machine = models.ForeignKey(Machine, blank=True,on_delete=models.DO_NOTHING) production_type = models.CharField(choices=PRODUCTION_TYPE_CHOICES, max_length=30) production_bond = models.CharField(choices=PRODUCTION_BOND_CHOICES, max_length=50) profile = models.CharField(choices=PROFILE_CHOICES, max_length=50) order_number = models.CharField(max_length=50) order_colour = models.CharField(choices=ORDER_COLOUR_CHOICES, max_length=50) order_finish = models.CharField(choices=ORDER_FINISH_CHOICES, max_length=10) order_gauge = models.IntegerField(choices=ORDER_GAUGE_CHOICES) order_width = models.IntegerField() date_received = models.DateTimeField(default=datetime.now) class Meta: ordering = ["date_received", "-profile"] def __str__(self): return (str(self.order_slug)) class Piece(models.Model): order = models.ForeignKey(Order,on_delete=models.CASCADE) coil = models.ForeignKey(Cut_Material ,on_delete=models.CASCADE) piece_length = models.DecimalField(max_digits=4, decimal_places=2) prime_pieces = models.IntegerField() reject_pieces = models.IntegerField() coil_constant = models.IntegerField(blank=True) def __str__(self): return (str(self.piece_length)) class Meta: ordering = ["-order","piece_length"] Here is what I want to do. Multiply the prime_pieces by the piece_length to get running_meters for each column I want to group the pieces by order_gauge, order_number, and sum the running_meters. Proposed solution piece = Piece.objects.all() order = Order.objects.all() For step 1 rm_data = Piece.objects.annotate(running_meters=ExpressionWrapper(F('piece_length') * F('prime_pieces'), output_field=FloatField())).values() For step 2 I am not sure Can someone help me please?