Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filter Django queryset for a dict value
I have a queryset of Products with JSONField attributes containing dict class Product(models.Model): attributes = JSONField( pgettext_lazy('Product field', 'attributes'), encoder=DjangoJSONEncoder, default={}) I want to filter Products where attributes['12'] == '31' Following one works: qs.filter(attributes__contains={'12': '31'}) Following one does not: qs.filter(attributes__12='31') Unfortunately I cannot use first solution, as this dict may contain more keys. Is this something I can achieve with PostgreSQL or should I move it to ES? -
Django - An existing connection was forcibly closed by the remote host
I am creating a function to logout from my website.(my admin account is currently logged in) And an error An existing connection was forcibly closed by the remote host triggers when I tried to logout. Here is the code: def logout_view(request): logout(request) return render(request, 'index/index.html', {}) There are two other exceptions: 'NoneType' object is not subscriptable and 'NoneType' object has no attribute 'split' Tracebacks are too long, if it is really necessary to see them, i can paste them here. Thanks your any help! -
How to set up 2 sites on 1 VPS?
I have 1 site on my VPS server with such NGINX config. It's /etc/nginx/sites-available/default server { listen 80 default_server; listen [::]:80 default_server; root /var/www/Era; # Add index.php to the list if you are using PHP index index.html index.htm index.nginx-debian.html; server_name eraart.ru; location / { try_files $uri $uri/ =404; } error_page 404 /404.html; location = /404.html { root /var/www/Era; internal; } } I want to deploy the second site on with django. I created /etc/nginx/sites-available/blog with upstream app_server { server unix:/home/split/Blog-Boards/run/gunicorn.sock fail_timeout=0; } server { listen 81; server_name www.progxother.stream; # here can also be the IP address of the server keepalive_timeout 5; client_max_body_size 4G; access_log /home/split/Blog-Boards/logs/nginx-access.log; error_log /home/split/Blog-Boards/logs/nginx-error.log; location /static/ { alias /home/split/Blog-Boards/static_root/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } created symbolic link to the sites-enabled folder and refresh nginx. Trying to open an ip adress with 81 port and get nothing. -
Tilde (~) symbol on Django regex url (Cookiecutter Django)
After installing Cookiecutter Django i saw the tilde (~) symbol in regex and don't know the meaning for url purposes. It's related to a regular expression or only a way to declare paths? ./users/urls.py: urlpatterns = [ ... url( regex=r'^~redirect/$', ... url( regex=r'^~update/$', ... ] -
can I register the same app twice under two different names in Django?
I know that sounds a bit weird task, but if I have one app, called App1 in my project folder, can I add it twice under two different names (let say App1_1, and App1_2? I know that it is theoretically possible using AppConfig but when I try to do it the error `Application names aren't unique, duplicates: foo” is raised. -
Django project: track migrations
While developing a Django project tracking it with git and GitHub, how should I manage migrations? Sometimes when I deploy a release to production some migrations crash due to files that I delete after this migration. How can I avoid this? Thanks. -
Django group permissions like linux file system permissions
Basically I would like to have a permission system like Linux file system. I want to classify the permissions whether the user is in the same group as the owner (creator) of the object. Example scenario: User can change objects created by someone in the same group as them. Group Admins can change and delete any object created by users in their group. Is it possible to do this with default django permission system? If not, is there a package you could recommend? I hope I am not missing anything basic in django docs but I couldn't find a way to accomplish this. -
Copy model object to another model
I want to copy recipes from my Recipe model to my Shoplist model so that certain combinations of recipes can be summarized in a shoplist. The user should be able to choose recipes which get added to a shoplist which the user can use to go to the store. The next time the user comes to the site he should be able to make another shoplist with other recipes. I imagine that the user should be able to trigger a function. But I do not know what the function should look like. If I need to provide to more details please tell me! recipe/models.py class Recipe(models.Model): """ A model describing a cookbook recipe. """ # Selection menu for the category of the product CATEGORY_1 = 'Vegetarisch' CATEGORY_2 = 'Pasta' CATEGORY_3 = 'Oosters' CATEGORY_4 = 'Vlees' CATEGORY_5 = 'Vis' CATEGORY_6 = 'Dessert' CATEGORY_7 = 'Simpel' CATEGORY_8 = 'Sauzen' CATEGORY = ( (CATEGORY_1, u'Vegetarisch'), (CATEGORY_2, u'Pasta'), (CATEGORY_3, u'Oosters'), (CATEGORY_4, u'Vlees'), (CATEGORY_5, u'Vis'), (CATEGORY_6, u'Dessert'), (CATEGORY_7, u'Simpel'), (CATEGORY_8, u'Sauzen'), ) title = models.CharField(u'Titel', max_length=255) slug = models.SlugField(unique=True) image = StdImageField(upload_to=UploadToAutoSlug(populate_from='title'), variations={'thumbnail':{'width': 300, 'height': 300, 'crop': True}}, verbose_name=u'recipe image') ingredients = models.ManyToManyField(Ingredient, verbose_name=u'ingredients') neccesities = models.TextField(u'Benodigdheden') preparation = models.TextField(u'Bereiding') number_of_portions = models.PositiveIntegerField(u'Aantal personen') category … -
Signal Call to Auto populate a User Field if it exists in another Model
I simplified my previous post to provide clarity. I'm attempting to auto populate a field in my custom user model with a 1 or a 0 if the formattedusername exists in another model using the following signal, but it will not work: @isthisflag def is_this(self, is_this): if cfo.ntname is user.formattedusername: return 1 else: return 0 I have a custom User model like the following: class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=7, unique=True) formattedusername = models.CharField(max_length=11, unique=True, primary_key = True) is_this = models.BooleanField(default=False) USERNAME_FIELD = 'username' I then have another model we'll call cfo that has a list of formattedusernames the ntname field is a FK to formattedusernames. class cfo(models.Model): ntname = models.CharField(db_column='CFO_NTName',primary_key=True, serialize=False, max_length=11) class Meta: managed = False db_table = 'cfo' If ntname exists as the User who logs with their LDAP authentication I want to place a 1 in the User.is_this field. -
Django - __str__ method not working, says name is not defined
I have the following model defined. class Response(models.Model): question = models.ForeignKey(Question, on_delete = models.CASCADE) STATEMENT_CHOICES = ( (-1, "Strongly Disagree"), (-0.5, "Somewhat Disagree"), (0, "Uncertain"), (0.5, "Somewhat Agree"), (1, "Strongly Agree"), ) statement = models.DecimalField( max_digits=2, decimal_places=1, choices = STATEMENT_CHOICES ) def __str__(self): return self.statement when I run the django shell, I create a question q that says you like pizza and response r which is 1 for strongly agree. then when I run the __str__ method on r I get an error saying name 'statement' is not defined. Here is the exact console output... >>> q <Question: You like pizza.> >>> r = Response(question=q, statement=1) >>> r.question <Question: You like pizza.> >>> r.statement 1 >>> r Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/TN/Documents/Programming/Django/Practice/myve /lib/python3.5/site-packages/django/db/models/base.py", line 572, in __repr__ u = six.text_type(self) File "/Users/TN/Documents/Programming/Django/Practice/mysite/personalityQuiz/models.py", line 48, in __str__ return self.statement NameError: name 'statement' is not defined -
Django: passing variable from view.py to html with render
I am new to Django and I have the following problem With views.py I render a page called 'results_links.html' located in application templates directory which has an 'include' statement toward another page 'MAPE_history.csv.html' located in 'upload' directory (which is also defined in settings.py as template directory). I want to dynamically pass the file to be used in 'included' statement from views.py. For the test I use same file: MAPE_history.csv.html The problem I have is that I receive a 'template not existing'error from include statement. If I remove the statement of I replace the 'content' variable with the file name, I do not receive a problem. Here is the code: ### views.py from django.shortcuts import render from django.http import HttpResponse import os from formupload import Best_model_forecast_v11 # Create your views here. def home(request): return render(request, 'index.html', {'what':'Django File Upload'}) def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) MAPE_file = 'MAPE_'+str(request.FILES['file'])+'.html' return render(request,'result_links.html',{'content':MAPE_file}) elif request.method == 'GET': return render(request,'result_links.html',{'content':'MAPE_history.csv.html'}) response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'upload/MAPE_history.csv; filename="MAPE_history.csv"' return response return HttpResponse("Failed") def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') if not os.path.exists('forecast/'): os.mkdir('forecast/') with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) #print(Best_model_forecast_v11.main('upload/' + filename)) return Best_model_forecast_v11.main('upload/' + filename) ### result_links.html … -
Django model fields mapping: Modelform vs ModelSerializer
I have a model.The required property of the fields is not same for the Modelform and Modelserializer. Please see the below example class Test(models.Model): name = models.CharField(max_length=200,null=False) streetname = models.CharField(max_length=200) Checking the fields mapping with ModelForm class Testform(forms.ModelForm): class Meta: model=Test fields=['name','streetname'] Properties of the fields are: name -> required=true (may be because of null=false or its the default value) streetname -> required=true (since default value is true) Checking the fields mapping with ModelSerializer: class TestSerializer(ModelSerializer): class Meta: model = Test fields=['name','streetname'] the field properties are serialized as: name -> required=true (may be because of null=false) streetname -> required=false (although the default is True, its showing false) How to understand the Modelserialize's streetname required property. -
Django database model design - linking 3 models
My project is written in Django. I have one model for academic articles. class Article(models.Model): title = models.CharField(max_length=300) abstract = models.TextField(blank=True) ... I have another model for questions that articles may be responsive to: class Question(models.Model): question = models.CharField(max_length=300) article = models.ManyToManyField(Article) An article can respond to a question in one of three ways: 'yes', 'no', and 'insufficient evidence'. But the same article may respond differently depending on the question. So for example, article1 may respond 'yes' to question1, 'no' to question2 and 'insufficient evidence' to question3. I'm struggling with how to design these responses into my model. I could create a separate model for responses like below: class Response(models.Model): response = models.CharField(max_length=25) then populate that model with my three responses ('yes', 'no', 'insufficient evidence') and then add a field in my Article model for responses like so: response = models.ManyToManyField(Response) But then how would I link an article's response to a question? How do I tell the database that article1's response to question1 is 'yes', its response to question2 is 'no' and its response to question3 is 'insufficient evidence'? Thank you. -
Django's REST framwork Quickstart Error
I followed all the steps from the tutorial here. But when I try to run the server I get the following error further down. Since I am new to django i am unsure where to start to debug. The full console output can be found Here Unhandled exception in thread started by <function wrapper at 0x7f4e9dc9c7d0> Traceback (most recent call last): File "/home/user/Projects/djangoApi/tutorial/env/local/lib/python2.7/site-packages/django/utils/autoreload.py", line 228, in wrapper fn(*args, **kwargs) ..... ValueError: Empty module name -
Django date picker range Javascript post
i'm trying to user Date Picker Range from http://www.daterangepicker.com/ and i have this on my html: <script type="text/javascript"> $(function() { $('input[name="daterange"]').daterangepicker({ locale: { format: 'DD/MM/YYYY ' }, ranges: { 'Hoy': [moment(), moment()], 'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')], 'Ultimos 7 dias': [moment().subtract(6, 'days'), moment()], 'Ultimos 30 dias': [moment().subtract(29, 'days'), moment()], 'Este Mes': [moment().startOf('month'), moment().endOf('month')], 'Mes pasado': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')] } }); $(window).scroll(function() { if ($('input[name="daterange"]').length) { $('input[name="daterange"]').daterangepicker("close"); } }); }); </script> <form action="{% url 'subestados' %}" method="post"> <div class="col-md-3 mb-3"> <label>Rango: </label> <input type="text" name="daterange" class="form-control"/> </div> </form> my urls.py: url(r'^subestados/$',se.tabla, name='subestados'), url(r'^subestados/(?P<yearb>[0-9]{4})/(?P<monthb>[0-9]{2})/(?P<dayb>[0-9]{2})/(?P<yearf>[0-9]{4})/(?P<monthf>[0-9]{2})/(?P<dayf>[0-9]{2})/$',se.tabla, name='subestados'), I've seen other post about this, but i can't find a solution that works for me, i understand there is a ajax method to make the post but i don't know how to implement it: $.ajax({ url:'/', type : "POST", data: {start : 'start', end : 'end'}, success: function(response){}, complete: function(){}, error: function(xhr, textStatus, thrownError){} }); The javascript works i can see the calendar and all the options but can't find the way to do what i want. Any clues about this ? -
SyntaxError at django with Apache and wsgi
This is error_log file of httpd when running the django app File "/var/www/html/mailqenv/lib/python3.4/site-packages/celery/utils/functional.py", line 11, in <module> [Tue Nov 28 21:26:18.349280 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from kombu.utils.functional import ( [Tue Nov 28 21:26:18.349296 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/__init__.py", line 5, in <module> [Tue Nov 28 21:26:18.349322 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from .compat import fileno, maybe_fileno, nested, register_after_fork [Tue Nov 28 21:26:18.349333 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/kombu/utils/compat.py", line 29, in <module> [Tue Nov 28 21:26:18.349350 2017] [:error] [pid 3665] [remote 41.187.94.200:84] from typing import NamedTuple [Tue Nov 28 21:26:18.349400 2017] [:error] [pid 3665] [remote 41.187.94.200:84] File "/var/www/html/mailqenv/lib/python3.4/site-packages/typing.py", line 133 [Tue Nov 28 21:26:18.349408 2017] [:error] [pid 3665] [remote 41.187.94.200:84] def __new__(cls, name, bases, namespace, *, _root=False): [Tue Nov 28 21:26:18.349412 2017] [:error] [pid 3665] [remote 41.187.94.200:84] ^ [Tue Nov 28 21:26:18.349416 2017] [:error] [pid 3665] [remote 41.187.94.200:84] SyntaxError: invalid syntax The conf file of httpd: Alias /static /var/www/html/mailqueue/static <Directory /var/www/html/mailqueue/static> Require all granted </Directory> <Directory /var/www/html/mailqueue/mailqueue> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /var/www/html/mailqueue> Order deny,allow Allow from all </Directory> WSGIDaemonProcess mailqueue python-path=/var/www/html/mailqueue:/var/www/html/mailqenv/lib/python3.4/site-packages WSGIProcessGroup mailqueue WSGIScriptAlias / /var/www/html/mailqueue/mailqueue/wsgi.py` But if I activated my virtual environment and run with python manage.py … -
Angular V5 and Django rest framework, Hide and show the navigation
I am working on Angular V5 with Django rest framework. I am trying to hide the and show the button like Login or Logout using AuthService functionality. It is working fine when logged in but when I load or Refresh the page it is showing "Login" button again. My code snippets are as below. 1- AuthService.ts export class AuthService { public isLoggedIn: boolean = false; private headers: Headers = new Headers({'Content-Type': 'application/json'}); constructor(private http: Http, private common: CommonService) {} login(user): Promise<any> { var csrftoken = this.common.getCookies(); console.log('CommonService :: ',csrftoken); let url: string = '/login/'; this.headers.set("X-CSRFToken" , csrftoken); return this.http.post(url, user, {headers: this.headers}).toPromise(); } public isAuthenticated(): boolean { return this.isLoggedIn; } logout(): boolean { return this.isLoggedIn = false; } } export class LoginComponent implements OnInit { user: User = new User(); constructor( private router: Router, private auth: AuthService) { } ngOnInit() { } onUserLogin(): void { this.auth.login(this.user) .then((user) => { if (user.json().status === 'success') { localStorage.setItem('user', user.json().id); // localStorage.removeItem('user'); this.auth.isLoggedIn = true; this.router.navigate(['/profile']); } }) .catch((err) => { this.user['status'] = 'failed'; this.user['message'] = err.json().message; console.log('onUserLogin Post call Error ::', this.user); }); } } 3- header.html page <nav> <a routerLink="/">Dashboard</a> <a routerLink="/profile">My Account</a> <a routerLink="/contactus">Contact Us</a> <a routerLink="/admin" *ngIf="!auth.isLoggedIn">Admin</a> <a routerLink="/logout" *ngIf="auth.isLoggedIn" … -
Django get object after save in save_model
it's possible get the object in function save_model after its save. For example: def save_model(self, request, obj, form, change): o = super(CampaignAdmin, self).save_model(request, obj, form, change) # do something with "o" -
Prefetch on a one-to-many in Django not behaving as expected
I have a simple one-to-many relationship in Django, for example: class Team(models.Model): team_mascot = models.CharField( max_length=200, null=True) class Player(models.Model): first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) team = models.ForeignKey( 'players.Team', blank=True, null=True, on_delete=models.SET_NULL, related_name='players', related_query_name='player', ) On the Player admin page(s), I want to display some information about the Team associated with that player if the player has a team, including information about other players on that team. I want to optimize this query with a prefetch for all the related players to the current players' team. This should be fairly simple, but I can't seem to get the right prefetch. Here's what I've tried: def prefetch_all_team_players(self): return self.prefetch_related( Prefetch('team__players', to_attr='all_team_players') ) and: def prefetch_all_team_players(self): return self.select_related('team').prefetch_related( Prefetch( 'team__players', to_attr='all_team_players' ) ) and: def prefetch_all_team_jobs(self): from myproj.players.models import Team team_queryset = Team.objects.all() return self.prefetch_related( Prefetch('team__players', to_attr='all_team_players', queryset=team_queryset) ) I'm using this on the appropriate admin page. However, all_team_players is not being populated as expected. I'm not getting any value. player.all_team_players.all() doesn't give me anything. The alternative is of course just using player.team.players.all() wherever I need it, which works. But I'm trying to gain performance with the prefetch. Any ideas on what I'm missing here? -
Allow just one domain in google auth in django
I need some help. I'm using google sing in in my django app, but i need to restrict the allowed domains. And i did not found any method to do this. The auth is working and all is already configured and working fine. Thanks in advance. -
Saving data from google map api to database in django
Hello I have got question what is the best way to save data from google map api in javascript to my MySQL database which I am using in Django project. Now I have got in forms museum name and museum category which i can save to my database and this is working, I want now to add option to add museum location to my database where User can search for this location and move marker directry on building where it is using google map api. The problem is I don't know how to save to my database position of lat and lng (x,y) and name of location where the marker was placed when user push Save button. My html page looks like this: {% extends 'base.html' %} {% block head_title %}Add museum | {{ block.super }}{% endblock head_title %} {% block content %} <h1>Add museum</h1> {% if form.errors %} {{ form.errors }} {% endif %} <form method="POST">{% csrf_token %} <input type="text" , name='name' , placeholder="Museum name"><br/> <input type="text" , name='category' , placeholder="Museum category"><br/> <div id="map"></div> <button type='Save'>Save</button> </form> <style> /* Always set the map height explicitly to define the size of the div * element that contains the map. */ … -
django 1.8 shell_plus stuck on importing 'logging.config'
I'm trying to upgrade my django 1.7.0 project to django 1.8. I've installed the new version, and am trying to run manage.py shell_plus. This appears to freeze. I've added a print statement in python2.7/importlib/__init__.py, and found that it's trying to import logging.config, and after this it appears to do nothing. I do not know how to fix this. -
Optional image input field's kicking me out of session
This problem has been puzzling me for few hours now. I'm designing an update profile page where user can update photo if user wishes. The problem is that when I leave the image input field blank and edit other fields and hit submit, nothing is changed and I get kicked out of session, on the other hand when I select an image to upload and hit submit everything is updated and function runs as I designed it. Here's relevant code: class User(models.Model): photo = models.CharField(max_length=100, null=False, blank=True) It's a Charfield 'coz I store only reference to the image in database. HTML: <input type="file" name='photo' class="form-control"> View: if request.method == 'POST': photo = request.FILES['photo'] if photo: fs = FileSystemStorage() filename = fs.save(photo.name, photo) uploaded_file_url = fs.url(filename) if uploaded_file_url[-4:] not in ALLOWED_EXTENSIONS: error = 'Invalid File Type' errors.append(error) print(uploaded_file_url) You can ignore the print statement. I spread bunch of those all over the this function so I can see how the function works at each stage. Thanks to this I was able to determine that when the file input field is left blank other code is no longer being processed and program exits out. But clearly the field is supposedly optional. I … -
UpdateView gives blank/empty forms instead of previous data I edit
I'm using UpdateView to edit data using forms. But, when I click edit button the forms are blank/empty without the previous data. I even added {% with server.id as server_id %} {% with forms.id as edit_form %} in my index.html.. Does anoyone have anyclue what I am missing? view.py- from django.shortcuts import render_to_response from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.template import RequestContext from django.views.generic import TemplateView, UpdateView, DeleteView, CreateView from DevOpsWeb.forms import HomeForm from DevOpsWeb.models import serverlist from django.core.urlresolvers import reverse_lazy from simple_search import search_filter from django.db.models import Q class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() if query: posts = serverlist.objects.filter(Q(ServerName__icontains=query) | Q(Owner__icontains=query) | Q(Project__icontains=query) | Q(Description__icontains=query) | Q(IP__icontains=query) | Q(ILO__icontains=query) | Q(Rack__icontains=query)) else: posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() if form.is_valid(): # Checks if validation of the forms passed post = form.save(commit=False) #if not form.cleaned_data['ServerName']: #post.servername = " " post.save() #text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text' : text} return render(request, self.template_name,args) class PostDelete(DeleteView): model = serverlist success_url = reverse_lazy('serverlist') class PostEdit(UpdateView): … -
How to assign position in a queryset to a model parameter in Django for all objects in queryset
I am trying to create a waitlist for an app in Django. In order to do this, each user is assigned a waitlist_position number in their user profile. The profile model looks like this: from django.contrib.auth.models import User from django.db import models class Profile(models.Model): user = models.OneToOneField(User) referral_count = models.PositiveIntegerField(null=False, default=0) waitlist_position = models.PositiveIntegerField(null=False, default=0) The position of the user in the waitlist is determined by their date joined and the number of referrals they've made. Rather than calculate the waitlist position every time the user accesses the app, I thought it would be most efficient to update the positions once everyday as a scheduled task. In order to do that I can get the updated ordering in the following queryset: queryset = User.objects.order_by('-profile__referral_count', 'date_joined') The waitlist position field should be equal to the position of the user in that queryset. My question is, what is the most efficient way to assign this value? I know I could iterate through the queryset, update the value and then save each user (one by one) to the database, but that seems like an unnecessary number of DB calls... Is there a way to batch update but with different values? Or to iterate …