Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store a user's cart in Django (e-commerce)
Please take a look and tell me if im wrong / if its a bad method and why. I need: 1. Anon user can add products to the cart. 2. Anon user can access his cart with the same computer even after he close browser. 3. Registered user can do the same + if he logs in with the other computer, he still can access his cart, made before. My thoughts: Registered user's model has products_in_the_cart field. models.py from django.contrib.auth import User class MyUser(User): products_in_the_cart = models.Charfield(max_length=200) Products, which been added to the cart, stores in cookies. If user is authenticated, it also stores in User model. views.py def add_product_to_the_cart(request, product_id): ... request.COOKIES['products_in_the_cart'].append(product_id) if request.user.is_authenticated(): request.user.products_in_the_cart = json.dumps(request.COOKIES['products_in_the_cart']) return render(request, ... ) Finally if user logging in, his current COOKIES['products_in_the_cart'], if exists, overrides model's data. If not exists, his model's data writes down in COOKIES. views.py def user_login(request): ... login(request, user) if request.COOKIES.get('products_in_the_cart', False): user.products_in_the_cart = json.dumps(request.COOKIES['products_in_the_cart']) elif user.products_in_the_cart: request.COOKIES['products_in_the_cart'] = json.loads(user.products_in_the_cart) ... -
Paginator and Django Model too slow
I have two models: Question and Answer. Question: - title - Description Answer: - Question - title - description I have a method called describe, and I use this to put answers in the same dict of questions. def describe(question): _question = model_to_dict(question) _question ['answers'] = Answers.objects.filter(question = question) return _question But when I use Paginator, I need to describe this first and this let my queryset too slow: described_question = [describe(question) for question in Question.objects.all()] Paginator = Paginator(described_question, 10) If I just pass the model inside Paginator, my requesto go to 99ms. But if I use my describe method, up to 200ms (in development envirolment). -
How do you show in the Django admin site the fields of a related manytoone model?
How do you show in the Django admin site the fields of a related manytoone model? For example, class A(models.Model): ... class B(models.Model): a = models.ForeignKey(A) class AAdmin(admin.ModelAdmin): list_display = [???] What do I put in A's list_display to display the 'a' in class B? -
Are Tornado or Django good at handling large file upload? [on hold]
SO folks! The requirement is simple: I want the server to be able to handle file uploading robustly (~100 QPS, 50~150 MB per request). I am about to use Django or tornadoweb but would love to know their performance before diving deep. A must-have feature is it should be able to handle breakpoint resume. -
Pandas DataFrame to Django API
I'm using pyodbc to query SAP HANA and using pandas to analyze data. It takes ~15 seconds to load: import pyodbc import pandas as pd cnxn = pyodbc.connect('DSN=DATABASE;UID=USERNAME;PWD=PASSWORD') cursor = cnxn.cursor() qry = "SELECT * FROM Sales" df = pd.read_sql(qry, cnxn) *do some manipulation* df_final Now I'd like to store the dataframe as an API. From: fruit units Apple 100 Bananas 200 To: [{fruit: 'Apple', units: 100}, {fruit: 'Bananas', units: 200}] So far I've created a model and serializer, but I'm a bit lost as to what to do next.. Model: class Sales(models.Model): fruit = models.CharField(max_length=16) units = models.FloatField() def __str__(self): return self.fruit Serializer: class FruitSerializer(serializers.ModelSerializer): class Meta: model = Fruit fields = ('fruit', 'units') -
Logout link not working django
In urls.py I have the following from django.conf.urls import url from django.contrib.auth.views import logout from core import views as core_views urlpatterns = [ url(r'^logout/$', logout, {'template_name': 'core/logout.html'}, name='logout'), url(r'^profile/$', core_views.view_profile, name = 'view_profile'), etc... ] I have a base.html that is included on every page: <!doctype html> <head> {% block head %} <title>base</title> {% endblock %} </head> <body> <a href = 'core/logout.html'>Logout</a> {% block body %} {% endblock %} </body> </html> The profile.html page: {% extends 'core/base.html' %} {% block head %} <title> Profile</title> {% endblock %} {% block body %} <h2>Profile</h2> <p> {{ user.first_name }}<br/> {{ user.last_name }}<br/> {{ user.email }}<br/> {{ user.userprofile.city }} </p> {% endblock %} The logout.html page: {% extends 'core/base.html' %} {% block head %} <title>Logout</title> {% endblock %} {% block body %} <p>Logged out</p> {% endblock %} The problem is if the user is at /profile and clicks the logout link at the top of the page it sends the user to /profile/logout which does not exist, how do I get it to send the user to /logout ? -
How to handle multiple values in values_list with distinct(), annotate() and count in view.py
I have the table(a_table) like this in my database: field0 field1 field2 field3 field4 field5 11:00 x y 2 a a_name 11:01 x y 11 d a_name 11:02 x y 6 k b_name 11:03 x y 13 a a_name and so on. I need to: When field5 = a_name, then 1. field12_pair = field1 -> field2 (which is field12_pair = x->y in this case) 2. Calculate sum of field3. In this case, it will be TotalNumber_field3 = 26 3. Count distinct value in field4. In this case it will be distinct_field4 = 2 I have code in view.py like this: field12 = a_table.objects.filter(field5=a_name).values_list('field1', 'field2').distinct() field12_pair = (item[field1] + '->' + item[field2]) for item in field12 TotalNumber_field3 =a_table.objects.filter(field5=a_name).aggregate(Sum('field3').values[0] distinct_field4 = =a_table.objects.filter(field5=a_name).values('field4').distinct.count() How can I combine all three queries in one query? -
AttributeError when trying to use _set in django form (for filter_horizontal widget)
I'm just trying to configure a filter_horizontal widget for one of the fields on the admin form for a model. but I get the following error when I try to use _set to reverse an m2m relationship. The model I'm creating a form for is called Statement. And I'm trying to work with a field it has calls keywords, which draws an m2m with another model. class Statement(models.Model): statement_id = models.CharField(max_length=200) title = models.CharField(max_length=200) issue_date = models.DateField("Issue-Date") author = models.ForeignKey(Person) released_by = models.ForeignKey(Organization) keywords = models.ManyToManyField('KeywordInContext') So in the form I try to configure the filter_horizontal widget, but I get an attribute error when I try to use keywords_set. class StatementForm(forms.ModelForm): statement_keywords = forms.ModelMultipleChoiceField( queryset=KeywordInContext.objects.all(), required=False, label=('Select keywords that you would like to assign to this statement on the left. Keywords that are assigned to this statement are on the right.'), widget=FilteredSelectMultiple( verbose_name='Keywords Associated with Statement', is_stacked=False ) ) def __init__(self, *args, **kwargs): super(StatementForm, self).__init__(*args, **kwargs) if self.instance.pk: self.fields['statement_keywords'].initial = self.instance.keywords_set.all() ##CAUSES ATTRIBUTE ERROR def save(self, commit=True): statement = super(StatementForm, self).save(commit=False) if commit: statement.save() if statement.pk: statement.keywords_set = self.cleaned_data['keywords'] #change to keyword if need be self.save_m2m() return statement The error message I get is File "./gtr_site/forms.py", line 73, in __init__ … -
Python JWT auth token does not authorize with django jwt api
i am trying to call my jwt authenticated django api that lives on an EC2 instance from my home laptop. the API will return me a auth key but when i try to use the auth key it tells me im not authorized. I have provided an example of the various methods i have tried to use to get this to work. is there anything specifically i am doing wrong in this code that would warrant my code to consistently return 401 error? when asking for an authenticated API with a JWT token is there anything specifically i need to do or a specific way i need to set my headers so that i can get a value to return? or does this look like an issue with the backend? import requests from urllib2 import Request, urlopen import jwt from requests_jwt import JWTAuth, payload_method import json def tryme(chats, payload, jwt): #method1 res = requests.post(chats, json=payload) print res.status_code # error 401 # method2 req = requests.get(chats, params=payload) print req.status_code # error 401 # method3 req = Request(chats) req.add_header('Authorization', 'Token token={}'.format(auth['token'])) req.add_header('content-type', 'application/json') res = urlopen(req) print res.status_code # error 401 #method4 token = JWTAuth(jwt['token']) out = requests.get(chats, auth=token) print out.status_code # … -
Authenticate and login users and opening new page
i have two pages in my Django website: home page and the chatting page! What i want is when the users clicks "start-chatting" app should Authenticate using the user name then do the login after that open the chatting page. my files: home.js: $('.btn-xl').click(function(){ var uname = ('.message-input').val(); $.ajax({ url : '/LogIIn/', type : 'POST', data : { name: uname },}); window.open('http://gadgetron.store/P_chat'); $('.message-input').val(null); document.getElementById('radio02').checked=false; document.getElementById('radio01').checked=false; }); views.py: from chatbot import settings from django.shortcuts import render from django.http import HttpResponse, JsonResponse,HttpResponseRedirect from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate from django.contrib.auth import login @csrf_exempt def P_home(request): context= locals() template= 'P_home.html' return render(request,template,context) @csrf_exempt def P_chat(request): context= locals() template= 'P_chat.html' return render(request,template,context) @csrf_exempt def LogIIn(request): name = request.POST.get('name') password = '!Emoo1989' user = authenticate(username=name) login(request, user) return HttpResponse("OK") i'm new in the authentication but the code didn't work with me -
Making a Javascript click function for model objects formatted in Django Tables2 that shows related divs
I'm trying to make a Javascript function involving a django-tables2 table featuring model objects that will show relevant information when clicked. Here is the relevant code: models.py class Student(models.Model): student_id = models.CharField(max_length=128, unique=True, null=True, blank=True) first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) ssn = USSocialSecurityNumberField(null=False) gender = models.CharField(max_length=128, choices=GENDER_CHOICES) country = CountryField(default='US', blank=True) primary_phone = models.CharField(max_length=128) email = models.EmailField(max_length=254, validators=[validate_email]) background = models.CharField(max_length=128, choices=BACKGROUND_CHOICES) location = models.CharField(max_length=128, choices=LOCATION_CHOICES, default='south_plainfield') created_at = models.DateTimeField(null=True, auto_now_add=True) tables.py class StudentListTable(tables.Table): name = tables.TemplateColumn('''{{ record.first_name }} {{ record.last_name }}''', verbose_name=u'Name') manage = tables.TemplateColumn('''<a href="/students/update_student/{{ record.id }}">Update</a> / <a href="/students/delete_student/{{ record.id }}" onclick="return confirm('Are you sure you want to delete this?')">Delete</a>''') assign = tables.TemplateColumn('''<a href="/students/id={{ record.id }}/add_studentcourse">Courses</a> / <a href="/students/id={{ record.student_id }}/add_studentemployment">Employment</a> / <a href="/students/id={{ record.id }}/add_studentcounselor">Counselor</a> / <a href="/students/id={{ record.id }}/show_student_lists">Show</a>''') class Meta: model = Student fields = ('student_id', 'name', 'gender', 'ssn', 'email', 'primary_phone', 'created_at', 'manage', 'assign') row_attrs = { 'id': lambda record: record.pk } attrs = {'class': 'table table-hover', 'id': 'student_list'} views.py def all_My_Student(request): student_list = Student.objects.order_by('-created_at') table = StudentListTable(student_list) RequestConfig(request).configure(table) return render(request, 'students/all_my_student.html', {'table': table, 'student_list': student_list}) all_my_student.html {% block main_content %} <div class="box box-primary" id="student_list_table"> {% if table %} {% render_table table %} {% endif %} </div> {% for student in student_list %} … -
django comments unexpected keyword argument error
I am working on a project using django and I had everything going well until I decided to implement comments. so after writing and codes I got stocked at a point where I got an error in the browser. this is my error Error __init__() got an unexpected keyword argument 'initial' Model post from django.core.urlresolvers import reverse from django.db import models from django.conf import settings from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import slugify from comments.models import Comment from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType # Create your models here. class Post(models.Model): ...... #objects = PostManager() def __str__(self): return self.title def get_absolute_url(self): return reverse("next", kwargs={"slug": self.slug}) @property def comments(self): instance = self query = Comment.objects.filter_by_instance(instance) return query @property def get_content_type(self): instance = self content_type = ContentType.objects.get_for_model(instance.__class__) return content_type Model comment from django.conf import settings from django.db.models.signals import pre_save from django.utils import timezone from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType #from posts.models import Post # Create your models here. class CommentManager(models.Manager): """docstring for CommentManager.""" def filter_by_instance(self, instance): content_type = ContentType.objects.get_for_model(instance.__class__) obj_id = instance.id query = super(CommentManager, self).filter(content_type=content_type, object_id=obj_id) return query #comments = Comment.objects.filter(content_type=content_type, object_id=obj_id) class Comment(models.Model): """docstring for Comment.""" user = models.ForeignKey(settings.AUTH_USER_MODEL, … -
Save user data in another table once a user is created in django admin
I am a beginner in django. I am using django 1.10 with allauth app which takes care of frontend registration, sending user confirmation email,validation, login with email etc. The allauth app inserts three rows in three tables when a user is created. 1. auth_user 2. account_emailaddress 3. account_emailconfirmation When adding a user from admin it creates a row in auth_user and general_userprofile table. I would like to insert a row in account_emailaddress table when admin creates a user. Fields in account_emailaddress are-- id email verified primary user_id The models.py looks like -- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.db.models.signals import post_save from django.dispatch import receiver from ciasroot.util import HashedPk from phonenumber_field.modelfields import PhoneNumberField import math, decimal, datetime, os User._meta.get_field('email').blank = False User._meta.get_field('email')._unique = True class EmailAddress(models.Model): verified = models.BooleanField(verbose_name=_('verified'), default=True) primary = models.BooleanField(verbose_name=_('primary'), default=True) class UserProfile(models.Model, HashedPk): user = models.OneToOneField(User, unique=True, related_name ='profile') job_title = models.CharField(max_length=128, blank=True, null=False, default="") website = models.URLField(max_length=255, blank=True, null=True) organisation = models.CharField(max_length=50, blank=True, null=True, default="") phone_number = PhoneNumberField( blank=True, null=True) @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) How can I get the user id and email which is created … -
Annotate method in django
I have a little problem with annotate. I want to display records from my class Kategorie in the main html file. I used the annotate method to take the query from db. I used in the second class Firmy the ForeignKey to class Kategorie. Now I dont know how to display for example how many websites added in the class Firmy are in the for example in category Business. Now I have something like: "Business (2)(3)(4)" when I used annotate with count by id. This is my models.py from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url') email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria') data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji') class Meta: verbose_name='Strona www' verbose_name_plural = 'Strony www' def publikacja(self): self.data_publikacji=timezone.now() self.save() def __str__(self): return self.nazwa And some part from views.py from django.db.models import Count wpisy_kat = Kategorie.objects.annotate(cnt_witryna=Count('Witryna')) So what kind of method or tags I have to use to display for example: Business(34) Industry(21) Health Care(11) where the … -
Keeping the order of Django Taggit tags
Im trying to keep the order of the tags a user adds. I work with Django Taggit and the sequence of the tags change when the user reloads the page. I added the drag and drop functionality and it works but its pretty useless when the tags always change position afterwards... Currently im trying to handle the issue by using Django taggits set() but its not running as expected. views.py: form = UserProfileForm(request.POST or None, instance=user.userprofile) if form.is_valid(): form.save() #when I save the form later the order is again mixed x2 = form.data['tags'].split(" ") # can't use cleaned_data since the order is wrong user.userprofile.tags.set(x2,clear=True) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) The Problem with this code is that x2 is valued as a string and not separated tags so the input is one very long tag. I can't use taggits add since the sequence is mixed afterwards. The only possibility is to give multiple variables to set but this is messy and can break the code easily if values are not given or not valid. The code would be something like: t0= x2[0] t1= x2[1] t2= x2[2] user.userprofile.tags.set(t1,t2,t3,clear=True) I know you could optimize this with try/expect or a for loop but I hope somebody has … -
Django Url not leading to the proper template Beginner
I am a beginner trying to extend the Mozilla Django tutorial, and have run into a problem. I've looked here and on the official Django tutorial and can't find the answer. Basically, I have a list of authors and adjacent links to a delete form: {% for author in author_list %} <li> <a href="{{ author.get_absolute_url}}">{{author.last_name }}<a> <a href="% url 'author_delete' author.pk %">Delete</a> </li> {% endfor %} This is the url pattern: urlpatterns+=[ url(r'^author/(?P<pk>\d+)/delete/$', views.AuthorDelete.as_view(), name='author-delete'), ] This is the views file: class AuthorDelete(DeleteView): model = Author success_url = reverse_lazy('authors') Somehow an idenitcally structured titles page works without problem. Thanks for any help. -
How to show ForeignKey value even if object deleted?
I have simple link below and it links to model object actor with id that is deleted (one table references to other). This rises an error, but I want to get that id to create link anyway. How to do that? <a href="{% url "actor:view" notification.actor.id %}"> error: Reverse for 'view' with arguments '('',)' not found. 1 pattern(s) tried: ['actor/view/(?P<id>\\d+)$'] -
POST request to Django DRF call working in cURL but not with Postman
I'm following the instructions to support TokenAuthentication in my rest-api site, shown here. Using cURL, I have been able to obtain my user's token (username - example, password - example), through the following command: curl -X POST -d "username=example&password=example" localhost:8000/api/login/ This returns a successful response, with example's authentication token. Yet when I do (what I think is) the same thing through Postman, it simply does not work. See image below. From the error code (400 - Bad request), it seems like it's not even receiving the POST parameters at all. Can anyone help me here? -
uwsgi + django + nginx: Python application not loading
Following a bunch of tutorials, I wrote my first django app and then decided to deploy it on a linode server. Following their tutorial, I only got so far. The best I could tell, that was based on an earlier version of Ubunto and I tried some other things, including the uwsgi quickstart tutorial. It seems as though there is some environment variable missing. When I try to start uwsgi from the command line with: uwsgi --http :8000 --module dynamicefl.wsgi I get the following: *** Starting uWSGI 2.0.15 (64bit) on [Fri Aug 11 19:37:04 2017] *** compiled with version: 6.3.0 20170406 on 10 August 2017 23:41:13 os: Linux-4.9.36-x86_64-linode85 #1 SMP Thu Jul 6 15:31:23 UTC 2017 nodename: roosevelt machine: x86_64 clock source: unix detected number of CPU cores: 1 current working directory: /home/django/worksheets/dynamic-efl detected binary path: /usr/local/bin/uwsgi !!! no internal routing support, rebuild with pcre support !!! *** WARNING: you are running uWSGI without its master process manager *** your processes number limit is 3941 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound on :8000 fd 4 spawned … -
Insert data in a table after a user is created from djando admin
I am a fresher in django. I am using django 1.10 with allauth app which takes care of frontend registration, sending user confirmation email,validation, login with email etc. So it all works in the frontend. In the backend I managed to change the user creation form by adding an extra field email. The allauth app inserts 3 rows in 3 tables when a user is created in the frontend. 1. auth_user 2. account_emailaddress 3. account_emailconfirmation When adding a user from admin it creates a row in auth_user and general_userprofile(extending django user model) table. I would like to insert a row in account_emailaddress table whenever a user is created via admin. Fields in account_emailaddress are-- id email verified primary user_id models.py -- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext as _ from django.db.models.signals import post_save from django.dispatch import receiver from ciasroot.util import HashedPk from phonenumber_field.modelfields import PhoneNumberField import math, decimal, datetime, os User._meta.get_field('email').blank = False User._meta.get_field('email')._unique = True class EmailAddress(models.Model): verified = models.BooleanField(verbose_name=_('verified'), default=True) primary = models.BooleanField(verbose_name=_('primary'), default=True) class UserProfile(models.Model, HashedPk): user = models.OneToOneField(User, unique=True, related_name ='profile') job_title = models.CharField(max_length=128, blank=True, null=False, default="") website = models.URLField(max_length=255, blank=True, null=True) organisation = models.CharField(max_length=50, blank=True, … -
When building a website using Django and Wagtail, what is the best practice for organizing externa l/ 3rd party apps?
Using Webtails and Django, I'm trying to keep things clean by separating my site's functionality into as many small apps as possible, rather than bloating a few out. How do people best organize externals apps, however? For example, I'm using django-registration-redux to handle all my user registration/account stuff, and as far as I can tell - as this is already a stand-alone app, it just sits as a 3rd party app in my project, rather than coupling with an existing app. Is that the correct way to do things, or would it be better long-run to start a new app that just handles this external one, even if the app itself doesn't do anything on its own? -
Django form: An invalid form control with name='reg_add_city' is not focusable
I have a form created with Django. When I use command "form.as_p" to create form it creates great and works fine. Data is saved to db. But when I try to edit form to my own 'design' I have an error in Chrome: An invalid form control with name='reg_add_city' is not focusable. Could you help me? Here is my code: register.html {% extends 'registration/base.html' %} {% block content %} <form method="POST" class=""> {% csrf_token %} <div class="col-md-6"> <div class="panel panel-default"> <div class="panel-heading"> Dane dziecka </div> <div class="panel-body"> <div class="form-group"> <label>Czy dziecko zostało już zgłoszone? *</label> {{ form.is_registered }} TAK </div> <div class="form-group"> <label>Imię *</label> {{ form.first_name }} </div> <div class="form-group"> <label>Nazwisko *</label> {{ form.last_name }} </div> <div class="form-group"> <label>Płeć *</label><br> {{ form.gender }} </div> <div class="form-group"> <label>Data urodzenia *</label> {{ form.birth_date }} </div> <div class="form-group"> <label>Miejsce urodzenia *</label> {{ form.birth_place }} </div> <div class="form-group"> <label>PESEL *</label> {{ form.pesel }} </div> <div class="form-group"> <label>Numer i seria dowodu osobistego</label> {{ form.id_card }} </div> <div class="form-group"> <label>Adres zameldowania *</label><br> <label><small>Ulica</small></label> {{ form.reg_add_street }} <label><small>Kod pocztowy</small></label> {{ form.reg_add_postal }} <label><small>Miasto</small></label> {{ form.reg_add_city }} </div> <div class="form-group"> <label>Adres zamieszkania </label><br> <input type="checkbox" id="child_address_is_diff" value="child_address_is_diff" onclick="showChildAddress()"> Inny niż zameldowania? <div id="child_address_diff"> <label><small>Ulica</small></label> {{ form.liv_add_city }} <label><small>Kod … -
Django-Rest-Framework-Filters: Using custom queryset methods in a filter being consumed via a RelatedFilter
I'm using Django-Rest-Framework-Filters in a similar manner as documented here. I would like to filter Author by some condition on the related Post class which is using a custom PostQuerySet queryset method. The filter, myfilter, is defined on PostFilter filterset as: class PostFilter(filters.FilterSet): myfilter = filters.BooleanFilter(name='date_published', method='filter_myfilter') class Meta: model = Post fields = ['title', 'content'] def filter_myfilter(self, qs, name, value): """ Calls myqueryset_method defined on PostQuerySet """ return qs.myqueryset_method() class AuthorFilter(filters.FilterSet): posts = filters.RelatedFilter('PostFilter', queryset=Post.objects.all()) class Meta: model = Author fields = ['name'] The trouble is, when trying to use this filter as part of Author's API, e.g. /api/authors?posts__myfilter=true an error is thrown: "AttributeError: 'Manager' object has no attribute 'myqueryset_method'" It seems counter-intuitive, but it appears you cannot execute the PostQuerySet method on the qs arugment because it is not a Post queryset when called by the RelatedFilter. As explained in the docs: [when making the filter calls] /api/posts?is_published=true /api/authors?posts__is_published=true "In the first API call, the filter method receives a queryset of posts. In the second, it receives a queryset of users." So how can you leverage custom queryset methods in the filter that is being consumed through a RelatedFilter? -
System check identified 3 issues (0 silenced)
what could the issue with my model.py .i have tried everything nothing happens.and i think i defined my foreign key the right way .could it be a problem with my defining or do i have to use memberid.user in my foreginkey or what would be effect.any contribution is welcomed. Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f6a926d69b0> Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: tithe.tithe.memberid: (fields.E300) Field defines a relation with model 'memberid', which is either not installed, or is abstract. tithe.tithe.memberid: (fields.E307) The field tithe.tithe.memberid was declared with a lazy reference to 'tithe.memberid', but app 'tithe' doesn't provide model 'memberid'. tithe.tithe: (models.E012) 'unique_together' refers to the non-existent field 'IntegerField'. System check identified 3 issues (0 silenced). Performing system checks... Unhandled exception in thread started by <function wrapper at 0x7f3d3ccdc9b0> Traceback (most recent call last): File "/usr/lib64/python2.7/site-packages/django/utils/autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "/usr/lib64/python2.7/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "/usr/lib64/python2.7/site-packages/django/core/management/base.py", line 405, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: … -
UNIQUE constraint failed erroe in django
I have a little problem with my migrations in django project. I have a models.py file and after first migrations I had a idea to add new field exacly : slug_kat = models.SlugField(max_length=255, unique=True, verbose_name='Odnośnik', default='') And when I wrote python manage.py makemigrations the system shows me something like: Add field slug_kat to kategorie After that i wrote the command python manage.py migrate firmy and boom... the error: django.db.utils.IntegrityError: UNIQUE constraint failed: firmy_kategorie.slug_kat Here is my models.py file with new line slug_kat: from django.db import models from django.utils import timezone class Kategorie(models.Model): glowna = models.CharField(max_length=150, verbose_name='Kategoria') slug_kat = models.SlugField(max_length=255, unique=True, verbose_name='Odnośnik', default='') class Meta: verbose_name='Kategoria' verbose_name_plural='Kategorie' def __str__(self): return self.glowna class Witryna(models.Model): nazwa = models.CharField(default="", max_length=150, verbose_name = 'Nazwa strony') adres_www = models.CharField(max_length=70, verbose_name='Adres www') slug = models.SlugField(max_length=250, verbose_name='Przyjazny adres url') email = models.CharField(max_length=100, verbose_name='Adres e-mail') text = models.TextField(max_length=3000, verbose_name='Opis strony') kategoria = models.ForeignKey(Kategorie, verbose_name='Kategoria') data_publikacji = models.DateTimeField(blank=True, null=True, verbose_name='Data publikacji') class Meta: verbose_name='Strona www' verbose_name_plural = 'Strony www' def publikacja(self): self.data_publikacji=timezone.now() self.save() def __str__(self): return self.nazwa