Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django : nombre de choice field dynamique et pas fixe
Bonjour, Alors voila je fait un formulaire dans django et j'aimerais pouvoir faire une commande d'articles. Je ne sais pas à l'avance combien d'articles l'utilisateur va vouloir, exemple N articles. Je ne sais pas du tout comment dynamiquement les déclarer dans le form pour que plusieurs case s'affiche. En gros pour l'url articles/5/ je voudrais que 5 forms.MultipleChoiceField apparaissent, pour artciles/7/ il y en ai 7. Je sais deja comment récuperer N en fonction de l'url, mais je sais pas les déclarer. J'ai essayer une list mais rien ne s'affiche dans mon site on dirait que ca ne marche pas. Mon code dans forms est : class ArticlesForm(forms.Form): article = [] def NumArticles(self, nbArticles): self.nbArticles = nbArticles MyProp = ((1, 'Item title 1'), (2, 'Item title 2'), (3, 'Item title 3'), (4, 'Item title 4'), (5, 'Item title 5')) for i in range(nbArticles): self.article.append(forms.MultipleChoiceField(choices = MyProp)) nom = forms.CharField(max_length=100) Ici y'a un charfield nom qui s'affiche, mais la list article semble toujours vide, quand je l'appel je fait form = ArticlesForm(request.POST or None) form.NumArticles(nbArticles) Et normalement dans ma tete la list d'article est modifié mais il semble que non ? est-ce que quelqu'un à une idée de comment afficher dynamiquement … -
How to store upperbound to infinite DecimalRangeField
from django.contrib.postgres.fields import DecimalRangeField Django3 and Postgres11 I need to store inf in the DecimalRangeField() from django.contrib.postgres.fields import DecimalRangeField from psycopg2.extras import NumericRange class Premium(models.Model): sum_insured = DecimalRangeField() NumericRange with small number is work def test_range_field(self): Premium.objects.create( sum_insured=NumericRange(3, 12), ) self.assertEqual(1, Premium.objects.count()) Problem: Premium.objects.create( sum_insured=NumericRange(3, float('inf')) ) It raises error django.db.utils.ProgrammingError: syntax error at or near "Infinity" Question: How do I store the inf in the DecimalRangeField? -
function() got an unexpected keyword argument 'name1'
I am keep getting this typeerror:fun() got unexpected keywar arg, can someone tell what is the issue. Thanks in advance def register(request): if request.method =='POST': nm=request.POST['nm'] email1=request.POST['email'] pass1=request.POST['pass1'] pass2=request.POST.get('pass2') num=request.POST['num'] if pass1==pass2: new=register(name1=nm,email=email1,password=pass1,phone=num) new.save() #message.success(request,"You are register Successfully!") print("User Register") else: return redirect('/register') else: return render(request,'register.html',) -
Django models error: ValueError: Field 'cat' expected a number but got '-'
i just add 2 models to my class and i got this error: ValueError: Field 'cat' expected a number but got '-'. my code: # Create your models here. class News(models.Model): title = models.CharField(default=',', max_length=50) name = models.CharField(default=',', max_length=50) short_txt = models.TextField() body_txt = models.TextField() date = models.CharField(default=',', max_length=12) writer = models.CharField(max_length=50) catname = models.CharField(max_length=20, default='-') catid = models.IntegerField(max_length=10, default=0) def __str__(self): return self.name I had a cat model, but I removed it before... Thank you for your time<3 -
Django custom authentication using an external API endpoint
I have an API endpoint from my company that takes username and password and returns 200 response if the user is authenticated. The response body has all details about the user like user_id, name etc. Another endpoint allows a GET request with user_id as a parameter and tells if user is authenticated. For login: I use the first endpoint with POST request to check response code and also set user_id in my session so that i can later use this user_id to send a GET request to see if user is still authenticated. How can I use this in combination of login_required decorator to make sure user is authenticated for all the views in my application? Or is there any other way I can customize middleware.py for this functionality? -
get_initial() function simplification
I am populating a form with instance objects of another model like this: class ProcessingCreate(generic.CreateView): model = ProcessingActivityInstance template_name = 'dpapp/processing-create.html' fields = '__all__' def get_initial(self): initial = super(ProcessingCreate, self).get_initial() initial.update({'processing_toptype': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_type': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_description': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_purpose': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_category': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_legalbasis': ProcessingActivity.objects.get(id=self.kwargs['pk']), 'processing_retention': ProcessingActivity.objects.get(id=self.kwargs['pk']), }) return initial This code works but I suspect there is a cleaner way to reach the same result and I don't find it. Could someone enlighten me please? Thank you very much ! -
Best Way To Manage Model Instances Based On Attributes In Django Admin
Lets say I have a model: class Applicant(models.Model): name = models.CharField() status = Models.CharField(choices=Choices) Lets say Choices gives the choices of Reviewed, Rejected, Accepted. I want to be able to declare a choice for an instance in the admin panel, and once I save the choice, the instance is moved to another section, preferably another admin folder such as Reviewed Applicants, Rejected Applicant, etc etc. Whats the best way to achieve this? Thank you -
Cron jobs from DB in Django
I have some DB records like class Rules(models.Model): server = models.ForeignKey(Servers, on_delete=models.CASCADE) rule_text = models.CharField(max_length=2000) i.e. some rules, linked with server. Each rule is a crontab string like 0 9-17/2 * * 1-5 I want to call server_stop(server) and server_start(server) basing on all the rules, I have in DB (and add/edit/delete rules) Is it possible? -
Django serializer not returning all fields in response
I have following serializer in Django. The serializer is however not returning all the fields in the response. 'amount' and 'amount_ordered' are not returned, all other fields are.. key point: these are the only 2 fields I have in my model. So I thought I only need to add them in the fields list? class AdminOrderItemSerializer(serializers.Serializer): purchase_order = serializers.CharField(source="get_purchase_order") reference = serializers.CharField(source="get_reference") class Meta: model = OrderItem fields = [ "purchase_order", "reference", "amount", "amount_ordered", ] def create(self, validated_data): pass def update(self, instance, validated_data): pass Model: class OrderItem(models.Model): ordered_amount = models.IntegerField(validators=[MinValueValidator(0)]) amount = models.IntegerField(default=0) order = models.ForeignKey( Order, on_delete=models.CASCADE, related_name="order_items" ) def get_purchase_order(self): return self.order.purchase_order def get_reference(self): return self.order.reference -
Is it possible to add permission to a group given by the admin to see this view?
I have a problem with adding permission for a group of users ('judges') and I would like to ask if there is any possibility to add such a decorator enter image description here enter image description here -
How to run a python script in the background django
I have a python script (ml.py)that generates some data. I want it to run it in the background daily at 1 AM. How to achieve that ? I tried installing django-background-tasks and created the following files tasks.py from background_task import background @background(schedule=1) def hello(): execute('./scripts/ml.py') hello(repeat=Task.Daily) In the shell, I executed the following command: python manage.py process_tasks Now I get an error saying that the name execute is not defined My other questions are : Do I have to write the command python manage.py process_tasks everyday ? Can I exit out of the command window and does the process still run everyday ? -
Django radio buttons appearing as bullet point list, inside mark_safe()
Background I have used 'mark_safe()' inside a form in order to display bullet points in my form label: class FormFood(forms.Form): CHOICES = [ (1,'Yes'), (2, 'No')] response = forms.ChoiceField(widget=forms.RadioSelect, label=mark_safe("Do you like any of these foods? <ul><li>Pasta</li><li>Rice</li><li>Cheese</li><</ul>"), choices=CHOICES) This outputs as: The problem As you can see above, bullet points are now also appearing next to 'Yes' and 'No' despite me not wanting this. Inspecting the elementing reveals that this is because they are also structured inside an unordered list tag (somehow?): <form method="POST"> <label for="id_response_0">Do you like any of these foods? <ul> <li>Pasta</li> <li>Rice</li> <li>Cheese</li> </ul> </label> <ul id="id_response"> <li> <label for="id_response_0"> <input type="radio" name="response" value="1" required="" id="id_response_0"> Yes </label> </li> <li> <label for="id_response_1"> <input type="radio" name="response" value="2" required="" id="id_response_1"> No </label> </li> </ul> <input type="hidden" name="csrfmiddlewaretoken" value="FaOTY4WlVLFMl3gNtut8BJihJKub1Is0wRJRxxLck1e2eJocJVXRiGoOLDr9jdvx"> <input type="submit"> </form> Is there a way I could stop this and just maintain the bullet points on the 'Pasta', 'Rice' and 'Cheese' whilst removing the bullet points/ list from 'Yes' and 'No'? -
IndexError: pop from empty list Django Rest Framework
I have an existing object but I want to create an object in the nested serializer, unfortunately, I am getting an error while creating object. What I have done so far here: class AppealSerializer(serializers.ModelSerializer): resolutions = ResolutionSerializer(many=True, allow_null=True, required=False) class Meta: model = Appeal fields = ['id', 'appeal_unique_id', 'short_name', 'category', 'dept', 'state', 'appeal_desc', 'location', 'address', 'created_at', 'updated_at', 'resolutions', 'user'] def update(self, instance, validated_data): bp_data = validated_data.pop('resolutions', []) bps = (instance.resolutions).all() bps = list(bps) instance.state = validated_data['state'] instance.save() for b_p in bp_data: bp = bps.pop(0) bp.user = b_p.get('user', bp.user) bp.comment = b_p.get('comment', bp.comment) bp.is_read = b_p.get('is_read', bp.is_read) bp.save() return instance here I am going to create many to one object by updating an existing object. with this code, in another project, I can cope with it but it does not work for this project. please if anything is not clear let me know I will try to explain in more detail. The keyword is to create an object by updating an existing object. Thanks in advance -
Tell Django tests.py to use fixture instead of actual database
I need to test my database without adding or deleting elements. For this I have created a fixture. Loading the fixture seems to be fine, at least it is not giving any errors. Now, how do I tell the test functions to interact with the test database instead of the real database. Also, how do I propagate this infomration to the functions that are being tested? This is my current code: """Module to test upload app.""" import os import wave from django.test import TestCase, Client from django.urls import reverse, resolve from equestria.settings import BASE_DIR from .views import UploadProjectView from .models import File from django.core.management import call_command from scripts.models import Project from django.core.files.uploadedfile import SimpleUploadedFile class TestUpload(TestCase): """Test the upload app.""" fixtures = ['equestria/upload/db.json'] def setUp(self): self.project = Project.objects.all()[0] self.url = reverse('upload:upload_project', args=[self.project]) self.client = Client() def test_upload_url_resolves(self): self.assertEquals( resolve( self.url ).func.view_class, UploadProjectView) def test_redirect_before_auth(self): response = self.client.get(self.url, follow = True) redir_url = response.redirect_chain[0][0] redir_code = response.redirect_chain[0][1] self.assertRedirects(response,'/accounts/login/?next=/upload/1',status_code=302, target_status_code=200) self.assertEqual(redir_code, 302) self.assertEqual(redir_url, '/accounts/login/?next=/upload/1') def test_valid_file_ext_upload(self): self.client.login(username='test', password='secret') initial_files = len(File.objects.all()) audio_file = wave.open(os.path.join(BASE_DIR, "upload/test_files/test.wav"), "rb") data = { 'f':audio_file } response = self.client.post(self.url, data, format='multipart') current_files = len(File.objects.all()) print(initial_files) print(current_files) self.assertEqual(initial_files + 1, current_files) self.assertEqual(response.status_code, 200) All tests run just fine … -
Django form : how to get data in a ManyToMany field?
My objective is to implement the same kind of features than in admin panel with a many to many relationship. Everything seem to work all right, but when I submit my form, I get some strange results: I'm probably missing something but I cannot fogure out what goes wrong. For now, when I add lines, everything is OK. Problems occur when I try to remove lines from the group. I'm taking about users, I have a first list of 'all users' and the second one will make a group. When I had a user, then remove another one, the form cannot be validated; the list is empty, the removed user "disappear" (it is not in the group list nor among "all users". If I remove one user, then add a new one, the only user in my form after validation is the one I added, all other ones are removed. I hope I'm clear, many thanks in advance for your advise. Here are the related code blocks. Models: class UserComp(models.Model): """ Link between users and companies Used to restrict display to companie(s) the users belong to """ user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name="Utilisateur") company = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name="Société") phone_regex = RegexValidator(regex=r'^0[0-9]([ … -
nginx docker container as reverse proxy for services running in docker containers
I have nginx running in a docker container which I want to use as reverse proxy for services running in docker containers. ATM I have two services, django and owncloud. Both services works when accessing them directory e.g. localhost:4000 and localhost:5000. When I'm accessing localhost/owncloud I get 502 Bad Gateway Nginx log: 2020-04-27T13:21:54.852082794Z 2020/04/27 13:21:54 [error] 6#6: *2 connect() failed (111: Connection refused) while connecting to upstream, client: 172.18.0.1, server: , request: "GET /owncloud/ HTTP/1.1", upstream: "http://172.18.0.4:4000/", host: "localhost" When I'm accessing localhost/django I get page not found from Django, which is fine, but I if I try to access localhost/django/admin I get page not found from Nginx. Nginx log: 2020-04-27T13:29:11.173933857Z 2020/04/27 13:29:11 [error] 6#6: *4 "/etc/nginx/html/sv/admin/index.html" is not found (2: No such file or directory), client: 172.18.0.1, server: , request: "GET /sv/admin/ HTTP/1.1", host: "localhost" I'm new to Nginx and have messed around with the nginx.conf a lot with no success. Here are the relevant files: /docker-compose.yml version: '3' networks: nginx-net: /nginx/docker-compose.yml version: '3' services: internal-nginx: build: context: ./nginx restart: unless-stopped image: web-nginx container_name: nginx ports: - "80:80" - "443:443" networks: - nginx-net depends_on: - internal-django - internal-owncloud /nginx/Dockerfile FROM nginx COPY nginx.conf /etc/nginx/nginx.conf COPY nginx.conf /etc/nginx/nginx-raw.conf RUN rm … -
How to create Django models from oracle table-synonyms using inspectdb command
I am using Oracle legacy database from which I am creating models using inspectdb command(inspectdb table_name) for existing tables. But this command is only working for tables and views not for table-synonym. Please correct me if I am wrong: There is no way to specify schema with table name as : [schema].[table_name] in Django framework. So, I found a solution on the given link How to access tables from a different schema in oracle 11g using django? I create private table-synonym in oracle db and use inspectdb [synonyme_name] command but unable to inspect the synonym. This command working fine for table and view but not for synonym. inspectdb WASTE2 error-screenshot -
How to display a spatial field on a map?
I have a spatial field in my Django model. I want to display this field on a map. How to do it? It works just fine in Django Admin with Django built-in OSMWidget and OpenLayers. If I try to access the spatial field in my template it is of this format: SRID=4326;GEOMETRYCOLLECTION (POLYGON ((54.57842969715517 23.34800720214843, 54.53144199643833 23.29547882080078, 54.52964902093564 23.38096618652343, 54.57444978782305 23.40499877929688, 54.57842969715517 23.34800720214843))) -
when I using celery with multiple processing , the notify signal can't be received by waiting thread
when I using celery with multiple processing , the notify signal can't be received by waiting thread. but when I run the code with script, it works normally. Whether the problem is caused by celery poor support for multithreading? Please give me a hint if you can resolve the problem, thank you! # tasks.py @shared_task(bind=True) def long_time_def(self, *args, **kwargs): tp = ThreadPool(5) tp.set_tasks(pv.check_position_effective, list(args)) res = tp.final_results() while len(res) < len(args): print(res) return 'finished' # ../public/tools.py class ThreadPool: def __init__(self, max_thread_num=5): self.over = False self.results = [] self.func = None self.args_list = None self.task_num = 0 self.max_thread_num = max_thread_num self.pool = ThreadPoolExecutor(max_workers=max_thread_num) self.cond = threading.Condition() def set_tasks(self, func, args_list): self.task_num = len(args_list) self.args_list = args_list self.func = func def get_result(self, future): self.results.append(future.result()) if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: print("result:%s"%self.results) while self.task_num != len(self.results): print(self.results) time.sleep(1) print('\n', 'finish') self.cond.acquire() ############ this place ############ self.cond.notify() ############ this place ############ self.cond.release() return def _start_tasks(self): for i in range(self.max_thread_num): if len(self.args_list): args = self.args_list.pop() task = self.pool.submit(self.func, *args) task.add_done_callback(self.get_result) else: break def final_results(self): self._start_tasks() if self.task_num == len(self.results): return self.results else: # print("main locked") # self.cond.acquire() ############ this place ############ print("main waiting") self.cond.wait() ############ this place ############ # print("main … -
Django application page not showing when deploying to pythonanywhere.com
My application works perfect when run locally on my mac os, but when it is deployed to pythonanywhere (and also on my partners windows os laptop) one of the pages just shows the html code instead of the actual page as shown below: I dont know what the problem is as it runs locally fine. Here is my html page: ''' {% extends "base2.html" %} {% load static %} {% block content %} <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/home/"><img src="{% static 'img/maplogbook1.png' %}" class="rounded mx-auto d-block" alt=""></a> </div> </div> </div> </header> <header class="masthead"> <div class="overlay"></div> <div class="container my-4"> <div class="border border-light p-3 mb-4"> <div class="text-center"> <a href="/logbook/create/" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a> <a href="/logbook/learner/" class="btn btn-lg btn-dark text-warning">New Post - Learner Driver &rarr;</a> </div> </div> </div> </header> <div class="container"> <div class="row justify-content-center"> <div class="col-md-8 mt-3"> {% for post in posts %} <div class="card mb-4"> <div class="card-body"> <div class="container p-3 my-3 bg-dark text-white"> <h2 class="card-title text-dark "> <a href="% url "logbook:detail" slug=post.slug %}" class="btn btn-lg btn-warning">New Post - Driving Instructor &rarr;</a>. </h2> <h2 class="card-title text-dark "><a href="{% url "logbook:detail" slug=post.slug %}">{{ post.title }}</a></h2> </div> <p class="card-text text-muted h6">{{ … -
Django 2.0.5 - Signature of method 'ContentCreateUpdateView.dispatch()' does not match signature of base method in class 'View'
I am learning Django and I am following a book project Django 2 by example. In one of there project "building an elearning site", the have the following code: class ContentCreateUpdateView(TemplateResponseMixin, View): module = None model = None obj = None template_name = 'courses/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: return apps.get_model(app_label='courses', model_name=model_name) return None def get_form(self, model, *args, **kwargs): Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({ 'form':form, 'object': self.obj }) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: Content.objects.create(module=self.module, item=obj) return redirect('module_content_list', self.module.id) return self.render_to_response({'form': form, 'object': self.obj }) But I am getting an error message from PyCharm (my IDE) on: def dispatch(self, request, module_id, model_name, id=None): And the error is: Signature of method 'ContentCreateUpdateView.dispatch()' does not match signature of base method in class 'View' less... (Ctrl+F1) This inspection detects inconsistencies in overriding method signatures. Is there … -
Dynamic inline CSS styling in Django template
I am new to Django and am trying to figure out how to use dynamic CSS that is only active for the current category a user is on. I have a side nav with some categories and whichever category the user is on should be active with the use of a class. This is currently how I have things: {% for category in categories %} <li><a href="{% url 'category' category.id %}" {% if category.id in request.path %} class="uk-text-bold" {% endif %} >{{ category.name }}</a></li> {% endif %} This is obviously not correct and doesn't work so I imagine there is a proper way to do something like this and I'm just having a hard time understanding or finding that out. Any help is appreciated! Thanks. -
How can I package a Django app with chocolatey?
I'd like to package a Django + SQLite + JS-Frontend app with chocolatey. Are there specifics to consider which are not obvious from the chocolatey docs? -
how to pass parameter from view to form #typedChoiceField #django
i'm new in django and I want to pass list_choices from view to forms Forms.py taille = forms.TypedChoiceField(choices=q) def __init__(self,*args,**kwargs): /* I don't now what I will do */``` **View.py** ``` tailles= Taille.objects.filter(valable=True) list= [(i.taille_name, str(i.taille_name)) for i in tailles] form = CartTailleForm(q=list)``` -
Optimum uwsgi configuration
I have a Django project configured with uwsgi and Nginx. The issue is that I am getting lot of 502 Bad gateway. The nginx error log says (104: Connection reset by peer) while reading response header from upstream. Looks like uwsgi is not able to give response for some of the requests. Below is my uwsgi configuration. Could the issue be due to the bad uwsgi configuration ? I have an ec2 t3.medium instance it has two vCPUs. These 502 gateways increase when the site load increases. Sometimes the processor is 100%, that is when the we get more of this error. I am thinking of upgrading the server to t3.xlarge which has 4 vCPUs. But how to make sure the issue is with the server performance ? Please check the uwsgi configuration and see if there is any issue with the configuration. [uwsgi] master = true socket = /tmp/uwsgi.sock chmod-socket = 666 chdir = <dir_path> wsgi-file = <wsgi.py path> processes = 16 threads = 8 cpu-affinity = 1 max-worker-lifetime = 3600 max-requests = 1000 reload-on-rss = 2048 worker-reload-mercy = 60 virtualenv = <ven_path> vacuum = true enable-threads = true daemonize= <log_path> stats= <stats_path> buffer-size = 65535