Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Pass Foreign Key to Second Model
I'm trying to create a fairly simply input view for a django webapp. I have the following simply models set up. At the end I've included the traceback as well. The question is how do I create an object in the CreateView class and pass the foreign key of the parent object? #models.py #imports... class Client(models.Model): client_id = models.AutoField( primary_key=True) class Item(models.Model): client = models.ForeignKey( Client, on_delete=models.CASCADE) item_id = models.AutoField( primary_key=True) The idea is to have a list of unique clients and then each client can have a list of unique items. The items are linked to the client. #views.py #imports... class ItemCreate(CreateView): model = Item fields = [ #list of fields ] def form_valid(self, form): form.instance.client_id = self.request.client.client_id return super(PermCreate, self).form_valid(form) Given these two class models, I'm trying to CreateView that will create a new Item and have it attached to the respective Client. I have a ListView that will iterate through Items for a given Client. The ListView has a link to the CreateView (Add New Item). I am not having a problem with the pk's in the views or even getting to the CreateView. I can't get the CreateView to save the object. I get an error … -
pass value to bootstrap modal form with django
When I use bootstrap modal for my form its only show first value. here my template.html {% for company in companys %} <tr> <td>{{ company.name }}</td> <td>{{ company.desc }}</td> <td align="center"> <button type="button" class="btn btn-warning margin-bottom" data-toggle="modal" data-target="#modal-default2"> delete </button> <div class="modal fade" id="modal-default2"> <div class="modal-dialog"> <form method="post" action="{% url 'system:company_delete' pk=company.pk %}"> {% csrf_token %} <div class="modal-content"> <div class="modal-body"> <input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}"> <input type="submit" class="btn btn-primary" value="Delete"> </div> </div> </form> </div> </div> </td> </tr> {% endfor %} its loop all the data, when click delete confirm form will popup. but its return same value. but if without modal-bootstrap its work fine. example: template.html {% for company in companys %} <tr> <td>{{ company.name }}</td> <td>{{ company.desc }}</td> <td align="center"> <form method="post" action="{% url 'system:company_delete' pk=company.pk %}"> {% csrf_token %} <input type="text" name="name" maxlength="100" required="" id="id_name" value="{{ company.pk }}"> <input type="submit" class="btn btn-primary" value="Delete"> </form> </td> </tr> {% endfor %} it's work fine. what I should do to make it work?... -
How to add entry having to lookup foreign key ID
I have multiple locations defined in my DB. For example purposes, say I have "Mimai" as a city. I am trying to understand how I add a Measurment entry and reference the Location ID for the city "Miami" in Location. Each Location will have many Measurements. class Location(models.Model): city = models.CharField(('city'), max_length=20) geolocation = models.PointField(('location')) class Measurement(models.Model): server = models.CharField(('server'), max_length=10) cpu_util = models.CharField(('cpu'), max_length=10) date = models.DateField(default=timezone.now) location = models.ForeignKey(Location, on_delete=models.CASCADE) Question #1 Would I do? m = Measurement.objects.update_or_create( server = "Bubba", cpu_util = "100%", location = Location.objects.get(city="Miami") ) Or (if this is possible?) l = Location.objects.get(city="Miami") m = Measurement.objects.update_or_create( server = "Bubba", cpu_util = "100%", location = l.id ) Question #2 There should only be 1 Measurement per day for each Location. In the event a Measurement is added twice with the same date, I take update_or_create would update cpu_util if the value was different? -
Force download file in a Django Web App on mobile browsers
I have a FileField with a movie, I'm trying to have the user on a mobile platform (chrome/safari) be able to click a download button and it download it. Currently it opens in a new window no matter what I do. My View def download(request): file_path = 'movie.mp4' if os.path.exists(file_path): with open(file_path, 'rb') as fh: response = HttpResponse(fh.read(), content_type="video/mp4") response['Content-Disposition: attachment'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 file path is hard coded for testing purposes atm. Everything I read tells me that it's impossible because safari and other mobile browsers view opening a better experience than downloading. I've tried changing mime types and other things. -
Python iterate list datetime values
I am using django-eventtools and have my occurrence data output as a tuple. I tried converting this to a list to be able to loop through it but I can't seem to get it to work. My querytest variable is my attempt and trying to iterate through the new list from the original tuple. Here is my method where I am just calling the context to a django template: def get_events_items_context(self): context = {} querylist = list(RecurringAudits.objects.all().all_occurrences()) querytest = [s for t in query for s in querylist] context['query'] = querytest return context Here is what the querylist variable output looks like: [(datetime.datetime(2018, 3, 31, 0, 0, tzinfo=<UTC>), datetime.datetime(2018, 3, 31, 0, 0, tzinfo=<UTC>), {'title': 'Monthly Update Schedule'}), (datetime.datetime(2019, 3, 31, 0, 0, tzinfo=<UTC>), datetime.datetime(2019, 3, 31, 0, 0, tzinfo=<UTC>), {'title': 'Monthly Update Schedule'}), (datetime.datetime(2020, 3, 31, 0, 0, tzinfo=<UTC>), datetime.datetime(2020, 3, 31, 0, 0, tzinfo=<UTC>), {'title': 'Monthly Update Schedule'})] My desired output(or something similar): 2018-3-31, 2018-3-31, Monthly Update Schedule, 2019-3-31, 2019-3-31, Monthly Update Schedule, 2020-3-31, 2020-3-31, Monthly Update Schedule -
Django formatting query as specific json
I am using Django Rest framework to create API for existing clients. my model.py is st like this: class Unit(models.Model): name = models.CharField(max_length=250, null=True, blank=True) summary = models.TextField(null=True, blank=True) location = models.ForeignKey(Location, null=True, blank=True) class Location(models.Model): name = models.CharField(max_length=250, null=True, blank=True) # refrenced in response json as category_name def __unicode__(self): return unicode(self.name) def __str__(self): return unicode(self.name) My API should be like this and I cannot change formatting in client side: { "data": [ { "category_name": "Block A -1", "items": [ { "id": "26", "name": "negar", "summary": "" }, { "id": "27", "name": "art coffee", "summary": "" } ] }, { "category_name": "Block B 2", "items": [ { "id": "14", "name": "kid house", "summary": "" }, { "id": "15", "name": "teen bookstore", "summary": "", } ] } ] } I read that must use APIView with customized serializer but cannot find way to format query into given format. Is there any correct way or simple trick to format queries as spacial json format? related questions reviewd: Where to change the form of json response in django rest framework? How to return custom JSON in Django REST Framework Custom JSON representation of query result Retrieving a Foreign Key value with django-rest-framework serializers -
call ForeignKey and count it on django template
I want to count that how many employees in every department and show it on django template. here my models.py class Company(models.Model): name = models.CharField(max_length=100) desc = models.TextField(blank=True, null=True, default='Tidak ada deskripsi') def __str__(self): return self.name def get_absolute_url(self): return reverse("system:company_list") class Employee(models.Model): name = models.CharField(max_length=100) company = models.ForeignKey(Company, default=0, on_delete=models.SET_DEFAULT, related_name='company') def __str__(self): return self.name def get_absolute_url(self): return reverse("system:detail",kwargs={'pk':self.pk}) and here my views.py class CompanyListView(ListView): context_object_name = 'companys' model = models.Company and here my company_list.html {% for company in companys %} <tr> <td>{{ company.name }}</td> <td>{{ companys.employee.count }}</td> <td>{{ company.desc }}</td> </tr> {% endfor %} Iam trying count the company with {{ companys.count }} and its work. and i think it will gonna be {{ companys.employee.count }} for counting the employee. but its dint work. did i miss something?... -
How to display multiple forms on the same page and store it on the database in django?
It is my model class Marking(models.Model): criteria = models.CharField(max_length=60) marks = models.PositiveIntegerField() assignment = models.ForeignKey(AssignAssignment, on_delete=models.CASCADE) It is my form class MarkingCriteria(forms.ModelForm): class Meta: model = Marking fields = ('criteria', 'marks', 'assignment') My requirement is how to create multiple marking criteria for marking on a page..lecturer can add as many as marking criteria on the same page and submit... any one have any idea how to do? -
How to add default value to Django Sessions
I'm making a multi-language site, and would like to have a default language set to a specific one. How would I add a default value to every new session? Namely, I would like to request.session['lang'] = 'de' to be the default value upon creation of every new session. By default, 'lang' is not stored in request.session, and attempting to call request.session['lang'] for purpose of finding out the prefered language of a user, would return Key error unless 'lang' has been set beforehand. So instead of checking for and setting default language in every view, how would I go about making <'lang':'de'> part of every new session? -
Editing Images, Image_titles, Image_description from a post with multiple images
Hi Djangonauts, I have a created a post with multiple images. it works perfectly fine but when I try to edit the post with multiple images I get a AttributeError. image of the error message posted below at the end of the question. below are my models.py class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField(allow_unicode=True, unique=True) message = models.TextField() post_image = models.ImageField() def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) class Prep (models.Model): #(Images) post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='post_prep') image = models.ImageField(upload_to='images/', blank=True, null=True, default='') image_title = models.CharField(max_length=100, default='') image_description = models.CharField(max_length=250, default='') def __str__(self): return self.post.title + " Image" now I have successfully created the post_create as you can see below this work perfectly fine and adds multiple images to my post, along with image_title and image_description @login_required def post_create(request): ImageFormSet = modelformset_factory(Prep, fields=('image', 'image_title', 'image_description'), extra=7) if request.method == "POST": form = PostForm(request.POST or None, request.FILES or None) formset = ImageFormSet(request.POST or None, request.FILES or None) if form.is_valid() and formset.is_valid(): instance = form.save(commit=False) instance.user = request.user instance.save() print(formset.cleaned_data) for f in formset.cleaned_data: try: photo = Prep(post=instance, image=f['image'], image_title=f['image_title'], image_description=f['image_description']) photo.save() except Exception as e: break return redirect('posts:single', username=instance.user.username, slug=instance.slug) else: form = PostForm() … -
Django subject_slug Name error
I am working on my homepage but I get an error when I click on myworkandresearch.html. related to template ? NameError at / myworkandresearch / name 'subject_slug' is not defined My views.py: from django.shortcuts import render, get_object_or_404 from django.template import loader, context from django.urls import reverse from .models import Category, Subject, Article # Create your views here. def myworkandresearch(request): category_list=Category.objects.all() subjects=Subject.objects.filter(slug=subject_slug, subject__category__slug=category_slug) context={ 'categor_list':category_list, 'subjects':subjects } return render(request, 'myworkandresearch/myworkandresearch.html', context) def category(request,category_slug): category_list = Category.objects.all() subject=Subject.objects.filter(slug=subject_slug, subject__category__slug=category_slug) article=Article.objects.filter(slug=article_slug, subject__slug=subject_slug, subject__category__slug=category_slug) context = { 'category_list': category_list, 'article': article, 'subject':subject } return render(request, 'myworkandresearch/category.html', context) -
django: renamed app, but I want to allow old URLs too. How to allow alternate URL patterns to one url namespace?
I have renamed an app in django 2.x, and this is completed successfully. However, I want to allow the old URLs to still be used. I could configure the front-end webserver to redirect, but I would like to know best practice for doing this in django. The old app has gone, so the old URLs now belong to the URL namespace of the new app. In my project-level urls.py, I could do this Attempt 1: url(r'^NEWAPP/', include('NEWAPP.urls')), url(r'^vOLDAPP/', include('NEWAPP.urls')), but this has the disadvantage of including NEWAPP.urls twice, which causes the warning that URL namespace NEWAPP is not unique. Attempt 2: url(r'^cin7_sync/|^voga/', include('cin7_sync.urls')), which doesn't work, the | is not working as an 'or'. -
Arithmetic Operator on django Templates
Here my models.py class HolidayListView(ListView): context_object_name = 'national_holidays' model = models.NationalHoliday I have a template like holiday_list.html <td>{{ holiday.date_from }}</td> <td>{{ holiday.date_to }}</td> <td>{{ holiday.date_to - holiday.date_from }}</td> how to make <td>{{ holiday.date_to - holiday.date_from }}</td> work, should i do with HolidayListView?... or can directly on my templates?... thank you! -
Django 2.0.2 Problems with modelform creation: AttributeError: 'str' object has no attribute '_default_manager'
Using Django 2.0.2 class Rischi(models.Model): RISCHIO = ( ('Nullo', 'Nullo'), ('Irrilevante', 'Irrilevante'), ('Basso', 'Basso'), ('Medio', 'Medio'), ('Alto', 'Alto'), ) azienda = models.ForeignKey( 'azienda.Azienda', on_delete=models.CASCADE, ) foto = models.ImageField(upload_to='rischi', blank=True) attivita = models.ForeignKey( Attivita, blank=True, null=True, on_delete=models.CASCADE, ) luogo = models.ForeignKey( Luoghi, blank=True, null=True, on_delete=models.CASCADE, ) macchina = models.ForeignKey( Macchine, blank=True, null=True, on_delete=models.CASCADE, ) sostanza = models.ForeignKey( Sostanze, blank=True, null=True, on_delete=models.CASCADE, ) fonte_rischio = models.ForeignKey( Fonte_rischio, on_delete=models.CASCADE ) pericolo = models.CharField(max_length=200) mansione = models.ManyToManyField( 'mansione.Mansione' ) livello_rischio = models.CharField(max_length=200) rischio = models.CharField(max_length=200, choices=RISCHIO) allegato = models.ManyToManyField( Allegati, blank=True, ) note = models.TextField(blank=True) data_di_creazione = models.DateField(auto_now_add=True) data_di_modifica = models.DateField(auto_now=True) def __str__(self): return self.fonte_rischio.nome + ", id: "+ str(self.pk) and this is the related form class RischiForm(ModelForm): class Meta: model = Rischi exclude = ['azienda'] when I execute runserver this is the message i receive AttributeError: 'str' object has no attribute '_default_manager' but when I set the form excluding mansione class RischiForm(ModelForm): class Meta: model = Rischi exclude = ['azienda', 'mansione'] everything is ok I tried to read the manual and I googled this message but I did not find any answer to this problem... -
use a custom form inside a template which is linked to another view django
How can i use my custom form called PayForm inside a template (Post.html) which is the template of a view called Post I tried to point both of the views to the same template but as i was told you can't point two views to the same template so i am currently stuck on this models.py from django.db import models from django.urls import reverse from PIL import Image # Create your models here. class Post(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255, unique=True) created = models.DateTimeField(auto_now_add=True) content = models.TextField(default="---") current_price = models.IntegerField(default=0) reduction = models.IntegerField(default=0) original_price = models.IntegerField(default=0) Status = models.CharField(max_length=5, default="✓") img = models.CharField(max_length=255) sold = models.IntegerField(default=0) endday = models.CharField(max_length=30, default="apr 27, 2018 16:09:00") class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.title def get_absolute_url(self): return reverse('Products.views.post', args=[self.slug]) def __str__(self): return self.title class Payment(models.Model): Author = models.CharField(max_length=255) Product = models.CharField(max_length=255) Payment_ID = models.CharField(max_length=255) Status = models.CharField(max_length=5, default="X") Review_result = models.CharField(max_length=255, default="Not yet reviewed") Address = models.CharField(max_length=255, default='') created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created'] def __unicode__(self): return u'%s'% self.Status def __str__(self): return self.Status views.py from django.shortcuts import render, render_to_response , get_object_or_404, redirect from .models import Post from django.contrib.auth import authenticate, login, logout from .forms import RegistrationForm, PayForm def … -
Testing django when is in production
I have a website made with Django and is now public and in full production (running with gunicorn and nginx). What are the best practices to make updates and/or debug errors that were unseen during development? Is it ok to run the usual python manage.py runserver 0.0.0.0:8000, make the changes I want to do, check the result through port 8000 and then restart gunicorn? -
What's the difference between py.test and python manage.py test in django
In django tests can be run using python path/manage.py test --settings=path_to_settings however after installing pytest and creating a simple url test. I can only run it using py.test without employing manage.py also running the traditional manage.py test does not find the test I have created. First concerns What is the difference between the two? How can they be used together? Like TestCase from django.test + pytest, best practices Second concern Even though py.test detects the written tests it throws an error... here is the console output when the command is run ============================= test session starts ============================== platform linux -- Python 3.5.2, pytest-3.5.1, py-1.5.3, pluggy-0.6.0 rootdir: /home/fenn/projects/testing, inifile: pytest.ini plugins: django-3.2.1, cov-2.5.1 collected 1 item products/tests/test_urls.py E [100%] ==================================== ERRORS ==================================== ______________ ERROR at setup of TestUrl.test_product_detail_url _______________ request = <SubRequest 'django_test_environment' for <Function 'test_product_detail_url'>> @pytest.fixture(autouse=True, scope='session') def django_test_environment(request): """ Ensure that Django is loaded and has its testing environment setup. XXX It is a little dodgy that this is an autouse fixture. Perhaps an email fixture should be requested in order to be able to use the Django email machinery just like you need to request a db fixture for access to the Django database, etc. But without duplicating a … -
How to automatically assign value in django models
I have a simple model class: class MyModel(models.Model): place = models.CharField(max_length=25, verbose_name='Place') name = models.CharField(max_length=25, verbose_name='Name') And I'd like to ask you, is there a possibility to automatically set as default value for place field as number of records in table + 1 so for example if there will not be records in table the system automatically change the line to place = models.CharField(max_length=25, verbose_name='Place', default='1') Will be thankful for your help, -
DJANGO MODELS, use one class objects in another class (ManyToManyField) (?)
I want to use one class object inside another class. What I want to achieve: I have already created some Ingredient objects like 'chicken', 'rice' and so on. Every with its own calories, proteins, etc. Now I want to create a Meal from those Ingredients and calculate calories summary. My goals: 1. Create meal: sample_dinner = Meal(name='sample_dinner',ing1='chicken',ing2='rise',ing3='tomato') 2. Calculate calories, function is easy to write but I need to pass args first 3. Show them in view (I have know how) models.py class Ingredient(models.Model): name = models.CharField(max_length=20,default='') calories = models.PositiveIntegerField(default=0) proteins = models.PositiveIntegerField(default=0) carbs = models.PositiveIntegerField(default=0) fat = models.PositiveIntegerField(default=0) class Meal(models.Model): name = models.CharField(max_length=100,default='') ingredientone = models.ManyToManyField(Ingredient) calories_value = calc_nut_value() def calc_nut_value(): ingr = Ingredient.objects.get(name=PASSED_ARGUMENT(f.e 'chicken')) calories = ingr.calories return calories -
Django update_or_create overwrites entries
I have the following two models. class Measurement(models.Model): location = models.OneToOneField('locations.Location', on_delete=models.CASCADE) server = models.CharField(('server'), max_length=10) avg_resp_server = models.CharField(('avg_resp_server'), max_length=20) avg_avail_server = models.CharField(('Average available server'), max_length=20) avg_resp_direct = models.CharField(('avg_resp_direct'), max_length=20) avg_avail_direct = models.CharField(('Average available direct'), max_length=20) date = models.DateField(auto_now=True) class Location(models.Model): city = models.CharField(('City'), max_length=20) geolocation = models.PointField(('location')) In summary, I am basically using Postgres as a time series DB for a small quantity of time samples. When I feed any quantity of measurement entries into add_measurement_to_db for a given date (e.g. 2008-05-05), all prior measurement entries are removed. The only entries that remain are the prior import. I believe my understanding of update_or_create is incorrect. My end goal is to be able to import measurement entires. Sometimes I have to import a set of measurement entries with duplicates. When duplicates are encountered, the latest import values should be used (which I thought was covered by update_or_create). def add_measurement_to_db(data_dict, import_date): for key, val in data_dict.items(): location = Location.objects.get(city=key) m = Measurement.objects.update_or_create( location=location, defaults={ 'server' : val['server'], 'avg_resp_server' : val['avg_resp_server'], 'avg_avail_server : val['avg_avail_server'], 'avg_resp_direct' : val['avg_resp_direct'], 'avg_avail_direct' : val['avg_avail_direct'], 'date' : import_date } ) -
Serializing and storing JSON array in Django REST Framework
I'm trying to make a demo website for job applications using Angular 6 and Django Rest Framework. One of my application fields involve listing your interests in a chip input field like this one. The JSON being sent to my API would look something like this: { ... 'firstname': 'Firstname', 'lastname': 'Lastname' ... 'interests': ['hobby1', 'hobby2', 'hobby3', 'hobby4'], ... } Now as far as I know Django REST Framework supplies a serializer field that is written something like this: interests = serializers.ListField( item = serializers.CharField(min_value=xx, max_value=xx) ) My question is, how do I proceed from here? What model fields do I use, or do I have to create my own save function that iterates through the interests and saves every single one? -
Django slug error
my error picture I am working on my homepage but I get an error when I click on myworkandresearch.html. related to template ? NameError at / myworkandresearch / name 'subject_slug' is not defined I have the following models: from django.db import models from django.utils import timezone from autoslug import AutoSlugField from django.urls import reverse # Modeller arasında sadece OneToOne ilişkisi kurulmuştur. # There is only one One To Onerelationship between the models. class Category(models.Model): name = models.CharField(max_length=200) statement = models.TextField() slug=AutoSlugField(populate_from='name') def __str__(self): return self.name class Subject(models.Model): name = models.CharField(max_length=200) statement = models.TextField() slug = AutoSlugField(populate_from='name') category_name = models.ForeignKey('Category', on_delete=models.CASCADE) def __str__(self): return self.name def get_absolute_url(self): return reverse('myworkandresearch:subject', args=[self.slug, self.category_name.slug]) class Article(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = AutoSlugField(populate_from='title') text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) subject_name = models.ForeignKey('Subject', on_delete=models.CASCADE) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_absolute_url(self): return reverse('myworkandresearch:detail', args=[self.slug, self.subject_name.slug, self.subject_name.category_name.slug]) it's views.py: from django.shortcuts import render, get_object_or_404 from django.template import loader, context from django.urls import reverse from .models import Category, Subject, Article # Create your views here. def myworkandresearch(request): category_list=Category.objects.all() subject=Subject.objects.filter(slug=subject_slug, subject__category__slug=category_slug) context={ 'categor_list':category_list, 'subjects':subjects } return render(request, 'myworkandresearch/myworkandresearch.html', context) def category(request,category_slug): category_list = Category.objects.all() … -
Django prefetch_related with reverse foreign key lookup
Given these models in the Django docs: class Topping(models.Model): name = models.CharField(max_length=30) class Pizza(models.Model): name = models.CharField(max_length=50) toppings = models.ManyToManyField(Topping) I want to get toppings and do stuff with their pizza_set: toppings = Topping.objects.all() for topping in toppings: pizzas_with_this_topping = topping.pizza_set() # do stuff with pizzas_with_this_topping How can I use prefetch_related (or another technique) to get all the pizza data without hitting the database for every topping? -
write a function that sends email django
i have following configurations in my settings.py for sending email EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = '********' EMAIL_PORT = 587 i am able to mail from python shell in following way from django.core.mail import EmailMessage email = EmailMessage('Subject', 'Body', to=['your@email.com']) email.send() how can i write a view or a function that does the same. I want to ask whether it will be post method or get method? and if it is not a view how to call it in urls.py -
Python function not storing in django database
I have written a function in python views.py, urls.py and models.py but it doesn't seem to store stuff in the database. views.py: @login_required def job_status_update(request): status = request.GET['status'] job_id = request.GET['Jobid'] if status == 'Active': flag = True else: flag = False job = Job.objects.get(pk=job_id) try: job.active = flag job.save() return HttpResponse(status) except Exception as e: return JsonResponse(status) urls.py: url(r'^job/status_update/$', views.job_status_update), models.py: active = models.BooleanField(default = True)