Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Microsoft Outlook Add-in can't extract/pass data to a localhost server via Ajax
I'm trying to build an Outlook add-in for encrypting/decrypting emails. The Add-in itself uses a web app, which in turn uses Javascript. I basically want to pass the unencrypted/encrypted email to a local server running python using GET/POST requests, perform some encryption/decryption on it in python, and then pass it back to Outlook Add-in. The problem is that the Add-in just won't pass any data to the local server nor get something in return. I have tried to work with both Django and Flask with the same results. I also configured the local servers to use locally-generated certificates and keys with no improvement. I even tried routing the HTTP connection using ngrok, but none came of it. Server response to GET request on HTTP Server response to GET request on HTTPS using Werkzeug The code given below never returns "Here5" on item-status. Clearly the success snippet isn't being run. $.ajax({ url: "https://127.0.0.1:8000/getPost/hello/", type: 'GET', dataType: 'json', // added data type success: function (res) { $('#item-status').text("Here5"); $('#item-message').text(res); } }); I've also added the required URLs in the App Domain part of the manifest file: <AppDomain>https://127.0.0.1:8000/getPost/hello/</AppDomain> The Add-in performs fine when running GET requests from other sites on the internet, like: https://api.github.com/users … -
how to access database object from another server in client sid
I have working on project that using Django.I have render some data as json format with httpresponse in url like this "1.1.1.1:8080/data". and get data with javascript and AJAX in client side, I should mention that this server have no access to intenet and it work in internal network of our company. this work prefect. but another server like 'example.com' want to render my html and i manage it, this work well but the data "1.1.1.1:8080/data" do not load and return error on pinging. so is there any solution to make access my django app load data on 'example.com'. best regarads -
How to pass value of a selection option to a class parameter in flask?
I am trying to create a flask app for a machine learning model. Here is the data.html file which contains the view. <select multiple name="features" class="form-control"> <option value=""></option> {% for col in columns %} <option value="{{col}}">{{col}}</option> {% endfor %} </select> Machine learning has long lines of code but here is how it looks ml.py: class sequential_learning: min_distances_list=[] y_pred_dtr_mean=None y_pred_dtr_std=None ... def __init__(self,dataframe,init_sample_size,target_treshhold,number_of_executions, sample_treshold,sigma,distance,model,strategy ): #constructor self.dataframe= dataframe self.model=model self.strategy = strategy print(type(self.dataframe)) self.apply_feature_selection_to_df(self.dataframe) self.apply_target_selection_to_df(self.dataframe) if(len(fixedtargets)>0): print(fixedtargets) self.target_df=self.target_df.join(fixedtargets)#self.dataframe[fixedtargets]) self.standardize_data() init_sample_set=self.init_sampling() def apply_feature_selection_to_df(self,dataframe): self.features_df = self.dataframe[features] Here is the flask app.py: @app.route('/data/slamd', methods=['GET', 'POST']) def slamd(): #print(df) dataset = df ... fixedtargets = request.form.get('fixedtargets') features = request.form.get('features') targets = request.form.get('targets') s = sequential_learning(dataset,initial_sample_size,target_quantile,iterationen,sample_quantile,std, dist,model,strategy) dt=DT("Decision Tree",s,target) s.model=dt s = s.main() return render_template('slamd.html', s=s, df = df, fixedtargets=fixedtargets, targets=targets, features=features) I have two questions here: 1 when I select the select box, it has the string but not the value which is in my file. 2 In my ml.py, the variables which are a get request are not recognized, such as the features inside my class are not recognized because I mentioned them in my app.py, not in ml.py. How to make it recognizable? -
django UserChangeForm not rendering "this form" link correctly with form.as_p
I'm trying to render it with form.as_p and it is rendering mostly as it should. However, the link to the change password section isn't rendering properly. Instead of the blue link on "this form" I get... "Raw passwords are not stored, so there is no way to see this user’s password, but you can change the password using this form." anyone ever deal with this problem? here's my HTML: {% extends 'base.html' %} {% block title %}Edit Profile{% endblock %} {% block content %} <h1>Edit Profile...</h1> <br/> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Update Profile</button> </form> </div> {% endblock %} And my forms.py: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User from django import forms class EditProfileForm(UserChangeForm): email = forms.EmailField(widget=forms.EmailInput(attrs={'class': 'form-control'})) first_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_name = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) last_login = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) is_superuser = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'})) is_staff = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'})) is_active = forms.CharField(max_length=100, widget=forms.CheckboxInput(attrs={'class': 'form-check'})) date_joined = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'class': 'form-control'})) class Meta: model = User fields = ('username', 'first_name', 'last_name', 'email', 'password', 'last_login', 'is_superuser', 'is_staff', 'is_active', 'date_joined') Views.py: from django.shortcuts import render from django.views import generic from django.contrib.auth.forms import UserCreationForm, UserChangeForm from … -
How to stream video from online camera in django
I want to use Django to live stream video taken from a video camera mounted on a Raspberry PI (compute module 4 IO board) connected to internet. I'm new in Django and I don't know if it's possible, how hard it is and from where I can start. I've tried to searched it on Internet but I can't really found an appropriate answer. I tried to search the same thing but using Ruby On Rails instead Django and it seams more simple do to (Can you confirm? Even there I appreciate some hint). There are some better solution? Can someone help me to start with my project? -
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 …