Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django "on_delete=models.CASCADE" not working in 2.0?
I am trying to create a simple model relationship with on_delete=models.CASCADE.Here is my code:- class Answer_Options(models.Model): text = models.CharField(max_length=200) class Quiz(models.Model): q_type = models.CharField(max_length=50) text = models.CharField(max_length=200) possible_answers = models.ManyToManyField(Answer_Options, on_delete=models.CASCADE) It is giving me the following error on terminal:- TypeError: _init__() got an unexpected keyword argument 'on_delete' Location:- django\db\models\fields\related.py", line 1129 -
uWSGI harakiri with Django does not always work
I have a Django application that's run on uWSGI. I have the following uWSGI settings: master = true processes = 8 enable-threads = true threads = 25 harakiri = 30 harakiri-verbose = true When I connect to this server by more than 30 seconds, the process should be killed. I verified the process termination by monitoring the log file. The long process was done by putting the thread to sleep (time.sleep(200)) in Django. What confuses me is that even though I've already seen from the log that the process has been terminated, sometimes, it still continue running (after the sleep). My expectation is that if the process has been running more than 30 seconds, it should be killed and never continue. Am I missing some details? or implementing it incorrectly? Is putting the thread to sleep somehow is the same as killing the thread and on wake up time, create a new thread with different id? Thus, killing the thread by uWSGI will not impact the thread on Django. Thanks in advance. -
Why doesn't Django Rest Framework APIRequestFactory support query_params for DELETE method?
In one of my view, I'm passing additional data as query params in APIView delete method. I'm able to fetch the same using the request.query_params in the view. But when I'm trying to test the same with DRF APIRequestFactory, the data is empty. Digging further through the APIRequestFactory code shows me that its only looking at request.data and not on QUERY_STRING. Is there any specific reason for this behaviour? -
URL conflict in django1.8 and DRF 2.4.8
Project level urls.py urlpatterns += [ url(r'^machines/api/', include('core.urls')), url(r'', include('apps.api.urls')), url(r'^machines', include('apps.machines.urls')),] App level urls.py urlpatterns = [ url(r'^user/edit/(?P<pk>[0-9]+)/$', core_view.ProfileEdit.as_view()), url(r'^group/', core_view.GroupList.as_view()), url(r'^groups/add/', core_view.GroupCreate.as_view()),] when i hit http://localhost:8000/machines/api/groups/add it is calling GroupList view instead of GroupCreate. I am not getting any reason why this is happening? -
How to pass values from a modal form to a views function in Django?
I have two images embedded in anchor tags in HTML : <a id="pop1" href="#"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSuFkPwpxwXwgnnwvPHLxW1sCbtPKfqdpz6jApGYbEbeD99Ob-Z" width="30px" height="25px" style="margin-bottom:6px;"> </a> and <a align="right" id="pop2" href="#"> <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSuFkPwpxwXwgnnwvPHLxW1sCbtPKfqdpz6jApGYbEbeD99Ob-Z" width="30px" height="25px" style="margin-bottom:6px;"> </a> When I click on the images both open the same modal box. Below is the modal box code: <div id="alarmModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> <h4 class="modal-title">Shutdown Machines with less than certain % CPU Utilization after N minutes</h4> </div> <div class="modal-body"> <p> Please fill in the specifics below:</p> <form id="alarm_form" action="/create_alarm/" method="POST">{% csrf_token %} <label for="period">Period of inactivity(in minutes):</label> <input type="number" id="period" min="0" max="60" step="5" required> <label for="cpu">CPU Utilization(in %):</label> <input type="number" id="cpu" min="0" max="100" step="1" required> <br> <div id="alarmresult"></div> </div> <div class="modal-footer"> <input class="btn btn-default" id="upload" type="submit" value="Optimize"></input> </form> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> What I need to do is pass the two form field values ('cpu' and 'period') when I submit the form to a views function in python. The views function needs the period and cpu values respectively. How can this be done ? Is this done using ajax ? Please respond. -
Django 1.11 login page loads fine, does not display index page after "submit"
I'm using django 1.11, class based views. Authentication is successful because it is following the proper path for successful login. After I submit credentials, I'm not being redirected to the index page. Well, I am. It is looking for it in exactly the right place, but I am getting the error below. Can you see where I am going wrong? This is my problem: Exception Type: NoReverseMatch at /irbSite/index/ Exception Value: Reverse for 'form' not found. 'form' is not a valid view function or pattern name. Here is my the last few lines of my settings.py (this is working as it should, but I assume you may want to see it): STATIC_URL = '/static/' STATIC_DIR = os.path.join(BASE_DIR, 'static') LOGIN_REDIRECT_URL = 'irbSite:index' LOGOUT_REDIRECT_URL = 'login' This is my traceback: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/irbSite/index/ Django Version: 1.11.11 Python Version: 3.6.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'irbSite'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\ <redacted>\Desktop\django3rd\project\irbSite\templates\base.html, error at line 0 Reverse for 'form' not found. 'form' is not a valid view function or pattern name. 1 : <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> 2 : <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> … -
How to store complex csv data in django?
I am working on django project.where user can upload a csv file and stored into database.Most of the csv file i saw 1st row contain header and then under the values but my case my header presents on column.like this(my csv data) I did not understand how to save this type of data on my django model. -
encrypting a python dictionary using client_id for using it as a token
I have client_id something like this 'xxxx.apps.googleusercontent.com' I have a python dict like this { "name" : "M.S.Dhoni", "job" : "Wicket keeper" } Is there any way encrypt this dictionary based on the client_id to make it use as a token for each and every server call. plz give me hint how to do it. Thanks. -
Getting attribute of field in serializer (django rest framework)
serializers.py from django.contrib.auth.models import User from engine.models import Game from rest_framework import serializers class GameSerializer(serializers.ModelSerializer): class Meta: model = Game fields = ( 'game_name', 'level', 'game_type', 'creator', 'id', ) I want to get creator.username as creator just returns the integer of the id of the user object that is the creator. How can I get creator.username instead of creator? -
Python: Django - vs code debugger error in manage.py
Problem: VS Code debugger in manage.py, these code is generated when you start a new project in django Actual Error: File "/../../../../../manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax manage.py: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "lib.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) Here's my config in launch.json: { "name": "Python: Django", "type": "python", "request": "launch", "program": "${workspaceFolder}/manage.py", "args": [ "runserver", "--noreload", "--nothreading" ], "debugOptions": [ "RedirectOutput", "Django", ] } -
Django The view didn't return an HttpResponse object. It returned None instead
Trying to check if variable 'avail.end_time:' is empty,and if so redirect to a url. If not create a session that matches session.end_time to avail.end_time. But get a returned none instead error. avail.endtime variable is being referenced from my Availabilities model where end_time = models.TimeField(null=False, blank=False) @login_required def enter_queue(request): # get the user from the Django request & map to variable django_user = request.user #link user_profile to django users profile model & get user's profile user_profile = django_user.profile #user_profile = Profile.objects.get(user=request.user) #Map user_availabilities variable to profile from Availability model users_availabilities = Availability.objects.filter(profile=user_profile) #mapping user_avail to user profile #creating an array to store all matching sessions all_matching_sessions = [] # avail is each Availability object for avail in users_availabilities: if avail.end_time: return HttpResponseRedirect(render(request,'mysite/profile.html')) else: matching_sessions = Session.objects.filter(end_time__lte=avail.end_time)#looping through all the sessions end times that match to availability #adding them to the array all_matching_sessions = all_matching_sessions + matching_sessions #If no matching sessions are available if len(all_matching_sessions) == 0: #create a session player_session = Session( game = 'random_game', start_time = users_availabilities[0].start_time, end_time = users_availabilities[0].end_time, ) player_session.save() return render(request, 'mysite/profile.html') else: player_session = Session( session = all_matching_sessions[0], profile = user_profile ) player_session.save() #return HttpResponse('Waiting in queue') return render(request, 'mysite/profile.html') -
django-progressbarupload Error
I'm attempting to implement django-progressbarupload into my django project. https://github.com/ouhouhsami/django-progressbarupload I've following the instructions, but I do have a couple of questions: Question 1: Point 3 in the instructions indicates that I should "Add "progressbarupload.uploadhandler.ProgressBarUploadHandler" to your FILE_UPLOAD_HANDLERS setting" FILE_UPLOAD_HANDLERS = ( "progressbarupload.uploadhandler.ProgressBarUploadHandler", "django.core.files.uploadhandler.MemoryFileUploadHandler", "django.core.files.uploadhandler.TemporaryFileUploadHandler", ) I don't currently have anything defined for FILE_UPLOAD_HANDLERS in my settings.py. Should I add all 3 lines into FILE_UPLOAD_HANDLERS? Is there anything else that I need to install to make the last two lines work if I do include them in my settings? Question 2: The instructions indicate to make some changes to admin.py and add the following code: admin.site.register(MyAwesomeModelWithFiles, UploadFileModelAdmin) When I do this, I get an error: NameError: name 'UploadFileModelAdmin' is not defined No where in the instructions does it say what UploadFileModelAdmin is nor is it imported into the admin.py file example that this give, which looks like this: from django.contrib import admin from my_awesome_app.models import MyAwesomeModelWithFiles class MyAwesomeModelWithFiles(admin.ModelAdmin): change_form_template = 'progressbarupload/change_form.html' add_form_template = 'progressbarupload/change_form.html' admin.site.register(MyAwesomeModelWithFiles, UploadFileModelAdmin) Thanks for your help! -
Django Custom Tag - Replace more than 3 line breaks with two line breaks
I am attempting to write a django custom tag to replace more than 3 occurrences of a line break (\n) with 2 line breaks. For example, I would like to replace the following \n\n\n\n\n\n\n\n\n or \n\n\n\n\n or \n\n\n with \n\n Here is my custom tag so far: @register.filter(name='replace_three_linebr') def replace_three_linebr(value): """Replaces all occurrences of GT 2 adjoined line breaks with 2 line breaks from the given string.""" return value.replace("\n\n\n", "\n\n") -
Askbot: unable to post when Chinese selected
Errors below, is this database configuration issue? I am new to askbot and python. text search configuration "chinese" does not exist CONTEXT: PL/pgSQL function get_language_name_from_code(text) while casting return value to function's return type PL/pgSQL function get_thread_tsv(text,text,text) line 5 at assignment PL/pgSQL function thread_insert_trigger() line 3 at assignment Request Method: POST Request URL: http://localhost:8000/zh-cn/questions/ask/ Django Version: 1.8.19 Exception Type: ProgrammingError Exception Value: text search configuration "chinese" does not exist CONTEXT: PL/pgSQL function get_language_name_from_code(text) while casting return value to function's return type PL/pgSQL function get_thread_tsv(text,text,text) line 5 at assignment PL/pgSQL function thread_insert_trigger() line 3 at assignment Exception Location: /Users/myUser/.local/share/virtualenvs/backend-ts-cP1eF/lib/python2.7/site-packages/django/db/backends/utils.py in execute, line 64 Python Executable: /Users/myUser/.local/share/virtualenvs/backend-ts-cP1eF/bin/python Python Version: 2.7.14 -
Django TEMPLATEDOESNOTEXIST; multiple settings files
I am trying to implement multiple settings files in Django using Docker. I have a settings package as follows: > settings __init__.py base.py testing.py I run docker-compose up with the following command in the .yml: command: python manage.py runserver 0.0.0.0:8080 --settings=mysite.settings.testing The manage.py file is updated as follows: if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings.testing") My testing.py simply contains the following as of right now: from .base import * I run dc-up command and the Django container starts without issue. However, when I try to load a webpage, it returns a TEMPLATEDOESNOTEXIST error. I have tried replacing .testing with .base and same error. I know it is settings package related because if I switch back to a single settings.py file, there is no error. Appreciate any help. -
Scaling Django with Channels and NGINX on Kubernetes
Hoping someone has some experience in this area... I'm trying to build a website that scales on Kubernetes using Django. Where I am struggling is with separating all my containers into separate pods, specifically my Django webserver from my Django websocket server (manage.py runworker). Before I go and spend hours on doing something, I just wanted to see if I am thinking of it everything the right way. If I create a pod for the Django webserver and a separate pod for websockets using runworker, and then route traffic using nginx, will everything work together... in theory? I'm just trying to figure out if runserver needs to communicate to the webserver at all, or if it serves websocket requests outside of the http requests... if that makes any sense? -
Django Custom Formset Javascript
There is a dynamic form field in the invoice form I prepared with Django. I've used django formset javascript to add a dynamic row.In this way, I can add and remove rows. I'm doing autocomplete on one of the fields (field = name). But the autocomplete script does not work when I add a new row. The javascripts are like the ones I send below. How can autocomplete work when I add a new row? Django FormSet Javascript code: $(document).ready(function () { function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+-)'); var replacement = prefix + '-' + ndx + '-'; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.name) el.name = el.name.replace(id_regex, replacement); } function deleteForm(btn, prefix) { var formCount = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val()); if (formCount > 1) { // Delete the item/form $(btn).parents('.item').remove(); var forms = $('.item'); // Get all the forms // Update the total number of forms (1 less than before) $('#id_' + prefix + '-TOTAL_FORMS').val(forms.length); var i = 0; // Go through the forms and set their indices, names and IDs for (formCount = forms.length; i < formCount; i++) { $(forms.get(i)).children().children().each(function () { if … -
increment another model field using django signals
I have two models, A and B. I want to increment the value in one field of model A whenever i insert another value in model B. I am using post_save signals but i keep getting this error "'update_fields' is an invalid keyword argument for this function" below is my code thank you for your help. class Sales(models.Model): id = models.AutoField(primary_key=True) order_details = models.ForeignKey(GeneralConsulting) medication_name_id = models.ForeignKey(Medication_List) dosage = models.CharField(max_length=10, blank=True) duration = models.CharField(max_length=10, blank=True) quantity = models.IntegerField(default=0) ... @receiver(signals.post_save, sender=Sales) class Product(models.Model): id = models.AutoField(primary_key=True) product_name = models.ForeignKey(Medication_List) description = models.TextField(blank=True) supplier = models.ManyToManyField(Supplier, blank=True) expiration_date = models.DateField(blank=False, null=True ) ... quantity_sold = models.IntegerField(default=0) minimum_stock_level = models.IntegerField(default=1) def add_on(self, sender, created, instance, update_fields, **kwargs ): if created or update_fields is 'quantity': b = Product.objects.get(product_name_id=instance.id) if b.quantity_sold + instance.quantity <= b.initial_qty: b.quantity_sold = b.quantity_sold + instance.quantity b.save(update_fields=['quantity_sold']) So all i want to do is to increase the value in the Product.quantity_sold field whenever a new sale is added. Kindly help, i am quite new with django signals. Is there a better way to do this? Thanks -
How to create a volume without permision like root
Im working with docker to create two containers: django & postgres. What is my issue? I want to create a volume in my project to has a database persistent and commit to my repository to download in another machine and has the same database. So, when I create a volume in my docker-compose.yml inside my project, after maked docker-compose up the folder created with volume of postgresql in my project, this have a permision like root, so I cant commit the folder in my repository... This is my docker-compose file: version: '3' services: db: #build: ./postgresqlDocker/ image: postgres # Utiliza una imagen la cual en caso de no tener, la descarga environment: POSTGRES_USER: postgres #CREA UN USUARIO Y UNA BASE DE DATOS CON PRIVILEGIOS POSTGRES_PASSWORD: password123 # LE ASIGNA UNA PASSWORD AL USUARIO Y SU BASE DE DATOS POSTGRES_DB: test_db ports: - "5432:5432" # (HOST:CONTAINER) volumes: - ./data/postgres:/var/lib/postgresql/data/ web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code # (HOST:CONTAINER) ports: - "8000:8000" # (HOST:CONTAINER) depends_on: - db This is the definition of database connection in my settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'password123', 'HOST': 'db', 'PORT': 5432, } } And when … -
prevent django session from expiring
I have a site where once a user logs in I would like them to never get logged out. I have set SESSION_COOKIE_AGE = sys.maxint but still, after some amount of time (I don't know exactly how long, but it's around 12 hours) the users get a login page. Is there a way to accomplish this? -
How to get a submit a form in a detail page in Django?
What I would like to accomplish is that I get the form from songcreate to in same url as the Detail.html so a person can add more songs without having to leave and comeback multiple times.Eventually I hope to do this process with AJAX but haven't advance to that stage yet since i can't get the form to start. I think it may just be something simple but have been unable to pin point what it is. Views.py class DetailView(generic.DetailView): # form_class = SongCreate model = Album template_name = 'post/detail.html' def get_form_kwargs(self): kwargs = super(SongCreate, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def get_object(self, *args, **kwargs): pk =self.kwargs.get('pk') obj = get_object_or_404(Roote, pk=pk) return obj def get_context_data( self, *args, **kwargs ): context =super(DetailView, self).get_context_data(*args, **kwargs) # context['create_form'] = SongCreate() # context['create_url'] = reverse_lazy("post:index") query = self.request.GET.get("q") if query: qs = Album.objects.search(query) return context This is the Song create view when using its on url. it works just fine but I want to be able to show this form in the detail page or list page if thats not possible. class SongCreate(CreateView): model = Song success_url = reverse_lazy('post:index') form_class = SongCreate def form_valid(self, form): if form.is_valid(): ----------(Here is validation which ill skip for … -
How to use django_filters with MultiSelectField?
I am attempting to get django_filters to work with a multislect value and can't seem to figure it out, here's the relevant code: models.py RGB = 'RGB' NO_BACKLIGHT = 'None' BACKLIGHT_CHOICES = ( (RGB, 'RGB'), (NO_BACKLIGHT, 'None'), ) backlight = MultiSelectField(choices=BACKLIGHT_CHOICES) filters.py backlight = django_filters.MultipleChoiceFilter(choices=hat.BACKLIGHT_CHOICES, widget=forms.CheckboxSelectMultiple, lookup_expr='contains') view.py hat= hat.objects.all().order_by('price') hats_filter = hatFilter(request.GET, queryset=hat) return render(request, 'hat_list.html', {'filter': hats_filter}) list.html <form method="get" id="search"> <div class="backlight"> {{ filter.form.backlight.label_tag }} {% for choice in filter.form.backlight %} <label class="checkbox-inline"> {{ choice.tag }} {{ choice.choice_label }} </label> {% endfor %} </div> I think the issue is MultipleChoiceFilter search for a a string where as the value of a hat's backlight is stored as a list within the database (specfically a multiselectfield.db.fields.MSFList), if I select the 'RGB ' option the url is ?backlight=RGB How would I go about over wirting django_filters forms to work with multiselectfield list fields? is this even possible to do with forms via GET or should I just manually write my own querset methods? Thanks -
form from model with multiple foreign keys in django
I want to create a template that renders content filtered. I used this Model to create the form (used to filter) : class ProjectCategory(models.Model): project = models.ForeignKey( Project, on_delete = models.CASCADE, related_name = 'projectCategories' ) parentCategory = models.ForeignKey( ParentCategory, on_delete=models.CASCADE) category = models.ForeignKey( Category, on_delete=models.CASCADE, ) class Meta: verbose_name_plural = "Project categories" Using a model form returns all the instance of the models ParentCategory and Category. What I want is to render only the values related to the projects. I tried something like this : class FilterbyCategory(forms.Form): parentCategory = forms.ModelChoiceField( queryset = ProjectCategory.objects.all(), empty_label="(Nothing)",to_field_name="parentCategory") But it doesn't work. Any hints ? -
Registering Django translation model loses model data
I just installed django-modeltranslation for an app and went through the install process. Have languages in settings, modeltranslation in installedapps, have made sure the translation fields are in the db for the model, and have a translation.py file for the module. When I go to register the model: from modeltranslation.translator import translator, TranslationOptions from .models import Country class CountryTranslationOptions(TranslationOptions): fields = ('capital', 'language', 'short_desc') translator.register(Country, CountryTranslationOptions) I lose all of the available model data (checked local DB and know the data is there), breaking my local site and admin. The outputted error is: _clone() got an unexpected keyword argument '_rewrite' If anyone wants to see the rest of my set up please let me know! Thanks! tldr; Registering models for translation loses Django's ability to see DB data. -
Django Rest Framework ListCreateAPIView not checking has_object_permissions?
I've been trying to figure this out for almost a full day now, and I can't seem to figure out why has_object_permission method isn't called when the ListCreateAPIView is called in DRF. I've tried all the solutions I could find, but according to the docs check_object_permissions is called in this class already. I know it has to be something stupid I'm missing. Code snippets are below, please help! views.py: from accountability.models import AccountabilityItem from accountability.serializers import AccountabilityItemSerializer from rest_framework import generics from .permissions import InGroup class AccountabilityItemListCreate(generics.ListCreateAPIView): queryset = AccountabilityItem.objects.all() serializer_class = AccountabilityItemSerializer permission_classes = (InGroup,) permissions.py: from rest_framework import permissions class InGroup(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_object_permission(self, request, view, obj): print('Checking for object') return False Another note, I've added the has_permission method to the permissions.py file, and this method runs all the time no matter what. Thanks!