Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Decentralization in blockchain project
I am creating a web application for storing data on the blockchain. There will be about a dozen holders of the system. The following question arose: how to create a decentralized and secure system and which method of data protection do you consider the best? -
Django Validation with and or rule
The condition supposed to be only if this field is filled other field do not need to filled. No with this code i have to fill out all the fields if (self.start==None and self.end==None) or (self.running==None and self.walking==None ) : raise ValidationError( { "start": _("Need to be filled"), "end": _("Need to be filled"), "running": _("Need to be filled"), "walking": _("Need to be filled") } ) -
django NOT NULL constraint failed:
I am getting 2 errors trying to add products to my cart in a website in django. IntegrityError at /apiadd/ NOT NULL constraint failed: cianshop_basketitem.basket_id_id in my console i see this: " productindividual?id=1:136 POST http://127.0.0.1:8000/apiadd/ 500 (Internal Server Error) addToCart.onclick @ productindividual?id=1:136 VM55:1 Uncaught (in promise) SyntaxError: Unexpected token I in JSON at position 0 " this is my models.py file: from dataclasses import is_dataclass from django.db import models from django.contrib.auth.models import AbstractUser class APIUser(AbstractUser): pass class Product(models.Model): id = models.IntegerField(primary_key=True) name = models.TextField() description = models.TextField(null=True) price = models.DecimalField(max_digits=6, decimal_places=2, default=0.0) #9999.99 image = models.FileField(upload_to='products', null=True) class Basket(models.Model): id = models.IntegerField(primary_key=True) user_id = models.ForeignKey(APIUser, on_delete=models.CASCADE) is_active = models.BooleanField(default=True) class BasketItem(models.Model): id = models.IntegerField(primary_key=True) basket_id = models.ForeignKey(Basket, on_delete=models.CASCADE) product_id = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def price(self): return self.product_id.price * self.quantity def product_name(self): return self.product_id.name class Order(models.Model): id = models.IntegerField(primary_key=True) basket_id = models.ForeignKey(Basket, on_delete=models.CASCADE) user_id = models.ForeignKey(APIUser, on_delete=models.CASCADE) datetime_ordered = models.DateTimeField(auto_now_add=True) total_price = models.DecimalField(max_digits=6, decimal_places=2, default=0.0) shipping_addr = models.TextField(default="") -
cannot find images in react response
I am trying to return multiple images in django to react. But I am unable to retrieve the images in react. My httpresponse is dictionary in this format: {id1:[image1,image2], id2:[image1,image2} but I am getting only integers as a response in react. django code: images = {} for id in post_ids: img_obj = PostImage.objects.filter(post_id=id) imgs = [img_obj[0].image.file] try: x = img_obj[0].other_image1.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file imgs.append(x) except ValueError: pass try: x = img_obj[0].other_image2.file print('type', type(x)) imgs.append(x) except ValueError: pass images[id] = imgs return HttpResponse(images) react code: const submit = () =>{ const token = localStorage.getItem('access'); axios.post(url, { token: token, }).then(res => { if (res.status===200){ console.log(res.data); }else{ alert('error'); } }) } output in cosole 234567 -
Exception in thread django-main-thread unable to run server
[Exception in thread django-main-thread:][1] [Exception in thread django-main-thread:][2] [1]: https://i.stack.imgur.com/b4KFS.png [2]: https://i.stack.imgur.com/w6ko3.png -
Django - How to add "or" condition to queryset.filter in custom filter
i want to make a search filter which searches in multiple fields with multiple conditions, using only one search field. I have this filters.py file: import django_filters from .models import Product class ProductFilter(django_filters.FilterSet): q = django_filters.CharFilter(method='search_filter', label='Cerca') class Meta: model = Product fields = ['q'] def search_filter(self, queryset, name, value): return queryset.filter(name__icontains=value, sku__iexact=value) but return queryset.filter(name__icontains=value, sku__iexact=value) doesn't work, neither return queryset.filter(Product(name__icontains=value) | Product(sku__iexact=value)) How can i do this? -
Django query in list view to group similar category records
I have my website which displays the records on website these records are of different categories how can group the records belongs to similar category and display them together category 1 List item 1 List item 2 List item 3 class Mymixin: def get_queryset(self): return Record.objects.all() class Model: category = models.Charfield() -
Django Exception Type: ProgrammingError Exception Value: no existe la función sum(character varying)
I got an error when i use postgresql total = DetalleFacturas.objects.filter(IdFactura__Fecha__range=[fechainicio, fechafinal], IdFactura__IdBodega__Vendedor__Email=request.user.email).aggregate( Sum('Total')) And i have got this error: ProgrammingError at /reportehelisa/ no existe la función sum(character varying) LINE 1: SELECT SUM("DetalleFacturas"."Total") AS "sum" FROM "Detalle... It's work fine in sqlite but postresql not work -
How to override get_queryset() whilst using UpdateView Django
I have inherited UpdateView and I am trying to override the get_queryset() method, but it keeps throwing an error: raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: UserProfileManagement is missing a QuerySet. Define UserProfileManagement.model, UserProfileManagement.queryset, or override UserProfileManagement.get_queryset(). models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True) first_name = models.CharField(max_length=50, blank=False, null=False) last_name = models.CharField(max_length=50, blank=False, null=False) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'last_name'] objects = CustomUserManager() def save(self, *args, **kwargs): self.first_name = self.first_name.capitalize() self.last_name = self.last_name.capitalize() return super(User, self).save(*args, **kwargs) def __str__(self): return self.email managers.py class CustomUserManager(BaseUserManager): def create_user(self, email, first_name, last_name, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, **extra_fields) user.set_password(password) user.save() return user views.py class UserProfileManagement(UpdateView): Model = User template_name = 'users/user_profile.html' fields = ['first_name', 'last_name'] def get_queryset(self): queryset = super(UserProfileManagement, self).get_queryset() return queryset.filter(pk=3) However, if I override the get_object() instead it works. def get_object(self, queryset=None): return User.objects.get(pk=3) -
how do I render shipping address_one object associated with a specific order
So the customer has an order page where I want to render their order details, specifically product name, date ordered, status, and their delivery location, right now I got everything to work except the delivery location("address_one"). I would really appreciate it if someone can help, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ shipping.address_one }}</div> </div> {% endfor %} -
Is there a way to make a mock timezone for a Selenium test in Django?
In my selenium test below I'm trying to test my Analytics model. I'm using a mock of an Analytics model instance from class AnalyticsFactory. When I run this test everything works fine except I get an error for the timestamp field in the Analytics model. Note: I'm using timezone.now() for this. It seems like the time from when I run the test and when the time is assigned to the Analytics factory is slightly different. For example this is the error I'm getting: AssertionError: datetime.datetime(2022, 4, 8, 13, 3, 28, 153988, tzinfo=<UTC>) != datetime.datetime(2022, 4, 8, 13, 3, 28, 48016, tzinfo=<UTC>) in the error above 153988 and 48016 are different Is there a way I could set a 'fake' timezone object instead of using timezone.now()? Since it seems like 'now' is so precise that I can't get this to work. test_models.py: from django.utils import timezone from django.test import TestCase from myapp.tests.factories import UserFactory, AnalyticsFactory from myapp.models import Analytics class MyTestCase(TestCase): def setUp(self): self.admin = UserFactory( username='first.last@gmail.com', email='first.last@gmail.com', password=12345 ) self.a1 = AnalyticsFactory( user=self.admin, timestamp=timezone.now(), views=10 ) def test_analytics(self): a = Analytics.objects.get(id=6) self.assertEqual(a.views, 10) self.assertEqual(a.user, self.admin) self.assertEqual(a.timestamp, self.a1.timestamp) <--- not working self.assertEqual(response.status_code, 200) factories.py: import factory from myapp.models import Analytics from … -
Creating a root comments and comments with ancestors from the same view
I'm creating comments system like in twitter. Everything works fine with displaying the tweet, its ancestors and descendants. The main problem is I want to create root tweets and tweets with ancestors from the same url (e.g 'compose/tweet/). At the moment my code for this task is working. I have hidden input in my form with parent id value attr if user wants to create an answer on tweet. Attr is empty if root tweet will be created. <form action="{% url 'tweets:make_tweet' %}" method="post" novalidate> {% csrf_token %} {% render_field tweet_form.parent value=id %} <div class="tweet-form-textarea mb-2" id="tweet-form-textarea{{ id }}"> {% render_field tweet_form.text class="form-control fs-5" rows="3" placeholder=placeholder %} </div> <div class="tweet-form-footer d-flex flex-row align-items-center" id="tweet-form-foote{{ id }}"> <span class="chars-counter visually-hidden"></span> <input type="submit" class="make-tweet-btn fw-bold btn rounded-pill" value="Tweet"> <div> </form> Form renders with inclusion template tag: @register.inclusion_tag('tweets/tweet_form_snippet.html', takes_context=True) def render_tweet_form(context, id=''): return { 'tweet_form': context['form'], 'id': id } And finally value attr is populating in template(simplified version): {% if not tweet %} {% render_tweet_form %} {% else %} {% render_tweet_form id=tweet.id %} {% endif %} The form is processed from class: class MakeTweetView(BaseCreateView): form_class = TweetForm def form_valid(self, form): tweet = form.save(commit=False) # Searching for value in hidden input parent = self.request.POST['parent'] … -
Failed to login already existing users in databse by username or email ?how to login by username, email or password with null token in django graphql?
I tried to log in to existing users or manually inserted users in the database, but I am not able to log in with those existing users who already exist in the database. On the other hand, when we register a new user through API and try to log in only that registered user who registered through APIs, it is working absolutely fine. the main problem is here that we have old existing users and those old users are not able to log in, so please help me regarding login those users who are not registered through APIs who are already existing in the database. -
Filtering DateTimeField by past and future django dates
My problem is that I make a timer until the next event on the site. I store the events in the django model. Making the date output in the template, I do not know how to make events output in turn. I managed to filter the past dates in the template, but I can't do an automatic event change when the previous event has passed. That is, there is 00.00.00 left before it. I am also unable to output the first already filtered element. Only {%if forloop.counter0 == 1%} works, but this outputs an element of the entire list, not an element of the filtered list. I was just trying to output the first event where the date is greater than the current one. I tried to use some internal loops after filtering, but I can't do it. I am addressing you with this problem because I have reached a big dead end. I would be very grateful for your help. There was an idea to filter the events immediately in views.py using filter, but I'm confused again. I'm still new to this business, but I would really like to finish this project. Template {% for x in date %} … -
Audio file is not passing through Ajax
I am trying to send data in form with audio file when ever I send data request this error in console pop up [enter image description here][1] [1]: https://i.stack.imgur.com/q5Hi2.png This is my form code <body> <h1>Audio</h1> <form id="form" method="POST"> {% csrf_token %}{{form.as_p}} <input type="text" id="first_name" placeholder="student Name"><br> <input type="text" id="Reg_No" placeholder="Registration No"><br> <input type="text" id="Health_status" placeholder="Health Status"><br> <input type="text" id="deparment" placeholder="Department"><br> <input type="submit" name="submit" value="submit"> <h1>{{message}}</h1> </form> <div id="output"> </div> <button id="startRecordingButton">Start recording</button> <button id="stopRecordingButton">Stop recording</button> <button id="playButton">Play</button> <button id="downloadButton">Download</button> <button id="SubmitButton">Submit</button> audio file is storing in blob variable blob = new Blob([view], { type: 'audio/wav' }); }); I am trying to send it through ajax in dataform submit.addEventListener("click", function (e) { e.preventDefault(); let formData = new FormData(); var recording = blob; formData.append("recording", recording); formData.append("first_name", first_name); formData.append("deparment", deparment); formData.append("Reg_No", Reg_No); formData.append("Health_status", Health_status); $.ajaxSetup({ headers: { "X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value, } }); $.ajax({ type: 'POST', url: "{% url 'HealthTest' %}", data: formData, dataType: "json", success: function (data) { // $('#output').html(data.msg) /* response message */ alert('created new user'); }, failure: function () { } }); }); here is my views.py function where i am actually storing data for audio file i just need to read audio and send it to pickle so i created … -
Can you iterate through model fields when you overwrite the save() method in django?
I'm calling a custom save method in my model. The save method is designed to produce some values in the model based on the content of a TextField. This content is stored in a dictionary, and is generated correctly. I'm trying to write a for loop to store the values of the dictionary. The keys correspond to the model field names: def save(self, *args, **kwargs): if self.text != "": results_dict = analyze(self.text) for field_name in field_names_list: self.field_name = results_dict[field_name] The value is not stored in the corresponding field. Do I need to use setattr here instead? -
Update a model field in save method based on other field values selected including m2m field
I am trying to update a model field by overriding save method: class DataTable(models.Model): id = models.AutoField(db_column='Id', primary_key=True) country= models.ForeignKey(Countries,on_delete=models.DO_NOTHING,db_column='CountryId') university=models.ManyToManyField(Universities,db_column='UniversityId',verbose_name='University',related_name='universities') intake = models.CharField(db_column='Intake',blank=True, null=True, max_length=20, verbose_name='Intake') year = models.CharField(max_length=5,blank=True,null=True) application_status = models.ForeignKey(Applicationstages,on_delete=models.DO_NOTHING, db_column='ApplicationStageId',verbose_name='Application Status') requested_count = models.PositiveIntegerField(db_column='RequestedCount',blank=True,null=True) class Meta: db_table = 'DataTable' def __str__(self): return str(self.application_status) def __unicode__(self): return str(self.application_status) def save(self,*args, **kwargs): super(DataTable,self).save(*args, **kwargs) country_id= self.country intake= self.intake year= self.year universities= self.university.all() courses = get_ack_courses(country_id,universities) all_data = get_all_courses(intake,year,courses) ack_data = get_acknowledgements_data(all_data) self.requested_count =len(ack_data) super(DataTable,self).save(*args, **kwargs) I am trying to update the requested_count field using the other field values, but in save method when I try to get the m2m field data ; it is returning empty. I tried with post_save signal also and there also m2m field data is empty. I want the count field based on otherfields from this model. How to save when we have m2m fields? -
django: Outputting CSV with JsonResponse
def export_csv(request,query): p = Path(os.path.dirname(__file__)) FILE_JUDGEMENT = str(p.parent)+"/static/pygiustizia" content = "" res = {} res["status"] = "ok" res["data"] = content response = JsonResponse(res, status=200) if os.path.exists(nameFile): response["Content-Description"] = "File Transfer" response["Content-Type"] = "application/octet-stream" response["Content-Disposition"] = 'attachment; filename="somefilename.csv"' response["Expires"] = 0 response["Cache-Control"] = "must-revalidate" response["Pragma"] = "public" writer = csv.writer(response,delimiter =';') writer.writerow(headerData.values()) totalRowData = 0 #fdata = toDict(fdata) #print("fdata",fdata) for keyRow,valueRow in fdata.items(): #print("valueRow",valueRow.values()) writer.writerow(valueRow.values()) totalRowData = totalRowData + 1 return response I have a controller-view in python django framework. My goal is output and download a csv created querying data from elastisearch. it create somefilename.csv but in header csv file I have {"status": "ok", "data": ""}sendername;controparte;nomegiudice;annosentenza;codiceufficio;fascicoloprecedente_annoruolo; Why? -
How to send a file with FTP in JavaScript?
I want when a user uploads a file, this file should be sent to the server with FTP without pressing a button or submitting a form. I try to do that but it is not working. Firstly, I created a function with time intervals, which checks whether the file input is empty or not. If it is not empty, it should send the file to the server. var file = "/uploads/" + {{ api_id }} this should be the address of the file on the server. How can I do that or where is my mistake? <input type="file" class="form-control-file" id="exampleFormControlFile1" name="bankStat1"> <script> setInterval(displayHello, 1000); function displayHello() { var is_File = false if (document.getElementById("exampleFormControlFile1").files.length >= 1){ is_File = true var file = "/uploads/" + {{ api_id }} var ftp = new FtpConnection("ftp://myftp/") ; ftp.login("myuser", "mypass"); ftp.cd("uploads") ftp.put(file,document.getElementById("exampleFormControlFile1").files[0]) ; ftp.close() ; file.close() ; } console.log(is_File) } </script> -
how Count field using django orm
Hi Everyone i trying to count active and inactive status sepratally, below mention code to count all, i need to count active and inactive status sepratally,pls help me out. Type.objects.all().aggregate(Count('status')) output=5 -
Azure App Services: multi-containers not starting
I had my Django web app running on Azure VM then decided to move to Azure App Services using a multi-container instances. However, celery seems to be breaking Following is my docker-compose configuration and error logs for Azure App Service services: application: image: expressway.azurecr.io/expressways_application:v1 ports: - 80:8000 depends_on: - queue working_dir: /data command: gunicorn config.wsgi:application 0.0.0.0:80 restart: unless-stopped queue: image: expressway.azurecr.io/redis:v1 restart: unless-stopped worker: image: expressway.azurecr.io/expressways_worker:v1 restart: unless-stopped depends_on: - queue - application command: bash -c /data/docker-worker-entrypoint.sh volumes: static-files: media-files: ${WEBAPP_STORAGE_HOME}/site/wwwroot:/var/www/html ${WEBAPP_STORAGE_HOME}/phpmyadmin:/var/www/phpmyadmin **However, the only thing that I see in my App Service logs is:** ` ``` 2022-04-08T11:47:32.913Z ERROR - multi-container unit was not started successfully 2022-04-08T11:47:32.929Z INFO - Container logs from testoms_application_0_cb8acd23 = 2022-04-08T11:47:24.232210483Z [2022-04-08 11:47:24 +0000] [1] [INFO] Starting gunicorn 19.9.0 2022-04-08T11:47:24.236012528Z [2022-04-08 11:47:24 +0000] [1] [INFO] Listening at: http://0.0.0.0:8000 (1) 2022-04-08T11:47:24.236677888Z [2022-04-08 11:47:24 +0000] [1] [INFO] Using worker: sync 2022-04-08T11:47:24.243640619Z [2022-04-08 11:47:24 +0000] [8] [INFO] Booting worker with pid: 8 2022-04-08T11:47:24.252172692Z [2022-04-08 11:47:24 +0000] [8] [ERROR] Exception in worker process 2022-04-08T11:47:24.252216296Z Traceback (most recent call last): 2022-04-08T11:47:24.252223297Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2022-04-08T11:47:24.252228597Z worker.init_process() 2022-04-08T11:47:24.252232898Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 129, in init_process 2022-04-08T11:47:24.252237698Z self.load_wsgi() 2022-04-08T11:47:24.252241799Z File "/usr/local/lib/python3.6/dist-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2022-04-08T11:47:24.252246299Z self.wsgi = self.app.wsgi() 2022-04-08T11:47:24.252250299Z File … -
how do I render 'address_one' object associated with a specific order
So the customer has an order page where I want to render their order details, specifically product name, date ordered, status, and their delivery location, right now I got everything to work except the delivery location("address_one"). I would really appreciate it if someone can help me out, thx! models.py class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) class Product(models.Model): name = models.CharField(max_length=150) description = models.TextField() class ShippingAddress(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, blank=True, null=True) address_one = models.CharField(max_length=200) views.py @login_required def orders(request): orderitems = OrderItem.objects.filter(order__customer__user=request.user) #how do I get the shipping address associated with order shipping = ShippingAddress.objects.filter() context = {"orderitems": orderitems, "shipping": shipping} HTML {% for orderitem in orderitems %} <div class="order-data-view"> <div class="order">{{ orderitem.product.name }}</div> <div class="date">{{ orderitem.date_added }}</div> <div class="status">dummydata</div> <div class="delivering-to">{{ shipping.address_one }}</div> </div> {% endfor %} -
serving apk file in heroku server via django not working?
I want to serve apk file in website hosted on heroku, it is serving also but while installing it shows error "There was a problem while parsing the package". And also downloaded apk file working in local server -> Backend is Django {% load static %} <a href="{% static 'app/home.apk' %}" download=""></a> -
how to submit onchange form without refresh in django
here is the code where submit onchange <div class="form-group row"> <div class="col-sm-10 col-md-7"> <select {{ form|validation_class:"devamsizlik" }} id="devamsizlik" name="devamsizlik" onchange="this.form.submit();"> <option value="">Gelme durumu</option> <option value="True"> <span style="font-family: wingdings; font-size: 200%;">&#10004;</span> </option> <option value="False"> <span style="font-family: wingdings; font-size: 200%;">&#10060;</span> </option> </select> </div> </div> ı try some ajax code but none of them working on it , ı could not find anything about while submitting on change page not reload. -
How to change admin model in external app in Django?
I have installed the tell-me app that is gathering users' feedback. I want to edit list_display and list_filter in the admin panel but I am not sure how to access this model in the admin.py file. Any advice on how to do that will be appreciated.