Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django HTML Dropdown with multiple values filter
I have this below mentioned dropdown with multiple values for each option <div class="form-wrapper"> <label>Fruits Selected</label> <input type="text" readonly class="form-control" id="fruits_selected" name="fruits_selected" value="{{fruits_selected.product}}" /> </div> <div class="form-row last"> <div class="form-wrapper"> <label for="">Fruits Type</label> <select id="Fruits" name="Fruits" class="form-control"> <option disabled="disabled" selected="selected">Choose option</option> <option value="Mango,Apple,Orange"> Fresh Fruits</option> <option value="Onion,Tomato"> Vegetable</option> <option value="Apple,Beetroot,Carrot"> Diet Fruits</option> <option value="Apple,Grapes"> Healthy Fruits</option> <option value="Tomato,Mango"> Juice Items</option> </select> </div> </div> Via Django, I will get the fruits like Apple, Orange. If the input in the {{fruits_selected.product}} is Apple then in the dropdown, I need to get the options Fresh Fruits, Diet Fruits, Healthy Fruits since the dropdown value consist Apple Similarly, if the option in {{fruits_selected.product}} is Tomato then in the dropdown, I need to get the options Vegetable, Juice Items since the dropdown value consist Tomato -
How do I filter possible field values in django admin or at model level for fields linked through nested ForeignKey?
I have the two following models: class Question(models.Model): question_content = models.TextField(max_length=500) related to: class PossibleAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=120) I would like to have a tree structure for a questionnaire, in which the option to go from one question or another might depend on the answer to the previous question. So I wanted to create another model as follows: class Relation(models.Model): child = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="child") parent = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="parent") parent_answer = models.ForeignKey(PossibleAnswer, on_delete=models.CASCADE, related_name="parent_answer") Now the issue I have, is that in the django admin, when selecting through parent_answer, it gives me the possibility to select any answer. That is, not only the ones that are linked to the selected parent question (via a foreign key). I believe that the admin does not do dynamic filtering, but I would at least like the possibility to select on parent_answer is filtered once the parent question has been selected and the record saved. Or that this would somehow be enforced at the model level. Is this possible? Any help highly appreciated! -
Django - ProgrammingError - column does not exist
I normally find a solution around this problem. I even tried the nuclear option of resetting the data base completely with python manage.py flush but no luck. the exact error message is the following: column main_reviewrating.venue_id does not exist Maybe it's the first time I pay attention to this but the venue**_id** seems strange. I am quite sure the usual message would have something like main_reviewrating.venue (without the _id When I run python manage.py showmigrations <your_app_name> it does show [X] 0001_initial I should also add that I am running this on my local, so no problem specific to deployment. Here is the code (models.py) class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) def __str__(self): return str(self.name) if self.name else '' class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) class Meta: db_table='Product' def __str__(self): return str(self.name) class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review =models.TextField(max_length=250) rating =models.IntegerField(choices=RATING, default=0) venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.CASCADE) def __str__(self): return '%s - %s'%(self.user, self.product) Any idea what I am doing wrong? -
Method Not Allowed (POST): /items/
So i'm trying to do a filter with django, to filter the items on the main page. A little context: An item can be assigned to a user or not. I want a filter, to see what items are assigned and which items aren't. This is my function in views.py: class ItemsView(ListView): template_name = 'inventory/items.html' context_object_name = 'items_list' def get_queryset(self): if (self.request.user.is_authenticated): if self.request.method == "get": searched = self.request.GET.get('searched') if searched == "None": return Item.objects.filter(assigned_user__isnull=True, company=getCompany(self.request.user)) else: return Item.objects.filter(assigned_user__isnull=False, company=getCompany(self.request.user)) else: return Item.objects.filter(company=getCompany(self.request.user)) And this is from my items.html: <form method="post" action="/items"> {% csrf_token %} <select name="item_filter"> <option value="None">Not Checked In</option> <option value="Checked_In">Checked In</option> </select> <input type="submit" value="filter"> </form> So basically what i want is, that the user can pick one of the two choices in the dropdown-menu, and the items should be listed based on the choice he made. When i use this form and click the submit button, the screen gets white and in my console, the error Method Not Allowed (POST): /items/ appears. Has this something to do with the fact i'm using the generic.ListView for my view? Thank you -
How should I change Parameter content type in swagger - django
I'm using the following serializer class to generate swagger UI. from rest_framework import serializers from django.contib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') The problem is my views accept form data but when using swagger UI to send requests, it sends json instead of form data. Is there any way to change Parameter content type in swagger? -
UTF-8 cannot decode ReportLab pdf
I'm having an issue regarding the decoding of pdf generated by reportlab library. Here is the code calling my function: print('Rendering Report and Sending Mail') r = renderTestPDF() sendTestPDF(r) This is the code creating the PDF: def renderTestPDF(): canvas = Canvas('hello.pdf') canvas.drawString(72, 72, "Hello, World") content = canvas.getpdfdata() return content This is the code sending the email and where I am getting the error: def sendtestpdf(report): # Variables For The Server emailhost = '' emailport = '' # Variables For The Email systemEmail = '' password = '' recieveremail = '' # Configure The Email Message message = MIMEMultipart() message["Subject"] = 'This is a test for pdf creation and attachment' message["From"] = systemEmail message["To"] = recieveremail html = """ <h1>Your report is here!</h1> """ # Turn The Message Into A MIME Object part1 = MIMEText(html, "html") **---- I THINK THIS IS WHERE THE ERROR IS LYING -----** binary_pdf = open(report, "rd") payload = MIMEBase('application', 'octate-stream', Name="Test.pdf") payload.set_payload((binary_pdf).read()) encoders.encode_base64(payload) payload.add_header('Content-Decomposition', 'attachment', filename='Test.pdf') # Add HTML/plain-text parts to MIMEMultipart message message.attach(part1) message.attach(payload) # Create Secure Connection with Server and Send Email context = ssl.create_default_context() with smtplib.SMTP_SSL(emailhost, emailport, context=context) as server: server.login(systemEmail, password) server.sendmail(systemEmail, recieveremail, message.as_string()) and lastly, this is the error I'm … -
How to solve FOREIGN KEY constraint failed ? DJANGO
I'm having a FK problem and I don't know if it's a problem with migrations or a diagram. Below are the models of my e-commerce. Where there are two types of users, Customers and Supermarkets. Each type can only assume one role. And each supermarket can have several products. The error happens when I associate a supermarket with a product. There is an error with my diagram ? products/models.py class Categoria(models.Model): nome = models.CharField(max_length=50) def __str__(self): return self.nome class Produto(models.Model): name = models.CharField(max_length=70) price = models.FloatField() qnt_stock = models.IntegerField() sold = models.IntegerField() category = models.ForeignKey(Categoria, on_delete=models.CASCADE) description = models.TextField(default="", blank=True, null=True) slug = models.SlugField(unique=True) image = models.ImageField(upload_to="products/%Y/%m/%d", blank=True, null=True) expiration_date = models.DateTimeField(null=True, blank=True) supermarket = models.ForeignKey( Lojista, on_delete=models.CASCADE, blank=True, null=True ) def __str__(self): return self.name def get_absolute_url(self): return reverse("produtos:produto_detail", kwargs={"slug": self.slug}) users/models.py class CustomUser(AbstractUser): class Role(models.TextChoices): SUPERMARKET = "SUPERMARKET", _("Supermarket") CLIENT = "CLIENT", _("Client") role = models.CharField(max_length=50, choices=Role.choices) def __str__(self): return self.username class Client(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Lojista(models.Model): def upload_photo_to(instance, filename): return f"brand/{instance.name}/{filename}" supermarket = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True ) brand = models.ImageField(upload_to=upload_photo_to, blank=True, null=True) cep = BRPostalCodeField() state = models.CharField(choices=br_states.STATE_CHOICES, max_length=2, null=False) city = models.CharField(max_length=128, null=False) district = models.CharField(max_length=128, null=True) street = … -
Nasting tables in serializer showing Null
Hi everyone I getting null I have a following: serializer class MeasurmentsSerializer(serializers.ModelSerializer): class Meta: model = Measurements fields = ('measurementid','measurement') class DeviceSerializer(serializers.ModelSerializer): lastmeasurementid = MeasurmentsSerializer(db_column='measurementTime') class Meta: model = Devices fields = ("devicename", 'deviceid', 'lastmeasurementid') Models -
"Python not found" after VSCode upgrade
I am using VSCode 1.52.1 to work with Python 3.9.1 and Django. I had to upgrade VSCode to 1.71.0 and when I run Django, I get the following error: VSCode terminal error messages Nothing changed with Python. Software installed, paths are the same. Do I need to change the JSON configuration file? Can someone help me solve this issue? Thanks and best regards, -
I need to run a background request on django app, what is the best way to do this
In index.html I have a form that accept files <form method="post" enctype="multipart/form-data" action=""> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary dropdown-toggle">Start Validation</button> </form> Then my app runs some functions to processes these files The problem is that the page keeps loading and waits for the return response my views.py class MainView(View): def get(self, request): form = UploadFileForm() return render(request, 'myapp/index.html', {'form':form}) def post(self, request): form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploadedFile = request.FILES['file'] function_to_processes_the_file(fil=request.FILES['file']) # Takes some time return redirect('/') So my question is how can I make it process the file in the background without the need to wait for a response, will it need javascript ? -
Django Python Foreign Key issue
I am showing "well" information linked to a specific project successfully based on well_id When I try to show drilling_tools in a similar fashion I get an error. Can anyone see what I am doing wrong in my views? def well_show(request, well_id): well = Well.objects.get(pk=well_id) drilling_tools = DrillingTool.objects.get(pk=well_id) return render(request, 'geodata/well_show.html', {'well': well, 'drilling_tools': drilling_tools}) -
NOT FOUND Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js IN A DJANGO PROJECT
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js while submitting a form in a django project , this comes up and no data is stored in database. GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 3019(this comes in the terminal) -
How do I solve the error on scrapy.clawer
Now, I develop web app with django and scrapy that has function of searching English word. When I input word with form on django, scrapy get the mean of transltated word into Japanese from internet dictionary. After inputting word ,activating scrapy and stop runserver, happning the error following: [scrapy.crawler] INFO: Received SIGINT, shutting down gracefully. Send again to force Error: That port is already in use. I can stop it by using command kill , but it is inconvinient to input command everytime happens error. So I want to know how to solve it like adding code etc. following is my code . def add_venue(request): submitted = False if request.method =='POST': form = VenueForm(request.POST) if form.is_valid(): name = form.cleaned_data['word']#入力した単語 queryset = Newword.objects.filter(word = name) print(queryset) if queryset.exists(): #コード未記入 else: #print(name) process = CrawlerProcess({ 'USER_AGENT': 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)' }) process.crawl(WordSpider, query=name)#入力した単語をnameに入れて、スクレイピングを実行。 process.start() # the script will block here until the crawling is finished form.save() return HttpResponseRedirect('/list/') else: form = VenueForm if 'submitted' in request.GET: submitted = True return render(request, 'form.html', {'form':form, 'submitted':submitted}) python3 manage.py runserver --nothreading --noreload django project is in scrapy project. -
How to create and save that file to Django model?
I want to create a file and save it to Django model within a view without creating any temporary files or anything like that. I plan to write a .txt file that contains information and I want to save the .txt file in the Django model. Does anyone know how to do this? Thank you -
How can I model a field to accep structures of the form [{names: [String!]!, scope: String!}]?
I want to add to the existing model myModel, a new field x, which can store structures of the form [{names: [String!]!, scope: String!}]. I also have to model the graphql mutation to update myModel, but I don't know how. I thought about the following solutions, but they don't seem to be the best: class myModel(models.Model): x = ArrayField(JSONField(default=dict), default=list, blank=True, null=True) class MyStructure(graphene.InputObjectType): names = graphene.List(graphene.NonNull(graphene.String, required=True), required=True) scope = graphene.String(required=True) class UpdateMyModel(ClientIDMutation): x = graphene.List(MyStructure) # x = graphene.List(graphene.JSONString) ? # x = graphene.List(GenericScalar) ? -
Stock Reduction
We are selling on an e-commerce platform and there is a part of the system where we have stocks and we want to experience a decrease in stocks in every sale. However, in the current system, for example, if we have 5000 ziplock bags, we use 2 pieces in one product and only one in the other. In such cases, since it would be very amateurish to write if for each product separately, what approach should we take for a more effective solution? My example code is: reduction_qty = { "Handmade": 1, "Vida": 1, "Dübel": 1, "Kilitli Poşet": 2, } other_items = Inventory.objects.filter( name__in=list(reduction_qty.keys())) for item in other_items: qty = reduction_qty.get(item.name) item.quantity = item.quantity - (transaction.quantity * qty) updated_items.append(item) -
How to fastly update field from a related model in django
I wanted to update a few milion records with a value from a related record using Django queryset but I got stuck on django.core.exceptions.FieldError: Joined field references are not permitted in this query Before I did it with a Subquery, but it was too slow. All I want is to execute this simple query, but wasn't able to find a Queryset equivalent for it, so I had to go with raw SQL. update card_cardtransaction set clearing_date = api_invoice.date_activated from card_cardtransaction ct join api_invoice on ct.invoice_id = api_invoice.id where ct.date_created > '2022-05-17' and id in %ids Any ideas how to compose this query using only queryset methods? This is the closest I was able to come with, but still with the error above. CardTransaction.objects.filter(id__in=ids) .select_related('invoice') .update( clearing_date=F("invoice__date_activated") ) -
Django do not auto escape characters
I have a code to play video in a django app <video controls autoplay id='vid' muted > <source src="{% static 'vids/videoplayback.mp4#t=10,30' %}" type="video/mp4"> </video> The problem is that django auto escapes the characters and gives an error GET http://127.0.0.1:8000/static/vids/videoplayback.mp4%23t%3D10%2C30 404 (Not Found) How do I prevent this from happening? -
Why is the entry not being added?
i am trying to add entries without using forms.py. But when saving, it redirects me to a non-existent page and does not save the product. Maybe a simple question but it puzzled me views def create(request): if (request.method == 'POST'): obj, created = Posts.objects.get_or_create(title=request.POST.get("title")) obj.text=request.POST.get("text") obj.save() return render(request, 'create.html ') html <form action="save" method="post"> {% csrf_token %} <input type="text" placeholder="Название" name="title"><br> <textarea placeholder="Текст статьи" rows="8" cols="80" name="text"></textarea><br> <input type="date" name="date"><br> <button type="submit">Добавить статью</button> </form> models class Posts(models.Model): title = models.CharField('Название', max_length=100, blank=True) anons = models.CharField('Анонс', max_length=250, blank=True) text = models.TextField('Текст статьи', blank=True) date = models.DateField('Дата публикации', blank=True) -
Django and HTML cannot start video from a specified time
I am trying to start playing a video from a specific location using Django: <video controls autoplay id='vid' muted > <source src="{% static 'vids/videoplayback.mp4#t=10,30' %}" type="video/mp4"> </video> This gives an error GET http://127.0.0.1:8000/static/vids/videoplayback.mp4%23t%3D10%2C30 404 (Not Found) as it seems Django automatically escaping the special characters is the culprit. Removing the #t=10,30 will autoplay the video without any issue. How do I fix this? -
AJAX calling Django view function not only once but for previous attempts as well
I have a code that should delete a list item. // Triggers when the item "element_to_click" is double clicked and calls the // function named show_hide_function() $( element_to_click ).one('dblclick', function(e) { show_hide_function(input_mt_key, update_form_mt, input_mt, button_text, csrfmiddlewaretoken)}); // Creates a button to delete the selected item, then calls delete_function() function show_hide_function(input_key, form, input, button_text, csrf_token){ const del_btn = document.createElement("button") del_btn.name="my_del_btn" form.appendChild(del_btn); const button_text_del = document.createTextNode("X") del_btn.appendChild(button_text_del) del_btn.setAttribute("class", "update_delete_buttons") // On click on del_btn, calls the function named delete_function() $( del_btn ).on('click', function(e) { delete_function(input_key,csrf_token)}); }; // Sends a form to backend (django) and on success, calls another function // named jsonToDict() which I believe, is not part of the problem. So I don't // include it here. function delete_function(input_key, csrf_token){ $(document).on('submit' , function(e){ e.preventDefault(); $.ajax({ type: 'POST', url: '/posted/delete/', data:{ item_id:input_key.value, projectURL: projectURL_, csrfmiddlewaretoken:csrf_token, }, success: function (data){ jsonToDict(data, "update_delete_form") }; }); }); }; And simplified version of my django view function looks like this: def deleteDictionary(request): print("called") if request.method == 'POST': var2 = request.POST['item_id'] projectURL = request.POST['projectURL'] value_holder = Task.objects.filter(taskID=var2).values_list('taskIdentifier') else: pass This is how my items look This is how they look on double click: When I delete first item, I get no error. When I do the same … -
Check if Django Group has Permission
I am developing a Django website where I can create groups, where permissions can be assigned. I can also assign groups to users. There is a simple way to check if a user has a permission: user.has_perm('app_name.permission_code_name') What I want to know is if there is a simple way to check if a specific group has a permission (without involving the user at all)? -
Model name of objects in django vews.py querysets
I'm trying to use django-taggit package for several applications on the site. I have two taggable models: Article, News (actually, more, but it does not matter). class TagListView(TagMixin, ListView): model = News, Article def get_queryset(self, **kwargs): my_tag = get_object_or_404(Tag, slug=self.kwargs['tag']) news = News.objects.filter(tags__in=[my_tag]).filter(is_published=True) articles = Article.objects.filter(tags__in=[my_tag]).filter(is_published=True) queryset = list(chain(news, articles)) return queryset In my template, I want to know, which model my objects belong to, in order to process them differently. The right place to do this would be add a 'content_type' feature to my objects in the queryset in my views.py. I imagine something like this: news = News.objects.filter(tags__in=[my_tag]).filter(is_published=True).select_related('django_content_type') articles = Article.objects.filter(tags__in=[my_tag]).filter(is_published=True).select_related('django_content_type') However, my models (news, articles) are not explicitly related to the model 'django_content_type'. Please somebody help me, I've got stuck! P. S. I'm aware that the proper way of doing this would be using generic keys, but I do not know how to work with them. If someone teaches me how to transform my example this way, it would be also great. -
Why does my property description get repeated in loop
So i have a for loop to display the every property in properties, I don't get why my property description gets repeated for every property. every other output is not repeated only the property description. {% for property in propertys %} <div class="listing-item"> <article class="geodir-category-listing fl-wrap"> <div class="geodir-category-img fl-wrap"> <a href="listing/{{ property.id }}" class="geodir-category-img_item"> <img src="{{property.header_image.url}}" style=" max-height: 210px;" alt="{{ property.header_image.url}}"> <div class="overlay"></div> </a> <div class="geodir-category-location"> <a href="#1" class="map-item tolt" data-microtip-position="top-left" data-tooltip="On the map"><i class="fas fa-map-marker-alt"></i> {{ property.location }}</a> </div> <ul class="list-single-opt_header_cat"> <li><a href="#" class="cat-opt blue-bg">{{ property.list_type }}</a></li> <li><a href="#" class="cat-opt color-bg">{{ property.home_type}}</a></li> </ul> <a href="#" class="geodir_save-btn tolt" data-microtip-position="left" data-tooltip="Save"><span><i class="fal fa-heart"></i></span></a> <a href="#" class="compare-btn tolt" data-microtip-position="left" data-tooltip="Compare"><span><i class="fal fa-random"></i></span></a> <div class="geodir-category-listing_media-list"> <span><i class="fas fa-camera"></i> 8</span> </div> </div> <div class="geodir-category-content fl-wrap"> <h3><a href="listing-single.html">{{ property.name }}</a></h3> <div class="geodir-category-content_price">$ {{ property.price }}</div> <p>{{ property.description }}</p> <div class="geodir-category-content-details"> <ul> <li><i class="fal fa-bed"></i><span>{{ property.bedrooms }}</span></li> <li><i class="fal fa-bath"></i><span>{{ property.total_bathrooms }}</span></li> <li><i class="fal fa-cube"></i><span>{{ property.lot_size}} ft2</span></li> </ul> </div> <div class="geodir-category-footer fl-wrap"> <a href="agent-single.html" class="gcf-company"><img src="{{ property.agent.profilepic.url }}" alt=""><span>By {{ property.agent.first_name }} {{ property.agent.last_name}}</span></a> <div class="listing-rating card-popup-rainingvis tolt" data-microtip-position="top" data-tooltip="Good" data-starrating2="3.9"></div> </div> </div> </article> </div> {% endfor %} -
mypy and Django type checking
I'm trying to enable type hints for my Django REST project. I installed django-stubs and djangorestframework-stubs and I have the following mypy.ini file: [mypy] plugins = mypy_django_plugin.main mypy_drf_plugin.main [mypy.plugins.django-stubs] django_settings_module = "core.settings.base" Some of the type hints do work; for example, if I have a variable inside of a method whose type is a model class, I get hints when I try to access a field or method defined on it. However, if I try to access a Django-specific field on the model, for example a reverse relation, that does not typecheck and gives me an error. Moreover, if I try to access fields on a related model of my model variable, the related object has type Any For example, with these two models: class User(models.Model): name = models.TextField() role = models.ForeignKey(Role) # definition of Role model not relevant class Badge(models.Model): user = models.ForeignKey(User, related_name="badges") then this will happen: u: User = get_user() print(u.name) # correctly hinted and typechecks print(u.badges.all()) # type error print(u.role.pk) # no hint on role.pk, role is Any How do I get my project to correclty type check all the Django-specific features such as foreign key fields, querysets, and reverse relationships?