Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Sessions + iOS App - Login only once - SESSION_COOKIE_AGE=0
I'm building an iOS app and I'm using Django as a backend. I want the users to only login once, when they open the app for the first time. In that case. Is adding SESSION_COOKIE_AGE=0 to settings.py considered a good practice? -
Showing user ratings with django-star-ratings
I have created a project where one registered user can rate another registered user, using django-star-ratings library. For this, I have used default User model provided with Django, with another model UserProfile which holds extra info of the User object and is related by OneToOne relation. Now, I can implement user rating in one of my templates, as given in the documentation. {% ratings post.author %} Where post.author points to the User object. But, I want to show the rating in also some other pages, in a raw form, suppose the User Dashboard page. Something like user.rating.average would do. How do I access the user's rating from the user object in the templates. -
success_url appending address
I have my urls file like this: urlpatterns = [ path('admin/', admin.site.urls), url(r'^people/', include(('imob.urls', 'imob'), namespace='people')) ] and my app urls: urlpatterns = [ url(r'^add/', PeopleCreate.as_view(), name='people-add'), url(r'^', PeopleList.as_view(), name='people-view') ] my views are like this: my PeopleCreate view looks like: class PeopleCreate(CreateView): model = People fields = ['name', 'doc'] template_name = 'people_form.html' success_url = 'people-view' what happens is that when I access localhost:8000/people/add and add a new item, instead of redirecting to localhost:8000/people, it is appending the address, so I end with: localhost:8000/people/add/people-view and it's not displaying the other template. What am I doing wrong? -
Reusing an existing websocket in Django Channels
I'm messing around semi-seriously with Python to create a sort of a gatekeeper server between a restricted-access system and a GAE application. I'm going to start with a more general question, before potentially moving on to a specific code-related question. Overview The restricted-access system is set up with a command-line Python app that opens a WebSocket connection to the Django Channels app running on an intermediate server, and begins sending out regular heartbeat frames, which the Django app acknowledges. So far so good. Every now and then, the Django app is going to receive an HTTP request, which it will verify, and if it passes, it'll send out an instruction to the other system. Now, in order to make it efficient, I had the idea of re-using the existing WS connection and piggy-back the instruction frame on that. Question Django allows me to receive frames on the socket easily, and act on said frames. What I'm having trouble with is sending a message down the existing pipe: I cannot for the life of me call the WebsocketConsumer.send() method from a method that is not in the consumer, but defined elsewhere. Is it even possible (this question points to it actually … -
Django Setting Custom Path for Storage ('str object is not callable')
I have a custom storage class I'm using and I am trying to set a different path to upload the file to but I keep getting "Str object is not callable". Here's the code where I call my custom class: fs = DGStorage(user_login=user_login, name=name, content=content, csv=True) fs.path = os.path.join("/u/vnc/web", "docs", "upload", "csv") When fs.save is called, I get the str object error (very annoying). I don't set the path in the storage class because it's set somewher else. -
Displaying User Specific Information with Django
So I know this question is a bit broad, but I am working on a web application using Django and I have hit a snag; So I want to have user specific data (that is imputed by the user) stored in the users model. (I have completed the user model and it works as expected, and I am using a custom user class so that I can have the needed data fields.) So the issue is I want to have one url for a page (ie. www.example.com/profile/) but have the information displayed to be specific to the user that is logged in. And have the user be able to change the info and have the database updated with the changes. I have read the Django documentation on sessions but I am unsure if it would work for my use case or exactly how I would implement it. Thanks for the help. Cheers -
Django AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
i need some help with this python code, i am trying to generate some time data based on user input but i keep getting an error : AttributeError: type object 'datetime.datetime' has no attribute 'datetime' I have tried several import statements like: "from datetime import datetime, timedelta" and also "import datetime" but the error persists. kindly help since i cant get my head around this. def generate_time_slots(available_from, available_to): entry = [] while available_from <= available_to: available_from = datetime(available_from).time() + datetime.timedelta(minutes=10).time() entry.append(doctor_id = '1', date = '2018-07-11', avalable_slots= available_from,) for x in entry: Slots.objects.bulk_create(entry) -
Deploy celery flower
I have deployed flower to monitor celery tasks, but the dashboard of flower don't show enough information. How can i get the full information dashboard as documents. https://flower.readthedocs.io/en/stable/screenshots.html -
Access to extra fields by directly querying the intermediate model
i have the following problem: I need to get the quantity of an ingredient for a recipe. This is my models.py: class Ingredient(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Recipe(models.Model): name = models.CharField(max_length=100) ingredients = models.ManyToManyField(Ingredient, through='RecipeHasIngredients') def __str__(self): return self.name class RecipeHasIngredients(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) quantity = models.IntegerField() def __str__(self): return str(self.recipe) -
GET error on Class Based View
I'm trying to set up a class based view. I have the view: class PeopleCreate(CreateView): model = People fields = ['name', 'document'] template_name = 'people_form.html success_url = 'people-view' the template: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>HTML5 boilerplate – all you really need…</title> </head> <body id="home"> <form action="POST">{% csrf_token %} {{ form.as_p }} <button type="submit" value="Save">Save</button> </form> </body> </html> and my URLs: urlpatterns = [ path('admin/', admin.site.urls), path('people/add/', PeopleCreate.as_view(), name='people-add'), path('', PeopleList.as_view(), name='people-view') ] when I try to submit the form, I get a Page not found error. What am I doing wrong? I tried reading the documentation but it is a bit confusing. -
How to assign GROUP to user from a registration form (for user) in Django?
The problem that I face, is that I do not know how to assign a group to a user directly from a formal registration of a template (application) in Django. My user registration view is this: def UserRegister(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() return render(request, 'register/user_register.html', {'form': form}) POSTDATA: to assign roles, I use django-role-permissions. I do not want to register a group, I just want to include it with the user who registers without having to do in the Django panel. -
Heroku won't start django app
17:09:59 web.1 | usage: gunicorn [OPTIONS] [APP_MODULE] 17:09:59 web.1 | gunicorn: error: unrecognized arguments: --access-logfile- It should have been "--access-logfile -", but somehow it lost the space. I only added some env vars and didn't change the code. Can it be a bug? On local, with 'heroku local ....' it works. -
Django multiple formsets in one view not working
I am trying to use multiple formsets in the same view and scale it using lists. However, it is not working. I modeled this code based on documentation: https://docs.djangoproject.com/en/2.0/topics/forms/formsets/#using-more-than-one-formset-in-a-view Yet, it gives validation error that management form is tampered with. Please kindly advise how to solve it. Thank you in advance. Very appreciated. VIEWS.PY from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions model_names = ['A', 'B', 'C', 'D', 'E', 'F', 'G'] def get_assumptions(request): AssumptionsFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names] if all([formset.is_valid() for formset in formsets]): for formset in formsets: for form in formset: form.save() else: formsets = [AssumptionsFormset(request.POST, prefix=thing) for thing in model_names] return render(request, 'assumptions.html', {'formsets': formsets}) ASSUMPTIONS.HTML <div class="form"> <form action="" method="post"> {% csrf_token %} {% for formset in formsets %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h1>{{formset.prefix}}</h1> <table id="formset" class="form"> {% for form in formset.forms %} {% if forloop.first %} <thead><tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr></thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %}"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% … -
Django - Teplatetag "readmore" wants to be "readless"
i have written a template tag some time ago which has the feature to collapse a textblock after 15 words. Now i want the exact opposite thing. i want that the user is able to get back to the original 15 words collapsed text after opening the collapsed textblock... i know sounds a bit wired. readmore.py from django import template from django.utils.html import escape from django.utils.safestring import mark_safe register = template.Library() import re readmore_showscript = ''.join([ "this.parentNode.style.display='none';", "this.parentNode.parentNode.getElementsByClassName('more')[0].style.display='inline';", "return false;", ]); @register.filter def readmore(txt, showwords=15): global readmore_showscript words = re.split(r' ', escape(txt)) if len(words) <= showwords: return txt # wrap the more part words.insert(showwords, '<span class="more" style="display:none;">') words.append('</span>') # insert the readmore part words.insert(showwords, '<span class="readmore">... <a href="#" onclick="') words.insert(showwords+1, readmore_showscript) words.insert(showwords+2, '">more</a>') words.insert(showwords+3, '</span>') # Wrap with <p> words.insert(0, '<p>') words.append('</p>') return mark_safe(' '.join(words)) readmore.is_safe = True -
Login doesn't go through with custom backend
I've tried to login using email instead of username, so I used a custom backend. The form does check if the email is right and the password matches (as in, I get errors if the form is not filled right), however it doesn't log the user in, whereas using the username (after removing AUTHENTICATION_BACKENDS), I can login just fine. So I think it comes from the backend however it seems like it working, I used prints and it does return a user. Here is my backends.py, stored in the file 'users' from .models import User class EmailBackend(object): def authenticate(self, username=None, password=None, **kwargs): try: user = User.objects.get(email=username) except User.MultipleObjectsReturned: return None except User.DoesNotExist: return None if getattr(user, 'is_active') and user.check_password(password): #print('reached') return user return None def get_user(self, user_id): try: User.objects.get(pk=user_id) except User.DoesNotExist: return None And here is how I call it AUTHENTICATION_BACKENDS = ( 'users.backends.EmailBackend', ) I'm actually puzzled as to why it doesn't log the user in if the role of the backend is just to return a user. So if someone could explain me what I did wrong and what is the actual purpose of the backend. Thank you. -
A TImed Rotating Log File Handler similar to ConcurrentLogHandler?
I have a web server deployment of a Django app running. The deployment uses 8 different worker processes to handle spikes in traffic requests. Another part of the app is that I'm logging a lot of user input into log files. In it's current state, I am using a TimedRotatingFileHandler to rollover files on midnight. The date-stamped files are then synched with an S3 bucket for storage. The initial deployment was just one worker process with the increase to 8 processes being a recent change. Since that change however, I have noticed issues with log files where the logs from yesterday are ending up being truncated, with entires from the current day appearing inside it. A similar problem was described here, but my question is that since that question is 5 years old, has there been any advances since that period that allow a concurrent timed file rotation to be done for logs across multiple processes? For code, I'll present a sample log declaration of my Django logs: 'test_session': { 'level': 'INFO', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': '/logs/test.log', 'when': 'midnight', # this specifies the interval 'interval': 1, # defaults to 1, only necessary for other values 'backupCount': 7, # how many backup … -
Remote debugging of Python server with rpdb
I need to debug remote server, Python. My Python app is running inside Docker container on some server and I have ssh access to that server. For remote debugging I want to use rpdb (I don't know other tools for that). My steps: enter remote server via ssh pip install rpdb add to code line import rpdb; rpdb.Rpdb(port=5555).set_trace() run ./redeploy.sh (this command will run my application) telnet 127.0.0.1 5555 As a result I get: ubuntu@ip-10-1-0-345:~$ telnet 127.0.0.1 5555 Trying 127.0.0.1... Connected to 127.0.0.1. Escape character is '^]'. I open url which is supposed to call rpdb and I get nothing. So, how I can reach rpdb from command line then? -
Django inlineformset how to not show id
So, I am working with inlineformset_factory and to properly receive all the fields in the post request, I am rendering all fields in the form (and not just the visible fields): {% for field in form %} <div class="form-group"> <div class="col-form-label">{{field.label}}</div> {% if field.name == "id" or field.name == "user" %} <!-- What to do to not show id and user. --> {% else %} {{field|add_class:"form-control w-100"}} {% endif %} </div> {% endfor %} So, what do I do to not show the id and user field labels? It seems like even if I try to skip these labels, they still show. -
create a particular detail view
i need help to formulate a query. my models are this: class Stage(models.Model): id_stage = models.IntegerField(default = 0,blank= True, primary_key=True) date = models.DateTimeField(default=timezone.now) tipo = models.CharField(max_length = 256,blank= True) start = models.CharField(max_length = 256,blank= True) end = models.CharField(max_length = 256,blank= True) km = models.CharField(max_length = 256,blank= True) profile = models.CharField(max_length = 256,blank= True) hc = models.IntegerField(default = 0,blank= True) UNOc = models.IntegerField(default = 0,blank= True) def __str__(self): return self.date class Rider(models.Model): id_rider = models.IntegerField(default = 0,blank= True, primary_key=True) first_name = models.CharField(max_length = 256,blank= True) last_name = models.CharField(max_length = 256,blank= True) display_name = models.CharField(max_length = 256,blank= True) birth = models.DateTimeField(default=timezone.now) place_of_birth = models.CharField(max_length = 256,blank= True) age = models.IntegerField(default = 0,blank= True) nationality = models.ForeignKey(Nation,related_name='nationality', on_delete=models.CASCADE,blank=True ,null=True) height = models.FloatField(default = 0.0 ,blank= True) weight = models.FloatField(default = 0.0 ,blank= True) team = models.ForeignKey(Team,related_name='team', on_delete=models.CASCADE,blank=True ,null=True) cost = models.IntegerField(default = 0,blank= True) stage = models.ForeignKey(Stage,related_name='stage', on_delete=models.CASCADE,blank=True ,null=True) def __str__(self): return self.display_name class Risultato(models.Model): TYPE_CHOICES = (('SR','sr'),('ITT', 'itt'),('HC', 'hc'),('1C','1c'),('TTT','ttt')) id_rider = models.ForeignKey(Rider,related_name='rider', on_delete=models.CASCADE) id_stage = models.ForeignKey(Stage,related_name='team', on_delete=models.CASCADE) type_ris = models.CharField(choices=TYPE_CHOICES,max_length = 256,blank= True) rank = models.IntegerField(default = 0,blank= True) punti = models.IntegerField(default = 0,blank= True) def __str__(self): return self.id_raider,self.id_stage,self.rank i need to create a Detail View to details of riders, somethings like … -
Django form dynamic required checklist
I have a ModelForm that I want to extend with a dynamic list of checklist items. So a user can only create an instance of my model when he ticked all checkboxes and the checkboxes are actually not part of the Model itself. The checklists and coresponding checklist items are dynamically created and will change in future. class Checklist(models.Model): name = models.CharField(max_length=100) class ChecklistItem(models.Model): checklist = models.ForeignKey(Checklist, on_delete=models.CASCADE) text = models.CharField(max_length=100) details = models.TextField(blank=True) So at the end of the form it should look something like this (similar to accepting the Terms of Service): desired form I cant come up with a solution of how to group the Items per Checklist. If I want to only list every item, without caring what Checklist it belongs to I could do: class SomeForm(forms.ModelForm): model = SomeModel fields = ['some_attribute', 'another_attribute'] def __init__(self, *args, **kwargs): super(SomeForm, self).__init__(*args, **kwargs) for checklist in Checklist.objects.all(): for item in checklist.checklistitem_set.all(): self.fields[item.text] = forms.BooleanField(required=True) But thats not what I like. I also dont know how I could access the details attribute of the ChecklistItem (for example for a tooltip) doing it this way. Does anybody know about an elegant solution on how to implement this? -
Django - return multiple querysets in view
Django 1.10 In my view, I have a function get_queryset() that, currently, returns one queryset. This function is called from another function, get_context(), which takes that data, uses it to get some values, and returns everything to the front end. However, I now want to return 2 querysets from get_queryset(), one that is the full queryset and one that has a filter applied to it. I assumed I could simply do something like: full_results = query.all() # do some filtering filter_results = full_results.someFilter() return full_results, filter_results However, I have another function where these results get sent to FIRST before being sent to the front end. I figured I would be able to access these querysets easily with bracket notation, like this - faceted = self.get_queryset()[0].facet('thing') However! Turns out that I am unable to do so. I am trying to access a property on each item in the queryset in this second django function but am getting an error - AttributeError: 'SearchQuerySet' object has no attribute 'feature' So clearly I am doing something wrong. Is it possible to do what I am trying to do? Or would it be better to just make another function to return this data? -
Invalid form not returning JSON/form field errors in modal
I'm trying to use modal forms with AJAX in Django and I've got it so that the modal shows the form content, and it submits/works correctly when there are no form errors, however when there are form errors it doesnt seem to send the response back in JSON (at least this is my guess). When there are form errors it will refresh the page and show the form in a new page (not in a modal) and the form will have the user input saved and it will show the form field errors. If this sounds confusing let me know and I can upload some screenshots of what its doing. Here is my jQuery/AJAX... <script> function apply_form_field_error(fieldname, error) { var input = $("#id_" + fieldname), container = $("#div_id_" + fieldname), error_msg = $("<span />").addClass("help-inline ajax-error").text(error[0]); container.addClass("error"); error_msg.insertAfter(input); } function clear_form_field_errors(form) { $(".ajax-error", $(form)).remove(); $(".error", $(form)).removeClass("error"); } function django_message(msg, level) { var levels = { warning: 'alert', error: 'error', success: 'success', info: 'info' }, source = $('#message_template').html(), template = Handlebars.compile(source), context = { 'tags': levels[level], 'message': msg }, html = template(context); $("#message_area").append(html); } function django_block_message(msg, level) { var source = $("#message_block_template").html(), template = Handlebars.compile(source), context = {level: level, body: msg}, html … -
How to POST multiple images with data to Django REST in single shot
I am designing the endpoint that receive single POST with multiple images. Here is my simple endpoint by Django REST models.py class CaseImage(models.Model): image = models.ImageField(upload_to='case_images') issue = models.ForeignKey(CaseIssue, related_name='images', related_query_name='images', on_delete=models.CASCADE) serializers.py class MyImageSerializer(serializers.ModelSerializer): class Meta: model = CaseImage fields = [ 'id', 'image', ] class NewCaseIssueSerializer(serializers.ModelSerializer): images = MyImageSerializer(many=True) class Meta: model = CaseIssue fields = [ 'id', 'machine', 'symptom', 'images', 'activities', ] def create(self, validated_data): from pprint import pprint import ipdb; ipdb.set_trace() images = validated_data.pop('images') instance = super().create(validated_data) tmp = [] for image in images: tmp.append(CaseImage(issue=instance, image=image)) CaseImage.objects.bulk_create(tmp) return instance I am imitating this answer My break point found empty list of images > /Users/sarit/Code/mp_resource/mp_resource/case_issues/api/serializers.py(115)create() 114 import ipdb; ipdb.set_trace() --> 115 images = validated_data.pop('images') 116 instance = super().create(validated_data) ipdb> validated_data {'machine': <Machine: eNYfySyXcDgplaeDXKbxxwmEYbFawyOOgDOhKaUTtBNExPxVbC>, 'symptom': 'First symptom', 'images': []} Questions: 1. Is it practical to POST multiple images in single shot? 2. If it is practical. How to do that in Postman application? -
Django: create object when server starts and use it in views
I have an image detector module, that takes about one minute to load. I would like to instantiate it once when the server starts, and use it in views. I know that i can run code when the server starts at urls.py, so, i tried the following: urls.py from django.contrib import admin from django.urls import include, path from module import Module urlpatterns = [ path('module/', include('project.urls')), path('admin/', admin.site.urls), ] module = Module() views.py from django.http import HttpResponse from project.urls import module def end_point(request): module.do_stuff() return HttpResponse("It works!") This approach did not work, because i can not import any variables from this file. Besides that, if urls.py die, i would get NameError: name 'module' is not defined. I do not use data base, i only want a REST API to my module. I would like to use Djongo, because i will use it in other services in my project. Summing up: i want a place to instantiate an object once when server starts, and be able to use my object in views. Thanks! -
Creating Django Rest Framework Serializer that abstracts/combines multiple instances of a model
Lets say I have the following models: Job(models.Model): name = models.CharField(max_length=255) JobDateRange(models.Model): job = models.ForeignKey(Job) start = models.DateField() end = models.DateField() Where a scheduled Job might have multiple active date ranges. While the database stores the dates in start-end ranges (legacy), the client interacts with a list of active dates. The API should not allow direct access to the JobDateRange objects, but rather provide get/create/delete/patch methods through the Job API endpoint. For example, if a job has linked date ranges 2018-01-01 -> 2018-01-02 and 2018-01-06 -> 2018-01-07: /api/v1/jobs/${some_id} <GET> would yield: { id: ${some_id}, name: "Job Name", dates: [ "2018-01-01", "2018-01-02", "2018-01-06", "2018-01-07" ] } This part is simple to do using a SerializerMethod field for dates, However, I need to be able to create/update data using the same format. E.g. - if I wanted to patch in a third date range, 2018-01-10 -> 2018-01-11 I'd hit do something like: /api/v1/jobs/${some_id} <PATCH> with a body of: { dates: [ "2018-01-01", "2018-01-02", "2018-01-06", "2018-01-07", "2018-01-10", "2018-01-11" ] } which would then need to create the new range. I have gathered that I need to create a custom serializer for JobDateRange, and use that in my JobSerializer, but since the JobDateRange serializer …