Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python-SQLAlchemy : Can't update or insert data to a MariaDB from a Debian machine
Everything works well when I am running the same code from a windows with both MySQL and mariaDB. Even on debian sqlAlchemy works fine with a Mysql. But when I host the same code on debian only select query works when connected to mariaDb using sqlAlchemy and any of update,insert or delete query does not work or give any error. A database user can connect to the server from another place. They have access permission. -
Test with locust and [Errno 111] Connection refused
I have django (1.6) app and I want to test it with locust. I installed locust==0.7.5 and pyzmq==16.0.2 and I revived a lot of fails: [Errno 111] Connection refused' more details below When I run app with command: locust --host=http://127.0.0.1 I receive the following error: ConnectionError(MaxRetryError("HTTPConnectionPool(host='127.0.0.1', port=80): Max retries exceeded with url: / (Caused by NewConnectionError('<requests.packages.urllib3.connection.HTTPConnection object at 0x7f7639d89750>: Failed to establish a new connection: [Errno 111] Connection refused',))",),) My locust file: from locust import TaskSet, HttpLocust, task class UserBehavior(TaskSet): @task def home(self): self.client.get('/') @task def programm(self): self.client.get('/programm') class WebsiteUser(HttpLocust): task_set = UserBehavior Any help on regarding how to resolve the error would be appreciated! -
grequests with requests has collision
I am using grequests python module to call some APIs. I want to make two functions. A single request(use requests module) A multiple request(use grequests module) When I use two modules in two different files, it runs normally, but when I import two modules in the same file, requests module fall in infinity recursive. #!/usr/bin/env python #-*- encoding:utf-8 -*- import requests import grequests def SingleRequest(): rs = requests.get("www.example.com") return rs def MultiRequest(): urls = [ "www.example1.com", "www.example2.com", "www.example3.com" ] rs = [grequests.get(u) for u in urls] rs_map = grequests.map(rs); return rs_map; If I call MultiRequest() -> do Well! but if I call SingleRequest() ..... ↓ Exception Type: RecursionError Exception Value: maximum recursion depth exceeded Exception Location: /usr/local/lib/python3.6/ssl.py in options, line 459 /usr/local/lib/python3.6/ssl.py in options super(SSLContext, SSLContext).options.__set__(self, value) X 100 times... Is it possible to use requests and grequests in one file? -
Working of @cache_page() decorator in django-redis-cache
I am using(trying) redis as a cache to my django app. This is how I was trying to do it. def postview(request): post_list = [] if cache.get("posts") == None: post_list = Post.objects.all() cache.set("posts", post_list, timeout=None) else : post_list = cache.get("posts") context = {"post_list" : post_list} return render(request, 'post_list.html', context) This works fine. The queryset is cached and the cache is working. But I have not understood the concept of the decorator @cache_page. I wrote something like this, @cache_page(60 * 15) def postview(request): post_list = [] post_list = Post.objects.all() context = {"post_list" : post_list} return render(request, 'post_list.html', context) But it did not cache anything. It is not working or I do not know how to make it work. They(link to article) say that it cache the result of this view. What type of result ? What is the key to which this result is stored ? And can I cache querysets used in the view ? If yes, how ? -
Secure URL/page for AnonUser to update a model field - Django Rest framework
I have a model called Lead which represents my possible future_customer. In order to update a boolean field called is_approved in this model, I'm sending an email to the Lead's email ID along with a URL and this URL will take you to a page in my website where it asks for Approval. How do I deal with permissions in Django Rest framework views? There is no django user associated with Lead model and I cannot use any authentication related classes. Obscured url along with AllowAny permission is good enough? -
serialize() not sending file data to Django
I am trying to send multiple files with multiple input fields from angularjs to Django(phyton). I am able to receive file data at the end of server(Django) when I send the formdata as follows <form enctype="multipart/form-data" id="formId" method="POST" action="url"> As it is redirecting me to the "url" given in action, I am using $().searialize() to send the form data, I am able to send the remaining data. But I am not able to read files <form enctype="multipart/form-data" id="formId" method="POST"> <input type="file" ngf-select ng-model="model1" name="fileType1" accept="pdf/*" ngf-max-size="20MB" required > <input type="file" ngf-select ng-model="model2" name="fileType2" accept="pdf/*" ngf-max-size="20MB" required > <button type="submit">Submit</button> </form> $('#formId').submit(function(e){ e.preventDefault(); $.ajax({ url: 'url', method: "POST", data:$('#formId').serialize(), success:function(response){ //whatever you wanna do after the form is successfully submitted if(response.code == 200){ } console.log(response.message); } }); }); -
Tastypie "always_return_data" option changed response Status codes
I have a Tastypie API, I wanted to get the "id" of the created resource on POST request, so the only solution I found was "always_return_data" which returns the whole object. from tastypie.resources import ModelResource from tastypie.authorization import Authorization from tastypie.authentication import SessionAuthentication from myproject.core.models import MyModel class MyResource(ModelResource): ... class Meta: queryset = MyModel.objects.all() resource_name = 'mymodel' allowed_methods = ['get', 'put', 'post'] authentication = SessionAuthentication() authorization = Authorization() always_return_data = True # Added later And this works just fine. But In the Beginning I had written tests and had: For POST: self.assertHttpCreated(self.api_client.post('self.detail_url', format='json', data=data)) And for PUT: self.assertHttpAccepted(self.api_client.put(self.detail_url, format='json', data=new_data)) Now after I had set always_return_data = True The old tests Fail, coz POST is returnin 200 instead of 201 and PUT is retuning 200 instead of [202/204] Is there a solution other than replaceing assertHttpCreated and assertHttpAccepted with assertHttpOK Or if possible, is it possible to just return th "id" of the newly-created resource on POST request without setting always_return_data = True. Any suggestion is welcome. Thank you. -
django - in what order are called post_migrate handlers?
Let's assume I have two custom apps APP1 and APP2 and in both I have registered post_migrate handler. APP1's handler creates new permissions and in APP2's handler. I'm trying to create new groups and assign previously created permission to those groups. Is there any way how to ensure deterministic order of handlers's execution? Thank you. -
Django Logging and Session Information
I have tried to google this one to death but could not find the answer, so if someone can point me to the doc or explain how to do this that would be great. I am trying to include Session information from the Django request (i.e cookies) in all logs, now this is fine in the views etc that have access to the request I can just format that in the message that I am logging. The issue is with installed packages, these have no knowledge of the session and log without this information and I am yet to find a way to define this in the formatter so that the formatter is more session aware. I need to do this as I have to send all logs to a syslog server and would like to be able to search the logs for an entire session and get even package level logs. EDIT: Sorry guys I am editing the question for a little more clarity. The overall goal is to wrap all messages that get generated in a api call with the session information this would include any packages that are not directly tied to the Django application itself, this … -
djcelery PeriodicTasks.changed method - update query running slow
I have been using celery (3.1), django-celery(3.1.17)(that is djcelery) with Django(1.9) for scheduling tasks. Recently I noticed that one update query to PeriodicTasks table takes a lot of time(around 1 minute) due to which the whole process of scheduling tasks is working slow. The update query to model PeriodicTasks is called by pre_save and pre_delete singals on PeriodicTask model1. Thus whenever a new object gets added in PeriodicTask table, signal triggers and calls PeriodicTasks.changed method2 which simply update the same PeriodicTasks object's value again and again. I am assuming the update query is working slow because millions of tasks gets published in a very short time and for each task same PeriodicTasks object is getting updated. The question is(if I don't want to upgrade to celery 4.x), what is the purpose of this update(of PeriodicTasks object)? If I will remove the signal call1, will it affect to the functionality of django-celery by any means? Also just to mention, for celery4 also same signal calls on pre_save and pre_delete of PreodicTask model happens3. So it will not help me even if I will upgrade to celery4. -
Django 1.10 - form CRUD for multiple model instances
I am trying to make a form for managing multiple instances of a single model. This is my wireframe: Form should load all existing people, and if user will change name or position and submits the form, update upon changed people should be preformed. If user will add a new person using button below, after submit, the new person should be created. If User will click the X on particular person and submits the form, missing person will be deleted. Is there any Djangy way how to do this? I tried to use inlineformset_factory, but it looks like it does work only when I want to add a NEW model instances. -
comment not showing in post_detail
I am new to Django and I want to include comment to my detail but it is not showing. Here is the relevant part of my views.py def post_detail(request, year, month, day, post): post = get_object_or_404(Post, slug=post, status = 'published', publish__year = year, publish__month = month, publish__day = day) comments = post.comments.filter(active= True) if request.method == 'POST': comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.save() else: comment_form = CommentForm() return render(request, 'detail.html', {'post':post}) Here is models.py file. I think the problem will be with my views file class Comment(models.Model): post = models.ForeignKey(Post, related_name='comments') name = models.CharField(max_length=60) email = models.EmailField() body = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return 'comment by {} on {}'.format(self.name, self.post) Here is my detail.html please notify me when you observe the error {% with comments.count as total_comments %} <h2> {{ total_comments }} comment{{ total_comments|pluralize }} </h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{ forloop.counter }} by {{ comment.name }} {{ comment.created }} </p> {{ comment.body|linebreaks }} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your … -
Django error : Expected string or buffer
I'm getting a Django error : expected string or buffer when I submit my Django form. I already read some SO questions according to the same problem but it doesn't seem to work. This is my models.py form : class BirthCertificate(models.Model): lastname = models.CharField(max_length=30, null=False, verbose_name='Nom de famille') firstname = models.CharField(max_length=30, null=False, verbose_name='Prénom(s)') sex = models.CharField(max_length=8, choices=SEX_CHOICES, verbose_name='Sexe') birthday = models.DateField(null=False, verbose_name='Date de naissance') birthhour = models.TimeField(null=True, verbose_name='Heure de naissance') birthcity = models.CharField(max_length=30, null=False, verbose_name='Ville de naissance') birthcountry = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance') fk_parent1 = models.ForeignKey(Person, related_name='ID_Parent1', verbose_name='ID parent1', null=False) fk_parent2 = models.ForeignKey(Person, related_name='ID_Parent2', verbose_name='ID parent2', null=False) mairie = models.CharField(max_length=30, null=False, verbose_name='Mairie') social_number = models.CharField(max_length=30, null=True, verbose_name='numero social', unique=True) created = models.DateTimeField(auto_now_add=True) This is my forms.py : class BirthCertificateForm2(forms.ModelForm): fk_parent1 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Père", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None) fk_parent2 = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Mère", label_func=lambda obj: '%s %s %s' % (obj.lastname, obj.firstname, obj.social_number), empty_label=None) lastname = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Nom", label_func=lambda obj: '%s' % (obj.lastname), empty_label=None) firstname = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Prénom", label_func=lambda obj: '%s' % (obj.firstname), empty_label=None) birthday = CustomLabelModelChoiceField(Person.objects.filter(), required=False, label = "Date de Naissance", label_func=lambda obj: '%s' % (obj.birthday), empty_label=None) birthcity = CustomLabelModelChoiceField(Person.objects.filter(), required=False, … -
How to acces a model attribute from another model
I newbie with Django Framework and I wish to know if is possible I access a attribute from the model X via model Y...In my case a have a model called "Evaluation" this model receive the scores of evaluations of the candidates..they have a ForeignKey that receive the Candidate(what is another model) and a PositiveIntegerField with receive a score what I want is access this PositiveIntegerField via Candidate model, it's possible? My models.py: from django.db import models from jsonfield import JSONField from site_.settings import MEDIA_ROOT from django.core.validators import MaxValueValidator class Criterion(models.Model): label = models.CharField(max_length=100) def __str__(self): return self.label class Candidate(models.Model): name = models.CharField(max_length=100) e_mail = models.EmailField(max_length=100, default = '') github = models.URLField(default = '') linkedin = models.URLField(max_length=100, default = '') cover_letter = models.TextField(default = '') higher_education = models.BooleanField(default = False) docfile = models.FileField(upload_to='/home/douglas/Documentos/Django/my-second-blog/site_/media', null=True, blank=True) def __str__(self): return self.name class Evaluation(models.Model): candidate = models.ForeignKey(Candidate) criterion = models.ForeignKey(Criterion, default='') score = models.PositiveIntegerField(default = 0, validators=[MaxValueValidator(10)]) appraiser = models.ForeignKey('auth.User') def __str__(self): return str(self.candidate) #model de teste class Teste(models.Model): nome = models.CharField(max_length=10) def __str__(self): return str(self.nome) -
When to use Django get_absolute_url() method
Django documentation says: get_absolute_url() method to tell Django how to calculate the canonical URL for an object. What is canonical URL mean in this is context ? I know this method provides some addition functionality in Django admin, redirection etc. And I am fully aware on how to use this method. But what is the philosophy behind it ? I have never actually used it in my projects. Does it serve any special purpose ? -
Django - how to save method apply only on new data
How do I manipulate this method to be applied only on new entries and does not have a previous entry. When in admin, I will add an record, this method is applied correctly. but when I edit the same record, this method is applied again. def save(self): p = Product.objects.last() if p: self.productnumber = 1000 + p.id else: self.productnumber = 1000 super(Product, self).save() -
Unusual setdefault's in Django
Here's a piece of code from Django's authentification models (UserManager): def create_superuser(self, username, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(username, email, password, **extra_fields) Why set a key-value pair and check it immediately afterwards? In what scenario would these conditions be met? -
create dynamic column name at runtime - Django
I am maintaining a table called store class Store(models.Model): name = models.CharField(max_length=225) brand_name = models.CharField(max_length=225,null=True,blank=True) brand_key = models.IntegerField(null=True, blank= True) I have a store info table where i store each info of store details in the below table class store_info(models.Model): name = models.CharField(max_length=50) brand_info = models.CharField(max_length = 200) brand_status = models.CharField(max_length=50) I need to create a custom field when adding a new store every time by the name of store. for example if i add lenovo as my store as name i have to add a lenovo_status as a field in my store_info table. Does Django has an option for creating custom field in run time? Please help me with some ideas how to create the field in dynamic way. -
django pass field-name as variable in get_or_create
I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary) Like so: def convert_value(cell_value, field_to_lookup): rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value) print ('created? ',created) return rem_obj The above wont work since it would look for 'field_to_lookup' as the key. This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable -
NoReverseMatch in 'a href' HTML link
I'm trying to make a link that redirects to another page in my django application, I have the view, I have the url and I have the template, all are ok in my eyes, but when I try to 'href' the page to do the link I get the Following error: Reverse for 'views.candidate_detail' with arguments '()' and keyword arguments '{'pk': ''}' not found. 0 pattern(s) tried: [] views.py from django.shortcuts import render, get_object_or_404 from .models import Candidate, Criterion, Evaluation from django import forms from .forms import CandForm from .forms import EvalForm from .forms import TestForm from django.shortcuts import redirect from django.db import IntegrityError def canditate_list(request): candidates = Candidate.objects.all() evaluation = Evaluation.objects.all() ######################## Ponho todos os candidatos e suas respectivas médias em um array em formato dict({Candidato:N}) sum = 0 cont = 1 med = 0 lista = [] for cand in candidates: cont = 0 sum = 0 med = 0 for e in evaluation: if cand == e.candidate: sum += e.score cont += 1 if cont > 0: med = sum / cont data = {str(cand):med} ## a Key recebe o candidato no formato string lista += [data] ##### passo os dicionários contidos na lista anterior para outra … -
Django background image disappear
I want to add the background image to my website. settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = '/static/' STATIC_ROOT = '' path about the file: project/app /static/css/base.css /images/img.jpg I tried the two ways,respectively int the html and css. add in html: html: {% load static %} <section style:"background-image: url({% static "images/img.jpg" %})"></section> add in css: html: <link href="/{{ STATIC_URL }}css/base.css" rel="stylesheet" type="text/css" /> <section id="intro-header"></section> css: section#intro-header{ background-image: url({% static "images/img.jpg" %}); background-size: cover; } Both of them don't work. What part I missed? -
Django runtime error
i was try to run my django application , but it shows runtime error raise self.error(token, e) RuntimeError: maximum recursion depth exceeded in instancecheck please suggest me how to solve this ? -
Django POST data in request.body but can not store in variable
I am posting some raw JSON to my backend { "access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb", "id": 3, "order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}] } However when I try to print (request.POST.get("access_token")) I receive None But, when I do print (request.body) The values seem to there: b'{\n\t"access_token": "hU5C7so4reJOYTzPyhKPs8PWq07tb",\n\t"id": 3,\n\t",\n\t"order_details": [{"meal_id": 1, "quantity": 3}, {"meal_id": 2, "quantity": 2}]\n}' I am using Postman to post the data. I want to store the access token into some variable like so: access_token = request.POST.get("access_token") with the post data I am still fairly new to Django, any help would be great. -
How to get dynamic fields in tastypie per object
I have an api with fields a,b,c I want to return fields a, b for all records. But want to return field "c" only for current user. How to do that ? -
Django Token Authorization based on IP
I am looking for some help with respect to token based authorization. We have a client server model. The client contacts the server for the first time and gets a token. This token has to then utilized whenever a new message is sent to the server. I don't have any users as such. The messages are triggers from the system.Can someone please suggest on how to proceed? I came across this link but I am confused when it comes to saving it against a user as I have request from a machine as such.