Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unicode Exception thrown when other Exception occurs
I have this strange behavior in my django project (1.11) running (example from the dev server): first I get a logging error, which might have to do with the setup However, the real strange thing is: whenever an exception is thrown, this causes a Unicode error. I am assuming there might be a problem with the language setup or python version interference? This is the view - I added the zero division to cause the error. When I remove it, everything works fine: class TestView(TemplateView): template_name = "table.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) dummy=1/0 return context Here the error log: --- Logging error --- Traceback (most recent call last): File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/views/generic/base.py", line 155, in get context = self.get_context_data(**kwargs) Traceback (most recent call last): File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/franzritt/.virtualenvs/sky/lib/python3.4/site-packages/django/core/handlers/base.py", line 185, in _get_response response … -
Django. Query array params
I have view generics.ListCreateAPIView and this view has filter_fields like groups filter_backends = (DjangoFilterBackend, filter_fields = ('groups', On the URL i can get list of groups like this: users/?groups=1&groups=2&groups=3 But in the Front-End programmer can create GET link like this(with []): users/?groups[]=1&groups[]=2&groups[]=3 If Django will has link like this users/?groups[]=1&groups[]=2&groups[]=3 filters will not works. My question is, what settings need to do for django project for link like this: users/?groups[]=1&groups[]=2&groups[]=3 ? -
Get all value from multiple form with same field name without formset
How to get all values from multiple form with same field name without formset? there is my view.py file ... test = str(request.POST.getlist('testing123[]')) ... and there is html file <div class="input-group"> <input type="text" class="form-control" name="testing123[]"> <a href="javascript:void(0);" class="add_button_rip btn btn-warning" title="Add field">+</a> </div> with js script to clone form <script type="text/javascript"> $(document).ready(function(){ var maxField = 100; //Input fields increment limitation var addButton = $('.add_button_rip'); //Add button selector var wrapper = $('.field_wrapper_rip'); //Input field wrapper var fieldHTML = '<div class="spacer-divide"></div><div class="input-group"><input type="text" class="form-control" name="test"><a href="javascript:void(0);" class="remove_button_rip btn btn-warning" title="Add field">-</a></div>'; //New input field html var x = 1; //Initial field counter is 1 //Once add button is clicked $(addButton).click(function(){ //Check maximum number of input fields if(x < maxField){ x++; //Increment field counter $(wrapper).append(fieldHTML); //Add field html } }); //Once remove button is clicked $(wrapper).on('click', '.remove_button_rip', function(e){ e.preventDefault(); $(this).parent('div').remove(); //Remove field html x--; //Decrement field counter }); }); </script> i tried to print with this print (test) for x in range(len(test)): print (test[x],end=" ") and the result just first value -
How to get a QuerySet with a range of "Created in the Last Five Minutes" according to the database clock
I'm trying to get a Django QuerySet that gives me objects created in the last five minutes according to the database clock. Presumably I want some type of __range thing, but I can't seem to work out the right Django magic to give me a range of "now" to "now minus 5 minutes". Any pointers to the documentation would be appreciated. -
Djanto starting id with a specific number?
i want to start using a app with a specific id and when i migrate i have a error that is saying that i dont have permission or does not exist. Well i am already db_owner so maybe the error is when i do ALTER SEQUENCEon my migrations. My Project myproject/ |-- myproject |-- dpo/ |-- projeto/ |-- models.py Projeto model.py class Projeto(models.Model): .......... So i do python manage.py makemigrations dpo --empty and then i went to file and in opererations i add : migrations.RunSQL('ALTER SEQUENCE dpo_projeto_Projeto_id RESTART WITH 7000;') and i have this error Cannot alter the sequence 'dpo_projeto_Projeto_id', because it does not exist or you do not have permission. -
encountering errors while adding a foreign key
I wanted to migrate some models but the ones with the foreignkey functions are causing some problems. i ran the following code and it caused an error python manage.py migrate and the foreign key seems the problem class Webpage(models.Model): name = models.CharField(max_length=264 , unique=True) url = models.URLField(unique=True) def __str__(self): return self.name Traceback (most recent call last): File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 337, in execute autoreload.check_errors(django.setup)() File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\helin\Anaconda3\envs\myenv\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\helin\Anaconda3\envs\myenv\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 985, in _gcd_import File "<frozen importlib._bootstrap>", line 968, in _find_and_load File "<frozen importlib._bootstrap>", line 957, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 697, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "C:\Users\helin\Downloads\my_django\first_project\first_app\models.py", line 12, in <module> class Webpage(models.Model): File "C:\Users\helin\Downloads\my_django\first_project\first_app\models.py", line 13, in Webpage topic =models.ForeignKey(Topic) TypeError: __init__() missing 1 required positional argument: 'on_delete' -
Django stay signed for two weeks or till browser is closed
I have a stay signed field in login form in my app and I want to allow user to decide whether he wants to stay signed for 2 weeks or being logged out when the browser closes. This is part of the code I wrote and am using, and it is working. I simply check if user checked to stay signed and when he didn't I set expire time of session to 0. I've looked into source of django SessionBase and it seems that 0 equals session expire on browser close. def form_valid(self, form): if not form.cleaned_data['stay_signed']: self.request.session.set_expiry(0) login(self.request, form.get_user()) redirect_url = self.request.GET.get(REDIRECT_FIELD_NAME, None) if redirect_url: return HttpResponseRedirect(redirect_url) return HttpResponseRedirect(self.get_success_url()) I wonder if this is a good and safe solution. -
Format number with space as thousands separator and comma for decimals
I would like to format these numbers to the corresponding format: 3911.940 -> 3 911,94 1970 -> 1 970,00 393.75000 -> 393,75 300000.50 -> 300 000,50 ... but I can't figure out how to do this easily. Thanks for any help solving this. -
Using variables as dict keys in django project settings
Is it safe and correct to use variables as dict keys in django project settings.py ? The chance for the names to be changed is small but it can happen in future. For example, I have something like that now: EXAMPLE_IDS = { 'name1': 1, 'name2': 2, 'name3': 3, } I want to change it for something like this so I could use the names independently: EXAMPLE_NAME_1 = 'name1' EXAMPLE_NAME_2 = 'name2' EXAMPLE_NAME_3 = 'name3' EXAMPLE_IDS = { EXAMPLE_NAME_1: 1, EXAMPLE_NAME_2: 2, EXAMPLE_NAME_3: 3, } Can this change generate any problems with my project in future? Or maybe, is it even better solution? -
Test fails with `django.db.utils.IntegrityError`
My test case gives me following error. django.db.utils.IntegrityError: insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: Key (user_id)=(1) is not present in table "auth_user". In my view class I have a log entry, during the test request.user.id is always None. so it use anonymous_user which is id = 1. (If I commented out the LogEntry.objects.log_action(), the test pass) My view class: class MyView(CreateAPIView): # For admin LogEntry anonymous_user_id = get_anonymous_user_id() def post(self, request, *args, **kwargs): """ ... """ LogEntry.objects.log_action( user_id=request.user.id or self.anonymous_user_id, content_type_id=self.content_type_id, object_id=target.id, object_repr=str(target), action_flag=ADDITION, change_message='message', ) return Response({}, status=status.HTTP_200_OK) My test: def test_myview_append_api_works(self): def myview_append(url, p1, p2): resp = None resp = self.client.post(url, data={'paraphrase': p1, 'data_id': p2}) return resp url = reverse('api-my_data:paraphrase_append') current_qa = Qa.objects.all()[0] # get current existing qa = the qa created in the setUp p1 = 'test paraphrase' p2 = target.id resp = myview_append(url, p1, p2) self.assertEqual(resp.status_code, status.HTTP_200_OK) I Tried using request_factory to set user in request but it didn't work request = self.request_factory.post(url, data={'paraphrase': p1, 'qa_id': p2}) request.user = self.user resp = MyView.as_view()(request) Can any one help me with this test. -
Check if there are only specified Django template variables in the string
I'm working on configurable email template and need to validate if only available_variables are used in the content. So if user put {{ apple }}, the form should return ValidationError('This variable is unavailable'). models.py: email_content = models.TextField() forms.py: def clean_email_content(self): email_content = self.cleaned_data['email_content'] available_variables = ['{{ company_name }}', '{{ user_name }}'] required_variables = ['{{ company_name }}'] for required_variable in required_variables: if not required_variable in email_content: raise forms.ValidationError("{} is required".format(required_variable)) # how to check if there are only `available_variables` in the content? -
how to make django database authenticate over a specific authentication_source database?
I have two databases(namely, test and admin) in mongodb. Admin is the default database. I have created an admin user as: use admin db.createUser( { user: "admin_1", pwd: "admin1234", roles: [ { role: "dbOwner", db: "test" }, { role: "userAdminAnyDatabase", db: "admin" } ] } ) I have created another user in test db with: { role: "dbOwner", db: "test" } I am using mongoengine and django DATABASES to connect to mongodb, like this: mongoengine.connect( db=config.main_db, host=config.host, username=config.username_test, password=config.password_test, authentication_source=config.authSource_test ) DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': config.main_db, 'USER': config.username_test, 'PASSWORD': config.password_test, } } This gives me an authentication failure error. However, when I use config.username_admin and config.password_admin in DATABASES it works fine. I don`t understand why it fails. Can someone fix this? I have secured these DBs with credentials and followed this method I expect that the DATABASES should take "test" credentials and work, not the "admin" credentials. Also, I want to remove the dbOwner role on test db in the admin db I am using: mongodb: 3.4, mongoengine: 0.16, django 2.1 and python3 -
In the django background, the text is too long to look good, how to shrink the text
In the django background, the text is too long to look good, how to shrink the text: -
What is the best strategy for implementing scheduled payment in Django
I wanted to implement scheduled jobs/actions in my DJANGO backend. Actions are basically deducting monthly recurring payment from the customer. Sending payment link say before 10 days etc. etc. The dates will be based on when the user buys the subscription. I have never implemented scheduled jobs before. I know there are some ways like cron tabs and celery. I wanted to know what will be the best strategy/tool for scheduled payments. So basically what I think i will do is that i will run the scheduled job every day at a particular time and will check the available candidates and will run the payment module. Is this strategy correct to run jobs everyday. Are there any better methods available. Is there a way that jobs run automatically when say the customers new billing cycle arrives. -
Django: I can't find right regex to get data-api-urls
I want to get values from regex. but I don't know how can I get it. I never learned about regex. It's too hard for me, please help me. regex is looks like this /book/?page=45 or /phone/?phonenum=010-7777-7777 or phone/?phonenum=01077777777 /book/ or /phone/ is page url and ?phonenum=xxx and ?page=xx I want to get two value from above regex, like this. {"phonenum" : 010-7777-7777} {"page": "45"} or maybe, it's fine that only take value of phonenum for page, like 010-7777-7777 or 45. What regex can get values from above -
Django Upload Multiple Files
I want to uplaod multiple files through Django Forms and save the path of uploaded files to the database table. But whenever i'm using this method to uplaod file data is been stored to database but different rows are been created in the database table for each file of multiple upload. I have tried following method Multiple files is been uploaded through other_files forms.py from django import forms from categories.models import Categories from .models import Process class ProcessingForm(forms.ModelForm): files = forms.ModelChoiceField(queryset=Categories.objects.all()) class Meta: model = Process fields = ('category', 'files', 'lookup_files', 'other_files') models.py from django.db import models class Process(models.Model): category = models.CharField(max_length=25, choices=CATEGORIES, null=True, blank=True) files = models.CharField(max_length=50, null=True, blank=True) lookup_files = models.FileField(upload_to='processing/%Y/%m/%d/Lookup', verbose_name=('Lookup File [For Tagging]'), validators= [validate_file_extension]) other_files =models.FileField(upload_to='processing/%Y/%m/%d/other_files', null=True, blank=True) views.py from django.shortcuts import render, redirect from categories.models import Categories from django.contrib import messages from .models import Process def process(request): if request.method == 'POST': form = ProcessingForm(request.POST, request.FILES) # print(form) if form.is_valid(): category = form.cleaned_data['category'] files = form.cleaned_data['files'] lookup_files = request.FILES['lookup_files'] other_files = request.FILES.getlist('other_files') print(len(other_files)) # file_list = [] for oth in other_files: print(oth) # file_list.append(oth) form = Process(category=category, files=files, lookup_files=lookup_files, other_files=oth) form.save() messages.success(request, 'File uploaded succcessfully') return redirect('process') else: print("Form is not valid") messages.warning(request, 'File extension … -
How to render data with different lengths, on a django template in a table?
I am trying to render some data I have been returned by a function on a table in django template. I am rendering two different lists, which have the same length, but when I render them in nested for loop, for some reason, I get extra copies of the inner loop. {% for d,t,r,y in open_route_info %} {% for k,v in open_trucks.items %} {% for i in v %} k = {{ k }} v = {{ v }} i = {{ i }} d = {{ d }} t = {{ t }} r = {{ r }} y = {{ y }} {% endfor %} {% endfor %} {% endfor %} For ^ this i get output as : k = Dehradun-Gurgaon v = [{: []}] i = {: []} d = 0.279 t = 07 Hours 19 Minutes r = googlemaps.com y = May 23, 2019, 4:31 a.m. k = Delhi-Mumbai v = [{: []}] i = {: []} d = 0.279 t = 07 Hours 19 Minutes r = googlemaps.com y = May 23, 2019, 4:31 a.m. k = Dehradun-Gurgaon v = [{: []}] i = {: []} d = 1413.204 t = 29 Hours 48 … -
How to handle formset for multiple instances?
I'm building a match system for a Tournament Manager. I have a "Match" model and "Set" model (code down below). First, I'd like to have a form that regroups all sets related to one match, how can I do that ? Secondly, how can I handle this if I have several matchs in my template ? models.py class Match(models.Model): isFinished = models.BooleanField(default=False) team1Win = models.BooleanField(default=False) team2Win = models.BooleanField(default=False) phase = models.ForeignKey(Phase, default=None, on_delete=models.CASCADE) teams = models.ManyToManyField(Team, default=None, blank=True) class Set(models.Model): timeSet = models.DecimalField(max_digits=5, decimal_places=2, blank=True, null=True) scoreTeam1 = models.IntegerField(null=True) scoreTeam2 = models.IntegerField(null=True) match = models.ForeignKey(Match, default=None, on_delete=models.CASCADE) models.py class SetUpdateForm(forms.ModelForm): class Meta: model = Set fields = [ 'scoreTeam1', 'scoreTeam2', 'match', ] -
why I get authentication error on migrate?
I'm running this command on a django project, and getting this error. ./manage.py migrate django.db.utils.OperationalError: FATAL: password authentication failed for user "user_admin" FATAL: password authentication failed for user "user_admin" what does it mean?? -
Django Model with associated Weather per entry
I have two models class Route(models.Model): start_destination = models.CharField(max_length=255) end_destination = models.CharField(max_length=255) length_in_miles = models.CharField(max_length=255) ... and class Weather(models.Model): name = models.CharField(max_length=255) I want to summarize all Routes for a given tour in a Trip class like so class Trip(models.Model): tripname = models.CharField(max_length=255) routes = models.ManyToManyField('Route') but each Route in the Trip Model should be associated by the weather at that time, so a Trip should look like this in the end: tripname routeA weatherA routeB weatherB routeC weatherC and I don't want to include Weather directly in Route, because the same Route can be driven twice but with different Weather in another Trip. -
django: Problem with arithmetic expressions with years in queries
It looks like django doesn't create a correct MySQL query when having a simple arithmetics with ExtractYear(). I have a model with two data fields: class Event(models.Model): start_date = models.DateField() finish_date = models.DateField() If I want to find all rows such that the years of start_date and finish_date are equal, I can do it so: from django.db.models import F from django.db.models.functions import ExtractYear >>> print Event.objects.annotate(year=ExtractYear(F('start_date'))).filter(finish_date__year=F('year')).only('pk').query SELECT `event`.`id`, EXTRACT(YEAR FROM `event`.`start_date`) AS `year` FROM `event` WHERE EXTRACT(YEAR FROM `event`.`finish_date`) = (EXTRACT(YEAR FROM `event`.`start_date`)) But if I want to find events that start and finish in consequent years, I try the following filter, and it gives me an incorrect MySQL query: >>> print Event.objects.annotate(year=ExtractYear(F('start_date'))).filter(finish_date__year=F('year')+1).only('pk').query SELECT `event`.`id`, EXTRACT(YEAR FROM `event`.`start_date`) AS `year` FROM `event` WHERE `event`.`finish_date` BETWEEN 0001-01-01 AND 0001-12-31 I tried to replace F('year')+1 with F('year')+Value(1) but it didn't help. Am I wrong somewhere, or does it look like a bug in django? I will also be grateful if you see any other methods to do the same! -
Files not passed in the request even after setting enctype=multipart/form-data?
I have a form which is dynamically generated. Input types can range from file, text and a table(using summernote). When i try to pass this form data to my Django view handler the file data is not received. request.FILES is empty. This is my JAvascript function making an Ajax call - function saveTagInputs() { // debugger; formData.append(getTagName[getTagId], $("#" + getTagId).get(0).files[0]); formData.append("tagdict", JSON.stringify(tagDict)); formData.append("tagnames", JSON.stringify(getTagName)); formData.append("tempid", tempData.selectedTemp); var $thisURL = window.location.href; if ($thisURL.charAt($thisURL.length - 1) == "#") { // alert(""); $thisURL = $thisURL.substring(0, $thisURL.length - 1); } for (var pair of formData.entries()) { console.log(pair[0] + ", " + pair[1]); } //ajax call passing template id's and taginput dictionary containing tag id and it's value $.ajax({ url: $thisURL + "savetaginput/", type: "POST", data: formData, cache: false, processData: false, contentType: false, success: function(data) { console.log("Tags saved successfully !"); } }); debugger; } When i log this data in console this is shown for the file input field- profile_image, [object File] where profile_image = name of input field and object file is the file... now when i pass this ajax call to my django view my request.FILES comes empty. This is my django view - def generate_taginputs(request): if request.method == "POST": #get temp id … -
TypeError: Object of type 'User' is not JSON serializable
How to return a list of objects in Django Rest Framework.I am calling a function which returns list of objects. from rest_framework.response import Response import json def get(self, request, *args, **kwargs): data=myfunction(a,b,c) # data={list}<class 'list'>: [<User: Negiiii | negiiii>, <User: Negiiii | negiiii>] data=json.dumps(data) return Response({"data":data}) Result that I need: [ { "name":"Negi", "rollno":14 }, { "name":"Negi", "rollno":13 } ] -
how to joins models in drf [duplicate]
This question already has an answer here: How to join two models in django-rest-framework 2 answers how to join twomodels in djangorestframework -
How to print Apache error log for clear view of WSGI error
I am deploying my first Django website on a Virtual Private Server and am getting a Internal Server Error when loading the site. The site worked on the server when it was in development settings but as soon as I installed Apache and put into production mode it started giving WSGI errors. I would like to know how I can use the error log to narrow down the issue. This is the process I have gone through so far: Rebooted server Checked httpd.conf file for syntax errors sudo service apache2 restart sudo /etc/init.d/apache2 reload Set the LogLevel to info instead of warn From there I looked up the logs using: tail -f /var/log/apache2/error.log. They returned: [Mon May 20 03:08:25.024764 2019] [wsgi:debug] [pid 9206:tid 140176740038400] src/server/mod_wsgi.c(9071): mod_wsgi (pid=9206): Started thread 10 in daemon process 'django_app'. [Mon May 20 03:08:25.024778 2019] [wsgi:debug] [pid 9206:tid 140176798787328] src/server/mod_wsgi.c(9071): mod_wsgi (pid=9206): Started thread 3 in daemon process 'django_app'. [Mon May 20 03:08:25.024811 2019] [wsgi:debug] [pid 9206:tid 140176731645696] src/server/mod_wsgi.c(9071): mod_wsgi (pid=9206): Started thread 11 in daemon process 'django_app'. [Mon May 20 03:08:25.024825 2019] [wsgi:debug] [pid 9206:tid 140176723252992] src/server/mod_wsgi.c(9071): mod_wsgi (pid=9206): Started thread 12 in daemon process 'django_app'. [Mon May 20 03:08:25.024846 2019] [wsgi:debug] [pid 9206:tid 140176714860288] …