Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Gunicorn Django raised exception call takes 4 seconds
If I throw a simple exception in my django code the time for that call is approx ~4 seconds as seen in network tab. Status code is 500 Dev: haproxy --> nginx --> gunicorn --> django url(r'^check/$', webhome.views.check) def check(request): raise Exception('') The same request in prod configuration takes ~40 seconds. Status code 404 Prod: firewall(checkpoint) --> haproxy --> nginx --> gunicorn --> django Why does is even take 4 seconds it should have returned in few milliseconds? And why such a huge difference in prod. -
Unable to log to google stackdriver logging django+gunicorn+nGINX? [on hold]
I've tried the below code for logging in django settings from google.cloud import logging as google_cloud_logging log_client = google_cloud_logging.Client() log_client.setup_logging() logconfig_dict = { 'version': 1, 'handlers': { 'console': { 'level': 'INFO', 'class': 'logging.StreamHandler', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler' }, 'stackdriver_logging': { 'class': 'google.cloud.logging.handlers.CloudLoggingHandler', 'client': log_client }, }, 'loggers': { 'django': { 'handlers': ['stackdriver_logging'], 'level': 'INFO', 'propagate': True, }, 'django.request': { 'handlers': [ 'stackdriver_logging', 'mail_admins' ], 'level': 'ERROR', } }, } gunicorn.conf.py bind = "127.0.0.1:8000" workers = 3 loglevel = "debug" proc_name = "hhh" daemon = False I was able write to stackdriver logging with django development server but logging not working when I use gunicorn. But django.request is working. Please help. -
Django 1.4 - Admin displays time in UTC despite Timezone settings
I'm working on a django (1.4...) app which has the following model: class FailedLogin(models.Model): user = models.ForeignKey(User, related_name='failed_logins') date = models.DateTimeField(default=timezone.now) def __unicode__(self): return u"Failed Login for {} on {}".format( self.user, self.date.strftime("%Y-%m-%d %H:%M:%S %Z"), ) As you can see the DatetimeField is set using timezone.now() Our settings.py has been set to use timezones: TIME_ZONE = 'Europe/Amsterdam' LANGUAGE_CODE = 'nl_NL' USE_I18N = True USE_L10N = True USE_TZ = True When I go to the object detailview in the Admin I can see that the values are set correct, but when I view the objects in the Admin their __unicode__ methods is returning a UTC time. For for example: Object A has been set on 17:15. When visiting the object in the admin (detail) I can see that the value is saved correctly. Yet when I view it in the admin the __unicode__ returns the following : Failed Login for Karl on 2018-08-03 14:11:20 UTC Does anyone know what I am missing? -
change context in django view
I have a view function whose context depends on the author as : def dash_django_page(request, author_id): # get the django context: author = get_object_or_404(Author, pk=author_id) print("Function: dash_django_page(): Getting 'dash_content'") dash_content = HttpResponse(dash_dispatcher(request,), content_type='application/json').getvalue() dash_content = clean_dash_content(dash_content) context = {'author':author, 'dash_content': dash_content} return render(request, 'dash_within_django/dash_django_page.html', context=context) I want to remove the author ID and modifie this function as : def dash_django_page(request): print("Function: dash_django_page(): Getting 'dash_content'") dash_content = HttpResponse(dash_dispatcher(request,), content_type='application/json').getvalue() dash_content = clean_dash_content(dash_content) context = { 'dash_content': dash_content} return render(request, 'dash_within_django/dash_django_page.html', context=context) -
Grab object in Django
This is probably very simple and basic but I'm struggling with grabbing a newly-created object in Django. It is for a basic library-style app. Over in models, I do this to create a Book object: def add_book(self, postData, user_id): title = postData['title'] first_name = postData['first_name'] last_name = postData['last_name'] user_obj = User.objects.get(id=user_id) if not Author.objects.filter(first_name=first_name, last_name=last_name).exists(): author_obj = Author.objects.create(first_name=first_name, last_name=last_name) else: author_obj = Author.objects.get(first_name=first_name, last_name=last_name) return self.create(title=postData['title'], created_by=user_obj, author=author_obj) Then in views, I call that method and wish to redirect to a page specifically for that newly-created object. I think you can see that I have most of the code down, but don't know what to put in place of the "????". Please help! def books_add(request): if request.method == "POST": errors = Book.objects.book_validation(request.POST) if not errors: Book.objects.add_book(request.POST, request.session['uid']) book_id = Book.objects.get(????).id return redirect('/books/book/{}/'.format(book_id)) else: context = { 'errors' : errors, } -
My MySQL connector works in IDLE but not in a Django view. It say 'procname must be a string'
I'm importing import mysql.connector from mysql.connector import MySQLConnection, Error And connecting to the database successfully (I believe) but I'm getting an error that's probably the Error that I imported above. The code is the following- conn = mysql.connector.connect( host='<aws database>' , database='<database>' , user='root' , password='<password>' ) cursor = conn.cursor(buffered=True) cursor.callproc('get_nodes', (None, '2018-01-01', '2018-07-31')) rows=cursor.stored_results().next().fetchall() for row in rows: print row Which in idle will produce output as expected, but using Django it says Procname must a string. How do I resolve this issue? -
Postgres TIME vs TIME with Time zone
Could someone please explain the logic that Postgres applies when dealing with the following situation. A Django view receives a string representation of time in the following format: 18:30 PM which it then persisted to Postgres. I created the 2 columns in the DB to highlight the difference in handling the above time: start_at time NOT NULL, start_at_tz timetz NOT NULL, Here's what get saved in DB: The behavior seems to be that some 7 hr difference that was applied to the timezone column. The value format doesn't seem to incorporate the 24 hr/day cutoff. Earlier times get converted into: 13:00 PM 14:00 PM Can someone please shed some light on the PostgreSQL bevahior. I'm on an EST time zone, if that' relevant. Thank you in advance. -
How to get redirect function's output in Django?
I am trying to get "authorization_code" from a provider (OAuth2 related task). I wrote a basic function in my views.py; # This is not the best function, I know. def auth_for_app(request): return redirect ('https://www.PROVIDER-WEBSITE.com/admin/user/auth?client_id=xxxx&response_type=code&state=1234567890&redirect_uri=http://127.0.0.1:8000/products/auth') I am getting the result on my console (terminal). I can see the authorization_code which I need for the further processes. How can I get it as a value in my code? -
Django can't process non-ascii symbols
We have a strange issue. If we use non-ascii symbols in Django, it displays them normally in the lists, but if we will try to enter that item, it falls down with following error: The sys.setdefaultencoding("utf-8") helps, but there is an opinion that this is the wrong way (Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?). How can I solve it correctly? And why the lists displays properly? Any ideas appreciated! -
upload .txt file into textarea in django?
I'm new to Django. I've made textareas for a website, using the django forms widget. I want to add a fileupload to be able to upload a .txt file that will be inserted into the text area. How do I go about it? I've checked the documentation at https://docs.djangoproject.com/en/2.1/topics/http/file-uploads/ How do I incorporate this code within what I've already written? forms.py class HomeForm(forms.ModelForm): textInput = forms.CharField(required=True, widget=forms.Textarea( attrs={ 'class': 'form-control', 'placeholder': 'Input text...', 'id': 'input1' } )) class Meta: model = Post #import Post model from home models.py fields = {'textInput',} #comma required to ensure tuple capability models.py class Post(models.Model): post = models.CharField(max_length=1000) user = models.ForeignKey(User, on_delete=models.PROTECT) #default .CASCADE date = models.DateTimeField(auto_now=True) #data saved into db views.py class HomeView(TemplateView): template_name='home/home.html' def get(self, request): form = HomeForm posts = Post.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = HomeForm(request.POST) if form.is_valid(): post = form.save(commit=False) #saves data (thanks to the model form) #comit is false as object still needs to be modified post.user = request.user post.save() text = form.cleaned_data['textInput'] #anticipates SQL injection #return redirect('home:home') args = {'form': form, 'text': text} return render(request, self.template_name, args) -
Django request deserialization
I am trying to deserialize request.body: from django import forms from django.contrib.auth.models import User from django.http import HttpResponse, HttpRequest from django.http import HttpResponseRedirect from django.shortcuts import render import json def register(request): if request.method == 'POST': if len(request.body) > 0 and len(request.FILES) == 0: data = json.loads(request.body) And I am getting JSONDecodeError right at the last line. Python 3.6.4 (no need to decode, shoukd accept bytes), Django 2.0.7. When I am trying to print out request.body I get: b'username=1&password=1&email=and%40gm.co&csrfmiddlewaretoken=1iv975vw86CmmcDQM7IbpWxKsRn3J0RguI4ek5qKmTSfnyCRmu3wy7tcG0f36Cmr' Also type(request) if that might help: What am I doing wrong? -
'ManyToManyDescriptor' object has no attribute 'all' in django 2
This is my forms.py: class NewsletterCreationForm(forms.ModelForm): class Meta: model = Newsletter fields = ['subject', 'body', 'email', 'status'] and this is my views.py : def control_newsletter_delet(request, pk): newsletter = get_object_or_404(Newsletter, pk=pk) if request.method == 'POST': form = NewsletterCreationForm(request.POST, instance=Newsletter) if form.is_valid(): newsletter.delete() return redirect('control_newsletter_list') else: form = NewsletterCreationForm(instance=newsletter) context = { 'form': form, } return render(request, 'control_panel/control_newsletter_delete.html', context) Now when I want to use my control_newsletter_delet() I face to this error : 'ManyToManyDescriptor' object has no attribute 'all' I checked this link: 'ManyToManyDescriptor' object has no attribute 'all' and it cant help me to solve my problem. is any body know why I get this error? In addition, I'm sorry for writing mistakes in my question. -
Django - form's ChoiceField not updating immediately
I have created a form in forms.py which uses select input based on objects from the database: from controls.models import Valve class CronjobForm(forms.Form): query = Valve.objects.all() VALVE_CHOICES = [ (valve.pk, valve.name) for valve in query ] valves = forms.ChoiceField(required=True, widget=forms.Select, choices=VALVE_CHOICES) At first, everything seemed to work just fine, the HTML's <select> with option got rendered. The problem is, when I add a new Valve object to the database, using the Django Admin interface, it takes a while for the ChoiceField field to get updated - I can't see the new option on front-end immediately. I tried to reload the page, force reload, even print out the query to the terminal - the variable query got updated immediately, just the HTML did not. It eventually gets updated after a while, minute or so, maybe thanks to the system checks or by repeating the runserver command. So I'm wondering, what am I missing? Is there some way to force update the form? Does the form get cached and that's what causes the problem? -
Django: How to include both limited access, and models in same view?
I have a django music project with a site called Add-Album. I want only registered users to upload abums. When I added the limited access in views.py, I had to change the view from class-view to function-view. But then i got a problem. Everything worked fine, without the template. No forms showed up in the template(when it was class-view the showed up). My question is how can I include both limited access, and the models in same view? #Views.py # .... # My model and fields # model = Album # fields = ['artist', 'album_title', 'genre', 'album_logo'] # before this was a class view with the model and fields def AlbumCreate(request): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] if not request.user.is_authenticated: return redirect('{}?next={}'.format(settings.LOGIN_URL, request.path)) return render(request, 'Music/album_form.html') class AlbumUpdate(UpdateView): model = Album fields = ['artist', 'album_title', 'genre', 'album_logo'] class AlbumDelete(DeleteView): model = Album success_url = reverse_lazy('Music:Music') # .... #models from django.db import models from django.urls import reverse class Album(models.Model): artist = models.CharField(max_length=100) album_title = models.CharField(max_length=150) genre = models.CharField(max_length=30) album_logo = models.ImageField(upload_to='albumlogo/') def get_absolute_url(self): return reverse('Music:detail', kwargs={'pk': self.pk}) def __str__(self): return self.album_title + ' - ' + self.artist #urls.py #... url(r'album/(?P<pk>[0-9]+)/$', views.AlbumUpdate.as_view(), name='album-update'), url(r'album/(?P<pk>[0-9]+)/delete/$', views.AlbumDelete.as_view(), name='album-delete'), url(r'album/add/$', views.AlbumCreate, name='album-add'), … -
Parent class "returns" JsonResponse, but child method continues execution
I have two classes, let's call them Parent and Child. Parent extends BaseCreateView and a custom mixin for handling emails, but i don't think this is relevant. Parent has quite massive form_valid methon in which has additional argument response=True works like djangos own forms save(commit=True) (i find it handy to be able to deal with parent's result in child overiden method. In that Parent's form_valid i make some additional checks, one of which if filed supposed to return self.form_invalid(form). Not that form_invalid is just returning JsonResponse with status=201 and some message. My Parent looks like that: def form_valid(self, form, response=True): try: check_something except: print("ABOUT TO RETURN AN ERROR!") return self.form_invalid(form) if response: return JsonResponse(status=200, ...) I call Child form_valid like that: def form_valid(self, form, response=True): super(CLASS_NAME, self).form_valid(form, response=False) ... // some child-specific work ... return JsonRespone(status=200, ...) The point is: I can see "ABOUT TO RETURN AN ERROR!" in console, but at the same time, I know child-specific is being done, namely, it tryes to .save() a model and triggers IntegriryError, which happens because of that failed check in Parent method. The questions are: What is going on? Why doesn't it breaks out of child method as well as out … -
Django: prefetch and paginate relative objects
I have a simple two-level comments system with model class Comment(models.Model): text = models.TextField() parent = models.ForeignKey('self', related_name='children') In view I need to paginate first and second level comments. Now I do it like this: from comments.models import Comment from django.core.paginator import Paginator def view(request): comments = Comment.objects.all() comments = Paginator(comments, 10).get_page(request.GET.get('page')) for comment in comments: children = comment.children.all() comment.paginated_children = Paginator(children, 10).get_page(1) return render(request, 'comments.html', { 'comments' : comments, }) Everything works great, but it looks like a bad plan and probably for performance it should be one query using somehow from django.db.models import F, Prefetch and .prefetch_related Is it possible? Or I can stay with for loop? -
request() got an unexpected keyword argument 'customer'
Was implementing the razorpay,got the above error. I need to create a new customer in the razorpay api. unable to get the customer as it is saying the error is unable to get customer. from django.db import models from customers.models import Customer from django.db.models.signals import post_save,pre_save import razorpay client = razorpay.Client(auth=("", "")) class BillingProfile(models.Model): customer = models.OneToOneField(Customer,null=True,blank=True) inserted = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) b_customer_id = models.CharField(max_length=120,null=True,blank=True) def __str__(self): return self.customer.name def billing_profile_recieved(sender,instance,*args,**kwargs): if not instance.b_customer_id and instance.customer: print(instance.id,"OOOOOOOOOOOOOOOOOOOoo") print(client,"------------------------------") customer = client.customer.create(customer=instance.id) //_______ ERROR print(customer) pre_save.connect(billing_profile_recieved,sender=BillingProfile) def user_created_reciever(sender,instance,created,*args,**kwargs): if created: BillingProfile.objects.get_or_create(customer=instance) print(instance.user_customer,client) post_save.connect(user_created_reciever, sender=Customer) -
Django REST Framework structure with homemade ERP client
I am about to create a new REST API where I have to implement an ERP api within, more of the Django APPS will have to have access to the ERP api. my questing is, where to put the "homemade" ERP api wrapper project - project - config - users - customers - libs / erp ??? requirements.txt and from the customers app then import from libs /erp what is best practice here? -
Django: object reference kept on exception
I've got a weird behaviour when I raise an exception inside my Django application. Please loot at this snippet (I removed all the unnecessary code): @csrf_exempt def main(request): ems_db = EmsDatabase() # raise AssertionError return HttpResponse('OK\n', content_type='text/plain') this is the EmsDatabase class: class EmsDatabase: def __init__(self): pass def __del__(self): print('>>>>>>>>>>>>>>>> DEL') running this function (obviously through a proper http call) the EmsDatabase class is instantiated e properly garbage-collected; I see the print output in the Django server log. But if I uncomment the raise AssertionError line I got no print output and the object is still alive; just modifying a source file to trigger the server reload makes the object to lose the reference to itself and be garbage-collected (the print line appears). The same thing happens running Django through Lighttpd + Gunicorn. Why is Django (v2.0.7, python 3.6, Linux) keeping a reference to my object or, more likely, to the frame of the main() function? What can I do? -
What is the equvalent of TEMPLATE_CONTEXT_PROCESSORS in django2
Hello I'am migrating a project from Django 1.9.12 to Django2.0 I haven't write it it was left behind from a collegue that doesnt work any more in our enterprise after installing Django2 from django.conf.global_settings import TEMPLATE_CONTEXT_PROCCESSORS returns error ImportError: cannot import name 'TEMPLATE_CONTEXT_PROCESSORS' what is the equivalent of TEMPLATE_CONTEXT_PROCCESSORS in django2 -
How can I test a model field that is populated from the related_name of another model?
I have some code that looks roughly like this: from django.db import models class Bar(models.Model): # ... @property def some_property(self): if self.something.all(): return "non-empty" return None class Foo(models.Model): x = models.ManyToManyField(Bar, related_name='something', blank=True) I want to test Bar.some_property. I attempted to mock.patch Bar.something.all(), but I received an attribute error on Bar because Bar has no attribute something. How can I test some_property if I cannot mock Bar.something? -
HOW TO ACCESS AND USE A DIFFERENT DJANGO VERSION IN A DIFFERENT VIRTUALENV
someone enlighten me,i installed django 1.8 in one virtual env and 2.0 in a another virtual env,whenever i want to create a project and an app using 2.0,i get error that django is cannot be reco -
attendance csv file upload django multiple employees
views.py def Add_Atten ( request ): data = {} attendance = Attendance.objects.all ( ) if "GET" == request.method: return render ( request , 'hr/attendance.html' , {'attendance': attendance} ) # if not GET, then proceed # try: # csv_file = request.FILES[ "csv_file" ] # if not csv_file.name.endswith ( '.csv' ): # messages.error ( request , 'File is not CSV type' ) # return render ( request , 'hr/attendance.html' , {'attendance': attendance} ) # # if file is too large, return # if csv_file.multiple_chunks ( ): # messages.error ( request , "Uploaded file is too big (%.2f MB)." % (csv_file.size / (1000 * 1000) ,) ) # return render ( request , 'hr/attendance.html' , {'attendance': attendance} ) else: added_by = request.POST.get('added_by', '') month = request.POST.get('month', '') year = request.POST.get('year', '') att = request.FILES['csv_file'] a1 = add_attendace(added_by=added_by, month=month, year=year,file=att) a1.save() csv_file = request.FILES["csv_file"] file_data = csv_file.read().decode("utf-8") lines = file_data.split ( "\n" ) # loop over the lines and save them in db. If error , store as string and then display for line in lines: fields = line.split(",") data_dict = {} data_dict["department"] = fields[1] data_dict["role"] = fields[2] data_dict["one"] = fields[3] data_dict["two"] = fields[4] data_dict["three"] = fields[5] data_dict["four"] = fields[6] data_dict["five"] = fields[7] data_dict["six"] … -
Django Issues: ManagementForm data is missing or has been tampered with
I'm trying to create a simple todo list using built-in generic views. Here's my views.py class TaskList(ListView): paginate_by = 5 template_name = 'todo/index.html' context_object_name = 'formset' def get_queryset(self): return TaskFormSet(queryset=Task.objects.all()) def post(self, request): formset = TaskFormSet(request.POST) if formset.has_changed() and formset.is_valid(): formset.save() return redirect('/todo') And here's my template <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div> {% for field in form %} {{ field }} {% endfor %} </div> {% endfor %} <input type="submit" value="+"> </form> So when I submit form I get ['ManagementForm data is missing or has been tampered with'] What's the deal? -
Django Model Inheritance - Multi-Table Inheritance
I am creating a database that has two tables customer and seller and they are both inherited from user table that uses Django auth user. and my question is that is it possible for a user be both customer and seller at the same time?