Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AutoComplete Light Filter Foreign Key Values
I am using the Django AutoComplete Light library to filter Form values based on a Primary key. I have two models as below: class Skill(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class SubSkill(models.Model): name = models.CharField(max_length=50) skill = models.ForeignKey(Skill, on_delete=models.CASCADE, null=True) def __str__(self): return self.name. However, these two field are used in another Employee model as I want to query base on this model. I had used Django Smart Selects to chain the models in the Employee model which works fine. However, I am trying to filter my subskills based on the skills using the Autocomplete library but getting all the subskills instead. My Django Autocomplete light view looks like this class SubskillsAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! # if not self.request.user.is_authenticated(): # return Country.objects.none() qs = SubSkill.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs and my model form looks like this: class EmployeeSkillForm(forms.ModelForm): class Meta: model = Employee fields = ('skills','sub_skills', 'experience','resume','certificates') widgets = { 'sub_skills': autocomplete.ModelSelect2Multiple(url='skills-autocomplete') } I cannot figure out why my subskills will not filter based on the skill instead of showing everything. -
Matching single column against multiple values without self-joining table in POSTGRES
I want to select a routing_id which has routing_id = 489. I use SQL subquery but it decreases the performance. Query:- select routing_id from ec.production_autoroutingtag where tag_type = 'mounting_type' AND tag_value='smd' and routing_id in (select routing_id from ec.production_autoroutingtag where tag_type = 'x_ray' AND tag_value='true' and routing_id in (select routing_id from ec.production_autoroutingtag where tag_type = 'depaneling' AND tag_value='false')) It working fine but what when numbers of rows are more so please give me the best solutions. Thanks in Advance. ![2]: https://i.stack.imgur.com/8plMV.png! -
How to disable 301 redirects in HAProxy
I have an internal load balancer (HAProxy 2.0.2) which proxy to my pool of application servers. When i directly access POST /hello on Application server it returns 404 since all my urls should end with trailing slash, But if i do the same with HAProxy POST /hello my requests are automatically routed and results of GET /hello/ are returned, but in haproxy access.log, status code 301 is logged. Note: I have to disable any auto redirect behaviours of HAProxy, ie HAProxy should server request on if that path exists, Else return 404. any config update update would be really helpful Valid URL's /hello/ Expected HAProxy Behaviour. Haproxy should return 404 if i hit /hello [without trailing slash] HAProxy Config global log /dev/log len 4096 local0 info log /dev/log len 4096 local1 notice chroot /var/lib/haproxy stats socket /run/haproxy/admin.sock mode 660 level admin expose-fd listeners stats socket ipv4@0.0.0.0:9999 level admin stats timeout 30s user haproxy group haproxy daemon defaults log global mode http option dontlognull option redispatch retries 3 timeout http-request 50s timeout connect 5s timeout check 5s timeout client 50s timeout server 50s frontend fe_web bind *:80 stats uri /haproxy?stats capture request header Host len 64 acl IS_V2 path_beg /api/v2 use_backend … -
Django - Managing messages strings by one single file
I'm currently experiencing that my application has become quite large and I'm handling a lot of diffrent messages at my views.py. I have to manually set every message string I return to my user at the specific view. Now my idea was to manage all potential messages my application returns to the user e.g. a error or a sucssess message by only one single file, so that i dont have to set the same message strings three or four times for basically the same thing ... Example - current state: if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC: messages.error(request, 'You have reached the maximum amount of Magic.') return redirect('magic') Example - Wanted state from app_messages import xyz # These containing the actual string that should get returned to the user if example.objects.filter(author=request.user, status='Magic').count() >= config.USER_MAX_MAGIC: messages.error(request, xyz) return redirect('magic') My question now is: How does xyz has to look like and is this in general a good idea to accomplish a management of error, success, info etc. messages like that? Thanks in advance -
What is the best way for Django microservices intercommunication?
I have a django microservice: M1 with admin page having fields: [link to field11] | [link to field 21] I have another django microservice: M2 with admin page having fields: field11 | field12 | field13 | field14 | field 15 I have another django microservice: M3 with admin page having fields: field21 | field22 | field23 | field24 | field 25 My requirement is to get all the fields of M2 and M3 into M1's admin page. What are the ways I can do this? I do not want to add more fields into M1's model. One way is to do interservice communication or do a GET call. What will be more feasible? -
About parametrizing base template page in Django
I have the following problem, there is a base template "base.html" which defines default header and body information, which will be used by other pages. base.html <!DOCTYPE html> <head> ... {% block head_stuff %} {% endblock %} ... </head> <body> ... <p>Parameter that depends on the request time in a non trivial way</p> ... {% block body_stuff %} {% endblock %} ... </body> </html> The pages that use it look like: a.html b.html c.html <!DOCTYPE html> {% extends "base.html" %} {% block head_stuff %} ... {% endblock %} {% block body_stuff %} ... {% endblock %} </html> What I'd like to do is to render a.html, b.html, c.html without passing informations about that parameter. In absence of inheritance, one would call render function by passing the parameter to a context, but in this case no views are used to construct the base.html. How can I approach this problem? -
mommy Recipe with OneToOne
I am using model_mommy with Django to create test objects. I want to implement Recipe functionality. I have a model "Teacher" and a model "TeacherSchedule": Teacher(models.Model): some fields ... TeacherSchedule(models.Model): teacher = models.OneToOneField( 'Teacher', on_delete=models.CASCADE, related_name='schedule', ) some fields... The Recipe I try to use then: schedule = Recipe( TeacherSchedule, ) teacher_with_schedule = Recipe( Teacher, schedule=foreign_key('schedule'), ) However, when I run my tests, it seems that the TeacherSchedule object is not created. Am I doing something wrong with the Recipe? -
i have added custom field to list_display but when add that field list_editable in django admin i get error:adminE121
i have a method on model admin class that get data of reverse relation field on list_display but when i add that field in list_editable as well i get an error <class 'app.admin.CustomerAdmin'>: (admin.E121) The value of 'list_editable[2]' refers to 'box_status', which is not an attribute of 'app.Customer'. these is model admin class @admin.register(Customer) class CustomerAdmin(AbstractModelAdmin): class Media: list_display = ['name', 'email', 'phone', 'stylist', 'box_schedule', 'drop_off_step', 'box_status', 'age''created_at', 'payment_status'] list_display_links = ('name', 'email') search_fields = ['name', 'email', 'id'] list_editable = ['stylist', 'payment_status', 'box_status'] below is my box_status method that is getting from related model field. def box_status(self, obj): det = list(obj.box.values_list('box_status', flat=True)) return det this works in list_display but system error in list_editable. -
django-modeltranslation - Django model get() SQL SELECT does not fetch translated fields
I use django-modeltranslation to translate some model fields to Dutch (nl) and French (fr). Now, all has been working fine except for one model: @register(Association) class AssociationTranslationOptions(TranslationOptions): fields = ( 'title', 'name', 'description', ) In the database, I can see the three fields with their translated equivalents: title, title_nl, title_fr, name, name_nl, name_fr, description, description_nl and description_fr. When I update these translated fields in django admin, or in the shell, they are saved correctly. The problem occurs when I fetch this data from the database. So if I fetch this data with Association.objects.all(), Association.objects.get(id=1), or just look at it in the django admin detail view, I see for each translated field the default data. When I inspect the SQL query that Django executed, I see this strange query: SELECT "member_association"."id", "member_association"."title", "member_association"."title", "member_association"."title", "member_association"."slug", "member_association"."name", "member_association"."name", "member_association"."name", "member_association"."description", "member_association"."description", "member_association"."description", "member_association"."mollie_api_key_test", "member_association"."mollie_api_key_live", "member_association"."mollie_profile_id", "member_association"."bank_account_number", "member_association"."created", "member_association"."last_modified" FROM "member_association" WHERE "member_association"."id" = '2' As you can see, there is three times title, three times name and three times description, without the language suffix. So for updating this model, django-modeltranslation works great but for fetching translated data from the database, it does not work for only one of my created models: # … -
How to pass variables from html file to any python file like file.py in Django?
I have a project in Django. And i have a form named report.html. This form has got fields that users enters date ranges. The form is shown below. This is a form that allows users to select date ranges So the project has got a model named sentiment.py this model takes sentiments from the database and analyses them the comments are filtered with date ranges . Below is the code of the file `# Main function def main(): print('Loading the Classifier, please wait....') classifier = joblib.load('svmClassifier.pkl') print('READY') context = { 'posts': Post.objects.filter(date_posted__gte=date(2020,1,1)).filter(date_posted__lte=date(2020,12,31)) } comment=str(context) print(predict(comment, classifier)) if __name__ == '__main__': main() ` instead of using static values like in the code, I need to input a variable that contains values that users punch on the report.html form. So i have tried taking the values from the views.py file shown below.. `def repos(request): wanted_dates = { "datemax" : request.POST.get('datemax',None), "datemin" : request.POST.get('datemin',None) , } return render(request, 'sentiment_analysis/report.html') ` so i have tried to call the variables datemax and datemin from sentiment.py after importing the views.py in sentiment.py Please help me guys on how i can achieve this -
Dajngo generate bar code and download via browser
I am able to generate the bar code and save the image file in the root folder using this library python-barcode. Now I am trying to generate the bar code image and download via browser as HttpResponse Here is my tryouts, import barcode from django.http import HttpResponse def download_bar_code(request): ean = barcode.get('upc', '123456789102', writer=ImageWriter()) ean.save('filename') image = ean.render() # Returns PIL image class # <PIL.Image.Image image mode=RGB size=523x280 at 0x7FAE2B471320> return HttpResponse(image, content_type="image/png") Here the image file is saving in the root folder, but not downloading via browser. I am not able to find the solution for this, I request you to please suggest me some solution to solve this, it will be very grateful for me. Thanks in advance. -
Having trouble with creating env variables that take affect while running my server
this is my first question here, so although I'll try my best to ask the question correctly, please have patience with me. I'm trying to run an OCR with Tesseract with Django on my server at some server (pythonanywhere, if it's important in any way), but I keep having this error: pytesseract.pytesseract.TesseractError: (1, 'Tesseract Open Source OCR Engine v3.04.01 with Leptonica Error opening data file /usr/share/tesseract-ocr/tessdata/heb.traineddata Please make sure the TESSDATA_PREFIX environment variable is set to the parent directory of your "tessdata" directory. Failed loading language \'heb\' Tesseract couldn\'t load any languages! Could not initialize tesseract.') So, at first, I thought I could just move the correct "tessdata" file (which exists on my server) into /usr/share/bin... but I couldn't do that without a root user. no matter what I tried in the Bash shell, I don't have access to the root user (although I was never asked to implement one). I cannot use the "sudo" command that I see so often, I guess it's because it's not a valid command in Bash shell (or Unix, I'm not sure how to refer to it). I guess I have a root user named "Orikle", but no matter what, I couldn't manage to … -
Django Model - ManyToManyField restrict select multiple items from same category
I want to restrict selecting two items from same category and to be able to limit the number of selected items. exemple models.py class Category(models.Model): item_categ = models.CharField() class Product(models.Model): item = models.CharField() item_categ = models.ForeignKey(Category) class CombineProducts(models.Model): combined = models.ManyToManyField(Product) I want User to not be able to select two items from with the same item_categ and limit to 3 products How i do that? Thanks -
What is the difference between Django-Q and Celery?
In the process of researching task queues for Django I encountered the problem - what is the difference between Django-Q and Celery? I know a bit that Django-Q is especially designed to work with Django and Celery is standard goto tool for big projects. I read comments of the Django-Q author but didn't find smth that is not present in both tools in one or other way. I want to know what is the main differences between these two. -
Ignore POST value from admin inline
in django i have inlineadmin with some checkboxes, i want one of them to be ignored from saving if some condition applies. I tried modifying request.POST['mykey'] or form.data['mykey'] in save_model() of main class with request.POST._mutable = True, but django save all anyway and for form.data it say is immutable. I know i can set value for obj.mykey but how to save others and ignore one? Many many thanks to all. -
How to fix error “ERROR: Command errored out with exit status 1: python.” when trying to install djangorestframework-extensions using pip
I am trying to install djangorestframework-extensions using the command: pip install djangorestframework-extensions and it shows the error: ERROR: Command errored out with exit status 1: command: /home/anamaria/workspace/licenta/AllFest2/festivals/venv/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py'"'"'; __file__='"'"'/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-install-r9q6vdlo/djangorestframework-extensions/pip-egg-info cwd: /tmp/pip-install-r9q6vdlo/djangorestframework-extensions/ Complete output (6 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-install-r9q6vdlo/djangorestframework-extensions/setup.py", line 48 print "You probably want to also tag the version now:" ^ SyntaxError: Missing parentheses in call to 'print'. Did you mean print("You probably want to also tag the version now:")? ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. What should i do? -
User Model Customisation in Django
I want to edit the User Model in admin.py but I am not able to figure out how can I do this? Here is the Image of Admin Panel of User Model Can someone please help me? I want to add some customized fields in the User model. -
Why doesn't Django 1.7+ Migrations generate meaningful names for migration files unlike South did?
Django South used to give the migration files meaningful names by default. Example from official docs, see the file name describing what the migration is actually doing: $ ./manage.py schemamigration southtut --auto + Added field dances_whenever_able on southtut.Knight Created 0002_auto__add_field_knight_dances_whenever_able.py. You can now apply this migration with: ./manage.py migrate southtut For the contrast, modern day Django built-in Migrations mechanism generates pretty boring names like 0003_auto_20200303_1439.py. As far as I know, both South and Django Migrations system were written by the same people. Does anyone know how or why that nice feature was removed/not reimplemented? For the clarity: I'm aware that in both cases it's possible to provide the desired name manually. That's not the topic of this question. The question is about the difference in the default behavior of the two tools. -
Why my django group permissions are not working?
I added some permission in django view like this.Later I assigned some user some group (which has this permission) but some unknown reason the user is not being able to process that view even if the user has this group. What might be the reason for this ? @permission_required('dashboard.can_do_something', raise_exception=True) def some_view(..).. -
DjangoFilterConnectionField filter_fields matching dictionary saved as string in database table
So to put things in perpective, I am relatively new to django not to python Have a django app where a DjangoFilterConnectionField is passed a DjangoObjectType in class Query In this app is class ptype(DjangoObjectType): class Meta: model = tablename interfaces = (Node,) filter_fields = { 'project': ('exact', 'in',), 'app': ('exact', 'in',), 'package': ('exact', 'in',) 'extra': ...... } . . . This reads fields from 'tablename' where project, app, package and extra are CharField Question is, extra in db table is stored in dictionary form but as a string extra_filter = "{context2: b, context1:a}", ( from db table ) as seen, extra filter is a string, so being a text there is no order when matching 'extra' field from db tablename and dictionary extra_filter = {'context1': 'a', 'context2':'b'} What should come here, 'extra': ..... , so that a dictionary matches an entry from table, which has dictionary saved as string "{context2: b, context1:a}" so that irrespective of order a match is successful when it is favorable ? -
docker-compose up error for django and mysql
I am trying to configure Django and MySql application with Docker containers. For Django I am using python:3.7-slim image and for MySql mysql:5.6. When I run docker-compose up it returns an error stated below - ERROR: for app_mysql_db_1 Cannot start service mysql_db: driver failed programming external connectivity on endpoint app_mysql_db_1 (c647d4793a198af2c09cc52d08191fb2cd984025ad0a61434ad1577d9dcccebe): Error starting userland proxy: listen tcp 0.0.0.0:3306: bind: address already in use I run command docker ps -a to check docker status and found that mysql container was created but the python container status was exited. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7d91795e0bae mysql:5.6 "docker-entrypoint.s…" 15 seconds ago Created app_mysql_db_1 fa0419ad0f21 e0bf94710555 "/bin/sh -c 'adduser…" 2 minutes ago Exited (1) 2 minutes ago pedantic_faraday can someone rewrite or suggest the modification for the configurations. Dockerfile FROM python:3.7-slim ENV PYTHONUNBUFFERED 1 RUN apt-get update RUN apt-get install python3-dev default-libmysqlclient-dev gcc -y COPY ./requirements.txt /requirements.txt RUN pip install -r /requirements.txt RUN mkdir /app WORKDIR /app COPY . /app docker-compose.yaml version: "3" services: eitan-application: restart: always build: context: . ports: - "8000:8000" volumes: - ./eitan:/app command: > sh -c "python3 manage.py runserver 0.0.0.0:8000 && python3 manage.py makemigrations && python3 manage.py migrate" depends_on: - mysql_db mysql_db: image: mysql:5.6 command: mysqld --default-authentication-plugin=mysql_native_password … -
How to add a day to date field value in Django views
I have the following code: my_date = request.POST.get('to_date') to_date = datetime.strptime(my_date,"%Y-%m-%d") + timedelta(days=1) This however gives me an error: strptime() argument 1 must be str, not datetime.datetime. So I tried this: my_date = request.POST.get('to_date') to_date = my_date + timedelta(days=1) This treats the my_date value as a string and gives the error: can only concatenate str (not "datetime.timedelta") to str. If I print type(my_date) it says <class 'str'>. Can someone please advise on how to handle this? -
Django queryset to filter objects with identical manytomany field
I've got a model like this. class Component(models.Model): options = models.ManyToManyField('prices.Option') period = models.IntegerField() I need to select all components with same period and same options as one component cmp. This queryset doesn't work. similar_components = Component.objects.filter(period=cmp.period, options=cmp.options) I can't find a way to make a queryset baset on this manytomany field options. -
cleaned_data() returns empty objects, when I try to upload multiple images in Django
models.py: class Object(PolymorphicModel): author = models.ForeignKey(ProfileUser, on_delete=models.CASCADE) title = models.CharField(max_length=300) city = models.ForeignKey(City, on_delete=models.CASCADE) address = models.CharField(max_length=300) phone = models.CharField(max_length=20, default='') email = models.CharField(max_length=100, default='') site = models.CharField(max_length=100, default='') facebook = models.CharField(max_length=100, default='') instagram = models.CharField(max_length=100, default='') content = models.TextField() rating = models.DecimalField(default=10.0, max_digits=5, decimal_places=2) created_date = models.DateTimeField(default=timezone.now) approved_object = models.BooleanField(default=False) admin_seen = models.BooleanField(default=False) def __str__(self): return f"{self.title}" class Restaurant(Object): seats = models.IntegerField() bulgarian_kitchen = models.BooleanField(default=False) italian_kitchen = models.BooleanField(default=False) french_kitchen = models.BooleanField(default=False) category_en_name = models.CharField(max_length=100, default='restaurants') category_bg_name = models.CharField(max_length=100, default='Ресторанти') bg_name = models.CharField(max_length=100, default='Ресторант') is_garden = models.BooleanField(default=False) is_playground = models.BooleanField(default=False) class Images(models.Model): object = models.ForeignKey(Object, default=None, on_delete=models.CASCADE) image = models.ImageField(upload_to='attachments', verbose_name='Image') forms.py: class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = [ 'title', 'content', 'city', 'address', 'phone', 'email', 'site', 'facebook', 'instagram', 'seats', 'bulgarian_kitchen', 'italian_kitchen', 'french_kitchen', 'is_garden', 'is_playground' ] class ImageForm(forms.ModelForm): image = forms.ImageField(label='Снимка') class Meta: model = Images fields = [ 'image' ] template (html): <form method="post" id="dialog_addObject_part"> {% csrf_token %} {% for hidden in postForm.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="fieldWrapper"> <div class="errorcode{{field.html_name}}"> {{ field.errors }} </div> {{ field.label_tag }} {{ field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} {{ formset.management_form … -
Django:how to set pagination as per user selected set?
Django:how to set pagination as per user selected set?