Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field 'content_object' does not generate an automatic reverse relation and therefore cannot be used for reverse querying
Django 3.0.5 class TaggedItem(models.Model): tag = models.ForeignKey(Tag, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') def __str__(self): return self.tag.tag I didn't do save programmatically: t = TaggedItem(content_object=..., tag=...) t.save() But I have just saved TaggedItems in the admin site: Anyway, saving is done. Then I want to select all the tags related to an object. class JumpsuitsDetailView(DetailView): model = Sneakers def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context def dispatch(self, *args, **kwargs): response = super(JumpsuitsDetailView, self).dispatch(*args, **kwargs) tagged_items = TaggedItem.objects.filter(content_object=self.object) And I get this: Internal Server Error: /sneakers/1/ Traceback (most recent call last): File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/michael/PycharmProjects/varnish/varnish/sneakers/views.py", line 16, in dispatch tagged_items = TaggedItem.objects.filter(content_object=self.object) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/query.py", line 904, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/query.py", line 923, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1350, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1381, in _add_q check_filterable=check_filterable, File "/home/michael/PycharmProjects/varnish/venv/lib/python3.6/site-packages/django/db/models/sql/query.py", line 1250, in build_filter lookups, parts, … -
importlib.import_module ignoring re-exports made in __init__.py
(Originally asked on r/learnpython, but figured I'd ask here too.) Since this problem came up while dealing with django, I'll explain in that context. So I have a django project folder, and some internal django apps living in that project folder, like this: project_module ├ apps │ ├ app_module1 │ │ ├ models.py │ │ └ ... │ ├ app_module2 │ └ ... ├ settings.py └ ... now the app_modules are available as project_module.apps.app_module1 and so on, but since there won't be anything colliding with the app names in project_module, I'd like to drop the .apps part so I can just refer to them as project_module.app_module1 and such, consistently. So, I create __init__.py everywhere, and put this into project_module/__init__.py: from .apps import app_module1 And this sort of works, since I can import project_module.app_module1 and it seems to work. BUT, Django internally uses importlib.import_module here and there, and in those cases I encounter ModuleNotFoundError: No module named 'project_module.app_module1'. In those cases I can use the .apps again, but this sort of breaks consistency. A bit of experiment later, I'm convinced import_module ignores re-exports from __init__.py; But why does this happen, and is there a way I can play around this in … -
Django count of sizes in product
I am creating a shop backend. I have product model and each product has many to many field to sizes model. But there is a problem: how to manage count of each size for product? I just want to make request every time when user puts smth in the cart and make increment to count of this size in this product. My models: class Size(models.Model): class Meta: verbose_name = "Размер" verbose_name_plural = "Размеры" size = models.CharField(max_length=255, verbose_name="Размер") def __str__(self): return self.size class Image(models.Model): class Meta: verbose_name = "Фотография" verbose_name_plural = "Фотографии" image = models.ImageField(verbose_name="Фотография", upload_to='product_images/') def __str__(self): return self.image.name class Product(models.Model): class Meta: verbose_name = "Товар" verbose_name_plural = "Товары" title = models.CharField(max_length=255, verbose_name='Название') images = models.ManyToManyField(Image, verbose_name="Фотографии") cost = models.IntegerField(verbose_name='Цена') sizes = models.ManyToManyField(Size, verbose_name='Размеры') description = models.TextField(max_length=2000, verbose_name='Описание') structure = models.CharField(max_length=50, verbose_name="Материал") sizes_image = models.ImageField(verbose_name="Сетка размеров", upload_to='product_sizes/') -
Django template displaying images in wrong position
I'm new to Django so apologies if this one is silly. I have a Django template with three spots for images, and I'm trying to let an admin user choose which image in the database should go in which spot (left, middle or right). However, My model looks like this: from django.db import models from django.urls import reverse from django.utils.text import slugify class Artwork(models.Model): art = models.ImageField(upload_to='artworks/%Y') title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) date = models.DateField(auto_now_add=True) herochoices = [('left', 'left'), ('middle', 'middle'), ('right', 'right')] hero = models.CharField(choices=herochoices, max_length=6, unique=True, null=True, blank=True, error_messages={'unique':'Another artwork already uses this hero position.'}) slug = slugify(title, allow_unicode=False) def get_absolute_urls(self): return reverse('artwork_list', kwargs={'slug': self.slug}) And my template looks like this: {% extends 'base.html' %} {% block content %} <div class="container"> <div class="row"> {% for artwork in object_list %} {% if artwork.hero == 'left' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for testing--> </div> {% elif artwork.hero == 'middle' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for testing--> </div> {% elif artwork.hero == 'right' %} <div class="col-sm p-3 align-items-center"> <img class="img-fluid rounded" src="{{ artwork.art.url }}" /> <p>{{ artwork.hero }}</p> <!--for … -
Css file not responding at django project
I am trying to change navbar color through css file at django. But cant. Here is the folders: folders of the project base.html home.html main.css -
Django, how to implement a formfactory in my models structure?
I have the following question for you. I have four models: Informazioni generali, Lavorazione, Costi_materiale and Mod. The first two give me the possibility to register "codice_commesse" and "numero_lavorazione" in this mannner: class Informazioni_Generali(models.Model): codice_commessa= models.CharField() CATEGORY_CHOICES=( ('BOZZA', 'BOZZA'), ('PREVENTIVO', 'PREVENTIVO'), ('COMMESSA', 'COMMESSA') ) status=models.CharField(choices=CATEGORY_CHOICES) nome_cliente=models.CharField() class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.IntegerField() prodotto=models.ForeignKey() sottoprodotto=models.ForeignKey() note=models.CharField() Once registred these two models, client have the possibility to register Costi_materiale and Mod, related to Lavorazione (itself related to Informazioni generali). class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) numero_lavorazione=models.ForeignKey(Lavorazione) conto = models.ForeignKey(Conto) tipologia = models.ForeignKey(Tipologia) sottocategoria = models.ForeignKey(Sottocategoria) quantita=models.DecimalField() prezzo=models.DecimalField() class Mod(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, on_delete=models.CASCADE, null=True) numero_lavorazione=models.ForeignKey(Lavorazione, on_delete=models.CASCADE, null=True) nome_cognome=models.CharField(') costo_orario=models.DecimalField() monte_ore=models.DecimalField() I have created the model forms for Informazioni_generali and Lavorazioni, but I have problems to implement the form for the last two models. I want to have the following structure, but I don't know how to implement it. I want to fill only one time "codice_commessa" and "numero_lavorazioni" for all models related (Costi_materiale and Mod). And I want to give the possibility to the user to add new form clicking on the "+" button. Do you have some suggestions? -
Need point values after addition in django templates
the problem is when is use add filter i get a raw result or a round off result like say 10 + 0.2 = 10 only (instead i want it to print 10.2). My models.py and templates file below models.py class Shop(models.Model): price = models.FloatField() i filled the value of price in database as 5. home.html {{ object.price }} it prints 5 (good) but when i use filter -> {{ object.price|add:0.2 }} it returns 10 (i want 10.2) on my homepage -
Python and python framework
I have learnt basic of python like list, dictionary, loop, condition.i am PHP developer.next what should be do? Which database is familiar with python? Which framework should be learn for web and which for desktop application? -
Django Custom middleware don't display tags in each page
I am trying to print a add like message using session in each page while user visit my page. And i came out with this code it display my marketing message in index.html. middleware.py--- from .models import MarketingMessage from django.utils.deprecation import MiddlewareMixin class DisplayMarketing(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def process_request(self, request): print("something") try: request.session['marketing_message'] = MarketingMessage.objects.all()[0].message except: request.session['marketing_message'] = False my views.py-- def index(request): products = Product.objects.all() marketing_message = MarketingMessage.objects.all()[0] context = {'products':products,'marketing_message':marketing_message} return render(request,'pro/index.html',context) models.py-- from django.db import models class MarketingMessage(models.Model): message = models.CharField(max_length=120) active = models.BooleanField(default=False) featured = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now=False,auto_now_add=True) updated = models.DateTimeField(auto_now_add=False,auto_now=True) start_date = models.DateTimeField(auto_now=False,auto_now_add=False,null=True,blank=True) end_date = models.DateTimeField(auto_now_add=False,auto_now=False,null=True,blank=True) def __str__(self): return str(self.message[:12]) base.html-- {% if marketing_message %} <div class="alert alert-success alert-dismissible alert-top-message" role="alert"> <h3> {{ request.session.marketing_message|safe }} </h3> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} -
Reverse for 'evolucion_paciente' with arguments '(5,)' not found. 1 pattern(s) tried: ['evolucion_paciente/(?P<id>[0-9]+)/(?P<id_e>[0-9]+)$']
I have created a view that accepts 3 arguments but I get the following error in the homepage.Reverse for 'evolucion_paciente' with arguments '(5,)' not found. 1 pattern(s) tried: ['evolucion_paciente/(?P[0-9]+)/(?P[0-9]+)$'] Proyect/views.py -- One of my views def VerEvoluciones(request, id): if request.method == 'GET': paciente = Paciente.objects.get(id= id) evoluciones = Evolucion.objects.filter(paciente= id).order_by('-fechaEvolucion') evolucionForm = EvolucionForm() else: return redirect('index') return render(request, 'evoluciones.html', {'evolucionForm': evolucionForm, "Evoluciones": evoluciones, "Paciente": paciente}) Another View, and the one which im having troubles with def VerEvolucion(request, id, id_e): evolucionForm= None evolucion= None try: if request.method == 'GET': paciente = Paciente.objects.get(id= id) evolucion = Evolucion.objects.filter(paciente= id).get(id= id_e) evolucionForm = EvolucionForm(instance= evolucion) else: return redirect('index') except ObjectDoesNotExist as e: error = e return render(request, 'evolucion.html', {'evolucionForm': evolucionForm, 'Evolucion': evolucion, 'Paciente': paciente, 'Ver': True}) In my template, the link that i need to redirect me from my firt view to my second one <a href="{% url 'evolucion_paciente' evolucion.id %}" class="btn btn-warning">Ver</a> -
How can I connect a python application to my Django PostgreSQL database to write data
I have seen many quite similar questions here but nothing quite like it. I would like to write a python(kivy) app with the functionality to add data to the postgreSQL database of my heroku-deployed Django web app. How would I go about approaching this? -
TEARING MY HAIR OUT trying to move databases from SQLite to Postgres
Not sure how/why, but I started out using SQLite in production; now I need to move to Postgres pronto. So I do this: python3 manage.py dumpdata --indent 4 --natural-primary --natural-foreign -e contenttypes -e auth.Permission -e sessions > dumpdata.json No problem so far. Changed my setting.py to point to new postgres db, then run: python3 manage.py migrate --run-syncdb Still no problem. Problem comes here, when I run this command: python3 manage.py loaddata dumpdata.json I get this nasty error: django.core.serializers.base.DeserializationError: Problem installing fixture 'dumpdata.json' Googled this error on Stack Overflow. Seems like it happens when the file isn't valid JSON. I run head -1000 dumpdata.json and tail -1000 dumpdata.json and everything looks good. No trailing commas, no weird strings, nothing. What gives!? -
Which data binding supported by Django? one way, two way or three way binding?
Which data binding supported by Django ? I am planning to develop a web application with django. So in term of developing UI with django which data binding django supports : one way, two way or three way binding ? -
How can i add something to the database with a submit button in Django?
I'm making a grocery list web app in django and i have a page with your groceries list and i have a page with all the products you can add to your list. every product has a button "add to list". The intention is that when you click on that button that that product automatically becomes added to the groceries list. Does someone know how to do that? thank you in advance. The Groceries List page The all products page models.py from django.db import models # Create your models here. class Brand(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class AllProducts(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class ShoppingList(models.Model): product = models.ForeignKey(AllProducts, null=True, on_delete= models.SET_NULL, blank=True) brand = models.ForeignKey(Brand, null=True, on_delete= models.SET_NULL, blank=True) quantity = models.CharField(max_length=200, null=True, blank=True) info = models.TextField(max_length=500, null=True, blank=True) def __str__(self): return self.product The class brand is a class with all the brands of the products. The class All_Products is a class with all the products that you can add to your groceries list. And the class ShoppingList is a class with all the products in the groceries list. Views.py def home(request): products = ShoppingList.objects.all() context = { 'products':products, } return render(request, 'groceries_list/home.html', … -
How to query the following use case in Django?
I have made a game similar to the drinking game piccolo where you have a list of challenges. Each challenges has variables that need to be filled in (e.g: Player X gives four sips to Player Y). Besides that, a challenge consists of rounds, with each round having an index and a description (e.g Round 0: X and Y drink 4 sips. Round 1: X and Y drink 5 sips now), with X and Y being the same names in both rounds. First we made a small console app that had the challenges hardcoded in them. The list of challenges would look like this: challenge_list = [ Challenge(["p(0)", "rand_phone_number()"],[[0, "{d[0]} moet een nummer bellen. Het volgende scherm bepaalt welk nummer"], [1, "Het nummer is {d[1]}"]]), Challenge(["p(0)", "rand(2,5)", "rand_char('a','z')", "rand(2,5)"], [[0, "{d[0]} noemt {d[1]} dieren die beginnen met de letter {d[2]} of drinkt {d[3]} slokken"]]), Challenge([], [[0, "Alle drankjes schuiven een plek naar links"]]), After requests from other friends we decided that it would be educational to migrate the project to Django, since we did not have much experience in web development and we want to learn something new. We came up with the following model to replicate the hardcoded challenges … -
Django save_model doesn't get called
I want to override the save_model(...) method of the django admin. For this I created following class and method in the admin.py file: class ArticleAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): print('IN ADMIN') super().save_model(request, obj, form, change) Now I know this doesn't do anything different but I just wanted to test if this method gets called and it doesn't (print since I got no debugger). According to the official documentation this is the accurate method. Does anybody know what I did wrong? -
how to send emails to all users?
How can I send email to all users whenever I want? I have built a blog app and I want to send some emails about news and updates to all the users and I have no idea how to do it. please help me with the code. I'm using the built in django user model for auth. thanks for the responses -
How to use self page database update in Django?
I have a question on my homepage that the user should answer through radio buttons. The user should press the submit button to send the answer, so basically it is a SELF PAGE submission. The user should not go to another page after submitting the answer but should remain on the same home page. Though I looked up some earlier questions, the code did not work out. I have created the TEMPLATE DIRECTORY under the root folder and under this directory, there is a 'pages' folder that has the index.html (homepage) inside which I am invoking the form The form code in the index.html page. <form action = "?" method = "POST"> I want to know what function should I write in the views. Since the form action does not call a named view I am not able to figure out how I should define the view that updates the data. def WHAT NAME SHOULD I GIVE HERE(request): .....other code Thanks -
django Download Link(filefield)
i am trying to create a Software download website, and each software has some file and download link (mac,windows,linux,..). Can anyone tell me how to use 'filefield' for download links(not one). (Sorry, my English is so weak). -
Django on Google App Engine in 2020, Cloud SQL slow and extremely costly, why is it the so popular or what am I doing wrong?
I have been testing django apps on google App engine following the tutorials from google, but I am experiencing extremely slow SQL, and looking at the billing it would be costing a ridiculous amount if I were not on the free credits that came with signup. At this stage I cannot see how this could work in production. It seems that running Django on app engine is more popular than ever, but I do not understand why? In my experience a simple django app would seem to incur charges of more than 100$ pr month from cloud sql and this is without any real traffic to the app? What could I be doing wrong (I am using the db settings from the tutorials)? Why is Django seemingly so popular if Cloud SQL charges are so high? Is there another way to run Django on app engine without using the costly Cloud SQL/PostgreSQL? I choose App engine for the scalability and to avoid having to maintain a VM but at this stage I am wondering if to avoid the GAE completely as I am very worried what the costs would be with a high traffic scenario.. -
I want to join 2 html pages but getting distorted output
I have two html pages one for navbar and other for contact form, when i try to join them both i get distorted single page. Image will be included below. I tried making section but its not helping out:/ This is for a django project so codes might b slightly different. Thanks in advance :) html of navbar <nav> <div class="logo"> <a class="h4" href="{% url 'home' %}">Nihaal Nz</a> </div> <ul class="nav-links"> <li><a href="{% url 'about' %}">About</a></li> <li><a href="#">Cool Cloud</a></li> <li><a href="{% url 'contact' %}">Contact</a></li> </ul> </nav> html of contact page <div class="container"> <form class="shake" action="{% url 'contact' %}" role="form" method="post" id="contactForm" name="contact-form" data-toggle="validator"> {% csrf_token %} <h2>Let me know what you felt.</h2> <div class="row100"> <div class="col"> <div class="inputBox"> <input type="text" name="name" required="required"> <span class="text">First Name</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <div class="inputBox"> <input type="text" name="email" required="required"> <span class="text">Email</span> <span class="line"></span> </div> </div> <div class="col"> <div class="inputBox"> <input type="text" name="subject" required="required"> <span class="text">Subject</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <div class="inputBox textarea"> <textarea name="message" required data-error="Write your message"></textarea> <span class="text">Type your message here...</span> <span class="line"></span> </div> </div> </div> <div class="row100"> <div class="col"> <input type="submit" value="Send"> </div> </div> </div> combined html code {% load static … -
Why do we pass in a function as an argument without execution in django?
When creating a post model that includes title, content, and author, I wrote author = models.ForeignKey(User, on_delete=models.CASCADE) for the author because one author can have many posts. My question is why is the function passed to the on_delete parameter not executed. In other words, why isn't it on_delete=models.CASCADE() instead(note the parentheses)? -
InlineFormset is_valid always return False
This is my models: class Company(BaseModel): name = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company Name')) class CompanyPicture(BaseModel): title = models.CharField(max_length=255, blank=True, null=True, verbose_name=_('Company Picture Title')) picture = models.ImageField(upload_to=UploadTo(title), default='static/base_picture_avatar/No Image.jpg', blank=True, null=True, verbose_name=_('Company Picture')) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True, verbose_name=_('Company')) This is my Company Form and Company Picture Form. class CompanyForm(forms.ModelForm): class Meta: model = Company fields = ( 'name', ) class CompanyPictureForm(forms.ModelForm): picture = forms.ImageField(widget=ImagePreviewWidget) class Meta: model = CompanyPicture exclude = () fields = ( 'title', 'picture', 'description', 'avatar_flag' ) Inline FormSet Company Picture: CompanyPictureFormSet = inlineformset_factory( Company, CompanyPicture, form=CompanyPictureForm, fields=( 'title', 'picture', 'company', 'description', 'avatar_flag' ), extra=0, ) Update View. Form Submit have problem at form_valid. pictures.is_valid always return False. I really don't think my models and my forms have problem. But i don't know why can't valid inline formset. class CompanyEdit(UpdateView): model = Company form_class = CompanyForm template_name = 'frontend/company/createdit.html' context_object_name = 'company' success_message = 'Company Information Updated!' def get_context_data(self, **kwargs): context = super(CompanyEdit, self).get_context_data(**kwargs) if self.request.POST and self.request.FILES: context['pictures'] = CompanyPictureFormSet(self.request.POST.get(), self.request.FILES, instance=self.object) else: context['pictures'] = CompanyPictureFormSet(instance=self.object) return context def form_valid(self, form): context = self.get_context_data() pictures = context['pictures'] with transaction.atomic(): form.instance.created_by = self.request.user.username self.object = form.save() if pictures.is_valid(): ##### This is always return is False print(pictures.instance) … -
my ajax request not worked in FF,IE but worked in chrome
i have two ajax function in my HTML file: 1 $(document).ready(function(){ $('#send').click(function(){ var value1 = document.getElementById("id1").value; $.ajax({ url: "http://somewhere/somedef", type: "post", // or "get" data: {'data1': value1}, headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token success: function(data) { }}); }); }); 2 $(document).ready(function(){ $('#check').click(function(){ var value1= document.getElementById("id1").value; var value2= document.getElementById("id2").value; $.ajax({ url: "http://somewhere/somedef", type: "post", // or "get" data: {'data1': value1,'data2':value2}, headers: {'X-CSRFToken': '{{ csrf_token }}'}, // for csrf token success: function(data) { }}); }); }); both work in Chrome right. but in FF and IE, just the first one workes! also the second one works in localhost but not in onlineserver!! -
can we know how many routers did my request touched before getting to the server
As in internet the request is passed through various routers . I am working on a web application in which i want to know how many routers is my request is being passed before reaching the server . Help will be appreciated