Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF - Nested serializer disappears after parent is_valid() call
TLDR; (full description below) Valid field with nested serializer is dropped upon validation of parent serializer. I read some StackOverflow posts about similar cases, but there the field was dropped because of being read_only=True which is not my case. After POSTing valid object to CreateParentView(generics.CreateAPIView) I get Http 400 Bad request error. I ended up debugging the create() method. # parsed_data is a QueryDict prepared from request.POST and request.FILES # to fit the nested serializers format. -> serializer.is_valid(raise_exception=True) (Pdb) parsed_data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3', 'child']) (Pdb) from .serializers import CreateChildSerializer; ch = parsed_data.get('child'); new_child = CreateChildSerializer(data = ch); (Pdb) new_child.is_valid() True (Pdb) new_child.errors {} # the parent serializer is invalid and drops the 'child' key (Pdb) serializer.is_valid(); False (Pdb) serializer.data.keys() odict_keys(['parent_field_1', 'parent_field_2', 'parent_field_3']) The response is 400 (Bad Request), "{"child":["This field is required."]}" Dafuq, I just provided you with that, and you, sir, dropped it :-( End Of TLDR; Okay, lets have a look on the View, the Serializer and the Model. I'm using a toy model, my real one is too verbose to reproduce here. Lets start with the models.py - the Child and Parent models are OneToOneField relationship. # models.py class Parent(models.Model): objects = ParentManager() user = models.ForeignKey('auth.User', on_delete=models.CASCADE) … -
validate no duplicates in streamfield
Need to create a long scroll page with sidebar nav for on-page navigation. This means each heading will have an id. Can I validate at the streamfield level to make sure a user doesn't put in a duplicate id? -
Select Serializer for field in Django Serializer class
i have Model where i can have owner is user or client @property def owner(self): return self.created_by_user or self.created_by_client and have serializer where i need this field class MessageSerializer(serializer.ModelSerializer): owner = (can be user or client) i take it from @property in model I have 2 serializer UserSerializer and ClientSerializer i want write for owner something like this owner = UserSerializer if insstance(User, value) or ClientSerializer if insstance(Client, value) Any idea?? -
Django Attribute Error: module 'appname' has not attribute models
I know my question probably deals with mutual/circular imports, and I did search SO before posting. The only solution I found that currently solves my problem is to move imports to the end of one of the files, just before the imported functions are actually used. But I've also read that's highly unrecommended. A recommended solution, to just do: in A.py -> import B and in B.py -> import A And then access the functions, isn't working. So I have three apps in my Django app: "core", "notifications", and "accounts". Here are snippets from them: core.models: from django.db import models from django.contrib.auth.models import User import notifications.models from z_misc import general_scripts # Create your models here. class BaseModel(models.Model): created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class Meta: abstract = True notification.models: from django.db import models import core.models import accounts.models class Notification(core.models.BaseModel): artist_id = models.OneToOneField(core.models.Artist, related_name="artist_notifications", null=False) release_group = models.OneToOneField(core.models.ReleaseGroup, related_name="rg_notifications", null=False) def get_rg_type(self): return self.release_group.type accounts.models: from django.db import models from django.contrib.auth.models import User import core.models from django.db.models import Q # Create your models here. class UserProfile(core.models.BaseModel): #TODO: add email_activated = models.BooleanField(default=False) user = models.OneToOneField(User, related_name="user_profile") As you can see, I'm following the advice not do from and then import, but to … -
Recursion loop in views and templates
I have 2 models, Category and Products class Product(Meta): categories = models.ManyToManyField(Category, related_name='products') class Category(Meta): parent = models.ForeignKey('self', blank=True, null=True, verbose_name='parent category', on_delete=models.CASCADE) When a user select a Category I need to show all the products in that category including all product of his children and grandchildren etc. The Category has a FK to itself, so the number of depth levels theoretically is infinite so I need to extract all product from any category below parent depth. -
Django hidden field is not saving to database
I am trying to save users IP address in my extended profile model. The goal is to make this a hidden field. Currently, I can debug by printing the IP address to the console. The issue arises when I try and save the info. views.py def index(request): #request.session.flush() if request.user.is_authenticated: return redirect('ve:dashboard') elif request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.refresh_from_db() # Load the profile instance created by the Signal user.profile.birth_date = form.cleaned_data.get('birth_date') user.ipaddress = get_ip(request) print(user.ipaddress) user.save() raw_password = form.cleaned_data.get('password1') user = authenticate(username=user.username, password=raw_password) login(request, user) return redirect('ve:dashboard') else: form = RegistrationForm() return render(request, 'index.html', {'form': form}) forms.py class RegistrationForm(UserCreationForm): # birth_date = forms.DateField(help_text='Required. Format: YYYY-MM-DD') birth_date = forms.DateField(widget=SelectDateWidget(years=range(1999, 1910, -1))) #ipaddress = forms.IntegerField(widget=forms.HiddenInput(), required=False) class Meta: model = User fields = ('username', 'email', 'birth_date', 'password1', 'password2',) exclude = ['ipaddress',] index.html <form method="post"> {% csrf_token %} {% for field in form %} <p class="text-left"> {{ field.label_tag }}<br> {{ field }} {% for error in field.errors %} <p style="color: red">{{ error }}</p> {% endfor %} </p> {% endfor %} <button type="submit">Sign up</button> </form> models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... ipaddress = models.CharField(default="104.236.0.10", max_length=30) This form was working fine before I tried adding the ipaddress … -
Use a constant inside models.Func()
I want to compute a datetime difference by using the timestampdiff sql function in django. I tried by this way : models.Func( models.Value('SECOND'), models.F('date1'), models.F('date2'), function='timediff') but models.Value() add quotes to the parameter which must be set as a constant. The final request I want to do is timestampdiff(SECOND,date1,last_date2) Can I do this with django and Func object ? -
Django retrieving object instances created during last two weeks
I have a model called Book which has an attribute when_added which stores the time when an instance of the object is created: class Book(models.Model): book_id = models.AutoField(primary_key=True) title = models.CharField(max_length=30) # Record the date whenever a new book is added, it will be helpful for showing new arrivals when_added = models.DateTimeField(auto_now_add=True, blank=True, null= True) #This helps to print in admin interface def __str__(self): return u"%s" % (self.title) I am writing a view that will return me list of books those were added during last two weeks: from datetime import date, timedelta @api_view(['GET']) def new_arrivals(request, library_id): """ List all new arrival books in a specific library """ d=date.today()-timedelta(days=14) print(d) if request.method == 'GET': books = Book.objects.filter(which_library=library_id) books = books.filter(when_added=d) print(books) serializer = BookSerializer(books, many=True) return Response(serializer.data) Here I get a warning saying RuntimeWarning: DateTimeField Book.when_added received a naive datetime (2017-11-27 00:00:00) while time zone support is active. and no book is returned. What am I doing wrong? -
oReverseMatch at /posts/post/18/comment/ Django Error
I've been getting this error, and I couldn't seem to fix it. Here is a screenshot of it: erros image Here my view's.py:' from django.shortcuts import render, get_object_or_404, redirect from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from posts.forms import PostForm, CommentForm from django.core.urlresolvers import reverse_lazy from django.http import Http404 from django.views import generic from braces.views import SelectRelatedMixin from . import forms from . import models from django.contrib.auth import get_user_model User = get_user_model() class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ("user", "group") class UserPosts(generic.ListView): model = models.Post template_name = "posts/user_post_list.html" def get_queryset(self): try: self.post_user = User.objects.prefetch_related("posts").get( username__iexact=self.kwargs.get("username") ) except User.DoesNotExist: raise Http404 else: return self.post_user.posts.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["post_user"] = self.post_user return context class PostDetail(SelectRelatedMixin, generic.DetailView): model = models.Post select_related = ("user", "group") def get_queryset(self): queryset = super().get_queryset() return queryset.filter( user__username__iexact=self.kwargs.get("username") ) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): # form_class = forms.PostForm fields = ('message','group') model = models.Post # def get_form_kwargs(self): # kwargs = super().get_form_kwargs() # kwargs.update({"user": self.request.user}) # return kwargs def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class DeletePost(LoginRequiredMixin, SelectRelatedMixin, generic.DeleteView): model = models.Post select_related = ("user", "group") success_url = reverse_lazy("posts:all") def get_queryset(self): queryset = super().get_queryset() return queryset.filter(user_id=self.request.user.id) def delete(self, *args, **kwargs): … -
heroku : git push heroku master
I wrote a web app and I want to deploy it by heroku.I'm new to this and couldn't figure out this problem.I already searched everything about this but didn't work.Hope you guys can give me some suggestions. This is my requirements.txt alabaster==0.7.10 asn1crypto==0.22.0 astroid==1.4.9 astropy==1.3.2 Babel==2.4.0 backports.shutil-get-terminal-size==1.0.0 comtypes==1.1.2 conda==4.3.21 contextlib2==0.5.5 cryptography==1.8.1 cycler==0.10.0 Cython==0.25.2 cytoolz==0.8.2 dask==0.14.3 datashape==0.5.4 decorator==4.0.11 distributed==1.16.3 dj-database-url==0.4.2 dj-static==0.0.6 docutils==0.13.1 entrypoints==0.2.2 et-xmlfile==1.0.1 fastcache==1.0.2 Flask==0.12.2 Flask-Cors==3.0.2 gevent==1.2.1 greenlet==0.4.12 gunicorn==19.7.1 h5py==2.7.0 ....... xlwings==0.10.4 xlwt==1.2.0 zict==0.1.2 psycopg2==2.6.1 When I got error I'll delete the line in requirements.txt.At the first I thought that is only one but the truth is more the one not found.Everytime I will commit ater I change requirement.txt.I don't know why and how to debug.I hope it can run and I can deploy it. This is my error C:\Users\user\django_project>git push heroku master Counting objects: 13090, done. Delta compression using up to 4 threads. Compressing objects: 100% (9553/9553), done. Writing objects: 100% (13090/13090), 118.21 MiB | 316.00 KiB/s, done. Total 13090 (delta 2753), reused 12586 (delta 2529) remote: Compressing source files... done. remote: Building source: remote: remote: -----> Python app detected remote: -----> Installing python-3.6.3 remote: -----> Installing pip remote: -----> Noticed cffi. Bootstrapping libffi. remote: -----> Installing requirements with … -
ModuleNotFoundError but path to module is correct
I have a Django project with my models, views, and URLs set up. The path structure is as follows: --MainProject --Measurements --views.py --urls.py --models.py --migrations --templates.py --management --commands --add_data.py --clear_data.py --init.py --_pycache_ When building this project, I created the models.py first and then made migrations. Afterwards, I migrated. The add_data.py file adds data to the table and the clear_data.py file removes the data. I ran the add_data.py file and it worked once, but I had similar errors leading up. I forgot how I made it run through the command line. However, now if I delete the database and try to run the add_data.py file I get this error: from measurements.models import Area, Category, Location, Measurement ModuleNotFoundError: No module named 'measurements' Here's my code: models.py from django.db import models from django.db.models import Avg class Area(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=200) longitude = models.FloatField() latitude = models.FloatField() def number_of_locations(self): return len(self.location_set.all()) # Function to get the average measurements of locations in area def average_measurement(self): return Measurement.objects.filter(location__area=self).aggregate(Avg('value'))['value__avg'] # Get all category names for area def category_names(self): categories = self.category_set.all() cList = "" for category in categories: cList+= category.name + ", " return cList[:-2] def __str__(self): return self.name class Location(models.Model): id = models.IntegerField(primary_key=True) … -
How to get one users object from a foreign key in Django?
I'm making a contact list and only want to display the contacts for the current user and not allow anybody who didn't make the contact view the contacts. Basically, I want to have contacts specific to the user that made them and viewable by only the person who made them views from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin from . import forms from . import models from django.views import generic from django.contrib.auth import get_user_model User = get_user_model() from django.http import Http404 # Create your views here. class ContactList(generic.ListView,LoginRequiredMixin): model = models.Contact template_name="PhoneBook/contact_list.html" def get_queryset(self): self.use = User.objects.prefetch_related("contacts").get( user__username__iexact=self.kwargs.get("username") ) return self.use.contacts.all() class CreateContact(generic.CreateView,LoginRequiredMixin): model = models.Contact form_class = forms.ContactForm def form_valid(self, form): self.object = form.save(commit=False) self.object.user = self.request.user self.object.save() return super().form_valid(form) class ContactDetail(generic.DetailView): model = models.Contact models from django.db import models from django.conf import settings from django.core.urlresolvers import reverse from django.contrib.auth import get_user_model User = get_user_model() from django.core.validators import RegexValidator class Contact(models.Model): user = models.ForeignKey(User,related_name="contacts") fullname = models.CharField(max_length=100) phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Invalid Input") phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True,null=True) email = models.EmailField(blank=True,null=True) def __str__(self): return self.fullname def get_absolute_url(self): return reverse( "PhoneBook:view", kwargs={ "pk": self.pk } ) class Meta(): unique_together = ('user', 'fullname') contact_list.html {% extends "base.html" %} {% block content … -
how to get a related value from a ForeignKey model django admin
I've a model with a fk, but when save method I need get related value, e.g: class Pedidos(models.Model): ped_cliente = models.ForeignKey(Clientes, verbose_name='Cliente') ped_remetente = models.ForeignKey(Remetentes, verbose_name='Remetente') ped_produto = models.ForeignKey(Produtos, verbose_name='Produto') ped_data_pedido = models.DateField(verbose_name='Data Pedido') ped_quantidade = models.DecimalField(verbose_name='Peso/Volume', max_digits=10, decimal_places=0) ped_key = models.IntegerField(unique=True, editable=False, verbose_name='Cod. Pedido') class Pagamentos(models.Model): pag_cliente = models.ForeignKey(Clientes, verbose_name='Cliente') pag_key_ped = models.ForeignKey(Pedidos, verbose_name='Cód. Pedido') pag_vencimento = models.DateField(verbose_name='Data Vencimento') pag_vlr_total = models.DecimalField(verbose_name='Valor Total', max_digits=10, decimal_places=2) I need when I save model Pagamentos the value field: pag_key_ped receive Pedidos.ped_key value How I do to access this value? -
Ordering a django queryset by sum of two (or more) fields
I have found a few questions that are similar to mine, but most of them are dated, or too (or too little) verbose to be helpful. I have a model like this: class Breakfast(models.Model): count_eggs = models.IntegerField() count_bacon = models.IntegerField() had_toast = models.BooleanField() Now, in building a RESTful API, I need the ability to sort Breakfast objects by the total of count_eggs + count_bacon without storing this permanently on the model. Many of the current and popular questions suggest something like this: Breakfast.objects.extra( select={'total_food':'count_eggs + count_bacon'}, order_by=('total_food',) ) This seems to work for many, but Django docs appear to dissuade this solution. So, in the 1.10+ world, What is the best/correct way to do this type of filtering on the sum of two (or more) fields in Django -
Cannot use extra_option with path django
I don't understand why I cannot use the path() method as documented here: https://docs.djangoproject.com/en/2.0/topics/http/urls/#passing-extra-options-to-view-functions in my apps urls.py. Here is the code I have: from django.conf.urls import url, include from django.contrib import admin from django.urls import path from . import views as AliasViews from permissions import views as PermissionsViews urlpatterns = [ ... path(r'^user/(?P<alias_id>\d{1,})/members/?$', AliasViews.UserAliasMember.as_view(), name='useralias_member', {'alias_type':'UserAlias'}), ... ] I get this error: SyntaxError: non-keyword arg after keyword arg. -
prefetch_related and Prefetch object tripple search(2 reverse), and one distinct
I have 3 models Category, Account, and Products class Product(Meta): categories = models.ManyToManyField(Category) company = models.ForeignKey(Company, related_name='products', on_delete=models.CASCADE) I want to get: the Products for Company, and the Categories of the Products the Categories distinct (use as a sidebar) to filter the Company products by Category first/by id Category of the Product to show as text near Product name On a View inheriting from DetailView: def get_queryset(self): qs = super().get_queryset() products = Product.objects.order_by('-updated_at', '-created_at').prefetch_related( Prefetch('categories', queryset=Category.objects.distinct())) return qs.prefetch_related( Prefetch('products', queryset=products)) are displayed as categories.Category.None So, I can access the products as company.products.all and category as product.categories.all in the loop Now the distinct works inside the Product relation, but how I get the all categories (not by product) distinct ? I tried {% regroup products.all.categories by products.all as category_list %} {% for cat in category_list %} {{ category.name}} {% endfor %} but is not working. Try also variation with or without calling all. -
'WSGIRequest' object has no attribute 'session' AT LOGIN
I'm trying to teach myself python\Django. This was built in Visual Studio with the Django starter site so all the settings.py etc where prebuilt and just added upon. When I attempt to login to the site from the IIS Server I get "AttributeError at /login/ 'WSGIRequest' object has no attribute 'session'" although when I attempt to run it on my local machine from "python manage.py runserver" it runs just fine. settings.py 1/3 | 2/3 | 3/3 -
How to filter in prefetch_related columns?
I have this code, where I combine a list of articles to their (translated) descriptions: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')) this works fine, but how can I now filter the descriptions? Let's say I only want the description "foo". I am looking for something like this: desc = models.ArticleDescription.objects.filter(lang__iexact=translation.get_language()) c = models.Article.objects.all().order_by('articleid').prefetch_related( Prefetch('articledescription_set', queryset=desc, to_attr='description_tr')). filter(description_tr__description="foo") But that doesn't work. How can I achieve this? -
CSRF verification failed. Request aborted. (Forbidden (403)) DJANGO
I'm trying to get POST from 2 diferents dropdown, I had get the parametres from the POST, but i get problems with the CSRF token .... index.html <form method="post" action="/getdata/">{% csrf_token %} <select name="Lista"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <select name="Lista2"> <option selected="selected" disabled>Objects on page:</option> <option value="10">10</option> <option value="20">20</option> <option value="30">30</option> <option value="40">40</option> <option value="50">50</option> </select> <input type="submit" value="Select"> </form> in spite of I use the csrf token in my html form, it didn't worked ... views.py from django.http import HttpResponse from django.template import loader from django.shortcuts import render from view.forms import * from django.shortcuts import render_to_response, redirect from view.models import * def index(request): if request.method == 'POST': Lista = request.POST.get('Lista') print "Lista 1 "+Lista Lista2 = request.POST.get('Lista2') print "Lista 2 "+Lista2 #FORMS form = FormsLista(request.POST) if form.is_valid(): newPost = Lista(num_lista_1=Lista, num_lista_2=Lista2) newPost.save() context = { 'Lista': Lista, 'Lista2': Lista2 } return render(request, 'showdata.html', context) else: template = loader.get_template('index.html') return HttpResponse(template.render()) models.py from django.db import models class Lista (models.Model): num_lista_1 = models.CharField(max_length=100, null=True) num_lista_2 = models.CharField(max_length=100, null=True) def __unicode__(self): return self.num_lista_1 I have the cookies activated by the way ... -
How save to model from a string as fieldname?
I'm trying to save some informations to my model, since my list of fieldname is dynamic I'd like to loop and save those informations to the fields rather than using conditions. models.py class Company(models.Model): name = ... email = ... phone = ... ... views.py text_fields = ['name', 'email', 'phone', 'organisation', 'address', 'website'] #dynamic list, might change depending the user's interaction. for index, json_dt in enumerate(data): #data consists of JSON texts = json_dt['texts'] for text in texts.values(): for field in text_fields: # <-- loop through the list of fieldnames if text['key'] == field: # if json key is equal to fieldname person.field = text['fields']['text'] # save the JSON key's value to the field # Doesn't work because field is a string. How can I achieve this ? -
Can't find my VM instance (Debian) in Google Compute Root user and Super user Password
In my VM instance I have username the same as my email address (without @gmail.com). It is created automatically, and I do not know the password for it. Also, another user which is a root user,and I do not know the root password. I need it because when I try to run fab secure it will ask me for the password whether I'm running it using a root user or another superuser. Please help. -
Check user permission in template (not request user)
Hello is there any way to check perms of custom user nit request user in template. Code example: {% for agency_user in users %} <tr> <td>{{ agency_user.username }}</td> <td>{{ agency_user.get_full_name }}</td> <td>{{ agency_user.groups.all.first.name }}</td> <td>{{ agency_user.min_price }}</td> <td>{{ agency_user.max_price }}</td> {% if agency_user|has_perm:'may_see_commerce_sell' %} #not working <td>some action</td> {% else %} <td>some action</td> {% endif %} <td> <a href="{% url 'user_edit' agency_user.id %}" class="edit icon"></a> <a user-id="{{ agency_user.id }}" class="trash icon" title="some action"></a> </td> </tr> {% empty %} <td style="text-align: center" colspan="11">some action</td> {% endfor %} Or I have to write custom model methods to each user permission? -
Where's the best place to transform snake-case api responses to javascript's camelcase properties
I have a django API which describes resources using snake_cased json. I also have a React app which consumes the API. I could map the snakecased properties in different locations, ex, in the API renderer, or at the component level. Is there a best practice on where to apply this transformation? -
how to use one for loop key with another for loop key in django template
i able to print values from below code in django views subMarks = [] for item in marks: for column in gridHeaderTableData: subMark = item[column['sub_exam_name']] subMarks.append(subMark) how to write above code in django templates -
Django add a field in a queryset
I have a queryset that contains a field named 'foo' defined in a Bar model. result = Bar.objects.values('foo').distinct() I would like to return a queryset containing 'foo' and a slug version of 'foo'. How can I do that without creating a new field in my Bar model?