Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django m2m produce Unnecessary inner join, that change sql result.
Django 2.1.4 (the like behavior exist on 2.0.4 too) Models: class Application(models.Model): # many fileds name = models.CharField(max_length=255) seers = models.ManyToManyField('Agency', through='ApplicationAgencySeer') class ApplicationAgencySeer(models.Model): application = models.ForeignKey(Application, on_delete=models.CASCADE) agency = models.ForeignKey('Agency', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) now I wanna filter # count 0 Application.objects.filter(seers__agency__id='c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24').count() # 0 # but count 1 ApplicationAgencySeer.objects.filter(agency__id='c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24').count() # 1 SELECT * FROM "app_application" INNER JOIN "app_applicationagencyseer" ON ("app_application"."id" = "app_applicationagencyseer"."application_id") INNER JOIN "app_agency" ON ("app_applicationagencyseer"."agency_id" = "app_agency"."organization_ptr_id") INNER JOIN "app_agency" T4 ON ("app_agency"."organization_ptr_id" = T4."parent_id") WHERE T4."organization_ptr_id" = 'c3e5ed58-a4d9-4ca6-a8f7-6793eb8e3e24' if remove INNER JOIN "app_agency" T4 ON ("app_agency"."organization_ptr_id" = T4."parent_id") all be right. i found the bug <djangoproject> but 6 years ago. I think it already fixes before 2.1.4 release. How to me compose right filter query, or avoid this situation. help me I am stuck. -
How to make django admin interface display the correct number for a (Big)Integer field (and not a rounded one)
I'm looking for a way to disable the rounding when displaying a number on the django (2.1) webinterface. Using images, here is what I see when I load the admin interface for an instance of my model: models.py : class DXXXXXUser(models.Model): dXXXXXd_id = models.BigIntegerField(primary_key=True, unique=True) # This is the field that get rounded when displayed on the admin interface abcd = models.CharField(max_length=200) efgh = models.IntegerField() # [...] -
Testing builtin `contrib.auth.login` with a Client.get() request
My goal : accessing the loging URL with Test Client with posting username/password to log a user in. I use built-in contrib.auth.login in Django 2.1.4 test.py : from django.contrib.auth.models import User from django.contrib import auth from django.test import Client from django.urls import reverse def test_login_valid(): U = {'username': 'bob','password': 'bobbobbob'} u = User.objects.create(**U) C = Client() r = C.post(reverse('login'), U) su = auth.get_user(r.wsgi_request) print(u) print(r) print(su) print(su.is_authenticated) print(r.wsgi_request.user) print(r.wsgi_request.user.is_authenticated) Running test: pytest --capture=no a14n/tests.py::test_login_valid (…) bob <TemplateResponse status_code=200, "text/html; charset=utf-8"> AnonymousUser False AnonymousUser False . registration/login.html: <form action="{% url 'login' %}" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> urls.py: from a14n import views as a14n_views urlpatterns = [ path('signup/', a14n_views.signup, name='signup'), path('', include('django.contrib.auth.urls')), ] On the other hand in a Django shell it works perfect : >>> from django.contrib.auth.models import User >>> from django.test import Client >>> from django.contrib import auth >>> from django.urls import reverse >>> U = {'username': 'bob','password': 'bobbobbob'} >>> C = Client() >>> r = C.post(reverse('login'), U) >>> u = User.objects.create(**U) >>> su = auth.get_user(r.wsgi_request) >>> print(u) bob >>> print(r) <HttpResponseRedirect status_code=302, "text/html; charset=utf-8", url="/accounts/profile/"> >>> print(su) bob >>> print(r.wsgi_request.user) bob >>> print(r.wsgi_request.user.is_authenticated) True >>> print(su.is_authenticated) True Why tests gives ma a … -
A search bar in my web app that returns a list of results from my models in Django
I'm creating a web application that will allow people to search book titles, authors, publishers etc. from a a database. The database is loaded and ready to go in Django, but I'm struggling to find out how to proceed. I assume I need to create a webpage with a form that accepts keywords that the user wants to search for, but how do I then search the database (which Django file would this code go into?) for the keyword and output the result in a list? Sorry if this is super broad. If this is a common question, I can delete it. I would appreciate any help and/or links that could help. Thanks! -
Django "no handlers could be found for logger"
I am developing a Django application where I defined in settings.py (following the instruction of the official docs https://docs.djangoproject.com/en/2.1/topics/logging/ ) my logging config like that LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './debug.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } Everything seems to work fine, I have my debug.log file created and I can see the requests and the query(if DEBUG mode) printed on it. Then, in my view I try to print manually something on it doing the following: import logging logger = logging.getLogger(__name__) logger.error("example") But, when this gets called, I got "no handlers could be found for logger 'package.className' " and nothing gets printed in my file. I don't really get why. My understanding was that the logging called in the view should automatically take the configuration from the settings.py . Am I missing something? -
How to post data with HttpResponseRedirect in Django?
How to post data with HttpResponseRedirect? def response_change(self, request, obj): ### response if "_peer-test" in request.POST: url = request.POST.get('obj', '/export') return HttpResponseRedirect(url) The first line def response_change(self, request, obj): has data so if i type obj.name I wil get dat object. What I want is to redirect to another view en post de information. -
Querying from sql with dynamic model name and fields in Django
I'm new in Django and struggling with some dynamic solutions. I am trying to make an application that user can create table from UI and import data into this table from flat file and then user can be able to browse that data by clicking url(for example, if user create a table for employee, then user should be able to have a url like this for employee : localhost/employee). I will work on import part later but for now, i am trying to find a solution to browse data. And below query is almost do this. But i am not able to use alias instead of column names. Is there any way to build something like that dynamic? def employee(request): entries = Employee.objects.annotate(First Name=F('FirstName')). only('FirstName','Email') print(entries) return render_to_response('employee.html',{'employees': serializers.serialize("json",entries, fields=('First Name','Email'))}) Above query give me below result. I have only email information here. So there is no First Name because annotate is not working. [{"model": "client.employee", "pk": 1, "fields": {"Email":"employe1@gmail.com"}}] -
Django REST Framework NOT NULL constraint failed
when I try to create a new Post by posting the following JSON: { "text": "test", "location": 1 } I get the following error: NOT NULL constraint failed: grapevineapp_post.location_id models.py: class Location(models.Model): name = models.CharField(max_length=80) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Post(models.Model): text = models.CharField(max_length=512) owner = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE) location = models.ForeignKey(Location, related_name='posts', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.text views.py: class PostList(generics.ListCreateAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer def perform_create(self, serializer): serializer.save(owner=self.request.user) class PostDetail(generics.RetrieveUpdateDestroyAPIView): permission_classes = (permissions.IsAuthenticatedOrReadOnly,) queryset = Post.objects.all() serializer_class = PostSerializer Serializers.py class PostSerializer(serializers.Serializer): id = serializers.IntegerField(read_only=True) text = serializers.CharField(required=False, allow_blank=True, max_length=512) owner = serializers.ReadOnlyField(source='owner.username') location = serializers.PrimaryKeyRelatedField(many=False, read_only=True) def create(self, validated_data): return Post.objects.create(**validated_data) def update(self, instance, validated_data): instance.text = validated_data.get('text', instance.text) instance.location = validated_data.get('location', instance.location) instance.save() return instance class UserSerializer(serializers.ModelSerializer): posts = serializers.PrimaryKeyRelatedField(many=True, queryset=Post.objects.all()) class Meta: model = User fields = ('id', 'username', 'posts') DB has already been cleared. Locations have been created by using the admin interface. I know that the issue is something trivial, but I just can't get it to work. -
Django many-to-many relationship between interests and users
I am trying to build a matchmaking website in Django. The main idea is to match users with the most interests in common. Thus, I have created a Hobby class and a Profile class. They are linked through a many-to-many relationship. However, I am doing something wrong because a user can select a Hobby multiple times. For example, Fishing can be added 'n' times. Also, I have to add the Hobbies in Django admin explicitly and only afterwards, the users can choose hobbies when registering. Below is the models.py file: class Hobby(models.Model): HOBBIES = ( ('Skiing', 'Skiing'), ('Fishing', 'Fishing'), ('Hunting', 'Hunting'), ('Golf', 'Golf'), ('Reading', 'Reading'), ('Football', 'Football'), ('Automobiles', 'Automobiles'), ('Fitness', 'Fitness'), ('Politics', 'Politics'), ('Fashion', 'Fashion'), ('Art', 'Art') ) hobby = models.CharField(choices=HOBBIES, max_length=20, null=True) def __str__(self): return self.hobby class Profile(models.Model): ..... ..... hobby = models.ManyToManyField(Hobby) Besides that, when I try to display the hobbies associated with the user I get the following: Hobby.None. Thanks in advance! -
getting name error when try to define urls in Django
I want to define URLs in Django but get an error: from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name="index"), ] the error is: nameError(name'view' is not defind) please inform me. thanks, Saeed -
Adding html to a crispy form in django
I want to customize one of my fields from my form. I would like to add a span tag to one of the input fields and apply a div and some classes. How do I apply these changes to a form rendered with crispy forms? -
AttributeError: '__proxy__' object has no attribute 'set_attributes_from_name' when using ArrayField in Django
I tried setting lazy translations in my models for an ArrayField. Something like this: from django.utils.translation import gettext_lazy as _ class MyModel(models.Model): choices = ArrayField( _('choices'), models.CharField(max_length=255), blank=True, null=True, help_text=_('Comma-delimited list.') ) However, I get this error: AttributeError: '__proxy__' object has no attribute 'set_attributes_from_name' Should it be verbose_name instead, and if so, why? ArrayFields are not relations. -
Why is gettext_lazy used in offical Django models?
I was looking at Django code that comes with the package, such as contrib.auth.models, and I noticed that the first argument in almost every field definition is using gettext_lazy along with the name of the field. Something like this: from django.utils.translation import gettext_lazy as _ class MyModel(models.Model): my_field = models.IntegerField(_('my field')) Why is this done? Is it part of some best practice habit? -
Django: cannot register model in admin panel
I've various models in my apps. However, there is this one that I cannot register so I can see it in the admin panel. So in my cart app, I can use: from django.contrib import admin from .models import Cart, CartItem # Register your models here. admin.site.register(Cart) But not: from django.contrib import admin from .models import Cart, CartItem # Register your models here. admin.site.register(Cart, CartItem) Because I get this error: File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/contrib/admin/checks.py", line 26, in check_admin_app errors.extend(site.check(app_configs)) File "/home/ogonzales/Escritorio/projects_envs/perfectcushion_env/lib/python3.6/site-packages/django/contrib/admin/sites.py", line 81, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'CartItem' object has no attribute 'model' models.py: from django.db import models from shop.models import Product # Create your models here. class Cart(models.Model): cart_id = models.CharField(max_length=250, blank=True) date_added = models.DateField(auto_now_add=True) class Meta: db_table = 'Cart' ordering = ['date_added'] def __str__(self): return self.cart_id class CartItem(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) cart = models.ForeignKey(Cart, on_delete=models.CASCADE) quantity = models.IntegerField() active = models.BooleanField(default=True) class Meta: db_table = 'CartItem' def sub_total(self): return self.product.price * self.quantity def __str__(self): return self.product -
uWSGI issue: dyld: Library not loaded: @rpath/libpcre.1.dylib
I've plugged in uwsgi to my Django application. I'm using macOS Mojave - 10.14.1 . Application runs fine with the below command. python manage.py runserver But when I use uwsgi to start the server. It fails. $uwsgi --socket 127.0.0.1:3031 --chdir /Users/antonybritto/mysite/mysite/ --wsgi-file mysite/wsgi.py --master --processes 4 --threads 2 --status 127.0.0.1:9091 dyld: Library not loaded: @rpath/libpcre.1.dylib Referenced from: /anaconda3/bin/uwsgi Reason: image not found Abort trap: 6 Can someone help me figure out what is wrong? -
Virtual filesystem for users on website with Django backend
What is a reasonable way to provide a virtual file system on a website with Django backend on a per-user-basis? Since a lot of websites (e.g. Overleaf, Cloud9 IDE) have such a feature I assume there is a feasible and ready-to-use solution? -
JSONDecodeError at /pro/product/5/
whenever i run the server at localhost i got this error cant figure out what the issue is here is the code of the request @api_view(['GET','POST']) def ProductView(request,id): # status = get_object_or_404(id=request.POST.get('id', '')) stat = get_object_or_404(Product,id=id) serializer =ProductSerializer # serializer = serializers.statusSerializer(stat,many=True) nice=stat.name # nice = str(stat.total) print(nice) # return Response(json.loads(reade r(nice))) return Response(json.loads(nice)) this the error JSONDecodeError at /pro/product/5/ Expecting value: line 1 column 1 (char 0) -
Customizing django admin
This is my Quiz model, class Quiz(Base): name = models.CharField(max_length=512, null=True, blank=True) genre = models.ForeignKey(Genre, on_delete=models.CASCADE, default="", ) This is a Question, class Question(Base): text = models.TextField() quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, null=True) image = models.ImageField(upload_to=question_image_path, null=True) And this is an answer, class Answer(Base): text = models.TextField(null=True) question = models.ForeignKey(Question, on_delete=models.CASCADE, null=True, blank=True) correct = models.BooleanField(default=False) Instead of the regular django admin display I want to display the entire quiz creation form in one page. How can I customize django admin to do this. -
Django REST framework: How can I associate with other model in POST request?
I'm really new to creating API and I might misunderstand a lot. I want to associate an object with other model in POST request as I do when posting as a form data in astual site. How can I do using rest framework? my api view is like this @api_view(['GET', 'POST']) def list_comment(request, pk): """ List all comments that belong to an entry or add a comment to the entry """ entry = get_object_or_404(Entry, id=pk) comments = Comment.objects.filter(entry=entry) if request.method == 'GET': serializer = CommentSerializer(comments, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = CommentSerializer(data=request.data) # I want to associate the comment with 'entry' here if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Also the rest framework page's form is kind of hard to experiment something and I want to change it to form. How can I change it? Even if I select form data, the content form doesn't change. -
SocialConnectView of django-rest-auth not working to connect existing user to social account
Im trying to connect social account to existing user. Social login works great, the problem is to connect an already registered user. as the docs: #views.py from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView, SocialConnectView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter class FacebookConnect(SocialConnectView): adapter_class = FacebookOAuth2Adapter and #urls.py ... from .views import FacebookLogin, FacebookConnect urlpatterns = [ .... path('facebook/connect/', FacebookConnect.as_view(), name='fb_connect'), path('facebook/', FacebookLogin.as_view(), name='fb_login'), .... ] on my fronend, when the user is logged in and try to connect his account to facebook: axios.post('auth/v1/facebook/connect/', { // token is access_token from facebook response access_token: token, }) but the backend response is: ... status: 401 statusText: "Unauthorized" detail:"Authentication credentials were not provided." ... my settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } ... # allauth settings ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False SOCIALACCOUNT_QUERY_EMAIL= True Am I missing something that I should send to '...facebook/connect/' besides access_token ? PS: Im using separated frontend with webpack -
Listing all movies of a specific cinema - Foreign Key Django
I am new to Django and I have a question regarding the models and foreignkeys. I have two models: Cinema and Movie. One Cinema can have multiple movies, so I placed the foreign key of cinema in the Movie model. class Cinema(models.Model): name = models.CharField(max_length=255) address = models.CharField(max_length=255) class Movie(models.Model): title = models.CharField(max_length=255) description = models.CharField(max_length=255) posting_cinema = models.ForeignKey('cinemas.Cinema', on_delete=models.CASCADE, null=True) Now I want to list all the movies of a specific Cinema. How can I do it? The idea is the following: The user clicks on a cinema, it opens a page with the cinema details and a button "see movies". If the user clicks this button, a new page opens and I want to have listed there the movies of that specific cinema. I tried to figured out some solutions but sadly I am stuck. I was thinking about Movie.objects.filter(#something) but I am not sure -
Django admin. TabularInline. How to show ForeignKey related model in TabulatInline view
I trying to show in my django-admin, related model of related model. Right now my models and admin.py looks like: class CharacterChoiceInline(admin.TabularInline): model = CharacterModel fields = ['nickname', 'gender', 'image'] extra = 1 class UserModelAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': [ 'username', 'email', ... ] }) ] inlines = [CharacterChoiceInline] admin.site.register(User, UserModelAdmin) My CharacterModel is related with another model RaceModel. class RaceModel(models.Model): name = models.CharField("Race", max_length=254) character = models.ForeignKey("CharacterModel", null=True, blank=True, on_delete=models.SET_NULL, related_name='+') class CharacterModel(models.Model): nickname = models.CharField("Character nickname", max_length=254) gender = models.CharField(choices=GENDER, max_length=10, default='male') image = models.URLField(blank=True) In Admin it looks like so: How can I add this additional RaceModel field as part of CharacterChoiceInline(admin.TabularInline):? -
Django | CKEditor - Image Upload option not showing in App
In admin all CKEditor option is showing and working properly. I can upload image in main admin dashboard. But in App in Image "Uoload" option is not showing. Please see those images than you have a clear view, Image 1 Image 2 Others option is working properly without image Upload. settings.py THIRD_PARTY_APPS = [ 'widget_tweaks', 'ckeditor', 'ckeditor_uploader', ] INSTALLED_APPS += THIRD_PARTY_APPS + LOCAL_APPS # CkEditor Upload path CKEDITOR_UPLOAD_PATH = 'uploads/' # CkEditor Custom Configuration CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'Custom', 'width': 680, 'extraPlugins': ','.join(['codesnippet']), }, } template.html <form method="post" enctype="multipart/form-data">{% csrf_token %}> {{ form.media }} {{ form.as_p }} <button type="submit">Submit</button> </form> -
Django apps aren't loaded yet when using asgi
I'm tring to run my django project with usage of asgi instead of wsgi. I have set up my routing.py and asgi.py as follows: routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter, URLRouter from channels.security.websocket import AllowedHostsOriginValidator, OriginValidator from channels.auth import AuthMiddlewareStack from some.consumers import SomeConsumer application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r'^some_url/$', SomeConsumer), ] ) ) ) }) asgi.py import os from channels.routing import get_default_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings") application = get_default_application() Now, as you can see it's standard setup and it works fine with default django server but when I try to run with some other (daphne or uvicorn) it's throwning this exception. Here is my INSTALLED_APPS INSTALLED_APPS = [ 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django_jenkins', 'easy_thumbnails', 'image_cropping', 'allauth', 'allauth.account', 'and_rest_of_my_own_apps', ] Has anyone had problem like this? -
Django queryset filtering and annotate
How to write in Django query that? I write in sql something like that: select distinct tt.client_id from (select tk.client_id, min(tk.changedon) min_date from app_tickets_ticket tk where tk.status_id=7 and tk.active=FALSE group by tk.client_id) tt, app_tickets_ticket tr where tr.client_id=tt.client_id and tr.status_id in(5,6) and tr.active=FALSE and tt.min_date::DATE between '2018-12-05'::DATE and '2018-12-06'::DATE and tr.changedon::DATE<=tt.min_date::DATE and tt.client_id not in(select tm.client_id from app_tickets_ticket tm where tm.active=FALSE and tm.changedon::DATE between '2018-12-05'::DATE and '2018-12-06'::DATE and tm.changedon<=tt.min_date and tm.status_id in(8,10,11,12,13,14,15,16,17))