Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Nested serializer: Data is null
class RacuniizlaznifinancijskiSerializers(serializers.ModelSerializer): poslovnipartneri_set = PoslovnipartneriSerializers(source='*') class Meta: model = Racuniizlaznifinancijski fields = ('kupacid', 'datumdospjeca', 'poslovnipartneri_set',) OUTPUT: "poslovnipartneri_set":{"naziv":null,"adresa":null}}, What here can be issue? -
Spring/SpringBoot Administration panel like Django Admin
I have a generic question about Spring-SpringBoot. I'm familiar with Django. Using Django it's possible to integrate the Administration panel to manage the entities and other functions. Using Spring/Spring boot is there the same concept? So, It's possible to have a configurable Administration panel to have the CRUD operations on your entities? -
Django form validation working unexpectedly?
I have this form in my view: joinform = JoinProjectForm(request.POST) print(request.POST) print(joinform) if joinform.is_valid(): joinkey = joinform.cleaned_data['joinkey'] project = Project.objects.filter(joinkey=joinkey).first() project.users.add(request.user) return redirect('problemdashboard:problem-dashboard', project_id=project.pk) else: joinform = JoinProjectForm() And this is my model: class Project(MainAbstractModel): users = models.ManyToManyField(User) title = models.CharField(max_length=25, default="") joinkey = models.IntegerField(null=True, unique=True) Now what I don't understand is, why is the form validation returning False? It says that a project with that joinkey already exists, but I'm not trying to create a new project with that joinkey, I simply want to add an user to the product with the joinkey that the user inputs in the form. What am I missing here? Oh and the form itself is very simple: class JoinProjectForm(ModelForm): class Meta: model = Project fields = ['joinkey'] -
How to store user all the information in Django sessions
i configured settings.py in database storing sessions and it is working properly but I am getting confuse how to collect and retrieve data in session -
RelatedObjectDoes not exist at / User has no customer
I have a Django web app. I have a products app and an accounts app. When I register a new user on my accounts app, it successfully creates a user then it gets redirected to my home page where a bunch of products are shown (controlled by the superuser). But when I login on the http://127.0.0.1:8000/login/ using the newly created user and not the admin, when the login is successful, I am supposed to be redirected to my home page, but there's an error that says. RelatedObjectDoes not exist at / User has no customer. I'm still new thanks! Here is my products/models.py from django.db import models from django.contrib.auth.models import User class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, null=True) email = models.CharField(max_length=100, null=True) My admin panel with all the models The customer model -
how to import one app model to another app?
I have created one app as appuser and second utility. I want to import model of appuser to the utility. I have mentioned both applications in the INSTALLED_APPS. But when ever i try to import model of appuser like appuser.model it gives an error. Please help -
How to set default value in relationship
I have relationship 1 -> M (case -> document) and how can I set default relationship when I am creating new document. My goal is: I have a list of cases, I open a case and I create new document in case and this document has default value (not blank) with document which was open. I have I want to have (default) view.py def sprawa(request, id): users = get_object_or_404(User, pk=id) users.save() cases = get_object_or_404(Case, pk=id) cases.save() documents = Dokument.objects.all() return render(request, 'sprawa.html', {'users': users, 'cases': cases, 'documents': documents}) def new_document(request): form = NewDocumentForm(request.POST or None, request.FILES or None) if form.is_valid(): form.save() return redirect('/sprawy/') return render(request, 'nowydokument.html', {'form': form}) nowydokument.html <form method='POST' enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <button type="submit">Dodaj sprawę</button> </form> -
OnetoOne (primary_key=Tue) to ForeignKey in Django
I have a OnetoOne field with primary_key=True in a model. Now I want to change that to a ForeignKey but cannot since there is no 'id'. From this: user = models.OneToOneField(User, primary_key=True, on_delete=models.CASCADE) To this: user1 = models.ForeignKey(User, related_name='questionnaire', on_delete=models.CASCADE) Showing this while makemigrations: You are trying to add a non-nullable field 'id' to historicaluserquestionnaire without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py So how to do that? Thanks! -
Why is the logo not showing on my site? I get a 404 not found error on the GET request to get the logo
I am trying to add a logo to my site, but for some reason it just isn't showing up.I have configured my code to the best of my knowledge but here is my code. First i made sure django.contrib.staticfiles is included in my INSTALLED_APPS. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'blog', ] i then ensured i defined STATIC_URL in my settings.py. I am only using one STATIC STATIC_URL = '/static/' STATICFILES_DIR = [os.path.join(BASE_DIR, 'static')] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') In my templates, i used the static template tag to build the URL for the relative path using the configured STATICFILES_STORAGE {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> {% block title%} {% endblock title%} <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="{%url 'index' %}"> <img src="{% static 'img/ATbrAaMRc.jpg' %}" alt='Image'> </a> Any help is appreciated. -
Redirect django url with javascript
i have countdown timer with javascript, I want to redirect to another page after countdown is over.countdown works pefectly but it's not redirecting to the result page i tried this: app.js var count = 15 var counter = setInterval(timer , 1000) function timer(){ count = count-1 if (count <= 0) { clearInterval(counter); return window.location.replace("{% url'app:result' %}") } document.getElementById("timer").innerHTML= count + " secs"; } -
Django - Dynamic filter Foreign Key choises on previοus user choice
I'm building an app for personel. Someone belongs in a company, wich have different departments. A department from one company may have the same name with the department of another company. The models: class Company(models.Model): COMPANIES = (('Comp1', 'Comp1'), ('Comp2', 'Comp2'), ('Comp3', 'Comp3'),) name = models.CharField(primary_key=True, max_length=5, choices=COMPANIES) def __str__(self): return self.name class Departments(models.Model): name = models.CharField(max_length=10) company = models.ForeignKey(Company, on_delete=models.CASCADE) def __str__(self): return self.name class Personel(models.Model): name = models.IntegerField(primary_key=True, unique=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) department = models.ForeignKey(Departments, on_delete=models.CASCADE) The (very basic) form: class PersonelForm(forms.ModelForm): class Meta: model = Personel fields = ['name', 'company', 'department'] Companies and Departments are managed from the admin page. The view: def new_personel(request): template = 'TestApp/new_personel.html' form = PersonelForm(request.POST or None) if form.is_valid(): form.save() return HttpResponseRedirect('/thanks/') context = { 'form': form } return render(request, template, context) The template: <form method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> With the current code, in the department select field are shown all the departments from all companies in the database. What I'm trying to achive is when the user selects the company, the department select field dynamicaly being filled with the departments from the selected company. All the solutions I managed to find requires the … -
Django message box while view is running
I have a Django app which performs a rather time consuming statistical model run within my views.py. As the computation progresses in the view I would like to inform the user perdiodically before the final HttpResponse, for e.g.: Step 1 completed Step 2 running... Is there a way to display a message to the front-end while the view is running? -
Why did the lower built in filter not work in Django template 2.2?
using Django built in filters for templates version is 2.2 my template looks like this {% load i18n %}{% blocktrans with site_name=current_site.organization.name site_domain=current_site.name %}Hello from {{ site_name }}! You're receiving this e-mail because your email is subscribed to receiving notification when a Quotation is Pending PO Release. {{ quote_type }} {{ quote_type|lower }} - Quotation: {{ display_quotation_number }} - PO Date: {{ po_date_display }} (New) {% endblocktrans %} {% blocktrans with site_name=current_site.organization.name site_domain=current_site.name %}Thank you for using {{ site_name }}! {{ site_domain }}{% endblocktrans %} I can say with 100% certainty that {{ quote_type }} definitely prints something out. {{ quote_type|lower }} prints nothing. What did I do wrong? I was certain that the filter is builtin? See https://docs.djangoproject.com/en/2.2/ref/templates/builtins/#lower -
Reformat Django REST Framework Serializer to get Output
I am trying to get data in a particular format but i'm not able to get the desired output. I want to get all expenses in the format given below.so when I hit the URL api/expenses I get the result in the following manner and also when I call api/expenses/<id> it shows all expense with that expense id. My Model: class Category(models.Model): name = models.CharField(max_length=40) class Expense(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") description = models.CharField(max_length=200) total_amount = models.IntegerField() class Expense_Details(models.Model): expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name="expense") user = models.IntegerField() amount = models.FloatField() type = models.CharField(max_length=100) ---->type is owe or lend When I request /api/expenses/: Expected Output { “total_expenses”: 10, “Expenses”: [{ “id”: 1, “category”: 1, “created_by”: 1, ------> user logged id “description”: “lunch”, “total_amount”: “105”, “owe”: [{ “user_id”: 1, “amount”: 10 }, { “user_id”: 2, “amount”: 95 }], “lend”: [{ “user_id”: 3, “amount”: 10 }, { “user_id”: 4, “amount”: 95 }], }, ... ] } My output: { "results": [ { "id": 1, "category": 1, "description": "lunch at the burj al arab", "total_amount": 105, "payment1": [ { "user": 1, "amount": -10 }, { "user": 2, "amount": -95 }, { "user": 3, "amount": 10 }, { "user": 4, "amount": 95 } ] … -
AttributeError: 'NoneType' object has no attribute 'ESC'
How to solve this problem? escs = esc.objects.filter(Education_Levels__in=studentenroll.values_list('Education_Levels')).order_by( 'id') edulevel = StudentsEnrollmentRecord.objects.filter(ESC__in=escs.values_list('id')).order_by( 'pk').first() when i tried this print("ESC", edulevel) i receive this message. ESC None how do i get the id of esc? this is my model class StudentsEnrollmentRecord(models.Model): Student_Users = models.ForeignKey(StudentProfile, on_delete=models.CASCADE,null=True) Education_Levels = models.ForeignKey(EducationLevel, related_name='+', on_delete=models.CASCADE,blank=True,null=True) ESC = models.ForeignKey(esc, on_delete=models.CASCADE,null=True,blank=True) -
Missing: -Add Field [variable_name] to [class_name]
I finally pinpoint the problem that I have and duplicate the style as shown below. I do not understand why my add field is not showing. I even extract written code from github but they all show the same result. from django.db import models class Programmer(models.Model): name=models.CharField(max_length=20) def __str__(self): return self.name class Language(models.Model): name=models.CharField(max_length=20) programmer=models.ForeignKey(Programmer, on_delete=models.CASCADE) def __str__(self): return self.name CMD Ideal Output (Dev) C:\Dev\src\testsite>python manage.py makemigrations inline_example Migrations for 'inline_example': inline_example\migrations\0001_initial.py - Create model Person - Create model Programmer - Add Field programmer to Language CMD Result (Dev) C:\Dev\src\testsite>python manage.py makemigrations inline_example Migrations for 'inline_example': inline_example\migrations\0001_initial.py - Create model Programmer - Create model Language -
Filtering on foreignkey django
I have two models: class Recipe(models.Model): title = models.CharField() .... class Ingredient(models.Model): recipe = models.Foreignkey(Recipe, related_name='recipe_ingredients') name = models.CharField() ... So what I want to do is filter out recipes by a given ingredient, I managed to do that this way: view.py class SearchResultListViewIngredient(ListView): model = Recipe paginate_by = 25 template_name = 'recipes/search_ingredient.html' def get_queryset(self): """ Filter out recipes by given ingredient """ ingredient = self.request.GET.get('ingredient') object_list = [] if ingredient: i = Ingredient.objects.filter(name__icontains=ingredient) object_list = [r.recipe for r in i] return object_list The problem with this is that it returns duplicate objects if their are more then one ingredients with the same name. So for example, a recipe that has as ingredient eggs and also eggplant. This object will appear twice after filtering. Is there a beter way of doing this filter? Thanks in advance. -
Django Query: Group/Count orders by foreign key of foreign key?
I have a hard time wrapping my head around how to achieve this. I have 3 fairly simple models: class Country(models.Model): name = models.CharField(max_length=200, null=True, blank=True) def __str__(self): return self.name class Seller(models.Model): name = models.CharField(max_length=200, null=True, blank=True) country = models.ForeignKey(Country, null=True, blank=True, on_delete=models.SET_NULL) def __str__(self): return self.name class Order(models.Model): order = models.PositiveIntegerField(null=True, blank=True) seller = models.ForeignKey(Seller, null=True, blank=True, on_delete=models.SET_NULL) order_date = models.DateField(max_length=200, null=True, blank=True) def __str__(self): return self.name "Orders" are simple product orders placed by "Sellers" are the businesses we supply and "Country" defines in which country these sellers are based. It could be the case that in country we have many sellers and that in the next country we only have 1. A simplified description of the orders for better understanding of my question: Order N° 1 by seller A from Germany Order N° 2 by seller B from Germany Order N° 3 by seller C from France Order N° 4 by seller D from Spain Order N° 5 by seller F from France What I would like to achieve is to group all orders from countries that exist in that Model. E.g.: ( Country | Count of all orders by country {Germany : 7 Spain : 12 France … -
Django: Fill the gaps in a view which is grouped by month
Although my problem seems to be quite standard, I could not find the solution for a Django view. I have timestamped items ("conversions") related to projects, my models.py looks like: class Project(models.Model): name = models.CharField(max_length=30) class Conversion(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) timestamp = models.DateTimeField() That's in my views.py (thanks to this help): def conversions_monthly(request): conv = Conversion.objects.values(month=TruncMonth( 'timestamp')).annotate(count=Count('pk')).order_by('-month') context = {'conversion': conv} return render(request, 'dummy/conversions_monthly.html', context) Template: conversions_monthly.html: {% extends "dummy/base.html" %} {% block content %} <table> {% for c in conversion %} <tr> <td>{{ c.month |date:"Y-m" }}</td> <td class="text-right">{{ c.count }}</td> </tr> {% endfor %} </table> {% endblock content %} With the following data: [ { "model": "dummy.project", "pk": 1, "fields": { "name": "Project A" } }, { "model": "dummy.project", "pk": 2, "fields": { "name": "Project B" } }, { "model": "dummy.conversion", "pk": 1, "fields": { "project": 1, "timestamp": "2020-03-10T05:00:00Z" } }, { "model": "dummy.conversion", "pk": 2, "fields": { "project": 1, "timestamp": "2020-03-12T17:00:00Z" } }, { "model": "dummy.conversion", "pk": 3, "fields": { "project": 1, "timestamp": "2020-05-19T12:00:00Z" } }, { "model": "dummy.conversion", "pk": 4, "fields": { "project": 2, "timestamp": "2020-05-20T16:10:03Z" } }, { "model": "dummy.conversion", "pk": 5, "fields": { "project": 1, "timestamp": "2020-05-20T16:30:00Z" } } ] I see this in … -
Django filtering objects from a filtered foreignkey object
I'm trying to filter a list of lectures which have a foreignkey relation with a model called content. Basically every lecture is related to a specific content. But I'm stuck. below is my code: models.py class CourseContent(models.Model): title = models.CharField(max_length = 250) course = models.ForeignKey(Course, on_delete = models.CASCADE, null = True) def __str__(self): return self.title class CourseLecture(models.Model): content = models.ForeignKey(CourseContent, on_delete = models.CASCADE, null = True) title = models.CharField(max_length = 50) file = models.FileField() def __str__(self): return self.title views.py def coursedetails(request, pk): course = Course.objects.get(id = pk) content = CourseContent.objects.filter(course = course) content_ids = content.values_list('id') lectures = CourseLecture.objects.filter(content__in = content_ids) reviews = course.review_set.all() rev_count = reviews.count() avg = reviews.aggregate(avg = Avg('rating')) total = reviews.aggregate(sum = Sum('rating')) print(content_ids) return render(request, "main/course_detail_view.html", {"course": course, "lectures": lectures, "content": content , "reviews": reviews, "rev_count": rev_count, "avg": avg, "total": total}) The problem here is that i cannot filter lectures on basis of specific content ids. The objects filtered is showing in all the content rather than showing in their specific section. Thanks in advance. -
How to pass a variable from javascript into url through href: django
I have seen various post allowing user to do this by including the var as part of the url something like this http://127.0.0.1:8000/?var1="var1"+var2="var2" But in my case I need to send the variable into href tag which goes to views function in my django app <a href="{% url 'process-payment'> I have the variable set like this: <td><strong>Rs.<span id="totalPrice">{{ order.get_cart_total}}</span></strong></td> . . <a href="{% url 'process-payment'> . <script> var totalPrice = document.getElementById("totalPrice").innerHTML; //picking a value through innerHTML </script> Can anyone help me build this url so the value goes to views function urls.py urlpatterns=[ path('payment/',views.process_payment, name='process-payment'), ] -
How to filter a concatenated value when using django tables2 and django_filters
I am using django tables2 and django_filters to filter my value fields being on the table. my models: class Woo_Orders(models.Model): oid = models.IntegerField("oid",null=True) site=models.ForeignKey(Site, null=True,blank=True,verbose_name="Site", on_delete = models.CASCADE) class Site(models.Model): ref_prefix = models.CharField(max_length=20, blank=True, null=True,verbose_name="REF") The Site is fk to the Woo_Orders model. my table: class WooOrderTable(tables.Table): ref_prefix = tables.Column(accessor='site.ref_prefix',verbose_name= 'Ref Prefix') class Meta: model = Woo_Orders template_name = 'django_tables2/bootstrap4.html' exclude = (...,...) sequence = ('ref_prefix',...,...) def render_ref_prefix(self,record): #site prefix + oid concatenated_prefix = record.site.ref_prefix + str(record.oid) return '%s' % (concatenated_prefix) The return value is the concatenated value of oid value from the Woo_Orders model plus the ref_prefix value of Site model. My problem is that I do not know how to return the concatenated value when i filter on the ref_prefix field. my filter: class WooOrderFilter(django_filters.FilterSet): site__ref_prefix = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = Woo_Orders fields = ['site__ref_prefix'] The filter is "catching" only the ref_prefix part of the Site model and not all the concatenated value as I want. How can i fix the filter part to search based on the concatenated value? -
Add a social logged in user to a group in django
I have added the code for a user to login. But the user has to be allotted a group first in order for him/her to view the home page. So could anyone help me by telling how to add a socially logged in user to a group in my app. -
$enable-shadows of Bootstrap only works on buttons
I have a Django app and I'm serving Bootstrap 4 with my static folder so I can customize. I imported Bootstrap with @import "./bootstrap/scss/bootstrap"; and set $enable-shadows: true;. Enabled shadows on cards with <div class="shadow-lg card mb-3">. But shadows never work on cards and even though I didn't set it, my buttons also get inner shadows. If I serve Bootstrap with CDN instead of static files (CDN over HTML template and SCSS both work fine), everything works fine but I cannot customize. Any idea how to solve it? -
Django, detect if object.filter returns 0 objects
I got such table structure class Item(models.Model): id = models.AutoField(primary_key=True) class Car(models.Model): vin_number = models.CharField(max_length=250, null=True, blank=True) item = models.OneToOneField(Item, on_delete=models.CASCADE) name = models.CharField(max_length=1000, null=True) year = models.IntegerField(null=True) class Yacht(models.Model): name = models.CharField(max_length=1000, default='') boat_type = models.CharField(max_length=1000, default='', null=True) item = models.OneToOneField(Item, on_delete=models.CASCADE) description = models.TextField(default='') year = models.IntegerField(null=False, default=0) So, both Car and Yacht has relation with Item table If I have only item id in request, what is the right way to write such query data = request.POST item = Car.objects.filter(item_id=data['item_id']).first() if not item: item = Yacht.objects.filter(item_id=data['item_id']).first() Is there any way not to use if/else statement?