Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django MySQL error : django.db.utils.OperationalError: (1054, "Unknown column 'Euro.id' in 'field list'")
I coded a website based on PHP and I've recently started switching the solution to Django since I need the website to be able to run Python Scripts. Previously, all the datas were located on a MySQL database and were fetched through PHP / SQL Queries. I started following tutorials to connect the existing database to the Django App, and so I generated all the models with the following command: python manage.py inspectdb > models.py The models are correctly generated but the problem is that when I try to fetch data and display it on the HTML page I get the following error : django.db.utils.OperationalError: (1054, "Unknown column 'Euro.id' in 'field list'") Here's the way I summon the data : Views.py : from django.shortcuts import render from django.http import HttpResponse from .models import Euro from django.template import loader # Create your views here. def index(request): listeEuro = Euro.objects.first() context = { 'lasteuro': listeEuro, } return HttpResponse(request, context) The HTML : <div class="d-flex" id="UpdateEuro" style="cursor: pointer;"> <div class="mt-2"> <h6 class="">Euro</h6> <h2 class="mb-0 number-font"> {{lasteuro}} </h2> </div> <div class="ms-auto"> <div class="chart-wrapper mt-1"> <canvas id="euro" class="h-8 w-9 chart-dropshadow"></canvas> </div> </div> </div> Models.py : class Euro(models.Model): date = models.DateField(db_column='Date', blank=True, null=True) # Field name … -
Filter in get_context_data and get_query_set not working
I have a listview where I'm trying to filter out products by category. Some products have a subcategory. When a product has a subcategory I want the listview to display them by subcategory. Problem is: The listview works perfect for items with a subcategory, but does not work for items who do not have a subcategory. Where am I taking a wrong turn here? Models: class Category(models.Model): category_name = models.CharField(max_length=200) sub_category = models.CharField(max_length=200,blank=True,null=True) category_picture = ResizedImageField(upload_to='category/', null=True, blank=True) category_info = models.TextField(blank=True, null=True) category_video = models.CharField(max_length=250,blank=True, null=True) def __str__(self): if self.sub_category is None: return self.category_name else: return f" {self.sub_category}" class Meta: ordering = ['category_name'] class Bottle(models.Model): category_name = models.ForeignKey('Category', on_delete=models.SET_NULL,null=True,blank=True) brand = models.ForeignKey('Brand', on_delete=models.CASCADE) bottle_name = models.CharField(max_length=255) bottle_info = models.TextField() bottle_tasting_notes = models.TextField() bottle_barcode = models.IntegerField() bottle_image = ResizedImageField(upload_to='bottles/',null=True, blank=True) bottle_shop_link = models.CharField(max_length=250, null=True, blank=True) def __str__(self): return f"{self.brand}, {self.bottle_name}" class Meta: ordering = ['bottle_name'] View: class BottlesByCategoryView(ListView): model = Bottle context_object_name = 'bottles' #Filter bij subcategory in the category model. If no subcategory exists, load by category_name def get_queryset(self): if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None: return Bottle.objects.filter(category_name__category_name=self.kwargs['category']) else: return Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) def get_context_data(self, **kwargs): context = super(BottlesByCategoryView, self).get_context_data(**kwargs) if Bottle.objects.filter(category_name__sub_category=self.kwargs['category']) is None: context['category_info'] = Category.objects.filter(category_name=self.kwargs['category']) else: context['category_info'] = Category.objects.filter(sub_category=self.kwargs['category']) return context URLS: path('BottlesByCategory/<str:category>/',BottlesByCategoryView.as_view(template_name='academy/bottlesByCat_list.html'),name='bottlesByCat_list'), … -
API that uses selenium for webscraping
I'm creating an API (Django/DRF with daphne) that accepts requests, scrapes website for data and returns it in response to user. Will this work properly for multiple users in the same time (in parallel)? Or it's impossible to scrape website for each request at the same time? -
update fields based on other table in django models using override method
I have two models, In activity model status is column name this column row has to update from 'Pending' to 'Done', when status column row update from 'Pending' to 'Done' in Item model. class Activity(models.Model): a_id = models.AutoField(primary=True, unique=True) status = models.CharField(max_length=225, blank=True,null=True, default="Pending") class Item(models.Model): item_id = models.AutoField(primary=True, uniue=True) activityid = models.ForeginKey(Activity, on_delete=models.CASCADE, related_name="activitynt") -
How to fetcha all data on the basis of search data
Family will book the tutor. Step-1: Family will search Tutor by Subject and which dates family want to tutor their kids by Teacher. Step--2: Need to show all tutor of that subject for those days which are not booked yet. class TutorProfile(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) which_grade = models.ForeignKey( Grade, on_delete=models.CASCADE, blank=True, null=True) tutoring_subject = models.ForeignKey( TutoringSubject, on_delete=models.CASCADE, blank=True, null=True) sat = models.BooleanField(default=False) sat_time = models.CharField( _("Saturday Time:"), max_length=255, null=True, blank=True) sun = models.BooleanField(default=False) sun_time = models.CharField( _("Sunday Time:"), max_length=255, null=True, blank=True) mon = models.BooleanField(default=False) mon_time = models.CharField( _("Monday Time:"), max_length=255, null=True, blank=True) tue = models.BooleanField(default=False) tue_time = models.CharField( _("Tuesday Time:"), max_length=255, null=True, blank=True) wed = models.BooleanField(default=False) wed_time = models.CharField( _("Wednesday Time:"), max_length=255, null=True, blank=True) thu = models.BooleanField(default=False) thu_time = models.CharField( _("Thursday Time:"), max_length=255, null=True, blank=True) fri = models.BooleanField(default=False) fri_time = models.CharField( _("Friday Time:"), max_length=255, null=True, blank=True) And the Booking Models is: class Booking(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) book_day = models.CharField( _("Book Day"), max_length=255, null=True, blank=True) book_time = models.CharField( _("Book Time"), max_length=255, null=True, blank=True) status = models.CharField( _("Status"), max_length=255, null=True, blank=True) Code in viewset.py: def get_queryset(self): subject_param = self.request.GET.get('subject') bookday = self.request.GET.get('book_day') grade = self.request.GET.get('grade') import ast li = list(bookday.split(",")) print("Book Info:", li) from datetime import datetime for … -
HOW TO SAVE AND CONTINUE IN DJANGO LIKE IN DJANGO-ADMIN
I have a Django form below, I want to save a form by using two buttons: "Save & Add" and "Save & Continue" like in Django Admin. <form method = 'POST' enctype = 'multipart/form-data'> {% csrf_token %} {form | crispy} <div class="form-group"> <button type="submit" name="save_add" class="btn btn-de-primary btn-sm text-light px-4 mt-3 mb-0">Save & Add</button> <button type="submit" name="save_continue" class="btn btn-de-danger btn-sm text-light px-4 mt-3 mx-4 mb-0">Save & Continue</button> <a href="{% url 'doctor:list_doctor' %}" class="btn btn-de-success btn-sm text-light px-4 mt-3 mb-0" type="button">Close</a> </div> </form> My code in views.py is as follows: def addDoctor(request): if request.method == 'POST': form = DoctorForm(request.POST, request.FILES) if form.is_valid(): form=form.save(commit=False) form.save() if request.POST.get('save_add'): messages.success(request,'Doctor is successfully added') return redirect('doctor:list_doctor') elif request.POST.get('save_continue'): return redirect('doctor:add_doctor') return redirect('doctor:list_doctor') else: form = DoctorForm() context = { 'form':form } return render(request,'doctor/add_doctor.html',context) -
UnboundLocalError: cannot access local variable 'u_form' where it is not associated with a value
@login_required def profile(request): if request.user.groups.filter(name='Student').exists(): try: profile = request.user.studentprofile except StudentProfile.DoesNotExist: profile = StudentProfile(user=request.user) if request.method == 'POST': u_form = UserUpdateForm(request.POST,instance=request.user) p_form = ProfileUpdateForm(request.POST, instance=profile) if p_form.is_valid(): p_form.save() messages.success(request, "Your information has been updated successfully.") return redirect('user-profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=profile) elif request.user.groups.filter(name='Employee').exists(): try: profile = request.user.employeeprofile except EmployeeProfile.DoesNotExist: profile = EmployeeProfile(user=request.user) if request.method == 'POST': p_form = EmployeeProfileUpdateForm(request.POST, instance=profile) if p_form.is_valid(): p_form.save() messages.success(request, "Your information has been updated successfully.") return redirect('user-profile') else: u_form = UserUpdateForm(instance=request.user) p_form = EmployeeProfileUpdateForm(instance=profile) context = { "u_form": u_form, "p_form": p_form, } return render(request, 'accounts/profile.html', context) I've been expecting for the django application to display the user profile but the error code is preventing that from actualizing -
OAuth and integration with the G suite
I have a DRF and Vue web application that uses OAuth for authentication via the drf-social-oauth2 package. Essentially, authentication goes like this: the user logs in with their Google account and gets a token from Google the frontend application issues a request to the convert-token token of my backend, which validates the Google token and issues an in-house token, which is also saved to my database from then on, the frontend application will include that in-house token in each subsequent request to my backend if that's the first time the user authenticates, a new account is created on my backend. This means that my backend, understandably, manages its own set of user accounts, which conceptually are twins of the Google accounts used to log-in. I'm now looking to integrate some Google applications into my webapp. To give a very simple example, I'd like to include a functionality that allows accessing Google slides and docs from the frontend of my app. Integration with those services is <iframe> based, so essentially I'd be embedding some iframes to access the resources on the G suite. Here's the issue: since, like I explained, requests to my backend are authenticated using an in-house token and … -
Django - CRUD functionality, Edit Profile Details
I am new to Django but I am creating a Realtor application, I would like the user to be able to update their details using CRUD functionality in the UI. But I can't get my request to work: Heres is my code (views.py): from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from contacts.models import Contact def register(request): if request.method == 'POST': # Get form values first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password = request.POST['password'] password2 = request.POST['password2'] # Check if passwords match if password == password2: # Check username if User.objects.filter(username=username).exists(): messages.error(request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error(request, 'That email is being used') return redirect('register') else: # Looks good user = User.objects.create_user( username=username, password=password, email=email, first_name=first_name, last_name=last_name) # noqa # Login after register auth.login(request, user) messages.success(request, 'You are now logged in') return redirect('index') # user.save() # messages.success( # request, 'You are now registered and can log in') # return redirect('login') else: messages.error(request, 'Passwords do not match') return redirect('register') else: return render(request, 'accounts/register.html') def login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user … -
How to resolve Profile matching query doesnot exist error in django
I am new to Django framework. This problem "profile matching query does not exist" comes and I don't understand where this problem is generating from. Please Let me know what else code is needed to resolve this error. I will update this question. profile matching query does not exist  I have rechecked the code in urls.py, views.py, index file. But I could not resolve this. urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index, name = 'index'), path('signup',views.signup, name = 'signup'), path('signin',views.signin, name = 'signin'), path('logout',views.logout, name = 'logout'), path('settings',views.settings, name = 'settings'), path('upload',views.upload, name = 'upload'), ] -
Exception ignored in thread started by: <function check_errors.<locals>.wrapper at 0x0000017C9E2FC1F0>
Don't know what the problem is. I am not able to run any of my Django servers. Every time gets the same error.enter image description here Tried reinstalling Django,python but always gets same error. -
TypeError non-string but other have str
why the first customer no name? other have name [] after click in customer 1, but other customer no problem [ -
Deleting characters in the list created using the getlist method
I created a list using the getlist method in my django project, and then I use this list in my form. Every time I update the form, it automatically adds a new character to the list. How can I prevent this? I used the strip and split methods but no results. I am attaching my codes below. models.py `class Records(models.Model): medications = models.CharField(max_length=1000, null=True,blank=True) scale_used = models.CharField(max_length=1000, null=True,blank=True) way_of_application = models.CharField(max_length=1000,null=True,blank=True) ` views.py `def insertList(request): records = Records() records.medications = request.POST.getlist('medications') records.scale_used = request.POST.getlist('scale_used') records.way_of_application = request.POST.getlist('way_of_application') records.save() return redirect('/index/tables') def getList(request,id): edit_records = Records.objects.get(id=id) if edit_records.medications is not None: edit_records.medications = edit_records.medications.strip('"]["').split(',') if edit_records.scale_used is not None: edit_records.scale_used = edit_records.scale_used.strip('"]["').split(',') if edit_records.way_of_application is not None: edit_records.way_of_application = edit_records.way_of_application.strip('"]["').split(',') return render(request,"update_record.html",{"Records": edit_records}) ` ** Output: medications = [''\'PULCET 40MG FLAKON\'"'', ''"\'METPAMİD 10MG/2ML AMPUL\'"'', ''"\'İZOTONİK 250ML\'"''] scale_used = [''\'1 FLAKON\'"'', ' ' " \'1 AMP\'"'', ' " ' 1 ADET'"', ' ' " \'\'''] way_of_application = [''\'I.V İnfüzyon\'"'', ''"\'I.V\'"'', ''"\'I.V\'"'', ''"\'\''']** I have given the codes I used with the outputs above, can you help with this? -
how to increment price if number of days increase in Django
view.py def booking(request): all_location = location.get_all_location() all_products = Product.get_all_products() data = { 'amount': 5000 } data['product'] = all_products data['location'] = all_location return render(request, 'booking.html', data) my html file put type='number' placeholder='enter days' </div> <div class="mb-5"> <div class="row"> <div class="col-6 form-group"> <input type="text" class="form-control p-4" placeholder="" required="required"> **{% comment %}Want to Get Value from days and save it variable {% endcomment %}** </div> </div> **<p>Amount = RS {{amount}} </p> **{% comment %}Want to Save amount in variable if user increase days then amount variable get increment {% endcomment %}** ** <div class="form-group"> <textarea class="form-control py-3 px-4" rows="3" placeholder="Special Request" required="required"></textarea> </div> </div> </div> I want to get and amount days value in variable then want to increment the amount if user increase days. I get the amount dynamically by view function and my other problem is that how to prevent user to change amount from source code. * -
Adding extra path to django get_full_path() through form
I just want to add something to mypath like: bla1/bla2/bla3/something or whatever pass in member! how can i do this? def to(request): if request.method == "POST": x = request.POST['username'] member = whome(unique_user=x) member.save() links.objects.create(path=request.get_full_path()) links().save() return render(request, "home.html") -
Django executing different url
urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include("dashboardapp.urls")), ] My terminal is showing Starting development server at http://127.0.0.1:8000/. But when I click the url its changing to different url http://127.0.0.1:8000/sales. But my url has no sales/. but my other project has sales/. Can anybody help with the solution for this -
NoReverseMatch on Django project
I am doing the CS50 web programming course and I am stuck with a url href, when I try to load the page it gives me a NoReverseMatch error. entry.html {% extends "encyclopedia/layout.html" %} {% block title %} Wiki {% endblock %} {% block body %} {% if msg_success %} <p style="color:green">{{msg_success}}</p> {% endif %} {{entry|safe}} <a href="{% url 'editEntry' title %}">[edit]</a> {% endblock %} The href in entry.html gives me the NoReverseMatch error. urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:title>", views.entry, name="entry"), path("search", views.search, name="search"), path("create", views.createEntry, name="create"), path("wiki/<str:title>/edit", views.editEntry, name="editEntry") ] If I visit the url wiki/TITLE/edit it renders the view but the href is not working. views.py def editEntry(request, title): if request.method == "GET": entry = util.get_entry(title) editForm = forms.EditPageForm(initial={'title': title, 'data': entry}) return render(request, "encyclopedia/edit.html", { "form": forms.NewSearchForm(), "editPageForm": editForm, "entry": entry, "title": title }) forms.py class EditPageForm(forms.Form): title = forms.CharField(label="", widget=forms.TextInput(attrs={ 'id': 'edit-entry-title'})) data = forms.CharField(label="", widget=forms.Textarea(attrs={ 'id': 'edit-entry'})) -
Is it possible to use a list of fields to query a model in Django
At the outset, let me be upfront that I am not too comfortable with what I am trying to achieve. But, here it is: I am trying to query a random model in my app for which the field names would be passed at runtime. Something like: fields_list = [field1, field2, ...] qs_target_model = target_model.values(fields_list) #, field3) Using the above setup, I get an error: 'list' object has no attribute 'split' The reason I am trying to do this: Both the model and its fields would be selected at runtime!! My question is: Is what I am trying to do possible at all? -
Context Processors in Python Django
context_processors.py from .models import Cart, CartItem from .views import _cart_id def counter(request): item_count=0 if 'admin' in request.path: return {} else: try: cart=Cart.objects.filter(cart_id=_cart_id(request)) cart_items=CartItem.objects.all().filter(cart=cart[:1]) for cart_item in cart_items: item_count += cart_item.quantity except Cart.DoesNotExist: item_count=0 return dict(item_count=item_count) Can someone explain these entire code to me. How's and what is the working of if loop here, return {}. -
Does Django model queries automatically make requests for foreign key reference objects?
Consider the following Django model: class Name(models.Model): pkid = models.BigAutoField(primary_key=True) person = models.ForeignKey(to=Person, on_delete=models.CASCADE) full_name = models.CharField(max_length=100) Will the following query automatically also do a join and retrieve the connected Person object, too? results = models.Name.objects.all() Or are all foreign key reference fields in Django automatically deferred until they are accessed? print(results[0].person) -
I don't want django to process path in order
Let say I have path something like bla1/bla2/bla3/bla4/...../something and I want django to look for last path something first instead of in order. I know we can do this with django-redirects but what if that something is dynamic? -
File not found when running django collectstatic with django pipeline
This is my pipeline setting: STATIC_URL = '/static/' STATIC_ROOT = SETTINGS_DIR + '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static_files"), ) STATICFILES_STORAGE = 'pipeline.storage.PipelineManifestStorage' STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'pipeline.finders.PipelineFinder', 'compressor.finders.CompressorFinder', 'beautycall.finders.LeftoverPipelineFinder', ) PIPELINE = { 'JAVASCRIPT': { 'main': { 'source_filenames': ( 'bower/jquery/dist/jquery.min.js', 'js/script.js', ), 'output_filename': 'compiled/main_script.js', }, 'datetimepicker': { 'source_filenames': ( 'bower/datetimepicker/jquery.datetimepicker.js', ), 'output_filename': 'datetimepicker.js' }, 'typeahead': { 'source_filenames': ( 'bower/typeahead.js/dist/bloodhound.js', 'bower/typeahead.js/dist/typeahead.jquery.js', ), 'output_filename': 'typeahead.js' }, 'remodal': { 'source_filenames': ( 'bower/remodal/dist/remodal.min.js', ), 'output_filename': 'remodal.js' } }, 'STYLESHEETS': { 'main': { 'source_filenames': ( 'css/style.scss', 'css/fonts.css', ), 'output_filename': 'compiled/main_stylesheet.css', }, 'datetimepicker': { 'source_filenames': ( 'bower/datetimepicker/jquery.datetimepicker.css', ), 'output_filename': 'compiled/jquery.datetimepicker.css' }, 'remodal': { 'source_filenames': ( 'bower/remodal/dist/remodal.css', 'bower/remodal/dist/remodal-default-theme.css' ), 'output_filename': 'remodal.css' }, 'website': { 'source_filenames': ( 'css/website/style.scss', ), 'output_filename': 'compiled/website/style.css', } } } Its return the error raise CompilerError(e, command=argument_list, pipeline.exceptions.CompilerError: [WinError 2] The system cannot find the file specified. When using custom pipefinder, the pipeline seem to miss all the file in source_filenames. Im using Windows and its no problem when i try it in Linux OS, if its help. It result in error when running this piece of code on django-pipeline : compiling = subprocess.Popen(argument_list, cwd=cwd,stdout=stdout,stderr=subprocess.PIPE, shell=False) At closer look the cwd argument seems fine, but 3 of 4 arguments in argument_list not exist … -
Does i need to use django.forms when i using ajax
I gonna made a few forms on one page and post it with ajax. So i got question - do i need use django forms for it, or just views? In my opinion django forms can validate html form by themself, but i actually don't know it. So what is the better decision in that case -
Is it possible to use Django ORM with JSON object?
I got two json objects that I need to combine together based on ID and do count and sort operations on it. Here is the first object comments: [ { "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto" }, { "userId": 1, "id": 2, "title": "qui est esse", "body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla" }, ] This is second json object: [ { "postId": 1, "id": 1, "name": "id labore ex et quam laborum", "email": "Eliseo@gardner.biz", "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium" }, { "postId": 1, "id": 2, "name": "quo vero reiciendis velit similique earum", "email": "Jayne_Kuhic@sydney.com", "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et" }, ] Is it possible to use django ORM to the json object? such as obj1.objects.count('title') or … -
How can I add atribute to webpage in django
screenshotI'm following a tutorial to create a website using django. I keep getting this error when running the server. path('page2',index.webpage2), AttributeError: module 'website.index' has no attribute 'webpage2'. Did you mean: 'webpage1'? Don't know what I'm missing, the tutorial ran the server without any problem. The only thing I noticed was that it also gave my a missing os error. I fixed this part. Thank you for your help