Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why Button is not showing in javascript
In my project, button not showing in frontend. what can i do for showing the button??? please help me. <script> function updatePopover(product_cart){ console.log('we are in updatePopover'); var popStr = ""; popStr = popStr + "<h5>cart for your items</h5> <div class='mx-2 my-2'>"; var i =1; for (var item in product_cart){ popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 25) + "... Qty: " + product_cart[item] + '<br>'; i = i+1; } popStr = popStr + "</div> <a href='/checkout' class='btn_1' id='checkout'>CheckOut</a> **<button class='btn_1' onclick='clearCart()'>Clear Cart</button><button class='btn btn-primary'></button>** " document.getElementById("popcarts").setAttribute('data-content', popStr); $('#popcarts').popover('show'); } <script> -
Django BooleanField if statement doesnt return content
For some reason when checking to see if BooleanField post.featured is true I get no output. If I remove that it works fine but not as I intend. <div class="carousel-inner"> {% for post in object_list%} {% if post.featured is True %} <!-- This post.featured is BooleanField --> {% if forloop.first %} <div class="carousel-item active"> {% else %} <div class="carousel-item"> {% endif %} <div class="col-md-6 px-0"> <h1 class="display-4 font-italic">{{ post.title }}</h1> <p class="lead my-3">{{ post.hook }}</p> <p class="lead mb-0"> <a href="{% url 'article-details' post.pk %}" class="text-white fw-bold"> Continue reading... </a> </p> </div> </div> {% endif %} <!-- and this --> {% endfor %} </div> Heres how it looks like when not checking if post.featured == true: Working However, content doesnt render with {% if post.featured is True %} or {% if post.featured %} Can someone please explain what im doing wrong -
Foreign Key with Django REST Serializers
I'm having trouble figuring out how to get the Foreign key relationship to work with my Django REST api. I have a model from django.db import models from django.core.validators import RegexValidator # Create your models here. class Hero(models.Model): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') name = models.CharField(max_length=60, blank=True, validators=[alphanumeric]) alias = models.CharField(max_length=60) def __str__(self): return self.name class SideKick(models.Model): alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') hero = models.ForeignKey(Hero, related_name='sidekicks', on_delete=models.CASCADE) sideKick_name = models.CharField(max_length=60, validators=[alphanumeric]) def __str__(self): return self.sideKick_name Serializers from rest_framework import serializers from .models import Hero, SideKick class HeroSerializer(serializers.HyperlinkedModelSerializer): sidekicks = serializers.SlugRelatedField(many=True, read_only=True, slug_field='title') class Meta: model = Hero fields = ('name', 'alias', 'sidekicks') class SideKickSerializer(serializers.HyperlinkedModelSerializer): sideKick_name = HeroSerializer() class Meta: model = SideKick fields = ('sideKick_name') Here is what the api webpage looks like I'm fairly new to this and was wondering how I can get the option to select a Hero to create a sidekick through the API webpage. every time i create a hero the sidekick field is blank. Any help would be apperciated. -
Django get values from field after order_by
I am trying to get the shared values from a field after ordering my model based on one of its fields. So for example I have a model named Course: class Course(models.Model): code = models.CharField(max_length=100) university = models.CharField(max_length=100) instructor = models.CharField(max_length=100) and then for ordering based on instructor I do: Course.objects.all().order_by('instructor').distinct('instructor') Which will then give me for example ABC123, Uni1, Adamson EFG456, Uni1, Adamson HIJ789, Uni1, James KLM321, Uni1, James How can I retrieve the results as a dictionary with the keys being the instructor and the value being a query set of model object? So I will get something such as: result = { "Adamson":<QuerySet[]>, "James":<QuerySet[]> } I cannot find an aggregate function that does this is there any way to do this using a single method? -
is there a way to change the date format in django/html?
i am still new to django and i am following a tutorial but when the guy i had the error the method he used didnt work for me - i am get this error althogh the default format for date is yyyy- mm-dd - any help will be appreciated ['“” value has an invalid date format. It must be in YYYY-MM-DD format.'] this is my save function that inputs the data into the database def add_seniorEmployee_save(request): if request.method!="POST": return HttpResponse("Method Not Allowed") else: first_name=request.POST.get("first_name") last_name=request.POST.get("last_name") username=request.POST.get("username") email=request.POST.get("email") password=request.POST.get("password") Dob=request.POST.get("Dob") Nationality=request.POST.get("Nationality") Address=request.POST.get("Address") Postcode=request.POST.get("Postcode") Telephone=request.POST.get("Telephone") Wage=request.POST.get("Wage") Passportnumber=request.POST.get("Passportnumber") passportexpirydate=request.POST.get("passportexpirydate") gender=request.POST.get("gender") kinname=request.POST.get("kinname") kinrelation=request.POST.get("kinrelation") kinaddress=request.POST.get("kinaddress") kinphonenumber=request.POST.get("kinphonenumber") kinemail=request.POST.get("kinemail") #try: user = CustomUser.objects.create_user(username=username,password=password,email=email,first_name=first_name,last_name=last_name,user_type=2) user.senioremployee.Dob = Dob user.senioremployee.Nationality = Nationality user.senioremployee.Address = Address user.senioremployee.Postcode = Postcode user.senioremployee.Telephone = Telephone user.senioremployee.Wage = Wage user.senioremployee.Passportnumber = Passportnumber user.senioremployee.passportexpirydate = passportexpirydate user.senioremployee.gender = gender user.senioremployee.profile_pic="" user.senioremployee.kinname = kinname user.senioremployee.kinrelation = kinrelation user.senioremployee.kinaddress = kinaddress user.senioremployee.kinphonenumber = kinphonenumber user.senioremployee.kinemail = kinemail user.save() this is the model for my senior employee who i am adding to the database this is the model to create the customer user class CustomUser(AbstractUser): user_type_data=((1,"Admin"),(2,"senioremployee"),(3,"employee")) user_type=models.CharField(default=1,choices=user_type_data,max_length=20) class senioremployee(models.Model): id = models.AutoField(primary_key=True) admin=models.OneToOneField(CustomUser, on_delete=models.CASCADE) Dob = models.DateField() Nationality = models.TextField() Address = models.TextField() Postcode = models.TextField() Telephone = models.TextField() … -
How to use OSMnx with Django?
I want to create app that will calculate route between given points on map. I'm using Conda for managing my environment. In my venv I have installed Django and OSMnx. After adding OSMnx server won't run. The stacktrace is pretty long and ends with this: with fiona._loading.add_gdal_dll_directories(): AttributeError: module 'fiona' has no attribute '_loading' In my Django project i have one app called planner and the view is using OSMnx (not sure if this code should go there) and it looks like this: from django.shortcuts import render from django.http import HttpResponse, JsonResponse import osmnx as ox ox.config(use_cache=True, log_console=True) # Create your views here. def index(request): # As for now it is ok to hardcode place and network type warsaw_streets = ox.graph_from_place("Warsaw", network_type="drive") return JsonResponse({}) Im new to Django and I don't know if I'm using external library wrong or what is the purpose of this error... -
configuring the urls.py gives problem in the url generation
I have an application running django 3.1. I do have problems with the urls. I guess there is either a problem with the urls.py or in my asociated view. In my application, the view (fil main.py) is called "main". If I go the the url http://127.0.0.1:8000/main/, I see a correct rendering of the view. My view includes a button to click on. When I click, the url is now: http://127.0.0.1:8000/main/**main/** which is an error (404 page not found). My url.py is: from django.urls import path from django.conf import settings from django.conf.urls.static import static from django.urls import re_path from django.views.static import serve from . import main urlpatterns = [ path('main/', main.main, name='main'), path('', main.main, name='main'), ] My view uses the following: return render(request,'main.html') Thanks. S/ -
What is the proper way to send a post with a file with createReadStream to a django server api?
I'm trying to send a large file with filestream over a post request this way m.request({ url: get_pam_url(kg('host')) + '/api/v1/arquivo_client/', method: 'POST', data: { content: fs.createReadStream(file_path), }, headers: { 'Authorization': 'Token ' + kg('token'), 'content_type': 'application/octet-stream', }, }) and on my django view, when i do. request.data it returns a json with this info. {u'content': {u'_readableState': {u'encoding': None, u'sync': True, u'paused': True, u'ended': False, u'autoDestroy': False, u'readableListening': False, u'objectMode': False, u'emitClose': False, u'destroyed': False, u'defaultEncoding': u'utf8', u'length': 0, u'reading': False, u'resumeScheduled': False, u'highWaterMark': 65536, u'buffer': {u'length': 0, u'head': None, u'tail': None}, u'flowing': None, u'readingMore': False, u'decoder': None, u'needReadable': False, u'awaitDrain': 0, u'endEmitted': False, u'pipes': None, u'pipesCount': 0, u'emittedReadable': False}, u'closed': False, u'end': None, u'readable': True, u'_eventsCount': 1, u'_events': {}, u'fd': None, u'mode': 438, u'autoClose': True, u'flags': u'r', u'path': u'\\Users\\my_folder\\project\\tmp\\2020aq.xlsx.gz', u'bytesRead': 0}} how can i get the complete .gz file correctly on my django view? -
SyntaxError while using XLSXWRITER
I'm using xlsx writer in django to write some data in an excel file for users to download, but I keep getting a syntax error in my views.py file. Here is the functions thats raising the error: def excelr(request): user = getuser(request) registrations = Registration.objects.filter(MUN = user) path = str(f"registrationsdb/{user.username}{str(datetime.now())}registrations.xlsx") workbook = xlsxwriter.Workbook(path) worksheet = workbook.add_worksheet() worksheet.write(0,0, 'Delegate Name') worksheet.write (0,1, 'Age') worksheet.write(0,2, 'Instiution') worksheet.write (0,3, 'Email - ID') worksheet.write(0,4, 'City') worksheet.write(0,5, 'Experience') experience=[] for row in registrations: dele = row.delegate exp = Experience.objects.filter(delegate = dele) experience.append(exp) for i in range(0, len(registrations)): worksheet.write(i+1,0, str(registrations[i].delegate.name)) worksheet.write(i+1,1, str(registrations[i].delegate.age)) worksheet.write(i+1,2, str(registrations[i].delegate.institution)) worksheet.write(i+1,3, str(registrations[i].delegate.email)) worksheet.write(i+1,4, str(registrations[i].delegate.city)) worksheet.write(i+1,5, str(expstring(exp[i])) workbook.close() return path In the abover expstring(arr) returns a string value. I'm having errors raised post the line with workbook.close() (This function returns a path to the views.py route function to create a download link for on my html) I've installed all the required packages but cant seems to figure out the fix. Looking for some help on the same. Thanks -
Single Click MultiFiles upload in Django Admin saves only the last file
Please safe my day. I am struggling to upload mulitple files in Django Admin Page but its saving only one file. I can select the multiple files but when I saving, its saving only one file and the Char field. Below are the codes models.py from django.db import models # Create your models here. class ProjectInfo(models.Model): project_title = models.CharField(max_length=30) class ProjectFiles(models.Model): projectinfo = models.ForeignKey(ProjectInfo, on_delete=models.CASCADE) uploaded_files = models.FileField() forms.py from django import forms class ShowProject(forms.ModelForm): uploaded_files = forms.FileField( widget=forms.ClearableFileInput(attrs={"multiple": True}), required=False, ) admin.py from django.contrib import admin from .models import ProjectFiles, ProjectInfo from .form import ShowProject # Register your models here. class InlineForm(admin.StackedInline): model = ProjectFiles form = ShowProject extras = 1 max_num = 1 class ProjectInfoAmin(admin.ModelAdmin): inlines = [InlineForm] def save_model(self, request, obj, form, change): obj.save() if (form.is_valid()): files = request.FILES.getlist('uploaded_files') for f in files: obj = ProjectFiles() obj.uploaded_files = f super().save_model(request, obj, form, change) admin.site.register(ProjectInfo, ProjectInfoAmin) Thanks for your support. -
Django OneToOne field, reverse not required
I want to have a OneToOne relationship between to models; class Pet(models.Model): name = models.CharField() class Collar(models.Model): color = models.CharField() pet = models.OneToOneField(Pet, related_name='my_collar', on_delete=models.CASCADE) class CollarSerializer(serializers.ModelSerializer): class Meta: model = Collar fields = ['id', 'collor', 'pet'] class PetSerializer(serializers.ModelSerializer): collar = CollarSerializer() class Meta: model = Pet fields = ['id', 'name', 'collar'] I run into a problem though: if I want to POST a new pet that doesn't have a collar, it won't let me, it says that field is required. I thought of using ForeignKeyField for this, but I want to make sure the system knows it is a one-to-one relationship so I don't get a list of one collar, but rather one collar. -
Django Filter ManyToManyField
I'm working on a django project, and as I'm quite new to this framework and backend in general, I'm having a hard time finding out how to do this. I'm building a ListView that is used to display a list of products in a template. However, I need it to only display the products made available on the site by the dealer who's currently logged in. So in other words, just a page where a dealer can see what products they've put on our site. Here's my view: class ArticleListView(ListView, LoginRequiredMixin): template_name = "accounts/list_articles.html" model = Product def get_context_data(self,**kwargs): context = super().get_context_data(**kwargs) context["website"] = Website.objects.first() context["product_list"] = context["product_list"].filter(published=True) return context Here's the Products and Dealers models (only the relevant parts): class Product(models.Model, CloneMixin): published = models.BooleanField(null=True,blank=True, default=False) title = models.CharField(null=True,blank=True,max_length=100) subtitle = models.CharField(null=True,blank=True,max_length=200) (...) dealer = models.ManyToManyField(Dealer, null=True,editable=True,related_name="product_to_dealer") (...) # Not sure what this does: _clone_many_to_many_fields = ['parameter', 'tag', 'category', 'dealer','images'] (...) class Dealer(models.Model, CloneMixin): dealer_check = models.ForeignKey("self",null=True, blank=True, on_delete=models.SET_NULL) published = models.BooleanField(null=True,blank=True, default=True) (...) users = models.ManyToManyField(User,null=True,blank=True, related_name='dealers') (...) As it is, my ListView just displays every products there is in the db. From what I've understood, I need something like def get_queryset(self): return Product.objects.filter(user=self.request.user) or in the get_context_data, … -
how to join two Models (tables) Using Django ORM , when there is no relation ship between them
How to join two models using Django ORM, in simple how to write join queries in Django ORM like SQL join query , even though there is no relation between two models . and one special doubt , how to list the employees with the second highest salary from a employee table; using Django query -
Positions in CSS
I am making a blog posting site in Django. When users post something it looks great if the title of the post has 21 characters. If the title for instance has 35 characters it moves the author, date and thumbnail to the right and if less than 21 it moves it to the left. I don't want this scenario to happen! This is how it currently looks The HTML code {% for post in posts %} <div class="blogpost"> <a class="post-title"> {{post.title}} </a> <img class="thumbnail" src="{{post.author.imageURL}}"> <a class="date-author">{{post.date}} - {{post.author}}</a> <br> <hr> <br> <div class="blogpost-content">{{post.context|linebreaks}}</div> <br> <br> <br> </div> <br> {% endfor %} The CSS code .blogpost { /*Whole blogpost div*/ border: 5px solid #149414; background-color: black; color: #149414; width: 700px; margin:auto; border-radius: 40px; border-width: 1px; } hr{ /*The middle line in the blogpost*/ height: 1px; background-color: #149414; border: none; } .thumbnail{ /*The author's image of the blogpost*/ height: 120px; width: 120px; position: relative; right: -70px; bottom: 4px; border: 3px solid #149414; border-radius: 50%; } .blogpost-content{ /*Content in the blogpost*/ text-align: left; margin-left: 30px; margin-right: 30px; } .date-author{ /*The date and author div in the blogpost*/ font-size: 12; margin:10%; } .green_link{ /*Green link to the random key*/ color:#149414; } .post-title{ font-size: … -
Creating a like button in django social media network
I'm new to django and I'm trying to create a like button for my blog posts. In my HomeFeed app However, I received this error when i click on the like button that i have created: ValueError invalid literal for int() with base 10: I am given a pointer that the problem comes from this statement: post = get_object_or_404(BlogPost, id=request.POST.get('blog_post_slug')) Is it because they are expecting all integers in the url but it is getting character values? I am unsure of how to change it and have tried for multiple hours. Views.py def LikeView(request, slug): context = {} post = get_object_or_404(BlogPost, id=request.POST.get('blog_post_slug')) if post.likes.filter(id=request.user.id).exists(): post.likes.remove(request.user) else: post.likes.add(request.user) return HttpResponseRedirect(reverse('HomeFeed:detail',args=[str(BlogPost.slug)])) def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() context['blog_post'] = blog_post context['total_likes'] = total_likes return render(request, 'HomeFeed/detail_blog.html', context) models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.chief_title def total_likes(self): return self.likes.count() urls.py from .views import( detail_blog_view, LikeView, ) urlpatterns = [ path('<slug>/detail/', detail_blog_view, name= "detail"), path('<slug>/edit/', edit_blog_view, name= "edit"), path('<slug>/like/', LikeView, name='like_post'), ] detail_blog.html <form action="{% url 'HomeFeed:like_post' … -
How to have a model field be based on another models fields?
Relatively new to Django. I think what I'm trying to do is very simple but I've never done this before. "irrelevant2" is an attribute in my class "one" that I want to refer to a direct element in the class "two" (this part is working fine). Additionally, I want there to be a field called RELEVANT_VARIABLE in my class "one" that is essentially a dropdown menu that chooses between two elements of the class "two" and can only pick one. I understand that I need a form but so far have not been successful. My hunch says RELEVANT_VARIABLE should be a ForeignKey but I'm not sure how to attach it to a dropdown of either attr1 or attr2 from class "two". class two(models.Model): attr1 = models.CharField(max_length=100) attr2 = models.CharField(max_length=100) class one(models.Model): irrelevant1 = models.ForeignKey(Account, on_delete=models.SET_NULL, null=True) irrelevant2 = models.ForeignKey(two, on_delete=models.CASCADE) RELEVANT_VARIABLE = models.ManyToManyField(two, related_name="team_selection") And then in forms.py class OneForm(forms.Form): def __init__(self, *args, **kwargs): super(OneForm, self).__init__(*args, **kwargs) self.fields[**not sure what to even put here**] = forms.ChoiceField( choices=[(o[**not sure**], str(o[**not sure**])) for o in Two.objects.filter(irrelevant2=self)] ) class Meta: model = two -
How to use {{ form }] in bootstrap 4?
I'm trying to add contact form on my web site. I have model.py class ContactMe(models.Model): email = models.EmailField(_("Your Email")) name = models.CharField(_("Name"), max_length=255) message = models.CharField(_("Message"), max_length=255) def __str__(self): return self.name Form.py from django.forms import ModelForm from .models import ContactMe class ContactMeForm(ModelForm): class Meta: model = ContactMe fields = ('email', 'name', 'message') View.py from django.views.generic.edit import FormView from django.shortcuts import redirect from .forms import ContactMeForm class ContactView(FormView): template_name = 'contacts/contact.html' form_class = ContactMeForm success_url = '../' def form_valid(self, form): form.save() return redirect(self.success_url) So, I want to add this form to templates. <div class="i-am-centered"> <form method="POST"> {% csrf_token %} <div class="form-group form-group-lg"> <label>Email</label> {{ form.email }} </div> <div class="form-group form-group-lg"> <label>Name</label> {{ form.name }} </div> <div class="form-group form-group-lg"> <label>Message</label> <textarea class="form-control" id="id_message" rows="5" value="{{ form.message }} </textarea> </div> <button type="submit" class="btn btn-primary">Submit</button> </form> </div> I want users to write me a message and it will be safe in database so I can see it as admin. Unfortunately, I don't know how to add style in templates. -
DJANGO: Multiple ListView on 1 html page (class based views)
I have a page (onboarding.html) where i would like each listview to be displayed, in the same page. The scenario, if you imagine a user uploading address details, and then bank details, and then ID etc. Currently I can get the user to upload address and bank, which insert into the DB - however, pulling them back is an issue-i get one or the other. I'm assuming it's got something to do with my URLS.py. I am using class based views urls.py Literally lookin at AddressListView and BankListView (their name is both 'onboarding', i didn't think this would be an issue being seperate listviewshomepage page with multiple listviews required from django.urls import path from django.contrib import admin from django.views.generic.list import ListView from .views import ( PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeleteView, UserPostListView, AddressListView, AddressDeleteView, BankListView, ) from . import views urlpatterns = [ path('', PostListView.as_view(), name='blog-home'), path('admin/', admin.site.urls, name='admin'), path('user/<str:username>', UserPostListView.as_view(), name='user-posts'), path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), path('post/new/', PostCreateView.as_view(), name='post-create'), path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'), path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'), path('onboarding/', AddressListView.as_view(), name='onboarding'), path('onboarding/', BankListView.as_view(), name='bank-onboarding'), path('onboarding/upload', views.upload_address, name='upload_address'), path('onboarding/upload/bank', views.upload_bank, name='upload_bank'), path('onboarding/<int:pk>/delete/', AddressDeleteView.as_view(), name='delete_address'), path('books/', views.book_list, name='book_list'), path('books/<int:pk>', views.delete_book, name='delete_book'), path('books/upload/', views.upload_book, name='upload_book'), ] models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import … -
How to create Mapbox Vector Tiles with Django ORM and Postgis
I would like to create a mapbox vector tile in Django, using the ORM. In sql (Postgresql, Postgis) the sql query looks like this for the tile with zoom=8, x=137, y=83: SELECT ST_AsMVT(tile) FROM (SELECT id, ST_AsMVTGeom(geometry, ST_TileEnvelope(8, 137, 83)) AS "mvt_geom" FROM geomodel WHERE ST_Intersects(geometry, ST_TileEnvelope(8, 137, 83)) ) AS tile; ST_AsMVT aggregates all rows and the output is a binary Field (bytea) which can be send as reponse. As geodjango does not include the specific postgis functions I created custom functions for them: class TileEnvelope(Func): function = "ST_TileEnvelope" arity = 3 output_field = models.GeometryField() class AsMVTGeom(GeoFunc): function = "ST_AsMVTGeom" arity = 2 output_field = models.GeometryField() I managed to create the inner Subquery and it works: tile_envelope = TileEnvelope(8, 137, 83) tile_geometries = GeoModel.objects.filter(geometry__intersects=tile_envelope) tile_geometries_mvt = tile_geometries.annotate(mvt_geom=AsMVTGeom("geometry", tile_envelope)) tile_geometries_mvt = tile_geometries_mvt.values("id", "mvt_geom") print(tile_geometrries_mvt) >> <QuerySet [{'id': 165, 'mvt_geom': <Point object at 0x7f552f9d3490>}, {'id': 166, 'mvt_geom': <Point object at 0x7f552f9d3590>},...> Now the last part is missing. I would like run ST_AsMVT on tile_geometries_mvt: SELECT ST_AsMVT(tile) FROM 'tile_geometries_mvt' AS tile; I tried to create a custom Aggregate function for ST_AsMVT, but was not successful. Normally aggregate function like "MAX" for example expect one column as input, whereas ST_AsMVT expects a "anyelement … -
Django CSRFToken middleware appends to URL and shows up after making a “PUT” request to the server. (AJAX issue)
I’m working on a Django Python/Javascript project. The PUT request is done through the client and sent back to the server. After sending the request successfully, the page makes a refresh which is causing the exposure of the csrf token middleware in the URL. I already implemented AJAX, returning false, added an event.preventDefault(), passed a cookie through the header of the fetch, used async functions, and added a try and catch syntax. And I can’t figure out why it is not affecting the resubmission. Hopefully, someone can let me know what I’m not seeing here. Thanks! // Set global variables to use in form submission var id, upt_prodName, upt_prodPrice, upt_prodDescpt; // Block to populate textarea that allows the user to update product info. const editProd_view = (response) => { let prod_id = response.id; let edit_name = response.name; let edit_price = response.price; let edit_descpt = response.description; let prod_idUpt = (document.querySelector("#prod_idUpt").innerHTML = prod_id); let new_name = (document.querySelector( "#editProdName" ).innerHTML = edit_name); let new_price = (document.querySelector( "#editProdPrice" ).innerHTML = edit_price); let new_textarea = (document.querySelector( "#editProdDescpt" ).innerHTML = edit_descpt); id = prod_id; //On submit, send product info to update the product. const edit_prod = (document.querySelector( "#editProd_form").onsubmit = async () => { try { // … -
Django IntegrityError: UNIQUE constraint failed
I'm trying to prevent a certain Insert on a condtion where a product can have only one base_image as True but as many as we want when base_image=Fasle. I've implemented it with django.db.models.UniqueConstraint, EVERYTHING WORKS FINE but in django admin panel instead of getting a red alert in adding view, I'm getting IntegrityError. here is my model (media.py): from django.db import models from apiv1.models.products import Product class Media(models.Model): """ Media table, contains images file names """ product = models.ForeignKey(Product, related_name='media', on_delete=models.CASCADE, blank=False) file_name = models.CharField(max_length=191, blank=False, unique=True) base_image = models.BooleanField(blank=False) class Meta: constraints = [ models.UniqueConstraint( fields=[ 'product', ], condition=models.Q(base_image=True), name='unique_base_image' ), ] def __str__(self): return self.file_name and this is the error: IntegrityError at /admin/apiv1/media/add/ UNIQUE constraint failed: apiv1_media.product_id Request Method: POST Request URL: http://127.0.0.1:8000/admin/apiv1/media/add/ Django Version: 3.1.4 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: apiv1_media.product_id Exception Location: /Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py, line 413, in execute Python Executable: /Users/sal/devel/artiashco_tipnety_cbir/env/bin/python Python Version: 3.7.3 Python Path: ['/Users/sal/devel/artiashco_tipnety_cbir', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python37.zip', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7', '/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/sal/devel/artiashco_tipnety_cbir/env/lib/python3.7/site-packages'] Server time: Wed, 30 Dec 2020 12:58:16 +0000 Expectation: red bootstrap alert in django admin panel -
disable some of django formfield after user enter category
I have a model that it must get some value from user input, but every category has different fields how can i handel this on one form and with every category disable some other fields? -
Django: show the sum of related Items in a template
I want to get the sum of all values from items related to a certain object. In concrete, I have invoices with one or many items. Each item has a price and I want to calculate the sum of the prices for all the items of one invoice. These are the essential parts of my models.py: from django.db import models from django.db.models import Sum class Invoice(models.Model): @property def price(self): return self.item_set.aggregate(Sum('price')) class Item(models.Model): invoice = models.ForeignKey(Invoice, on_delete=models.CASCADE) price = models.DecimalField(max_digits=8, decimal_places=2) The view.py is simple: class InvoiceDetailView(DetailView): model = Invoice In my template invoice_detail.html, {{ invoice.price }} delivers something like {'price__sum': Decimal('282.400000000000')} So I added get('price__sum') to the price property of the Invoice Model like that: return self.item_set.aggregate(Sum('price')).get('price__sum') The result actually is fine now, i.e. the template shows something like 282.400000000000 (which I still could style a bit), but I wonder, if that's the way to do something like that or if there is a better way? -
Can I use prometheus to count all emails sent by django server in one day?
Actually this is the question. How could I implement this? django-prometheus 2.1.0 prometheus-client 0.8.0 django 2.2.17 -
same tablename in multiple schemas in postgres legacy database
I have legacy postgres db which have same table names in different schemas. when i create models, only one class is created for tablenames which has same tablenames. Settings.py 'rulestore': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS' : { 'options': '-c search_path=adherence,classification,clinicalrules,clinicalvariables,clinicalvariablesrealization,dbo,demographics,deprecated,dosage,druginstance,druglistdefinition,druglistrealization,drugsubstitutiondefinition,drugsubstitutionrealization,incidenceduration,lab,logicalcombination,medicalconditiondefinition,medicalconditionrealization,resultcheck' }, 'NAME': 'SQLOPS_CREF_Rulestore', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'localhost', 'PORT': '5432', } table called drug is available in multiple schemas. Is there any way to get models for tables which has same tablename