Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to construct this Django ORM queryset query?
I'm trying to determine how to construct a query. I have two models from an external database that I"m trying to import into a different schema. The source data has two tables: - Group (basically, a musical band.) - Membership (a list of those in the band through time) In the Memberships, I have fields representing the person and band, with create dates and update dates, as well as other relevant data. Here's the problem: the Membership rows don't have any field that represents which is the canonical record, and they mix and match persons and dates and other data. What I'm doing currently is taking all the Memberships for a given band, running distinct on them for the combination of band and person and using those results to query the Memberships again for the latest instance of each particular combination. While this works, as you might imagine is is unspeakably slow and I know there must be a better way. So I'm looking for how to use some of the advanced django query expressions (Window? Over, F-expressions?) to get this done as much as possible on the database. Here is the code that is getting me the records I … -
creating models inctances from button click
I am new to django and I build an online restaurant website as a task . I have a problem in getting orders into data base . here are the codes models.py from django.db import models from django.contrib import admin from django.contrib.auth.models import User from django.db.models.signals import post_save class UserProfile(models.Model): user = models.OneToOneField(User) phone = models.IntegerField() address = models.CharField(max_length=500) def create_profile(sender , **kwargs): if kwargs['created'] : user_profile = UserProfile.objects.create(user=kwargs['instance']) post_save.connect(create_profile , sender=User) class Category(models.Model): category_title = models.CharField(max_length=100 , unique=True) def __str__(self): return self.category_title class Order (models.Model): time = models.DateTimeField(auto_now_add=True) total = models.IntegerField() created_by = models.ForeignKey(User, related_name='orders') class Item (models.Model): name = models.CharField(max_length=100 ,unique=True) details = models.CharField(max_length=1000) price = models.IntegerField() item_logo = models.FileField() category = models.ForeignKey(Category, related_name="items" ,on_delete= models.CASCADE) order = models.ForeignKey(Order, related_name="orderItems", null=True, blank=True) def __str__(self): return self.name class ItemInline(admin.TabularInline): model = Item class CategoryAdmin(admin.ModelAdmin): inlines = [ ItemInline, ] views.py from django.http import Http404 from .models import Category, Item , Order from django.shortcuts import render, redirect from django.core.urlresolvers import reverse_lazy from django.contrib.auth import authenticate , login from django.views import generic from django.views.generic import View from .forms import UsrForm class IndexView(generic.ListView) : template_name = 'res/base.html' context_object_name = 'all_categories' def get_queryset(self): return Category.objects.all() def detail(request, category_name): try: category = Category.objects.get(category_title = … -
Override Django Handler404 with JSON type handler
I'm using Django 2.0.1 and I'm trying to override Django 404 page with another response. Instead of returning a regular template, I want to return a JSON response. here is my project/urls.py from django.conf.urls import include from django.contrib import admin from django.urls import path from django.conf.urls import handler404 from django.http import JsonResponse urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('accounts.urls')) ] def response(status=200, message='Not Found', data=None): data = {'status': 404, 'message': message, 'data': data} return JsonResponse(data=data, status=status) handler404 = response(status=404) but by it 404 returns it still return me the basic Django 404 page even if I change Debug option to True in settings.py file -
AngularJs: ng-click is not calling the method.
I am just learning AngularJS and I started working with it in Django. I created an array that I would display as a list and provide an Input field for the user to add more items to it. {% verbatim %} <div ng-controller="ScrumBoardController"> <div ng-repeat="list in data"> <h3>{{ list.name }}</h3> <ul> <li ng-repeat="card in list.cards">{{ card.title }}</li> </ul> <input type="text" ng-model="new_title"></input>{{ new_title }} <button ng-click="addition(list, new_title">ADD</button> </div> </div> {% endverbatim %} The above HTML code is going through all the data and displaying it properly, but whenever I try to call the ng-click to add a user argument to the card it's not working. The only thing I could think of was changing the name of the function and that didn't work either. (function () { 'use strict'; angular.module('scrumboard.demo', []) .controller('ScrumBoardController', ['$scope', ScrumBoardController]); function ScrumBoardController($scope){ $scope.addition = function (list, title){ var card = { title: title }; list.cards.push(card); }; $scope.data = [ { name: 'django demo', cards: [ { title: 'Create Models' }, { title: 'Create View' }, { title: 'Migrate Database' } ] }, { name: 'Angular Demo', cards: [ { title: 'Write Html' }, { title: 'Cry' }, { title: 'repeat' } ] } ]; } })(); -
Django: Grouping of records
Apologies if the title of question is not correct. Please someone correct it if the detail here gives you idea what I am asking for. I am not English speaker so may make a mistake in wording the title. I have this model: class ClinicDoctor(models.Model): doctor = models.ForeignKey('User', related_name='doctorsF') # single quotes (') because User table is defined down the code. clinic = models.ForeignKey(Clinic, related_name='clinicsF') I am trying to fetch all doctor records and their clinics. Some doctors may have multiple clinics. In my template I loop over the below query set: doctorsQuerySet = ClinicDoctor.objects.filter(doctor__groups__name='Doctor') This returns records BUT I wanted to show records in a table like this: DoctorHeader-------------ClinicsHeader Doctor 1 ----------------Clinic 1, Clinic 2. Doctor 2 ---------------- Clinic 3 Doctor 3 ---------------- Clinic 4, Clinic 5, clinic 7 The idea is that I want to show every Doctor only once and then put all his related clinics in that single row of that Doctor. Right now I am looping over the query set in the template but that is going to show same doctor record multiple times(as many as associated clinics). Is there any way in which I can modify that Query above to achieve the grouping or … -
How to handle favicon request in Django rest framework?
I am coming from nodejs and i have a nextjs frontend that communicate with a django rest Api. However, each time i make a request to my django api, the app do an additional request : GET /favicon.ico I've tried to add favicon route in urls.py favicon_view = RedirectView.as_view(url='/static/images/favicon.ico', permanent=True) url(r'^favicon$',favicon_view) but it doesn't works Any suggestion ? -
Custom ManyToManyfield ordering
Is there a way to use user-defined ordering on a ManyToManyField without killing performance / cluttering the database? EX: I have a model: class MyModel: myfield = models.ManyToManyField(other_model, ...) And I have a form which allows adding multiple other_model objects and I want to allow the user to sort / order these (say using jquery-ui sortable or another method).. However, this isn't reflected on the front-end since this ordering state isn't preserved - just the objects being added to the relation. All I can think of is to just create a new model instance every single time with the order attached (as a custom many to many field) and adding to the M2M but that's killing the DB / structure instead of having single field instances / preventing duplicates. -
pip install requirements.txt not working properly
I'm trying to install all my Python/Django packages on my Digital Ocean Django server. I have my requirements.txt in the root directory, so I perform pip install -r requirements.txt - however it doesn't work. Here's my requirements.txt: amqp==2.2.2 billiard==3.5.0.3 celery==4.1.0 coverage==4.4.2 decorator==4.0.11 defusedxml==0.4.1 Django==1.11.8 django-allauth==0.29.0 django-apptemplates==1.2 django-celery-beat==1.0.1 django-common-helpers==0.9.1 django-cron==0.5.0 django-el-pagination==3.1.0 django-fs-trumbowyg==0.1.4 django-markdown-deux==1.0.5 django-trumbowyg==1.0.1 django-widget-tweaks==1.4.1 get==0.0.0 imageio==2.1.2 kombu==4.1.0 markdown2==2.3.1 moviepy==0.2.3.2 numpy==1.13.3 oauthlib==2.0.1 olefile==0.44 Pillow==4.0.0 post==0.0.0 public==0.0.0 python-magic==0.4.12 python3-openid==3.0.10 pytz==2017.3 query-string==0.0.0 request==0.0.0 requests==2.11.1 requests-oauthlib==0.7.0 schedule==0.4.3 setupfiles==0.0.0 tqdm==4.11.2 vine==1.1.4 here's the log: Collecting amqp==2.2.2 (from -r requirements.txt (line 1)) Using cached amqp-2.2.2-py2.py3-none-any.whl Collecting billiard==3.5.0.3 (from -r requirements.txt (line 2)) Using cached billiard-3.5.0.3-py3-none-any.whl Collecting celery==4.1.0 (from -r requirements.txt (line 3)) Using cached celery-4.1.0-py2.py3-none-any.whl Collecting coverage==4.4.2 (from -r requirements.txt (line 4)) Using cached coverage-4.4.2-cp35-cp35m-manylinux1_x86_64.whl Collecting decorator==4.0.11 (from -r requirements.txt (line 5)) Using cached decorator-4.0.11-py2.py3-none-any.whl Collecting defusedxml==0.4.1 (from -r requirements.txt (line 6)) Using cached defusedxml-0.4.1.tar.gz Requirement already satisfied: Django==1.11.8 in ./env/lib/python3.5/site-packages (from -r requirements.txt (line 7)) Collecting django-allauth==0.29.0 (from -r requirements.txt (line 8)) Using cached django-allauth-0.29.0.tar.gz Collecting django-apptemplates==1.2 (from -r requirements.txt (line 9)) Using cached django-apptemplates-1.2.tar.gz Collecting django-celery-beat==1.0.1 (from -r requirements.txt (line 10)) Using cached django_celery_beat-1.0.1-py2.py3-none-any.whl Collecting django-common-helpers==0.9.1 (from -r requirements.txt (line 11)) Using cached django-common-helpers-0.9.1.tar.gz Collecting django-cron==0.5.0 (from -r requirements.txt (line 12)) Using cached django-cron-0.5.0.tar.gz … -
Django Managing forms for related models using parent form field vlaue
I have three models, Problem, Choice, and Solution. Choice and Solution models are related to Problem by Foreign Key. That is, a problem can have many choices and solutions. Number of choices required for a problem is controlled a Problem.type field. I want to make a form in which lets a user edit Problem, Choice(s) and Solution in the same form. I am able to display Problem and Solution forms easily and handling the Choice form/formsets using Ajax. My Questions: Is there a more Pythonic (Djangonic) way of doing these kind of stuffs? Suppose I refresh my browser in the midway, knowingly or accidentally, Firefox shows all the fields as they were (including data filled in, and problem type selected) before refreshing, but the part of the form which was rendered via Ajax is lost. Is this a expected behaviour? In Chrome, entire form is reset upon refreshing. Is this behaviour expected? How I can prevent loss of half filled form data? One of the solutions that I have thought of is filling up the form step by step- First the problem details, followed by choices and Solution at last. This approach makes editing previous steps difficult. A user might … -
Ordering Django ModelCluster many to many field
Is there a way to re-order a (many-to-many) field using a ParentalManyToManyField from modelcluster.fields when editing an object instance? As I understand it the cluster defers the m2m save and it caches this. My object is a wagtail page and I'm doing the following: form.save(commit=False) # Clear the cache of the m2m fields.... Using self.object.(field).clear() form.save_m2m() # Save a wagtail revision for moderation through the admin interface After approving the change the fields are still int he same order? Is this not possible? -
Django when processing a list of model formsets on invalid form only return last of the list
I'm trying to process a list of InlineFormsets on a Django TemplateView. Basically is a list of projects, retrieved by a query of the parent object that binds them together. For each project retrieved I'm gonna show a form for asking some values of increments and start dates and so on. I'm restricting to just one FormSet per project for now. The are two problems: on POST it appears that the forms are complaining about the parent instance (proyecto): (Hidden field proyecto) The inline foreign key did not match the parent instance primary key. Then when the form_invalid function is called, the template just renders one of the forms with its data(apparently the last of the list). I'm guessing the first problem has to do with the instance object of the formset, but so far I haven't being able to find a solution to retrieve the formset list and assign again the instance object on POST. I'm sure the problem its very trivial, but I can't see it through. I'm relatively new to Django and Python (currently using 1.11 and 3.6.3 respectively). I appreciate any help or hint you could give me. This is the related code: models class Macroproyecto(models.Model): … -
How to properly increment a counter in my postgreSQL database?
Let's say i want to implement a "Like/Unlike" system in my app. I need to count each like for sorting purposes later. Can i simply insert the current value + 1 ? I think it's too simple. What if two user click on the same time ? How to prevent my counter to be disturbed ? I read i need to implement transactions by a simple decorator @transaction.atomic but i am wonder if this can handle my concern. Transactions are designed to execute a "bloc" of operations triggered by one user, whereas in my case i need be able to handle multiple request at the same time and safely update the counter. Any advise ? -
Pylibmc can't find libmemcache.so.10
I recently upgraded a server from Ubuntu 14 to 16, and now my Django app using pylibmc for managing a memcache backend is failing with the error: ImportError: libmemcached.so.10: cannot open shared object file: No such file or directory However, the file /usr/lib/x86_64-linux-gnu/libmemcached.so exists on the server. Why is Pylibmc looking for the *.10 specifc extension and/or unable to find find the more general library? I'm using the most recent version of Pylibmc and Django. -
django-leaflet: How can you add layer controls to the controlLayer for the Tiles created in settings.py?
I have map tile layers configured in my settings.py and they properly appear and work. When my site is loaded, I am also getting data to add two layers to the map and I also add them to a controlLayer. controlLayers.addOverlay(restaurantMarkers, 'Restaurants'); controlLayers.addOverlay(parksMarkers, 'Parks'); and then I add the control layer to the map var controlLayers = L.control.layers().addTo(map); This all works, but they are in their own control layer separate from the tiles control layer so now I have two control layers. How do I add additional controls to the controlLayer created for the Tiles? Thanks so much! -
Django max similarity (TrigramSimilarity) from ManyToManyField
I have to implement a search function which is fault tolerant. Currently I have the following situation: Models: class Tag(models.Model): name = models.CharField(max_length=255) class Illustration(models.Model): name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) Query: queryset.annotate(similarity=TrigramSimilarity('name', fulltext) + TrigramSimilarity('tags__name', fulltext)) Example data: 1;"Dog",["Animal", "Brown"] 2;"Cat",["Animals"] When I run the query with "Animal", the similarity for "Dog" should be higher than for "Cat", as it is a perfect match. Unfortunately both tags are considered together somehow. Currently it looks like it's doing something like: TrigramSimilarity("Animal Brown") => xyz But I would like to adjust it like this: Max([TrigramSimilarity("Animal"), TrigramSimilarity("Brown")]) => xyz Can somebody give a hint how to achieve what I described? -
In Django, how can I generate csrf token when not using templates
I'm writing pages in my own code, not using Django templates. Because I'm overloaded on new things to learn and trying to get this done. Now I had some easy cases with templates, and {% csrf_token %} worked just fine. But they used render() and a template. I have a bunch of custom HTML I can't immediately figure out how to put in a template, so I can't use render(). Instead, I return HttpResponse() applied to my page, and that does not deal with {% csrf_token %}. How do I get that element into the form part of my page? I'm willing to generate the form from a template, but not the rest of the page. -
Django ModelForm with model having ForeignKey field does not display selectBox correctly
This is probably easy to solve. I created a form which use forms.ModelForm. My model has ForeignKey field. Form creates a select field for foreignKey, but but does not display value correctly. models.py from django.db import models # Create your models here. class Gender(models.Model): name = models.CharField(max_length=8, null=True) class Meta: db_table='gender' class UserExample(models.Model): name = models.CharField(max_length=16,null=True) age = models.IntegerField(blank=True, null=True) gender = models.ForeignKey('Gender', on_delete=models.SET_NULL, null=True) class Meta: db_table='userExample' def __str__(self): return "" forms.py from django import forms from .models import UserExample, Gender class UserForm(forms.ModelForm): class Meta: model = UserExample fields = ('name', 'age', 'gender') views.py from django.shortcuts import render from .forms import UserForm # Create your views here. def index(request): form = UserForm return render( request, 'index.html', {'form': form} ) urls.py from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), ] index.html <html> <head> <title>test </title> </head> <body> <form action="formreturn/" method="post"> {{ form.as_p }} <input type="submit" value="Submit" /> </form> </body> </html> And after I launch my app. In select box I get only selection for gender objects but not for gender names. Optional I used to add values using sqllite3 like this: sqlite> insert into gender values(1,"Male"); sqlite> insert into gender values(2,"Female"); -
Django: User doesn't get assigned to an instance of a model
I am new to django and I have the following problem. When I login and create a company using the createCompany.html, the company gets created in the database but its 'user' attribute stays empty. The user attribute is supposed to be the user who is logged in and creating the company. What do you think is wrong with my code? models.py from django.db import models from django.contrib.auth.models import User class Company(models.Model): name = models.CharField(primary_key = True, max_length = 100) city = models.CharField(max_length = 30, null = True) user = models.OneToOneField(User, on_delete=models.SET_NULL, null = True) yontemler =(('3CNC', '3 eksen CNC'),('5CNC', '5 eksen CNC'),) imalatyontem = models.CharField(max_length=30, choices=yontemler, null=True, verbose_name = 'İmalat Yöntemleri') industries =(('Imalat', 'İmalat'),('Kimya', 'Kimya'),('Hammadde', 'Hammadde'),) industry = models.CharField(max_length=20, choices=industries, null=True, help_text='Sektörünüzü Seçin') @classmethod def create(cls, name, city, user, imalatyontem, industry): company = cls(name=name, city=city, user=user, imalatyontem=imalatyontem, industry=industry) return company def get_absolute_url(self): return models.reverse('company-detail', args=[str(self.id)]) def __str__(self): return self.name views.py from .forms import CompanyCreationForm def createCompany(request): if request.method == 'POST': form = CompanyCreationForm(request.POST) if form.is_valid(): form.save() name = form.cleaned_data.get('name') city = form.cleaned_data.get('city') user = request.user imalatyontem = form.cleaned_data.get('imalatyontem') industry = form.cleaned_data.get('industry') Company.create(name, city, user, imalatyontem, industry) return redirect('index') else: form = CompanyCreationForm() return render(request, 'createCompany.html', {'form': form}) forms.py from django … -
Python2 versus Python3 post request
I've looked at seemingly all the other python3 urllib posts and nothing seems to work. I have a Django (v1.11.1, using Python2) application that should be accepting POST requests (e.g. sending it some JSON data); it works in python2 using urllib/urllib2, but with python3 (and urllib) I cannot get it to send a request that Django understands. Looking for some help in getting this sorted. My Django view function: def update_db(request):print dir(request) print request.POST return HttpResponse('Thanks for visiting.') Here's a working request in Python2: import urllib import urllib2 import json d={'foo': 1, 'bar': 2} data = urllib.urlencode(d) req = urllib2.Request(url, {'Content-Type': 'application/json'}) f = urllib2.urlopen(req, data=data) # works! Looking at the logs in my Django app I see that it understood the request: <QueryDict: {u'foo': [u'1'], u'bar': [u'2']}> Now, for Python3 here's my request method: import urllib.parse import urllib.request import json d={'foo': 1, 'bar': 2} data = json.dumps(d).encode('utf8') req = urllib.request.Request(url, data=data, headers={'Content-type': 'application/json'}) f = urllib.request.urlopen(req) And my Django log shows: <QueryDict: {}> Django also reports that request.method was indeed POST, but for whatever reason it's not understanding the actual JSON I'm sending as part of the post request. I also tried the requests library, as suggested in other … -
Django Authenticate returns none if registered via a front-end registration form
I've searched everywhere for a solution to this problem. Yet, no resolution as of yet. The problem After successfully creating a user via a front-end registration form, upon logging in using a front-end login form, the "Authenticate" function returns "None". The interesting part, if I am to create a new user via the admin panel (using similar code), I am then able to login via the front-end login form. The custom user model I've created does use an email address as the Username. If a user registers using the front-end register form, the user details are saved to the database, where the password is properly hashed. Here is the code: From Forms.py from django import forms from django.contrib.auth.forms import ReadOnlyPasswordHashField from .models import User as CustomUser from django.conf import settings class RegisterForm(forms.ModelForm): password1 = forms.CharField(label='', widget=forms.PasswordInput) password2 = forms.CharField(label='', widget=forms.PasswordInput) class Meta: model = CustomUser fields = ('email', 'full_name') def __init__(self, *args, **kwargs): super(RegisterForm, self).__init__(*args, **kwargs) self.fields['email'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Email (you@company.com)'}) self.fields['full_name'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Full Name'}) self.fields['email'].label = '' self.fields['full_name'].label = '' self.fields['password1'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Your Password'}) self.fields['password2'].widget.attrs.update( {'class': 'form-control loginInput', 'placeholder': 'Confirm Password'}) def clean_email(self): email = self.cleaned_data.get('email') qs = CustomUser.objects.filter(email=email) … -
Django: How to monitor time specified in Model class and do some actions when current time is equal to the one specified in Model?
I have Model "Task" and DateTimeField "deadline" in it. How can I monitor current time and execute some actions (like sending notifications to user, that own that task) when there is, for example, 1 hour left to deadline, or deadline has already come? I'm using Django 2.0. I've already read about Celery, but I'm not sure whether it is an appropriate solution for such task. I'll be glad to hear your opinions. -
Implementing Django taggit labels widget outside of admin
I’m using the django-taggit-labels module, which provides a clickable widget for django-taggit. It works great in admin interface of my project, so I wanted to implement it in on the user side as well. Unfortunately, as the authors clearly stated: This is a widget for use in the Django admin interface... I tried setting the same forms I use in admin to views.py, but the tags are unresponsive (they cannot be selected). In addition, I fail the test_selected_tags, which I've copied from django-taggit-labels’ test widget. The forms and models are pretty straightforward and they work as intended in admin. models.py class MyModel(models.Model): name = models.CharField() description = models.TextField() tags = TaggableManager() def __str__(self): return self.name forms.py class MyModelForm(forms.ModelForm): tags = TagField(required=True, widget=LabelWidget,) class Meta: model = MyModel fields = '__all__' The question is, what should I do to deploy it in non-admin interface? Is it the same issue as with ManyToManyField and with list_display in ModelAdmin? If so, I would be grateful for some guidance as to how to limit queries. In my admin.py I do something simple, like: class MyModelAdmin(admin.ModelAdmin): def tags(obj): return ', '.join(list(obj.tags.names())) fields = ('name', 'description', 'tags') form = MyModelForm list_display = ('name', 'description', tags,) admin.site.register(MyModel, … -
ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package
I'm using django 2.0.2 to develop a simple web app. I'm not sure what's wrong with my code. I'm getting the error ModuleNotFoundError: No module named 'myapp.views.hello'; 'myapp.views' is not a package Here is my code for views.py from django.shortcuts import render def hello(request): return render(request,'myapp/templates/hello.html',{}) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include urlpatterns = [ path('admin/', admin.site.urls), path('hello/', include('myapp.views.hello'), name='hello'), ] Throwing the same error even when I did from myapp.views import * What is wrong with my code? -
How to calculate and store scores in django betting game?
I'm working on my first django project which is a sport betting game. My models are: class Game(models.Model): home_team = models.CharField(max_length=200) away_team = models.CharField(max_length=200) home_goals = models.IntegerField(default=None) away_goals = models.IntegerField(default=None) class Bet(models.Model): gameid = models.ForeignKey(Game, on_delete=models.CASCADE) userid = models.ForeignKey(User, on_delete=models.CASCADE) home_goals = models.IntegerField() away_goals = models.IntegerField() score = models.IntegerField(default=None, null=True) logic for calculating scores is: WHEN polls_bet.home_goals = polls_game.home_goals AND polls_bet.away_goals = polls_game.away_goals THEN 2 WHEN polls_game.home_goals > polls_game.away_goals AND polls_game.home_goals > polls_game.away_goals THEN 1 WHEN polls_bet.home_goals < polls_bet.away_goals AND polls_game.home_goals < polls_game.away_goals THEN 1 ELSE 0 I was able to solve it easily using database view that combines all data in one table but it seems that it does not play well with django migrations.. So I was thinking about sql trigger after update of game goals, but then I don't know how to pass conditions like user's id. 2nd idea is to create additional 'scores' table with: gameid, userid, betid, score But then again I don't know how to calculate scores. Please advice how this should be done properly, without using sql view. I appreciate all answers! -
Tagging a friend in Django
Trying to build a tagging system in django, where upon writing a friend's name in a post or a comment, a notification would be generated. Friendship and notification systems are already in place and working. Any ideas how to start.