Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django generates wrong hostname in links (paginating and HyperlinkedModelSerializer)
My question is: everywhere in the project incorrect links are generated, on pages with pagination and when using HyperlinkedModelSerializer. For example: the link should be: http://1.g.cluster:8001/api/v1/admin/sys_logs/?limit=100&offset=100 And this one is generated: http://web/api/v1/admin/sys_logs/?limit=100&offset=100, where the web is the service name from the docker-compose.yml file, it is also in the settings in the settings.py file: ALLOWED_HOSTS = ['web', 'localhost', '192.168.36.85', '192.168.36.47', '0.0.0.0', '127.0.0.1'] Project with Django (1.11.22) and Django Rest Framework (3.10.2) nginx and docker. I don’t know how to configure the correct links, please help -
View didn't return an HttpResponse object. It returned None instead., when used normal form with FormView , django
urls.py path('shift/<int:pk>/assign/', employee_views.ShiftAssignView.as_view(), name="shift_assign"), models.py class Employee(models.Model): name = models.CharField(max_length=120) phone = models.CharField(null=True, blank=True, max_length=20) salary = models.IntegerField(default=0) shift = models.OneToOneField(Shift, on_delete=SET_NULL, null=True, blank=True, related_name='employee') def __str__(self): return self.name def get_absolute_url(self): return reverse('employee_details', args=[str(self.id)]) class Shift(models.Model): branch = models.ForeignKey(Branch, on_delete=CASCADE) start_time = models.TimeField() end_time = models.TimeField() def __str__(self): return str(self.branch) + ' ( ' + str(self.start_time) + ' / ' + str(self.end_time) + ' )' def get_absolute_url(self): return reverse('branch_details', args=[str(self.branch.id)]) forms.py class AssignEmployeeForm(forms.Form): employee = forms.ModelChoiceField(queryset=Employee.objects.filter(shift__isnull=True), widget=forms.Select()) views.py class ShiftAssignView(SuccessMessageMixin, FormView): form_class = AssignEmployeeForm template_name = 'back_office/assign_employee.html' def get_context_data(self, **kwargs): context = super(ShiftAssignView, self).get_context_data(**kwargs) context['current_shift'] = Shift.objects.get(id=self.kwargs['pk']) return context def get_success_url(self): obj = Shift.objects.get(id=self.kwargs['pk']) return reverse_lazy('branch_details', args=[str(obj.branch_id)]) def form_valid(self, form): employee_instance = form.cleaned_data['employee'] shift_object = Shift.objects.get(id=self.kwargs['pk']) employee_instance.shift = shift_object employee_instance.save() super(ShiftAssignView, self).form_valid(form) NOTE The object is already being saved , but it shows this http error ! -
How to read django variable radio button name in jQuery?
TOP PS:To summarize my problem I don't put every thing here. This question is about making a quiz page in django where user answers the questions and get the result. Okay so I have a dictionary in django views which is soru_cevaplar that includes soru(question) and cevap(answers). Also cevap includes answers for their (Foreign key) question. I have read many questions like this but couldn't get it. So in my template I have this: {%for soru, cevap in soru_cevaplar.items%} <p>{{soru.soru_soru|safe}}</p> {% for c in cevap%} <label> <input name="{{c.cevap_soru}}" type="radio" value="{{c.cevap_content}}"/><span>{{c.cevap_content|safe}}</span> </label> {% endfor %} {% endfor %} <input id="test" class="btn btn-outline-info" type="submit" value="End Test"></input> <script type="text/javascript"> var cevap = "{{soru_cevaplar}}"; </script> Cevap is string in JS so can't use it like in python dictionary. My answers are radio buttons and in my jQuery I know I need to do something like this: $("#test").on("click", function(){ var radioValue = $("input[name='{{c.cevap_soru}}']:checked").val(); console.log(radioValue); }); which returns nothing because input name isn't right. So what I want to do get the all answer values for each question control them in JS file and after user submit the button tell them the results. And the problem is like to pass cevap or sorular_cevap to the JS … -
Django ORM Query to find all records with second largest value of age | Django Interview Question
I was recently asked the below question in a Django interview. I want to know how I could improve this query. Question:- Given an Employee table, with fields name, age. Find all the rows with the second maximum age. Consider the below table id name age 1 a 10 2 b 11 3 c 12 4 d 10 5 e 11 In this case query should return all records with age 11 My Solution :- First I will order all age values in Descending order with out repeating them. Employee.objects.order_by().values('age').distinct().order_by('-age') Then since we want the second largest value it will be at 1 index, if you want second then use 2 and so on... Employee.objects.filter(age=Employee.objects.order_by().values('age').distinct().order_by('-age')[1] This will give us a dictionary with the key as age, {'age': 13} TO access the age, we will use Employee.objects.order_by().values('age').distinct().order_by('-age')[1]['age'] Then to Get all the records with the age, I used filter, below is the final query Employee.objects.filter(age=Employee.objects.order_by().values('age').distinct().order_by('-age')[1]['age']) How can I do it with fewer hits to the database? -
Django unique constraint not working properly
I have a model with a custom _id that has to be unique, and soft delete, deleted objects don't have to have a unique _id, so I did it as follows: class MyModel(models.Model): _id = models.CharField(max_length=255, db_index=True) event_code = models.CharField(max_length=1, blank=True, default='I') deleted = models.BooleanField(default=False) deleted_id = models.IntegerField(blank=True, null=True) objects = MyModelManager() # manager that filters out deleted objects all_objects = MyModelBaseManager() # manager that returns every object, including deleted ones class Meta: constraints = [ UniqueConstraint(fields=['_id', 'event_code', 'deleted', 'deleted_id'], name='unique_id') ] def delete(self, *args, **kwargs): self.deleted = True self.deleted_id = self.max_related_deleted_id() + 1 self.save() def undelete(self, *args, **kwargs): self.deleted = False self.deleted_id = None self.save() def max_related_deleted_id(self): # Get max deleted_id of deleted objects with the same _id max_deleted_id = MyModel.all_objects.filter(Q(_id=self._id) & ~Q(pk=self.pk) & Q(deleted=True)).aggregate(Max('deleted_id'))['deleted_id__max'] return max_deleted_id if max_deleted_id is not None else 0 The whole logic of the deleted_id is working, I tested it out, the problem is, the UniqueConstraint is not working, for example: $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.create(_id='A', event_code='A') $ MyModel.objects.filter(_id='A').values('pk', '_id', 'event_code', 'deleted', 'deleted_id') [{'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', 'pk': 1}, {'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', 'pk': 2}, {'_id': 'A', 'deleted': False, 'deleted_id': None, 'event_code': 'A', … -
How to use CSRF security for a backend django?
I'm developing a backend for a mobile app with Django where for user registration the user data are sent with the POST method. Since Django provide CSRF security as a middleware. Here my problem is if I have a front end I can enable CSRF token by jinja code as {% csrf_token %} but since it's a backend and how to resolve this problem -
BeautifulSoup - find img with different extensions
I'm working on a project in django and I have to find photos in the provided .csv file in Text column. The problem is that at this point I'm downloading only those with the .jpg extension. How to download e.g. those with the extension .png in one line, as follows: I am using to this task BeautifulSoup. soup = BeautifulSoup(row['Text'], features="html5lib") images = soup.findAll('img', src=re.compile('.jpg')) -
Django Queryset: join two querysets with one as a list or set
I have two separate querysets (A and B), with one having a foreign key relationship to the other (1 to many, where B is many). Is it possible to join the two querysets somehow, creating an object which looks something like this: A: { some_field: ..., list_of_B: [...], } I have already found a relatively slow solution by just iterating over A's values and adding the field: for i in range(len(A.values())): result[i] = A[i] result[i]['list_of_B'] = list(images.filter(fk_in_B=A[i]['id'])) For performance reasons I would like to do this within the querysets if possible. Is it even possible to have lists/sets in fields/columns of a queryset? If so, what would be a possible approach? -
I am getting AttributeError: module 'app' has no attribute 'helpers' when running Djanog runserver on Linux VM
I am getting AttributeError: module "app" has no attributes 'helpers' when I am trying to import as follow in HlperConnector.py: import app.Helpers.SubHelper as shelpr Same setup works perfectly on my VSCode but when deploying on Digital Ocen Linux VM (Ubantu 18.04.3 version). Here is my directory structure: ├───app │ │ admin.py │ │ apps.py │ │ forms.py │ │ tests.py │ │ urls.py │ │ __init__.py │ │ │ ├───Helpers │ │ │ helper1.py │ │ │ HelperConnector.py │ │ │ helper2.py │ │ │ __init__.py │ │ ├───SubHelper │ │ │ │ subhelpers1.py │ │ │ │ subhelpers2.py │ │ │ │ __init__.py └───Project │ asgi.py │ dosettings.py │ settings.py │ urls.py │ wsgi.py │ __init__.py │ Can someone please help me to resolve the above issue? I check the Django version which i use for my development (windows PC) is 3.0.6 and Production environment (Ubantu 18.04) is 3.0.7. But my guess is that this should not be an issue. Thank You. -
Long-term and Versatile Saved Searches?
I have an articles table that might change in the future built into a Django web app. That's to say, a row name might change, a row might get added or deleted, etc... I have to develop a data model for saving advanced searches made on this table that is as future-proof as possible and I'd like you opinions on the solution I came up with. For some background on how searches are made, a user fills out a standard advanced search form (keywords, date ranges, checkboxes...) and the form data is turned into a query string in the form .../?field_1=arg_1&...&field_n=arg_n and sent to the API. Currently searches are saved by simply saving the query string. However, if the article field name changes or gets removed, that user's saved search breaks. This is my proposed saved search model (I made a typo in that the operations field in the Saved Search table is meant to be a many-to-many relationship to the Saved Search Operations table): Essentially, when a user clicks a "Save Search" button, it will create the necessary rows and when it comes time to reactivate that search, it will join the necessary tables and create a valid query … -
sms sent but not received - Twilio
I am developing a Django application where I am using the Twilio free trial account. I have $11 as a trial balance in Twilio. But the fact is, SMS sent from Twilio but it does not reach my phone. Can anyone help me out plz? -
pytz AmbiguousTimeError related to a specific datetime
This is coming up in the context of a django project. All datetime objects are tz aware. One day the production server crashed with the follow error: pytz.exceptions.AmbiguousTimeError: 2020-11-01 01:00:00 The strange thing is that if I change this date manually in the database to almost anything else, the error goes away. Also, if I copy the problematic date into any other datetime field in the database, the same exception is thrown. I have also tried to add this datetime to other records, and the same problem occurs with those records. Same applied to test and dev databases. Any ideas? I am using a mysql database. -
Celery - Chaining groups of tasks
Im having trouble creating a chain of tasks in a group. I'll show a snippet of what I have tasks.py @shared_task def fast_task_1(arg1, arg2): return @shared_task def fast_task_2(arg1,arg2): return @shared_task def slow_task_1(arg1, arg2): return @shared_task def finished_both(): # Do something return And the following groups fast_job = group([fast_task_1.s(arg1, arg2), fast_task_2(arg1,arg2)]) fast_result = fast_job.apply_async(queue='fast_queue') slow_job = group([slow_task_1.s(arg1, arg2)]) slow_result= fast_job.apply_async(queue='slow_task') Is it there a way to make a group in which all the fast and slow tasks are ran in their respective queues and, when both of them finish, call the finished_both task? Another option I thought was to send the result of each group to finished_both and check there if each group had finished, but I still cant figure out how to create chain of tasks after reading the docs. -
How to render a ManyToMany Extra Field in my form? (E.g. quantity of each topping on my pizza)
I wish to build an offer generator for my colleagues and I am a bit stuck. In an offer, we have 1 main product that can have many different accessories in different quantities. E.g. a Pizza with several toppings where you may have 1 x cheese, 2 x pepperoni, etc. #models.py class Accessory(models.Model): name = models.CharField(max_length=200, null=True, blank=True) price = models.PositiveIntegerField(null=True, blank=True) class Offer(models.Model): customer = models.CharField(max_length=200) product = models.ForeignKey(Product, null=True) accessories = models.ManyToManyField(Accessory, through='Addons') class Addons(models.Model): offer = models.ForeignKey(Offer, on_delete=models.CASCADE) accessory = models.ForeignKey(Accessory, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) #forms.py class Offerform(ModelForm): accessories = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple(), queryset=Accessory.objects.all()) class Meta: model = Offer fields = '__all__' I have linked my offer accessories through a custom table (Addons) where I have specified the quantity. Nonetheless, how do I manage to get "quantity" as a field in my form so that I can select an accessory and specify the quantity? -
Django, url configuration reverse question. Gives ImproperConfigured
I tried to use this 2 lines to check if url reverse works...: from django.urls import reverse reverse('country-autocomplete') It suppose to give me: u'/country-autocomplete/' I did this earlier and it worked perfectly, since I had couple of problems and did couple of changes in environment(?). Now I'm trying to run these commands in cmd->python with swthed on environment and it gives me this fault: from django.urls import reverse reverse('raildict-autocomplete') Traceback (most recent call last): File "", line 1, in File "C:\Users\me\Envs\sc_project\lib\site-packages\django\urls\base.py", line 31, in reverse resolver = get_resolver(urlconf) File "C:\Users\me\Envs\sc_project\lib\site-packages\django\urls\resolvers.py", line 69, in get_resolver urlconf = settings.ROOT_URLCONF File "C:\Users\me\Envs\sc_project\lib\site-packages\django\conf__init__.py", line 76, in getattr self._setup(name) File "C:\Users\me\Envs\sc_project\lib\site-packages\django\conf__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting ROOT_URLCONF, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. What could be done to make it not working and what could be done to make it work? Thank you! -
How to show Django page with VenoBox?
Need the content of the Django page in the grey container but it's displayed over it That's how I link from <a href="{% url 'work' work.id %}" data-vbtype="ajax" class="venobox" title="Portfolio Details"></a> enter image description here -
relationships's visualization on localhost admin
I've settled one models.py (with two different classes), both of them appear on admin (localHost) where are pointing to two different databases. from django.conf import settings from django.db import models class Alimenti(models.Model): alimento = models.CharField(max_length=250, null=True) codice_alimento = models.IntegerField(unique=True, null=True) parte_edibile = models.FloatField(blank=True, null=True) def __str__(self): return '{} {} {} '.format( self.alimento, self.codice_alimento, self.parte_edibile ) class Genere(models.Model): alimento = models.CharField(max_length=250, null=True) gruppo_merceologico = models.CharField(max_length=250, null=True) codice_alimento = models.IntegerField() def __str__(self): return '{} {} {}'.format( self.alimento, self.gruppo_merceologico, self.codice_alimento ) Between the two classes, there is only one column with same IntegerField (codice_alimento) which I would like to use as one-to-one relationship, so that if I visualize on the admin page and I click over that column's value it open the correspondent row of the other Class' value. First, is it possible? Second, how to process it? I've tried both cases, one-to-one relationship and foreign-keys, none of these were working properly. I did NOT set primary keys since it does automatically when I run makemigrations but it doesn't lead me anywhere. None of cases here posted enlighten me about the solution. I am stuck on that issue and lost energies to figure it out, help please. -
Which framework is better to work with pycharm and django? [closed]
I have 45 lakh record in database. I need to develop a system in python using django which will perform elastic search on the database by searching for names and ID's Which framework i can use to build this system pycharm or vscode? -
Postgresql Generated Column requires sum of multiple integer array columns
I have a table that has 2 integer columns and 2 integer array columns that keep scores in them. For example, my row would look like the follow: { physical_ed: 40, music: 90, first_term: {10,23,43}, second_term: {1,5,5,7} } The array fields are declared as an integer[]. I need to generate a score column that sums up all of these fields. So far I have tried: ALTER TABLE scores DROP IF EXISTS score; ALTER TABLE scores add COLUMN total_score integer GENERATED ALWAYS AS (physical_ed::integer + first_term[3]::integer + second_term[1]::integer + second_term[2]::integer + second_term[3]::integer) STORED; The problem I have with the above, is it does not account for varying values in the array but sometimes that field could have 5 different values instead of just 3. I have tried running a select statement and I can calculate the sum of each array in a select statement normally like so: SELECT *, (SELECT SUM(s) FROM UNNEST(first_term) s) as total_first_term from scores; Unfortunately, this does not work inside a generated column query and we do need it to be part of our generated total_score sum. -
Update MySQL database with new field in Django
I have an existing MySQL database and all the models are created using makemigrations Django command. I updated my models with a new field and I run: python manage.py makemigrations <app> python manage.py migrate Although the makemigrations command adds the new field to my model, when the migrate command runs, I get the output: No migrations to apply. I want to update my schema without deleting the previous one. any thoughts? -
how to define a form field in modal django inlineformset
i want to submit child form with javascript pop up ,if number_of_cars = 3 it will pop up a form with 3 input fields for Car car_name , i have dont it from front end , but i dont know to add them to the pop up form <form method="POST">{% csrf_token %} <div class=" col-12 "> <div class="col-12 col-sm-9 col-md-12 divColor mt-2 mx-auto row " > <div class=" col-12 col-sm-9 mx-auto row p-0"> <div class="col-12 col-md-6 p-0 mx-auto text-center"> <br> {{form.owner | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.number_of_cars | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:qua'}} <input type="button" class="btn btn-light col-12 col-sm-10 mx-auto" name="" id="CARBTN" value="CAR" data-target="#CAR" data-toggle="modal"> </div> </div> <button class="col-4 mx-auto shadow-lg border-right border-left">insert</button> </div> </div> <div id="CAR" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="my-modal-title" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="my-modal-title">CAR</h5> <p class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span></p> </div> <div class="modal-body"> </div> </div> <button type="submit">save</button> </div></div> </form> <script> $(document).ready(function(){ $('#CARBTN').on('click',function () { let allValue=[]; let numberOfInput=$('#qua').val(); let allContent=''; let justforName=0; let numOfContent=$('.modal-body input').length; for(let j=0;j<numOfContent;j++){ justforName=j+1; allValue.push($('input[name="CAR'+justforName+'"').val()); } if(numOfContent!=numberOfInput){ for(let i=0;i<numberOfInput;i++){ justforName=i+1; allContent+='<input class="form-control"' +'type="text" name="CAR'+justforName+'"' +'placeholder=" CAR '+justforName+'">'; } $('.modal-body').html(allContent); } for(let j=0;j<allValue.length;j++){ justforName=j+1; $('input[name="CAR'+justforName+'"').val(allValue[j]) }})}) </script> class Car(models.Model): car_name = models.CharField(max_length=20,unique=True) owner = models.ForeignKey(Creator,on_delete=models.CASCADE) class Creator(models.Model): … -
Unable to Cancel Orders in Django
I would like to add the option for customers on my site to cancel their orders, but I'm having trouble getting it to work. I've created the view and the URL, but something is evidently wrong with them. Here's how it looks on the site: delete_order View: def delete_order(request, pk): """ Cancel an order from the profile page """ order = Order.objects.get(id=pk) if request.method == "POST": order.delete() return redirect('/') return render(request, "delete_order.html", {'item': order}) Order Model: class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) full_name = models.CharField(max_length=50, blank=False) phone_number = models.CharField(max_length=20, blank=False) country = models.CharField(max_length=40, blank=False) postcode = models.CharField(max_length=20, blank=True) town_or_city = models.CharField(max_length=40, blank=False) street_address1 = models.CharField(max_length=40, blank=False) street_address2 = models.CharField(max_length=40, blank=False) county = models.CharField(max_length=40, blank=False) date = models.DateField() date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) def __str__(self): return "{0}-{1}-{2}".format(self.id, self.date, self.full_name) Django Url: url(r'^delete_order/(?P<pk>\d+)/$', delete_order, name="delete_order") Html Url: <a class="btn btn-sm btn-danger" href="{% url 'delete_order' order.id %}">Cancel</a> This is the error I am getting: Any feedback is greatly appreciated! -
Django webpack loader: how to refer to static images compiled by webpack
I'm setting up webpack for a a Django application, for which django-webpack-loader appears to be the obvious choice. I can compile my js and scss files just fine, but I've hit a wall when it comes to loading in the images. My webpack.config.js file looks like this (I removed the scss, minifiers, babel, etc. for conciseness): const path = require('path'); const webpack = require('webpack'); const BundleTracker = require('webpack-bundle-tracker'); const MiniCssExtractPlugin = require("mini-css-extract-plugin"); const TerserPlugin = require("terser-webpack-plugin"); const { CleanWebpackPlugin } = require('clean-webpack-plugin'); module.exports = { context: __dirname, entry: { main: ['@babel/polyfill', './ledger/static/ledger/js/index.js'] }, output: { path: path.resolve('./ledger/static/ledger/compiled_assets/'), filename: "[name]-[hash].js" }, module: { rules: [ { test: /\.(png|jpe?g|gif|svg)$/, use: [ { loader: "file-loader", options: { outputPath: 'images' } } ] } ] } mode: 'development' } As far as I've been led to believe, file-loader is what I need to load in the static image files. When I run the build, the image file happily sits in my compiled_assets/images directory with its hash added. The problem seems to be in how to refer to the file. While the js files load fine by using the {% render_bundle 'main' 'js' 'DEFAULT' %} tag, I can't get the image files to appear. The … -
Django how to create a modal edit with Ajax?
I have created in my app a form with which I could store data in my database. But now I'm trying to create an edit button (using an ajax call with jQuery) in the datatable such as last column. I want that when I press on the button 'edit' that open a modal form it gives me the possibility to modify the data just filled. This is my models.py: class Materiale(models.Model): conto = models.ForeignKey(Conto, on_delete=models.CASCADE, null=True) class Conto(models.Model): nome=models.CharField('Nome Conto', max_length=30, blank=True, default="") def __str__(self): return self.nome And this is my table, with the button in the last column: <tbody> {% for element in elements %} <tr id="element-{{element.id}}"> <td class="elementConto userData" name="conto">{{element.conto}}</td> <td> <button class="btn btn-light p-0" onClick="editUser({{element.id}})" data-toggle="modal" data-target="#myModal"> </button> </td> So after I have created my modal code in the template.html: <form id="updateUser"> <div class="modal-body"> <input class="form-control" id="form-id" type="hidden" name="formId"/> <label for="conto">Conto</label> <input class="form-control" id="form-conto" name="formConto"/> </div> </form> After that I have created the ajax call in the following manner: function editUser(id) { if (id) { tr_id = $("#element-" + id); conto = $(tr_id).find(".elementConto").text(); $('#form-id').val(id); $('#form-conto').val(conto); $("form#updateUser").submit(function() { var idInput = $('input[name="formId"]').val(); var contoInput = $('input[name="formConto"]').val(); if (contoInput) { $.ajax({ url: '{% url "crud_ajax_update" %}', data: { 'id': … -
What is the difference of URL and Path in Django?
I have come across path and url methods in urlpatterns of url.py file. It's clear that both these methods can be used to declare the url path but what is the significant usage of them and when should I use one over the other?