Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Bootstrap Progress Bar Not Loading Progression
I am trying to link the progress bar to my SQLite3 database column to show how far each individual has made it through the interview process. I've replaced the width with my column in my database that shows their step in the process (e.g. 1,2,3,4,5) but the bar shows blank for everyone. Why would this not work? pick_list.html <tr id="{{ pick.pk }}"> <td><img src="http://127.0.0.1:8000/media/files/{{ pick.photo }}" width="50"/></td> <td><a href="{% url 'app:lead-list' pick.pk %}" title="Leads">{{ pick.name }}</a></td> <td>{{ pick.hometown }}</td> <td>{{ pick.occupation }}</td> <td>{{ pick.age }}</td> <td> <div class="progress"> <div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="{{ pick.step }}"></div> </div> </td> <td style="text-align: center;"> <a href="" class="btn btn-sm border-0 reorder" title="Reorder"> <i class="fa fa-sort text-secondary"></i></a> </td> </tr> model class Pick(models.Model): name = models.CharField(max_length=50, verbose_name='Name', null=True, blank=True) photo = models.ImageField(upload_to="media", max_length=500, verbose_name='Photo', null=True, blank=True) hometown = models.CharField(max_length=50, verbose_name='Hometown', null=True, blank=True) age = models.IntegerField(verbose_name='Age', null=True, blank=True) step = models.IntegerField(verbose_name='Progress', null=True, blank=True) occupation = models.CharField(max_length=50, verbose_name='Occupation', null=True, blank=True) rank = OrderField(verbose_name='Rank', null=True, blank=True) def __str__(self): return self.name def get_fields(self): return [(field.verbose_name, field.value_from_object(self)) for field in self.__class__._meta.fields] def get_absolute_url(self): return reverse('app:pick-update', kwargs={'pk': self.pk}) class Meta: db_table = 'pick' ordering = ['rank'] verbose_name = 'Pick' verbose_name_plural = 'Picks' -
Django error the view didn't return an HttpResponse object. It returned None instead
For an ecommerce website trying to do this : When I click on order now button it should redirect to a payment url(the url takes a parameter order_id). But instead, I get "The view ecomapp.views.pay didn't return an HttpResponse object. It returned None instead." ERROR I know this question been asked before but none of the solutions have helped me solve the problem. Kindly help! views.py @login_required(login_url="/login") def checkout(request): form = CheckoutForm(request.POST or None) cart_id = request.session.get("cart_id", None) if cart_id: cart_obj = Cart.objects.get(id=cart_id) if form.is_valid(): form.instance.cart = cart_obj form.instance.subtotal = cart_obj.total form.instance.discount = 0 form.instance.total = cart_obj.total form.instance.order_status = "Order Received" del request.session['cart_id'] o = form.save() form = CheckoutForm() return redirect(reverse("pay") + "?o_id=" + str(o.id)) else: cart_obj = None return render(request, "checkout.html", {'cart': cart_obj, 'form': form}) pay def pay(request): o_id = request.GET.get("o_id") orderr = Order.objects.get(id=o_id) order_amount = orderr.total*100 order_currency = "INR" order = client.order.create( dict(amount=order_amount, currency=order_currency)) context = { 'order_id': order['id'], 'amount': order['amount'], 'key_id': key_id } return render(request, "pay.html", context) ERROR ValueError at /pay The view ecomapp.views.pay didn't return an HttpResponse object. It returned None instead. Request Method: GET Request URL: http://127.0.0.1:8000/pay?o_id=63 Django Version: 4.0.1 Exception Type: ValueError Exception Value: The view ecomapp.views.pay didn't return an HttpResponse object. It returned … -
Autocomplete for Django Textarea widget
Form: from django import forms class Form(models.ModelForm): query = forms.CharField(widget=forms.Textarea()) For query (sql) field I would like to implement autocomplete in admin. For example when user starts typing "sele" autocomplete suggests "select". I googled some but found solutions for pure js and no packages for Django. Maybe anyone here knows how to do this or can advise a package or a link? -
Multiple Themes with their own url.py and views.py in Django
I am trying to build a web-application in Django similar to WordPress. Where each theme folder will have it's own set of url.py, view.py, stylesheet etc. So far, I have been able to implement multiple themes, but all of theme rely on a single common url.py & views.py. Which gives less flexibility. Themes are placed inside a "Templates" folder on root. I want each theme to process and display data independently just like WordPress theme that has their own PHP scripts. Any help in achieving this will be highly appreciated. -
Content Security Policy: Couldn’t parse invalid host http://localhost/static/css
I am using Django with Nginx. My dev enviornment mirrors my prod environment. In development I go through Nginx to access Django in local dev (using docker-compose). Now I am working on making my website more robust security-wise as per Mozilla Observatory. My site it a B right now. The big thing I am working on next is getting the Content Security Policy (CSP) for my website configured. Not only do I want to get my site to an A because gamification, I also want to avoid having XSS attack planes. After some searching I found Django CSP which looks great. I installed it, added the middleware, and then add some CSP configuration in my settings.py like this: CSP_DEFAULT_SRC = ("'none'") CSP_FONT_SRC = ("https://fonts.gstatic.com") CSP_IMG_SRC = ("'self'", "https://www.google-analytics.com") CSP_SCRIPT_SRC = ( "'self'", "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js", "https://code.jquery.com/jquery-3.2.1.slim.min.js", "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js", "https://www.google-analytics.com/analytics.js", "https://www.googletagmanager.com/gtag/js", "https://www.googletagmanager.com/gtm.js;", ) CSP_STYLE_SRC = ( "'self'", "https://fonts.googleapis.com/", "https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/", ) I fire up my website in local dev and I see this error message in Firefox dev tools: Content Security Policy: Couldn’t parse invalid host 'http://localhost/static/css/ Why is localhost invalid? Is it that CSPs do not really work in development? I'd really prefer not to "test my CSP code live" in production if I … -
Django Startapp What is the difference between a django-admin startapp and python3 manage.py startapp?
Can someone explain why we use manage.py startapp over django-admin startapp? I was watching the CS50 Django tutorial on youtube and he does it with the manage.py but I was trying to work from memory(practicing) and i used the django-admin startapp and it worked and created the files just fine. Just wondering if i should just delete the thing and recreate it with manage.py or it's all the same. Thank you! -
Django/ HTML image is breaking and size of image is not ok
hi all, I am developing locally Django site, seems I have two issues here: One picture on top is like 4 times smaller that original picture, original is size 610x 150px. I would like to have my picture on page same size as original, how I can do it? Picture below" About us" seems has no gap on right side, on left side you can see gap between picture and square. Also this is working fine on full screen but when I make page smaller above mentioned happens. Do you know reason? base.html: <!DOCTYPE html> <html> <head> <title>Django Central</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Tangerine"> <meta name="google" content="notranslate" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> </head> <body> <style> body { font-family: "Tangerine", serif; font-size: 37; background-color: #fdfdfd; } .shadow { box-shadow: 0 4px 2px -2px rgba(0, 0, 0, 0.1); } .btn-danger { color: #fff; background-color: #f00000; border-color: #dc281e; } .masthead { background: #3398E1; height: auto; padding-bottom: 15px; box-shadow: 0 16px 48px #E3E7EB; padding-top: 10px; } img { width: 610px; height: 150px; object-fit: contain; </style> {% load static %} <center> <img src="{% static 'blog/moj.png' %}" alt="My image"> </center> <!-- Navigation --> <nav class="navbar navbar-expand-sm navbar-light bg-light shadow" id="mainNav"> <div … -
Updating data in a model from views Djnago
Hi i have a problem with updating data which is stored in a model. I would like to update the data which is stored in a model without a form, it is a function which sums up every user transaction and after every change I would like it to update. my models: class Portfolio(models.Model): portfolio_id = models.AutoField(primary_key=True,blank=True) portfolio_title = models.CharField(unique=True,max_length=200, null=True,blank=True) user_name = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL,blank=True) p_shares_num_sum = models.DecimalField(decimal_places=2,default=0,max_digits=999,editable=True, null=True,blank=True) p_last_mod_date = models.DateField(auto_now_add=False,null=True,editable=True,blank=True) p_comp_num_sum = models.DecimalField(decimal_places=2,default=0,max_digits=999,editable=True, null=True,blank=True) p_to_buy_percentage = models.CharField(max_length=200,editable=True, null=True,blank=True) p_profit_earned = models.DecimalField(decimal_places=6,editable=True,default=0,max_digits=999, null=True,blank=True) def __str__(self): return self.portfolio_title if self.portfolio_title else '' ``` The data which I want to send to it after every entry on site summary_data = [int(shares_num_sum),int(comp_number),mod_date,str(to_buy_percentage),float(profit_earned)] The function is written and prints me: [4, 2, datetime.date(2021, 12, 20), '100%', 0.9] -
How to return an error message when denying the connection with django-channels?
I've set up django-channels along with an endpoint to handle web socket connection, however, I'm stuck on the part of how to return an error message/error code when the connection is denied? For example, if a user does not have the sufficient permissions, I don't want to accept the connection and want to return the reason of why is that. -
Deleting via id from MongoDB in an Angular-Django app
I have written the following code to delete specific customers from a MongoDB collection: Angular service: deletepost(id: number): Observable<Post> { const url = `${this.baseApiUrl}` + `/handle_post/` + id; return this.httpClient.delete<Post>(url) .pipe( retry(3), catchError(this.handleError) ); } Django view: @csrf_exempt @api_view(['GET', 'DELETE', 'PUT']) def handle_post_by_id(request, id): try: post = PostModel.objects.get(pk=id) except PostModel.DoesNotExist: exceptionError = { 'message': "Post with id = %s" %id, 'posts': "[]", 'error': "" } return JsonResponse(exceptionError, status=status.HTTP_404_NOT_FOUND) if request.method == 'DELETE': try: post.delete() posts_serializer = PostModelSerializer(post) return HttpResponse(status=status.HTTP_204_NO_CONTENT) except: exceptionError = { 'message': "Cannot delete post!", 'posts': [posts_serializer.data], 'error': "" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) It never reaches this method that takes an id, but instead goes to the following method: @csrf_exempt @api_view(['GET', 'POST', 'DELETE', 'PUT']) def handle_post(request): if request.method == 'DELETE': try: PostModel.objects.all().delete() posts_collection.delete_many({}) return HttpResponse(status=status.HTTP_204_NO_CONTENT) except: exceptionError = { 'message': "Cannot delete successfully!", 'customers': "[]", 'error': "" } return JsonResponse(exceptionError, status=status.HTTP_500_INTERNAL_SERVER_ERROR) My URLs are as follows: urlpatterns = [ url(r'^handle_post/', handle_post), url(r'^handle_post/(?P<id>\d+)/$', handle_post_by_id), ] What am I doing wrong that when I try to delete a customer with id, it goes to the other method and deletes everyone? -
Heroku Django Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch
I am trying to add Tailwind to my Django web application, which has required be to install node.js. The application seems to build without error in Heroku how throws the following error when the dyno starts up: 2022-01-12T13:31:44.946174+00:00 app[web.1]: [heroku-exec] Starting 2022-01-12T13:32:43.574277+00:00 heroku[web.1]: Process exited with status 137 2022-01-12T13:32:43.700696+00:00 heroku[web.1]: State changed from starting to crashed 2022-01-12T13:32:43.126165+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch 2022-01-12T13:32:43.397665+00:00 heroku[web.1]: Stopping process with SIGKILL I followed the documentation at https://django-tailwind.readthedocs.io/en/latest/. It seems to working as expected in my local but is not working in a production environment when deployed to Heroku. I am adding both the heroku/nodejs and heroku/python Buildpacks. Procfile: web: gunicorn card_companion_v2.wsgi --log-file - package.json { "name": "theme", "version": "3.0.0", "description": "", "scripts": { "start": "npm run dev", "build": "npm run build:clean && npm run build:tailwind", "build:clean": "rimraf ../static/css/dist", "build:tailwind": "cross-env NODE_ENV=production tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css --minify", "sync": "browser-sync start --config bs.config.js", "dev:tailwind": "cross-env NODE_ENV=development tailwindcss --postcss -i ./src/styles.css -o ../static/css/dist/styles.css -w", "dev:sync": "run-p dev:tailwind sync", "dev": "nodemon -x \"npm run dev:sync\" -w tailwind.config.js -w postcss.config.js -w bs.config.js -e js", "tailwindcss": "node ./node_modules/tailwindcss/lib/cli.js" }, "keywords": [], "author": "", "license": … -
Django REST Framework with ForeignKey on_delete=models.PROTECT
when I try to delete Django model object that is ForeignKey in another model with option on_delete=models.PROTECT, the error returned is the normal Django 500 Exception HTML web page, how to make Django rest frame work return json response with the error, is there a way for DRF to do that by default or it should be customized? -
django subtracting one query from another
I have two identical models in django class Car(models.Model): brand = models.ForeignKey( 'Brand', on_delete=models.CASCADE, verbose_name="ID бренда") car_name = models.TextField(verbose_name="Авто") year = models.IntegerField(verbose_name="Год") price = models.PositiveIntegerField(verbose_name="Цена") power = models.FloatField(verbose_name="Мощность двигателя") engine_type = models.TextField(verbose_name="Тип двигателя") drive = models.TextField(verbose_name="Привод") transmission = models.TextField(verbose_name="КПП") mileage = models.FloatField(verbose_name="Пробег") city = models.TextField(verbose_name="Город") photo = models.URLField(verbose_name="Фото") url = models.URLField(verbose_name="Ссылка") vin = models.TextField(verbose_name="VIN") class Meta: verbose_name = "Машина" verbose_name_plural = "Машины" def __str__(self): return f'{self.brand}' and the same table Don't mind the Russian names, I couldn't find the answer in Russian new_cars_values.union(old_cars_values) I need to find the differences between the two tables, find what was added and what was removed. The first table stores old machine data, the second stores new machine data. To get the deleted machines I have to subtract the first from the second and the new machines from the first from the second. I tried using .union, but I have asynchronous parser and it always gives me different values and I can't compare the lists because they are always different. How to compare data in two tables regardless of their indexes? -
Search form input - Search "as you type" with HTML/Javascript
I have following search form in an HTML page on website built with Django: <form method="get"> <input class="form-control" type="text" name="q" id="id_q" placeholder="Search..."> </form> I would like it to perform a search while typing (not having to press enter). I know we could use onchange or onkeyup, but I don't seem to be able to make it work. The javascript at the bottom of the page is as follows: <script type="text/javascript"> document.getElementById("id_q").value = "{{query}}" </script> -
My ModelForm isn't getting auto-populated
In the update template my form isnt getting prepopulated however the functionality of updating is working fine. the form stays empty when i am trying to parse an instance of a specific ID My view.py : def update_component(request, pk): component = Component.objects.all() component_id = Component.objects.get(id=pk) form = ComponentModelForm(instance=component_id) if request.method == 'POST': form = ComponentModelForm(request.POST, instance=component_id) if form.is_valid(): form.save() return HttpResponseRedirect(request.path_info) context = { 'components': component, 'form': ComponentModelForm(), 'component_id':component_id, } return render(request, 'update_component.html', context) The form in template : <div> {% load widget_tweaks %} <form class="component-form-flex" method='POST' action=''> {% csrf_token %} <div style="width:50%;" > <br> <span class="component-label-text">Name</span> {% render_field form.name class="component-form" %} <span class="component-label-text">Manufacturer</span> {% render_field form.manufacturer class="component-form" %} <span class="component-label-text">Model</span> {% render_field form.model class="component-form" %} <span class="component-label-text">Serial Number</span> {% render_field form.serial_number class="component-form" %} <span class="component-label-text">Price</span> {% render_field form.price class="component-form" %} <span class="component-label-text">Note</span> {% render_field form.note class="component-form" %} {% render_field form.parent class="component-form" %} <input type="submit" class="form-submit-button" value='Update Component' /> </div> <div> <img class="maintenance-nav-list-img" src="{{ component_id.image.url }}" /> {% render_field form.image %} </div> </form> </div> urls.py : from django.urls import path from . import views appname = 'maintenance' urlpatterns = [ path('', views.index , name='maintenance'), path('<int:pk>/update/', views.update_component , name='update_component'), ] -
mach-o, but wrong architecture - psycopg2
I've set up my PostgreSQL database and running with Django, but I get the error mach-o, but wrong architecture. I'm on M1 Macbook Air. Info Platform: Django Database: PostgreSQL Virtual environement: conda settings.py database configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'pfcbookclub', 'USER': 'admin', 'PASSWORD': 'g&zy8Je!u', 'HOST': '127.0.0.1', 'PORT': '5432', } } Description This error occurs when I try to run python3 manage.py runserver. Error and stack trace Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 954, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in … -
Django JSONField Constraint
I have a model that represents an email, which was sent via my Provider X. Im getting a callback from X with data, that I would like to save in the field called additional_recipients. Because of some mailing list only allowing 5 max additional recipients, i need to limit the jsonfield to only contain max 5 emails per row class EmailCallback(models.Model): additional_recipients = models.JSONField(default=list) Is it possible, to limit the JsonField so it it only holds max 5 values? [{"value": "email1"}, {"value": "email2"}, {"value": "email3"}, {"value": "email4"}] I know i can do class Meta: constraints = [ CheckConstraint(...) ] But i was wondering if thats even doable? Using Django 3.2.8 :) -
Django testinng of models.py foreign key error
I am testing the testing the models.py file which contain two class one is Farm and another one is Batch and Batch has a foreign key related to farm while testing the batch I have tested all the other columns but not sure how should I test the foreign key column of batch class models.py file lopoks like class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) farm_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0.1)], help_text="In Percentage", null=True, blank=True) class Batch(models.Model): commodity_id = models.PositiveIntegerField(null=True, blank=True) commodity_variety_id = models.PositiveIntegerField(null=True, blank=True) farm_id = models.ForeignKey(Farm, on_delete=models.CASCADE, related_name="batches", null=True, blank=True, db_column='farm_id') start_date = models.DateTimeField(null=True, blank=True) acerage = models.FloatField(verbose_name='Batch Acerage', help_text="In Acres;To change this value go to farms>crop" , validators=[MaxValueValidator(1000000), MinValueValidator(0.01)]) batch_health = models.IntegerField(validators=[MaxValueValidator(100), MinValueValidator(0)], help_text="In Percentage", … -
django - How to auto-populate existing data in django form while updating
I want to auto populate my update form in django with the existing data, but instance=request.user and instance=request.user.profile seems not to be auto populating the form views.py def UserProfile(request, username): # user_profiles = Profile.objects.all() user = get_object_or_404(User, username=username) profile = Profile.objects.get(user=user) url_name = resolve(request.path).url_name context = { 'profile':profile, 'url_name':url_name, } return render(request, 'userauths/profile.html', context) @login_required def profile_update(request): info = Announcements.objects.filter(active=True) categories = Category.objects.all() user = request.user profile = get_object_or_404(Profile, user=user) if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile.user) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Acount Updated Successfully!') return redirect('profile', profile.user.username) else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form, } return render(request, 'userauths/profile_update.html', context) -
daemonizing celery worker and beat (environment variables problem or settings.py problem?)
I've been trying to daemonize celery and celerybeat using init scripts and systemd. The problem is that celery's tasks can't access rabbitmq and django database(postgresql in my case) because i moved my username and passwords to ~/.bashrc. for solving this problem celery documentation suggests: The daemonization script is configured by the file /etc/default/celeryd. This is a shell (sh) script where you can add environment variables like the configuration options below. To add real environment variables affecting the worker you must also export them (e.g., export DISPLAY=":0") Daemonization docs this gave me a hint to set variables in /etc/default/celeryd like this: export DJANGO_SETTINGS_MODULE="project.settings" export CELERY_BROKER_URL="ampq..." export DATABASE_USER="username" export DATABASE_PASSWORD="password" export REDIS_PASS="password" so after this, celery worker connects to rabbitmq virtualhost sometimes! most of the time it connects to rabbitmq as default guest user. before this it would always connect as guest user. when it connects as my user, worker and beat perform tasks without any problem. my tasks get and update objects from database and cache(redis). they work fine when i run them manually. I've read logs and it's always postgresql auth error by beat or the fact that worker is connected to rabbitmq as guest user. What is the solution … -
How to develop in django external python script management system?
Pseudocode: Uploud file xml or csv. I have many external python script which i want to run in queue (for example one script check if XML contains something...) I want decide which task must be switch off via admin panel. I need a report whats is the result of function. Requirements: Files size up to 150 MB size Unlimited amount of script Running scripts in sequence and saving the result Easy disabling scripts in admin panel How to build a concept of such an application in django? the scripts sequence process will be carried out in sequence. One file, then another - in a queue. The results will be available after some time. -
How can I clear the local storage when clicking the 'Login as user' button on django admin?
I want to delete the local storage of my browser when I click the button login as user of django admin page (see image). Is there a way to extend the code of that button? I have not found a way to override it. We are using django 1.11 (I know, it's old, but we cannot change that right now). -
Custom view with email parameter in django changing the url and showing http status code 301,302
myapp model: class GroupMailIds(models.Model): local_part = models.CharField( max_length=100, verbose_name='local part', help_text=hlocal_part ) address = models.EmailField(unique=True) domain = models.ForeignKey(Domain,on_delete=models.CASCADE, related_name='domains') def __str__(self): return self.address In myapp urls.py: from . import views from django.urls import path, include from django.http import * urlpatterns = [ path('', views.index, name='index'), path('groupmailids/<str:email>/details', views.get_groupmailid_details, name='get_groupmailid_details'),] myapp views.py: def get_groupmailid_details(request, email): data = {} if request.method == 'POST': return redirect('home') else: try: groupmailid_obj = GroupMailIds.objects.filter(address=email)[0] print(groupmailid_obj, '--------groupmailid_objjjjjjjj') except Exception as e: groupmailid_obj = None if groupmailid_obj: data.update( {'groupmailid_id':groupmailid_obj.id, 'address':groupmailid_obj.address, }) print(data) return JsonResponse(data) But when in browser I use the url: localhost:8000/admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details id displays the main menu with message: Group email id with ID “newgroup@saintmartincanada.com/details” doesn’t exist. Perhaps it was deleted? The above code worked for sometime very well, but suddenly stopped working, in the console can see trace log messages like: "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details HTTP/1.1" 301 0 [12/Jan/2022 18:18:22] "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details/ HTTP/1.1" 302 0 [12/Jan/2022 18:18:23] "GET /admin/mailmanager/groupmailids/newgroup@saintmartincanada.com/details/change/ HTTP/1.1" 30 Unable to fix this issue. Why is it appending '/change' to the url? and returning to the admin page in GUI? It is showing http status code 301, 302 in the logs ? I am using django 3.2 , python 3.7 Please can you suggest the correct code? -
Creating a chart based on the last id introduced in the database
this is going to be a big question to read, so sorry for that, but I can't get my head around it. I want to create a chart, but only with values for the last added id in the database, for that i have the following model: class Device (models.Model): patientId = models.IntegerField(unique=True) deviceId = models.CharField(unique=True,max_length=100) hour = models.DateTimeField() type = models.IntegerField() glucoseValue = models.IntegerField() I have an upload button that accepts an txt, it converts it into a excel file and then it add every row in the database, here is the UI: The UI of the application For sending the data, I'm using the following code in views.py: def html(request, filename): #Data for the graph id = list(Device.objects.values_list('patientId', flat=True).distinct()) labels = list(Device.objects.values_list('hour', flat=True)) glucose_data = list(Device.objects.values_list('glucoseValue', flat=True)) data = glucose_data test123 = select_formatted_date(labels) print(test123) #f = DateRangeForm(request.POST) context = {"filename": filename, "collapse": "", "patientId": id, "dataSelection": test123, "labels": json.dumps(labels, default=str), "data": json.dumps(data), #"form": f } For accepting the data, i have the following structure in index.html: var ctx = document.getElementById("weeklyChart"); var hourly = document.getElementById("dailyChart"); var myLineChart = new Chart(ctx, { type: 'line', data: { labels: {{ labels|safe}}, datasets: [{ label: "Value", lineTension: 0.3, backgroundColor: "rgba(78, 115, 223, 0.05)", … -
How to change automatic datetime to a date is given in Json Django?
I am new to Django. I am trying to save the datetime that is given in the json structure in a start_date field which is auto_now. But it does not work it keeps saving the cuurent date in the database not the date that is given in Json: ( "available_from_date": "2022-07-08 00:00:00.000000"). How can I change that to the date given in json. In my model.py: start_date = models.DateTimeField(auto_now=True) In my views.py: room_status = RoomStatus( room =room_obj, status=5, date_start=room["available_from_date"] ) room_status.save() In json: "room": [ { "available_from_date": "2022-07-08 00:00:00.000000" } ]