Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to add object in a Model Intermediate in Django DRF?
I have two Models, Group and GroupMember. In Group, I have the field customers, ManyToMany to customer in GroupMember. Here my Models. class Group(models.Model): name = models.CharField(max_length=64) members = models.ManyToManyField(User, through='GroupMember') class GroupMember(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) member = models.ForeignKey(User, on_delete=models.CASCADE) joined_at = models.DateTimeField(auto_now_add=True) Here are my Serializers. class GroupMemberSerializer(ModelSerializer): class Meta: model = GroupMember fields = ['group', 'member', 'joined_at'] class GroupSerializer(ModelSerializer): class Meta: model = Bill fields = ['name', 'members'] So, members are Users logged in my application, but I dont know to do to add a UserLogged(Member) in a GroupMember in Django RestFramework. First, I want create a group and add a user logged to member in GroupMember, in this case when a Create a Group, I need too create a object(GroupMember) for this Group, and then another member can be joined at GroupMember, with a group has been created, in a method like add_in_groupmember. Basically, I need two Views, the Firts View for create a Group and add user_logged(members) in object GroupMember, and then object GroupMember is created, I need a view for add another user in member(GroupMember). -
django-parler - M2M Relationship Issue with Admin M2M Field (Circular Dependency?)
we're facing an issue with the use of M2M relationships - It seems we have a circular dependency issue? We need to make a M2M relationship to a TranslatableModel field (which is M2M under the hood), exposed in the Admin (we have a multi-select widget that utilises the M2M field). Lots of research has only revealed this specific debug info (thanks to @egasimus): models.py # Here's a pretty basic model with a translatable M2M field. class ContentItem(TranslatableModel): translations = TranslatedFields( title = models.CharField(max_length=200), content = models.TextField(blank=True), primary_media = models.ForeignKey( 'media.MediaAsset', related_name='cards_where_primary', blank=True, null=True) extra_media = models.ManyToManyField( 'media.MediaAsset', related_name='cards_where_extra', blank=True, null=True)) author = models.ForeignKey(settings.AUTH_USER_MODEL) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) admin.py class ContentItemAdmin(TranslatableAdmin): fields = ('title', 'content', 'primary_media', 'extra_media', 'author', 'created', 'modified') # The above code results in the following error: # FieldError at /admin/cms/contentitem/1/ # Unknown field(s) (extra_media) specified for ContentItem. Check fields/fieldsets/exclude attributes of class CardAdmin. class ContentItemAdmin(TranslatableAdmin): pass # And, if I don't explicitly define fields, the `extra_media` field doesn't show up at all. # This is confirmed if I run `manage.py shell` and I retrieve a ContentItem instance: # it simply does not have an `extra_media` attribute. However, if I do manually retrieve # a translation instance, … -
Django ManyToMany field returns None but it has related records
I have a model with a ManyToMany field, but when I make a query, this field returns None even when it has values in the database (I have checked it with Django Admin util). This is my model: class Profile(models.Model): name = models.CharField(max_length=50, unique=True, verbose_name=_('Name')) cities = models.ManyToManyField(City, related_name='profiles', verbose_name=_('City')) class Meta: verbose_name = _('Profile') verbose_name_plural = _('Profiles') def __str__(self): return "[{}]{}".format(self.name, self.cities) This is my query: profile_city = models.Profile.objects.get(id=profile_id) print(profile_city.id, ' ', profile_city.name, ' ', profile_city.cities) And this is the result in console: 1 Quintana Roo GeneralApp.City.None When I try to iterate over ´Profile.cities´, I get this error: ´TypeError: 'ManyRelatedManager' object is not iterable´. I am new to Django and I thought ManyToMany fields returned an array, but It is not, apparently. Thanks for your help. -
Django Background-tasks interval
I am using background_task lib in django app I am trying to execute simple function every interval (5 min) How can I set the interval Code in views.py @background(schedule=60) def read_filters(repeat=60*5): print("Hello") and I run in powershell python manage.py process_tasks but it not execute every 5 min I think it execute every second how can I set it?? -
Django reverse m2m query
Using the models from https://docs.djangoproject.com/en/dev/topics/db/queries/#making-queries with minor modifications: from django.db import models class Blog(models.Model): name = models.CharField(max_length=100) class Author(models.Model): name = models.CharField(max_length=200) joined = models.DateField() def __str__(self): return self.name class Entry(models.Model): blog = models.ForeignKey(Blog, on_delete=models.CASCADE) headline = models.CharField(max_length=255) authors = models.ManyToManyField(Author) rating = models.IntegerField() I would like to create a dictionary from Author to Entries, where the Author joined this year, and the Entry has a rating of 4 or better. The structure of the resulting dict should look like: author_entries = {author1: [set of entries], author2: [set of entries], etc.} while hitting the database less than 3'ish times (or at least not proportional to the number of Authors or Entries). My first attempt (db hits == number of authors, 100 authors 100 db-hits): res = {} authors = Author.objects.filter(joined__year=date.today().year) for author in authors: res[author] = set(author.entry_set.filter(rating__gte=4)) second attempt, trying to read entries in one go: res = {} authors = Author.objects.filter(joined__year=date.today().year) entries = Entry.objects.select_related().filter(rating__gte=4, authors__in=authors) for author in authors: res[author] = {e for e in entries if e.authors.filter(pk=author.pk)} this one is even worse, 100 authors, 198 db-hits (the original second attempt used {e for e in entries if author in e.authors}, but Django wouldn't have it. The only method … -
Django template : display objects in cascade with foreign key
I'm trying to display some django objects in my template which are connected by Foreign Key field. I tried to make an easy example in order to illustrate what I would like to get in my template with accordion html. My django model : class Grandparent(models.Model): name = models.CharField(...) age = models.IntegerField(...) def __str__(self): return f"{self.name} : {self.age}" class Parent(models.Model): name = models.CharField(...) age = models.IntegerField(...) grandparent = models.ForeignKey(Grandparent, related_name='grandparent') def __str__(self): return f"{self.name} : {self.age}" class Child(models.Model): name = models.CharField(...) age = models.IntegerField(...) parent = models.ForeignKey(Parent, related_name='parent') def __str__(self): return f"{self.name} : {self.age}" As you can see, child depends from parent which depends from grandparent. My html template : Now I would like to display something like that in my HTML template : So my HTML looks like below and I don't overcome to get what I want : {% for grandparent in grandparent_list %} <div class="accordion-publication panel-group" id="accordion" role="tablist" aria-multiselectable="true"> <div class="panel-primary"> <div class="panel-heading" role="button" id="head_0" data-toggle="collapse"> <span>{{ grandparent }}</span> </div> {% for parent in parent_list %} <div class="panel-collapse collapse in" role="tabpanel" aria-expanded="true"> <div class="panel-body"> <div class="panel panel-default"> <div class="panel-heading collapsed" role="button" data-toggle="collapse" aria-expanded="true"> <span class="panel-title">{{ parent }}</span> </div> <div class="panel-collapse collapse in" role="tabpanel" aria-labelledby="head_0"> <div class="panel-body"> {% … -
django_tables2 pagination and sorting don't work
I'm using django_talbes2 and the table renders correctly (in a sense that it displays all the information it should), but when I click on a column header to sort it or on a page number to go to the next page it "breaks" -- it returns to the home page and I'm not on the view which renders the table anymore. Actually, the problem is VERY SIMILAR to the one described here But the accepted solution wouldn't work in my case because I'm not using any <base> tags, which were causing the problem there. This is my table: class FactTable(tables.Table): class Meta: model = Fact template_name = 'django_tables2/bootstrap.html' exclude = ('id',) This is my view: def results(request, fields): table = FactTable(Fact.objects.filter(category__category=fields['category'], fact_name=fields['fact'], time_year__year__range=(startyear, endyear))) RequestConfig(request).configure(table) return render(request, 'main/results.html', {'table': table}) My urls: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^results/', views.results, name='results'), ] And the template {% load render_table from django_tables2 %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <title>Results</title> </head> <body> {% render_table table %} </body> </html> Many thanks in advance for any help! -
How to login in Django with Postman POST request
I'm using the default Django login system (only changed the template of the login page) and i'm trying to login via POST request with POSTMAN. I'm giving X-CSRFToken as header and as raw body the username and the password. I'm getting status code 200 and the same login page as a result. Result should redirect me to LOGIN_REDIRECT_URL setted in settings.py. -
Can PASSWORD_RESET_TIMEOUT_DAYS in Django be set to .5 days or hours?
I'm using Django's built-in Reset Password Views. As the title says, I wonder if I can set the PASSWORD_RESET_TIMEOUT_DAYS to half days (for example 1.5)? If not, I guess I could extend and customize the Django auth view that makes use of this variable, but I have not been able to trace which one that would be? -
Django/JS: ChoiceField for >1000 items
I'm creating a sample project in Django. User has to choose an item from an existing list, this list has >10000 items. To start with, Prefilled list like this: https://leaverou.github.io/awesomplete/ . Dinamically filled list (after keyrelease event), via ajax query after keyrelease event, without csrf_form. One field to search for the item, and another field to actually hold the pk. What way is better? Any suggestions? Any framework to do this? -
How to use Django imports in a django app without starting the app
Let's say my main app structure is like App - API - - __init__.py - abc.py Custom- - __init__.py - s1.py - s2.py Normally when running django I can do from API.abc import function. However I want to run s1 file separately. So how can I make existing imports work. -
Frameworks, backend and front end languages
I’m building a web application from scratch and i’m Trying to figure out which frameworks, backend and front end languages fits my needs and what’re the disadvantages and advantages of using this SDK. I’ve been doing my own research but the resources I found are more aimed at people who have less coding experience. Is there a place where I can find this information? I’m not asking for your opinion on which SDK I should use. I want to know, universally, which features from a framework or language could fit my needs. -
Django 1.8 migrations output
Is there a way to recreate the same output of the migration as when first created. For example: Output: Migrations for 'blog': 0001_initial.py - Create model Category - Create model Post So after migrate can we interrogate the migration file to re-produce this useful output? -
Why am i gettting 'bool' object is not callable? [duplicate]
This question already has an answer here: TypeError: 'bool' object is not callable g.user.is_authenticated() [duplicate] 2 answers My traceback refers me to process_view import re from django.conf import settings from django.shortcuts import redirect class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') if not request.user.is_authenticated(): if True: return redirect(settings.LOGIN_URL) tried to have a browse but couldn't find anything. TIA for the help -
signup form isn't working while login is working fine on django
I cant do sigup while Login is working fine from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput) class Meta: model=User fields=['first_name', 'last_name', 'email', 'username', 'password'] label={ 'password':'Password' } def clean_email(self): if self.cleaned_data['email'].endswith('@gmail.com') return self.cleaned_data['email'] else: raise ValidationError("error") def save(self): password=self.cleaned_data.pop('password') u=super().save() u.set_password(password) u.save() return u Link to project- https://github.com/tsuryaa/my_project/ -
page opening even if not logged in, Django
I have made a small project. User first logs in then he is redirected to the home page. But if a user has not logged in then also that homepage is opening if we paste the url of that home page. I have tried many things given on net but it's not working. This is my urls.py from django.conf.urls import url from django.contrib import admin from blog import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', views.login, name='login'), url(r'^register/$', views.register, name='register'), url(r'^home/$', views.home, name='home'), url(r'^javaq/$', views.javaq, name='javaq'), url(r'^javar/$', views.javar, name='javar'), url(r'^csq/$', views.csq, name='csq'), url(r'^csr/$', views.csr, name='csr'), url(r'^cq/$', views.cq, name='cq'), url(r'^cr/$', views.cr, name='cr'), url(r'^cppq/$', views.cppq, name='cppq'), url(r'^cppr/$', views.cppr, name='cppr'), url(r'^pythonq/$', views.pythonq, name='pythonq'), url(r'^pythonr/$', views.pythonr, name='pythonr'), url(r'^mini/$', views.mini, name='mini'), ] This is my view.py from django.shortcuts import render from .models import logininfo,CSTEST,CTEST,CPPTEST,JAVATEST,PYTHONTEST,result from django.http import HttpResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.views.decorators.cache import cache_control import datetime def login(request): if request.method=="POST": user_name=request.POST.get("username") sid=request.POST.get("sid") password=request.POST.get("password") article = logininfo() article.user_name = user_name article.sid = sid article.password = password article.save() return render(request,'login.html') def home(request): if request.method=="POST": sid=request.POST.get("sid") password=request.POST.get("password") request.session['sd'] = sid user_obj=logininfo.objects.filter(sid=sid,password=password) if user_obj.count()==0: return HttpResponse("Sorry wrong password try again") return render(request,'home.html') def register(request): return render(request,'register.html') def javaq(request): context = { 'query_results' : … -
What is the best way to get different output for different request methods in django REST API?
So I have a model having, say, 'field1' and 'field2' fields. And I need to have next results depending on the request method was used: http POST http://127.0.0.1:8000/app 'someinput' > {'field1': 'content1'} http GET http://127.0.0.1:8000/app/1 > {'field1' : 'content1', 'field2': 'content2'} I guess it has something to do with serializer's to_representation() method? but I can't figure out how can I check if the method that triggered to_representation() was 'POST' or 'GET'. -
doubts regrading Django PayPal app integration
I want to use "PayPal Pro" in my "Django" powered site. When i went through pip install django-paypal documentation i found that i have to use db for it as i have to mention it in INSTALLED_APPS and migrate it. INSTALLED_APPS = [ # .. 'paypal.standard', 'paypal.pro', ] But i am instructed not to use database at all. So how can i integrate PayPal in website without using db!Is there any detailed tutorial regarding this? -
How to change http to https using LetsEncrypt with 'docker: nginx + uwgsi + django + solr + db + ...'?
Currently I use official nginx docker image + my own 'django with uwsgi' build and everything works ok. I want to add SSL to the project using jwilder/nginx-proxy + jrcs/letsencrypt-nginx-proxy-companion. The structure of my project is the next: myproject/ | -- data/ | -- media/ | -- static/ | -- sources/ | -- dockerfiles/ | -- nginx/ | -- nginx.conf | -- uwsgi_params | -- solr/ | -- default/ (configs) | -- Dockerfile | -- web/ | -- Dockerfile | -- requirements.txt | -- myproject/ | -- app_1/ | -- app_2/ | -- settings/ | -- myproject_uwsgi.ini | -- docker-compose.yml The relative configs are below: # myproject/sources/docker-compose.yml version: '2' services: nginx: image: nginx:latest container_name: myproject_nginx-container ports: - "80:80" depends_on: - web volumes: - ./dockerfiles/nginx:/etc/nginx/conf.d - ../static:/static - ../media:/media web: build: ./dockerfiles/web/ container_name: myproject_django-container command: bash -c 'uwsgi --ini ./settings/myproject_uwsgi.ini' volumes: - ./web:/web - ../static:/static - ../media:/media solr-docker: build: ./dockerfiles/solr/ container_name: myproject_solr-container entrypoint: - docker-entrypoint.sh - solr-precreate - default ports: - "8983:8983" volumes: - ./dockerfiles/solr/default:/opt/solr/server/solr/mycores/default # configs - ../data/solr/default/data:/opt/solr/server/solr/mycores/default/data # indexes # other-services... next: # myproject/sources/myproject/settings/myproject_uwsgi.ini [uwsgi] master = True lazy-apps = True # Number of worker processes for handling requests %k = cpu count processes = %(%k * 2) # … -
return single response with validation errors including unique username constraint
I'd like to return a single response to a request containing invalid data. If i duplicate a username (post a username that's already in the base [it's a pk]) then I get the response: { "username": [ "A user with that username already exists." ] } That's great, but if i then select a unique username, and there are other errors in the request, there will be the following response: { "gdpr_value_error": [ "GDPR must be accepted" ], "role_value_error": [ "Role must correspond to an existing role" ], "email": [ "A user with that email already exists." ] } I want this: { "gdpr_value_error": [ "GDPR must be accepted" ], "role_value_error": [ "Role must correspond to an existing role" ], "email": [ "A user with that email already exists." ], "username": [ "A user with that username already exists." ] } My serializer is: class SeaUserCreateSerializer(UserCreateSerializer): class Meta: model = User fields = ('id', 'username', 'email', 'first_name', 'last_name', 'role', 'gdpr', 'password',) def validate(self, attrs): errors_to_return = {} if attrs['gdpr'] != True: errors_to_return["gdpr_value_error"] = "GDPR must be accepted" CAPTAIN = 'cpt' CREW = 'crw' OTHER = 'oth' ROLE_CHOICES = { CAPTAIN: _('Captain'), CREW: _('Crew'), OTHER: _('Other'), } if attrs['role'] not in … -
How to add a page view count for django detail view?
I am performing a Blog application using django.. I want to track the count of the page view whenever a user see a particular blog whether it is a registered user or non-registered users... And also want to display the most viewed blogs according to the view count.. Can anyone help me out in this.. Thank you -
Template tag interpreting a Decimal as a String causing error in django test
I've got a django application which I created a template_tag for showing of currency in my app. The template tag looks like this: @register.filter def currency(dollars): dollars = round(float(dollars), 2) return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:]) When I do runserver it all shows up fine with the dummy data I have - it's formatted appropriately and looks like this:$6,825,435.54 - but when I run my tests, it fails with the error: dollars = '' @register.filter def currency(dollars): > dollars = round(float(dollars), 2) E ValueError: could not convert string to float: myapp/templatetags/myapp_tags.py:32: ValueError I have a cost model that looks like this: class WorkerCost(DiffModel): end_year = models.IntegerField(db_column='endYear') unique_id = models.CharField(db_column='uniqueID', primary_key=True, max_length=30) loc_id = models.IntegerField(db_column='locID') worker_cost = models.DecimalField(max_digits=38, decimal_places=2, db_column='workerCost') class Meta(object): managed = getattr(settings, 'UNDER_TEST', False) db_table = '[test_data].[myapp_workerCost]' In my view I'm getting the cost by the location's ID and putting it in a dictionary which contains information about the location: for cost in location_costs: if cost.loc_id == l.id: location['worker_cost'] = cost.worker_cost print(location) location_list.append(location) When that print statement runs with my test data it returns: {'location_id': 9, 'location_name': <bound method Location.short_name of <Location: Building Location-8>>, 'current_year_count': 963, 'current_year_fet': 0, 'current_year_class_average': None, 'worker_cost': Decimal('1893252.32')} {'location_id': 10, 'location_name': <bound method … -
Django login_required decorator with view based behavior
I have a url structure in in Django like this: urlpatterns = [ # ... path('me/', profile_view, name='my_profile'), path('<uuid:account_id>/', profile_view, name='user_profile') ] and my profile_view is like this: @login_required def profile_view(request, account_id=None): # ... I want to use login required decorator to only require login if account_id = None? So, if someone goes to /accounts/me URL, the system must require authenticated user. Otherwise, the page should be accessible. -
the "post" method in djago
I created three files: 2-view.py : class AddTeamView(View): def get (self, request): form = TeamForm() context = {'form': form} return render(request, 'add_team.html', context) 1-forms.py: class TeamForm(forms.Form): name = forms.CharField( max_length='100') details = forms.CharField(max_length='250') 3-add_team.html: -here there is another file called "base.html" {% extends 'base.html' %} {% block title %} add team {% endblock %} {% block content %} <form action="/add_team/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> {% endblock %} and i went to cmd and entered the server "python manage.py runserver" it appeared on the browser: "This page isn’t working If the problem continues, contact the site owner. HTTP ERROR 405" -
Login Required Decorator and Django Session
I am logging in a user by session in django, i use file to save session. When a user logs in it creates a session and when it logs out it deletes the session, i want to use stop user accessing urls which will be available only after login.But when i use login required it doesnt recognize session logged in user and redirects me to the home page when because i have given login_url = 'home' in login_required decorator while defining a function. So how can i make my decorator to recognize logged in session?