Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such column: blog_category.parent_id
enter image description here enter image description herem4I.jpg -
Deploying Django + Vuejs in containers (AWS Elastic Beanstalk)
I'm developing an app with Django and Vuejs and the time has come to test deployment related things. My app will be deployed several times (1 instance per future customer) so I'd like to use containers for faster deployments and removal of virtual machine maintenances. The thing is : I do not now how to build the vuejs part in production. The Django backend is supposed to serve the bundle assets and, while I see on the AWS documentation that I can migrate, collect static files,... a Django application when the container starts, I do not know when/where I'm supposed to build the vuejs part in order to let Django collect the built things. Can someone help me on this ? When/where/how should I build the vuejs part ? Thanks in advance for your help. If more information is needed I will edit this post. -
Django how to get all the column names from the given sql table (model.py)
I am trying to fetch all the columns from the given SQL table in Django (model.py). I found most of the tutorials discussing getting a specific column using its column name. In my case, I can expect unknown columns in the future and I want to see them in the Django dashboard. Is there any possible way to get all the column names from the given table without giving any column names inside the model.py (Django)? -
Loading Flask app on ubuntu webserver without port number
I am new in web development and trying to load my website on ubuntu web server for the first time. The website is developed with Flask at backend. I loaded the website on local server and it's loading well on 127.0.0.1:5000/. I purchased a droplet on digitalocean.com and uploaded it on ubuntu webserver. It is loading well on 157.245.243.108:5000/. I purchased domain name from godaddy.com. The problem is that website is loading well with ip address (157.245.243.108) along with 5000 port. The godaddy DNS does not accept port value. It only asks for ip address. When I upload ip address only (without port) it only loads apache2 server page. The question is: How to load website to IP address only without port number? I am willing to share my code if required. -
Dynamic dropdown base on other input fields in django form
This is my model: class Location(BaseModel): value = models.CharField(max_length=255) class Category(BaseModel): location = models.ForeignKey( Location, on_delete=models.CASCADE, related_name="categories" ) name = models.CharField(max_length=255) class Food(BaseModel): category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="foods" ) name = models.CharField(max_length=255) Now in my food creation form, I have to select first a Location from a dropdown and then the next dropdown will be the categories under the selected Location. Can this be done in forms.py? This is my forms.py now. class FoodForm(NoFormTagMixin, forms.ModelForm): location = forms.ModelChoiceField( queryset=Location.objects.all(), required=True ) class Meta: model = Food fields = ( "name", "location", "category", ) -
What's the best way to approach relation does not exist error?
I'm getting a ProgrammingError relation does not exist for my site. I recently made changes to Postgres. I'm not even sure what would be the best thing to share to help someone understand the issue. Please let me know if you are familiar with this issue. I have seen a lot of problems with this on Stack Overflow. -
How to submit the same form multiple times all at once with the same submit button
I am still exploring and learning python and django, and I'm also working on some projects as well. I am currently building a student management system, but I failed to continue since I can't make my duplicate form accept marks input of multiple students. Here's my code! In my forms.py class AdvancedMathsForm(forms.ModelForm): class Meta: model = ResultsALevel fields = ('student_name', 'advanced_maths_1', 'advanced_maths_2',) Then here's my models.py class ResultsALevel(models.Model): objects = models.Manager() student_name = models.ForeignKey(AdvancedStudents, on_delete=models.CASCADE, related_name='a_level_student') title = models.OneToOneField(ExamTitle, on_delete=models.CASCADE, null=True) accountancy = models.CharField(max_length=4, default=None, blank=True, null=True) advanced_maths_1 = models.CharField(max_length=4, default=None, blank=True, null=True) advanced_maths_2 = models.CharField(max_length=4, default=None, blank=True, null=True) Here's my views.py class MarksEntryView(LoginRequiredMixin): def form_5_entry_maths_view(self, request): student_first_name = request.POST.get('first_name') student_middle_name = request.POST.get('middle_name') student_last_name = request.POST.get('last_name') maths_1_marks = request.POST.get('maths_paper_1') maths_2_marks = request.POST.get('maths_paper_2') print(f"{student_first_name}, {maths_1_marks}, {maths_2_marks}") for student_first in student_first_name: print(student_first) current_teacher = User.objects.get(email=request.user.email) logged_school = current_teacher.school_number students_involved = User.objects.get(school_number=logged_school).teacher.all() data_taken = ResultsALevel(student_name=None, advanced_maths_1=maths_1_marks, advanced_maths_2=maths_2_marks) data_taken.save() context = {'students': students_involved} return render(request, 'analyzer/marks_entry/marks_entry_page.html', context) And here's my html file ''' {% extends 'analyzer/layouts/base.html' %} {% block title %} Page User {% endblock %} {% block stylesheets %}{% endblock stylesheets %} {% block content %} {% load static %} <div class="row"> <div class="col-md-12"> <div class="card "> <div class="card-header"> <h4 class="card-title">Form 5 Students</h4> … -
Django Listing in Page Issue, "Data Not Appearing"
I ran into the problem that no results were listed when pulling a processed data into my SQlite class database. However, I did not encounter an error code. Related pages will be a page where each member will see their profile page and information. I want the data to be pulled according to the column I defined named user_id other than id. views.py def bilgilerim(request,id): bilgilerim_cek=players.objects.get(user_id=id) context={ 'bilgiler': bilgilerim_cek, 'bilgitum': players.objects.filter(user_id=id), } return render(request,'profil/bilgilerim.html', context) bilgilerim.html {% for bilgilerim_x in players %} {{ bilgilerim_x }} <div class="TopInfoStatistic w-100"> <p class="text-start w-75 float-start "><img class="m-0 p-0" src="../img/teams/{{ bilgilerim_x.team_id }}.png" alt="Generic placeholder image" style="width: 15px; height: 15px;"><strong class="text-dark">Dumlupınar S.K</strong></p> <p class="text-end w-25 float-end align-middle">{{ bilgilerim_x.dogecoin }}<img class="align-content-center" src="../img/icon/dogecoin.svg" style="width: 14px; height: 14px;"></p> </div> <div class="row w-100 InfoStatisticScore m-0 mb-3"> <div class="w-25 float-start m-0 p-0 pe-3" data-bs-toggle="modal" data-bs-target="#profilphoto"> <img class="m-0 p-0 border rounded-3 border-warning" src="{{bilgilerim_x.photo}}" alt="Generic placeholder image" style="width: 90px; height: 90px;"> </div> <div class="w-75 m-0 p-0"> <p class="w-100 m-0 p-0 ps-3" style="font-size: 20px; font-weight: 500;" data-bs-toggle="modal" data-bs-target="#namesurname">{{bilgilerim_x.name_surname }}</p> <p class="w-100 m-0 p-0 ps-3" style="font-size: 16px; font-weight: 500;" data-bs-toggle="modal" data-bs-target="#mobilenumber"> {{ bilgilerim_x.mobile_number}}</p> <p class="w-100 m-0 p-0 ps-3" style="font-size: 14px;" data-bs-toggle="modal" data-bs-target="#ageheightweight">Yaş: {{ bilgilerim_x.age }} - Boy: {{ bilgilerim_x.length }} - Kilo: {{ bilgilerim_x.weight … -
Bypass validator for title in model in UpdateView - Django
Heads up: this is pretty complicated to wrap your head around - in took me 30 minutes just to write this question Hi everyone, I am created a replica of stackoverflow. I am using a CreateView to allow them to create questions. CreateView: class CreateQuestionView(LoginRequiredMixin, CreateView): model = Question template_name = 'questions/questions-part/ask-a-question.html' fields = ['title', 'content', 'tags'] As you can see, it is using the Question model. Question: class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=120, validators=[is_unique_title]) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) num_of_ans = models.IntegerField(default=0) num_of_votes = models.IntegerField(default=0) tags = models.CharField(max_length=30) I have also put a validator in place for the title, so that you can't use a already-used title. def is_unique_title(value): titles = [i.title for i in Question.objects.all()] if value in titles: raise ValidationError(gettext_lazy('%(value)s is already taken'), params={'value': value},) I have put an UpdateView to update the post. class UpdateQuestionView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Question template_name = 'questions/questions-part/question-update.html' fields = ['title', 'content', 'tags'] context_object_name = 'question' success_url = reverse_lazy('list-questions') def test_func(self): post = get_object_or_404(Question, id=self.kwargs['pk']) if post.author == self.request.user: return True return False Now, my problem is this. When I update a question, and I don't change the title, django thinks that I am using a title … -
How to fix "Facebook has detected MySite isn't using a secure connection to transfer information" in social-auth-app-django?
I have no idea why I'm getting this error, I'm all ears to hear from you. Facebook has detected MySite isn't using a secure connection to transfer information -
View the scheduled tasks of celery in Django
I am scheduling some tasks with apply_async() providing the countdown for the task. Once the tasks executes I can view the state and logs with django-celery-results's task_results model. Now, I know all the scheduled tasks are added to the message queue from where I should be able to retrieve the scheduled tasks that haven't executed yet. But is there any other way to view them with state/logs etc. Or will I need to create a model similar to task_results andimplement the feature myself. -
Django Index Error: List Index out of Range using try catch
How do I throw in a try catch exception if there is no data within field student? I haven't put any data inside student for debugging purposes and I just want it to say "No Data found" or "You have no books issued" Here is my views.py: def viewissuedbookbystudent(request): student=models.StudentExtra.objects.filter(user_id=request.user.id) issuedbook=models.IssuedBook.objects.filter(enrollment=student[0].enrollment) li1=[] li2=[] for ib in issuedbook: books=models.Book.objects.filter(isbn=ib.isbn) for book in books: t=(request.user,student[0].enrollment,student[0].branch,book.name,book.author) li1.append(t) issdate=str(ib.issuedate.day)+'-'+str(ib.issuedate.month)+'-'+str(ib.issuedate.year) expdate=str(ib.expirydate.day)+'-'+str(ib.expirydate.month)+'-'+str(ib.expirydate.year) #fine calculation days=(date.today()-ib.issuedate) print(date.today()) d=days.days fine=0 if d>15: day=d-15 fine=day*10 t=(issdate,expdate,fine) li2.append(t) context={'li1':li1,'li2':li2} return render(request,'library/viewissuedbookbystudent.html',context) I get this error every time I run it and I know it's because of no data within student field: IndexError at /viewissuedbookbystudent list index out of range Request Method: GET Request URL: http://127.0.0.1:8000/viewissuedbookbystudent Django Version: 3.2.4 Exception Type: IndexError Exception Value: list index out of range Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\query.py, line 318, in __getitem__ Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.4 Python Path: ['E:\\C drive\\Users\\Admin\\PycharmProjects\\librarymanagement-master', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39', 'C:\\Users\\Admin\\AppData\\Roaming\\Python\\Python39\\site-packages', 'C:\\Users\\Admin\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages' Can I fix it using a try catch? If yes, how? -
Django Object Value Pull Resulting in Tuple?
New to Django and trying to understand a mysql query that I currently have working somewhat. It is pulling my database values but it is print this off as an array or tuple? I'm not sure exactly which one, I am assuming there is some .value like DFs but using object.value I thought would have done this? Seems so easy but after a few hours I need a nudge please. view.py from django.shortcuts import render from django.http import HttpResponse from .models import PreviousLossesMlbV2 def show_view(request): games = PreviousLossesMlbV2.objects.values('actual_over_under_result_field') results = PreviousLossesMlbV2.objects.values('actual_over_under_result_field') return render(request,"show.html", {'games': games, 'results': results}) show.html <!DOCTYPE html> <html lang="en"> <head> <title>Django CRUD Operations</title> <meta charset="utf-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <table class="table table-striped"> <thead> </thead> <tbody> <tr> {% for game in games %} <p>{{ game }}</p> {% endfor %} {% for result in results %} <p>{{ result }}</p> </tr> {% endfor %} </tbody> </table> </div> </body> </html> This works, but the problem is, here is the values displayed on the webpage. "{'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': None} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'UNDER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'UNDER'} {'actual_over_under_result_field': 'UNDER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': 'UNDER'} {'actual_over_under_result_field': 'UNDER'} {'actual_over_under_result_field': 'OVER'} {'actual_over_under_result_field': None} … -
Issue with Include template tag and forms
Disclaimer: I am aware of several other posts that raise my issue, but they do not apply to my code. Hi everyone, I am creating a knockoff of stackoverflow using Django, and I came into an issue. I have a View that shows a question that has been asked. Obviously, anyone coming to that question should be able to answer it. Here are the views and templates: This view displays the question and some other info: class QuestionsDetailView(DetailView): model = Question template_name = "function/questions/questions_detail.html" def get_context_data(self, *args, **kwargs): context = {} question_detail = Question.objects.filter(id=self.kwargs.get("pk")).first() answers = Answer.objects.filter(question=question_detail) context["question"] = question_detail context["questioncomments"] = QuestionComment.objects.filter(question=question_detail) context["answers"] = [[answer, AnswerComment.objects.filter(answer=answer)] for answer in answers] return context This view allows you to answer: class AnswersCreateView(LoginRequiredMixin, CreateView): model = Answer fields = ["content"] template_name = "function/answers/answers_create.html" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): return reverse("function-questions-detail", kwargs={"pk": self.kwargs.get("pk")}) On stackoverflow, when you view a question, you can answer it by scrolling down and providing your answer. I wanted to do something similar, so instead of having the answer view on a separate page, I put in in the question detail page using the 'include' template tag. Here are the templates: This is the … -
How to add data from multiple models to HTML template - Django
Background I have created an small app that can add projects, and show it in the index page, all those projects can be access individualy to its own "profile proJect page" clicking on the project name. Inside the project's profile page, it can be seeing data as ProjectName, ResponsableName, Description and so on. Problem I would like to fetch data from different tables to projects profile page until now I can only retrieve data from project table, but not from the rest of them, How could archive that ? views.py def registro(request, proyecto_id): proyecto = Proyecto.objects.get(pk=proyecto_id) return render (request, "Portafolio/registro.html", { 'proyectos': proyecto }) models.py from django.db import models # Create your models here. class Proyecto(models.Model): NombreProyecto = models.CharField(max_length=64) ResponsableProyecto = models.CharField(max_length=64) EvaluadorProyecto = models.CharField(max_length=64) DescripcionProyecto = models.CharField(max_length=500) class Financiamiento(models.Model): MontoProyecto = models.IntegerField(null=True, blank=True) MontoPropio = models.IntegerField(null=True, blank=True) MontoBanca = models.IntegerField(null=True, blank=True) MontoPublico = models.IntegerField(null=True, blank=True) proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) class Beneficio(models.Model): Rentabilidad = models.BigIntegerField(null=True, blank=True) proyecto = models.OneToOneField(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) class Infraestructura(models.Model): Infraestructura= models.CharField(max_length= 64) Tiempo = models.IntegerField(null=True, blank=True) Costo = models.BigIntegerField(null=True, blank=True) proyecto = models.ForeignKey(Proyecto, on_delete=models.CASCADE, primary_key=False, null=True) class Herramienta(models.Model): Herramienta= models.CharField(max_length= 64) Cantidad = models.IntegerField(null=True, blank=True) Costo = models.BigIntegerField(null=True, blank=True) proyecto = models.ForeignKey(Proyecto, on_delete=models.CASCADE, … -
How to get <div class> into datatable dropdown
I am using jquery datatable. In one column, a box is made in custom.css rather than text, and a color box that satisfies each condition is output. .box { margin: 0; padding: 0; width: 20px; height: 20px; border: 1px solid; } .green { background: #5BC236; } .red{ background: #ae163e; } <td> {% if test.participate == 'no' %} <div class="square-box red"></div> {% elif test.participate == 'hold' %} <div class="square-box green"></div> {% endif %} </td> <script type='text/javascript'> $(document).ready(function() { $('#search-result-table').DataTable( { "ordering": false, initComplete: function () { this.api().columns([7]).every( function () { var column = $(this).siblings('td.table-icon').find('img').attr('class'); var colTitle = this.header().innerHTML; var select = $('<select><option value="" selected>' + colTitle + '</option> </select>') .appendTo( $(column.header()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option>'+d+'</option>' ) } ); } ); } } ); } ); </script> The dropdown list for this column is not output as an empty value. I think it was because I used instead of text, It seems that you need to change the last part of JavaScript, select.append() But I haven't been able to solve it for … -
how to save and data to different Model in Django
you all, I wanna try to implement saving data in another table. There is favorite table and food table and what I need to do is to transfer to a food on favorite model to food table when users click add button. When transferring I don't want lose the adding data from the favorite table, instead keeping it in the favorite table. Any comment is helpful and thanks for your time in advance!! def add_to_today_foods(request, pk): favorite = get_object_or_404(Favorite, pk=pk) food = favorite if request.method == 'POST': food.user = request.user food.save() return redirect('today_foods') context = { 'food': food, 'favorite': favorite, } return render(request, 'base/add_to_today_foods.html', context) from django.urls import path from .views import FoodCreate, FoodUpdate, FoodDelete, FoodList, TargetCreate from . import views urlpatterns = [ path('', views.foods, name='today_foods'), path('all_foods', FoodList.as_view(), name='all_foods'), path('all_foods/search/', views.food_search, name='food_search'), path('favorite', views.favorite, name='favorite'), path('favorite/delete/<int:pk>', views.favorite_delete, name='favorite_delete'), path('favorite/update/<int:pk>', views.favorite_update, name='favorite_update'), path('favorite/add_to_today_foods/<int:pk>', views.add_to_today_foods, name='add_to_today_foods'), path('target', TargetCreate.as_view(), name='target'), # path('', FoodList.as_view(), name='foods'), path('create/', FoodCreate.as_view(), name='food-create'), path('update/<int:pk>', FoodUpdate.as_view(), name='food-update'), path('delete/<int:pk>', FoodDelete.as_view(), name='food-delete'), ] {% extends 'base.html' %} {% block title %}|お気に入り登録{% endblock %} {% block content %} <div class="header-bar"> <a href="{% url 'today_foods' %}">&#8592; 戻る</a> </div> <div class="body-container"> <div class="body-header"> <h1>お気に入り登録</h1> </div> <div class="notion2"> <p>※数字は半角で打ち込んでください</p> </div> <form action="{% url 'favorite' %}" … -
unable to give path to templates in Django
Django question here: So I was trying to get some html files to work through templates. I put this in the views.py file: def about (request): return render(request, 'about.html') def contact (request): return render(request, 'contact.html') def pricing (request): return render(request, 'pricing.html') def faq (request): return render(request, 'faq.html') and this in the urls.py file: path('about', views.about, name='about'), path('contact', views.contact, name='contact'), path('pricing', views.pricing, name='pricing'), path('faq', views.faq, name='faq'), ] Yet when I try to go there through the home page, it doesn't work and I get this: Error page Does anyone know how to fix this?!?!!! My templates folder and manage.py are in the same folder -
Modern practical option for Django search with Postgres? Need multiple criteria, but icontains is too inefficient
Django search / filter in views.py using icontains and gte, simplified: def BootstrapFilterView(request): qs = Table.objects.all() food_contains_query = request.GET.get('food') country_contains_query = request.GET.get('country') price_min_query = request.GET.get('pmin') qs = qs.filter(food__icontains= food_contains_query) qs = qs.filter(property_locality__icontains= country_contains_query) qs = qs.filter(purchase_price__gte=price_min_query) gte works fine but upon testing icontains is unsuitably inefficient. Indexing doesn't help for icontains and I think iexact might work, but users can't be expected to provide exact matches. I'm bewildered by more advanced options for a task well beyond my understanding and am reluctant to attempt potentially obsolete approaches. Using Postgres 11.6 with millions of rows, and need multiple optional search criteria. There are thousands of unique food and all are children of one of dozens of country. Django Postgres has full text search but all search criteria are nouns so don't need lexeme conversion but spelling correction (eg. "burito" → "burrito") and synonym matching (eg. "hamburger" → "cheeseburger") are desirable. Is Postgres full text suitable and can this be used with other search criteria of gte and similar numeric operations? What's a modern and practical way to improve performance? -
How can I get a blank quantity field to update as a 0 and stop my stripe payment from crashing?
I'm really stuck here and could use some help. When testing my project I found a flaw I'm having an issue fixing. In the shopping cart, if I remove the amount of any item and click Update Quantity: ...then I get the following error, and I would appreciate any tips or tricks. I'm thinking forcing it to update with 1 somehow? Thank you! -
AttributeError: module 'django.db.models' has no attribute 'RESTRICT'
Both CASCASE and PROTECT are working, but I cannot get RESTRICT to work. I am going through the Mozilla tutorial. book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True) I am getting this error when I try to make migrations AttributeError: module 'django.db.models' has no attribute 'RESTRICT' I am running django 3.2.4 -
i am trying to upload image in django but it gives me MultiValueDictKeyError at /index 'myfile'
I tried to insert image into sqlite but it didn't worked with it gives me error evertime this is my code def index(request): dbname = 'user1' cursor = connections[dbname].cursor() if request.POST.get('done'): cursor.execute('insert into images values(%s)', [request.FILES['myfile']]) return render(request, 'index.html') and this is the error MultiValueDictKeyError at /index 'myfile' Request Method: POST Request URL: http://127.0.0.1:8000/index Django Version: 3.2 Exception Type: MultiValueDictKeyError Exception Value: 'myfile' Exception Location: D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ Python Executable: D:\omar\pythonProject\venv\Scripts\python.exe Python Version: 3.9.2 Python Path: ['D:\\omar\\pythonProject', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\DLLs', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39\\lib', 'C:\\Users\\taha_lab\\AppData\\Local\\Programs\\Python\\Python39', 'D:\\omar\\pythonProject\\venv', 'D:\\omar\\pythonProject\\venv\\lib\\site-packages'] Server time: Mon, 28 Jun 2021 00:18:52 +0000 Traceback Switch to copy-and-paste view D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 76, in __getitem__ list_ = super().__getitem__(key) … ▶ Local vars During handling of the above exception ('myfile'), another exception occurred: D:\omar\pythonProject\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars D:\omar\pythonProject\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars D:\omar\pythonProject\Dhb\views.py, line 5951, in index cursor.execute('insert into images values(%s)', [request.FILES['myfile']]) … ▶ Local vars D:\omar\pythonProject\venv\lib\site-packages\django\utils\datastructures.py, line 78, in __getitem__ raise MultiValueDictKeyError(key) I tried to insert image into sqlite but it didn't worked with it gives me error evertime -
Basic data model for a food tracker
I am new to data modeling and trying to develop a Django model for a simple food tracker. What did you eat? Pancakes Meal Breakfast Ingredients Eggs Flour Milk Allergens Eggs When the user logged their Food, Meal, and Ingredients it would lookup to see if any of those ingredients are a known allergen. What would be the appropriate data model for this? My guess is below. Food Name Notes User_Id Meal Name User_Id Ingredients Name User_Id Allergens Name -
django 3.2 Import
Any idea why I'm not able to import files? For example if i use the period to import from the current package, it works. But if I try to explicitly define it or import from a remote application withing the project, it does not work. from device.serializer import DeviceSerializer ModuleNotFoundError: No module named 'device.serializer' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'django_countries', 'customer.apps.CustomerConfig', 'device.apps.DeviceConfig', ] -
Using yaml key values globally in Django
I want to use some key values from yaml file in my django project. example of 'Validation_Errors.yaml' file: errors: ERROR-BAD-REQ: PL : "Wprowadziłeś błedne dane spróbuj jeszcze raz" EN : "Wprowadziłeś błedne dane spróbuj jeszcze raz" RU : "Wprowadziłeś błedne dane spróbuj jeszcze raz" ERROR-BAD-CITY: PL : "To miasto jest błędne" EN : "To miasto jest błędne" RU : "To miasto jest błędne" I wrote a class that is initialized in views after the start: class UploadYaml(Exception): _file = 'Validation_Errors.yaml' _category = None _errors = None _error_code = 'ERROR-BAD-REQ' error_desc = str _language = 'PL' required = bool def __init__(self, **params): with open(self._file, 'r') as yaml_file: yaml_file = yaml.safe_load(yaml_file) self._errors = yaml_file.get(self._category) UploadYaml.error_desc = self._errors.get(self._error_code).get(self._language) for k, v in params.items(): if not k.startswith("_"): if hasattr(self, k): self.__setattr__(k, v) and it's working but I think there is a better method to do it. For example, can I initialize these code descriptions somewhere else globally in the application and use them everywhere I want (load file only once when application starts)? If I am initializing my class and want to import it into a different place there are some issues with correctly import file from the directory I know that I can …