Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
group the json object by month, product and total product sale in a month
my ouput: "dataSource1": [ { "date": "Oct-20", "product": "A", "sale": 10 }, { "date": "Nov-20", "product": "A", "sale": 12 }, { "date": "Oct-20", "product": "B", "sale": 12 }, { "date": "Nov-20", "product": "B", "sale": 13 }, { "date": "Oct-20", "product": "C", "sale": 13 }, { "date": "Nov-20", "product": "C", "sale": 14 }, expected output: { "date": "Oct-20", "A": 10, "B": 12, "C": 13, }, { "date": "NOV-20", "A": 12, "B": 13, "C": 14, }, -
in django models how can i create view for boolean value in django
i create a models for user in django models.py all i want is only when user Select true then save the form and redirect to page otherwise in other page without saving the form models.py class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,) yes = models.BooleanField(null=True, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) def __str__(self): return self.user.username forms.py class CustomerForm(forms.ModelForm): model = Customer fields = '__all__' exclude = ['user','joined_date'] the view i created is just basic view i know it's not gonna work like that views.py def customer(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid: form.save() return redirect('/Ecommerce/') else: form = CustomerForm() return render(request, 'customer.html', {'form': form}) my html {% extends 'masteraccount.html' %} {% load crispy_forms_tags %} {% block head %} <link rel="stylesheet" href="{% static 'css/bootcss/bootstrap.min.css'%}"> {% endblock%} {% block content %} <div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} <div> {{ form.yes||as_crispy_field }} <button type="submit"></button> </div> </form> </div> {% endblock %} -
How to request by Ajax in django
I have a simple django chat app so I don't want to reload the page every request, it make the UX too bad, here is my code : this is the function of the chat room def chat_room(request, id): chat_room = ChatRoom.objects.get(id = id) messages = UsersContact.objects.filter(chat_room_id = id).order_by('-created')[:30] chat_room.new = False chat_room.save() return render(request, 'chat_room.html', {'messages': messages, 'chat_room': chat_room, 'id': id}) this is the function of creating reply on the chat room def create_reply(request, id): chat_room = ChatRoom.objects.get(id = id) author = request.user profile = Profile.objects.get(profile_id = chat_room.reciever.id).user if request.method == 'POST': content = request.POST['reply'] chat_room.new = True chat_room.save() Reply.objects.create(chat_room_id = chat_room.id, author = author, profile = profile, content = content).save() return redirect('contact:chat_room' ,id = id) This is the template code {% for message in messages reversed %} {% if request.user != message.author %} <div> <img src="/media/{{message.author.profile.photo}}"> <p> {{message.content}} </p> <span>{{message.created}}</span> </div> {% else %} <div> <img src="/media/{{message.profile.profile.photo}}"> <p> {{message.content}} </p> <span>{{message.created}}</span> </div> {% endif %} {% endfor %} <form method="POST" action="{% url 'contact:create_reply' chat_room.id %}"> {% csrf_token %} {% if request.user == chat_room.sender %} <input type="text" name="reply" placeholder="Send message to {{chat_room.reciever}}" required> {% else %} <input type="text" name="reply" placeholder="Send message to {{chat_room.sender}}" required> {% endif %} <button type="submit">Send</button> … -
django proxy model's property to a real model
I am trying to use proxy models to differentiate two user types and add some more attributes through another model: class User(AbstractUser): full_name = models.CharField(max_length=300) class Patient(User): class Meta: proxy = True @property def profile(self): return self.patientprofile class PatientProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='PatientProfile') blood_type = models.CharField(max_length=2, blank=True) #some attributes here The problem is that I am not sure how should I connect my proxy model's profile to a PatientProfile. The first thing that comes to mind is to connect them at instance creation time, but it doesn't feel right. I think there is a way to link them as the model is a proxy. I looked through the documentation, but all I could find is how to use modelManagers... -
What is the best way to migrate my AWS RDS database (django)?
I am in the process of setting up a Django deployment with a relational database service (RDS) from amazon (AWS). I wonder what is the best way to update the database? What I did first First I worked with container commands in project/.ebextensions/db-migrate.config: container_commands: 10_migrate: command: | source $PYTHONPATH/activate pipenv run python ./manage.py migrate option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: <app>.settings I found that this resets the database every time. Also, I couldn't use the "createsuperuser" command because I can't interactively add a username and password (the logs give a similar error). What I do now: I added my IP to the incoming rules from the database. Then I changed the database configuration in settings.py to the RDS endpoint. Now I can use migration commands and I can create a superuser. But is this the usual way? Can you tell me more about security? -
how can I get all reverse relation names in the Django model?
how can I get all reverse relation names in the Django model? I wanna know all related_name that link to my model, How can I do that? -
Django update boolean field with a form
My simple web-application has two models that are linked (one to many). The first model (Newplate) has a boolean field called 'plate_complete'. This is set to False (0) at the start. questions: In a html page, I am trying to build a form and button that when pressed sets the above field to True. At the moment when I click the button the page refreshes but there is no change to the database (plate_complete is still False). How do I do this? Ideally, once the button is pressed I would also like to re-direct the user to another webpage (readplates.html). This webpage does not require the pk field (but the form does to change the specific record) Hence for now I am just refreshing the 'extendingplates.html file. How do I do this too ? My code: """Model""" class NewPlate(models.Model): plate_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=200) created_date = models.DateTimeField(default=timezone.now) plate_complete = models.BooleanField() """view""" def publish_plates(request,plate_id): newplate = get_object_or_404(NewPlate, pk=plate_id) newplate.plate_complete = True newplate.save() #2nd method NewPlate.objects.filter(pk=plate_id).update(plate_complete = True) return HttpResponseRedirect(reverse('tablet:extendplates', args=[plate_id])) """URLS""" path('readplates', views.read_plates, name='readplates'), path('extendplates/<pk>/', views.show_plates, name='showplates'), path('extendplates/<pk>/', views.publish_plates, name='publishplates'), """HTML""" <form method="POST" action="{% url 'tablet:publishplates' newplate.plate_id %}"> {% csrf_token %} <button type="submit" class="button" value='True'>Publish</button></form> Thank you -
How to pass JavaScript variable from Django-object in html template?
Here, I'm trying to convert the text to speech from django object and sorry to say that I don't know basic Js. Here is what I've tried. Code HTML <p class="mb-1">{{ obj.reply }}</p> <button class="btn btn-dark" onclick="txttospeech(obj.reply)">listen</button> js function txttospeech(txt) { var utterance = new SpeechSynthesisUtterance(); utterance.text = txt; speechSynthesis.speak(utterance); } -
Django include fields from AbstractUser to registration form
I am new to Django and need some help. I am trying to include two fields into my registration form. Sow person how wonts to register can determine if he or she wants to register as majstor or korisnik. I added, into AbstractUser. Tho's fields majstor and korisnik as BooleanField.How to add optional fields in a form, sow a person can choose one of those values? This is mine korisnik/model.py file: from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse class CustomKorisnici(AbstractUser): majstor = models.BooleanField(default=False) korisnik = models.BooleanField(default=False) username = models.CharField(max_length=100,unique=True) last_name = models.CharField(max_length=100) first_name = models.CharField(max_length=100) phone_number = models.CharField(max_length=100) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) email = models.EmailField(max_length=100,unique=True) This is mine members/forms.py file from django.contrib.auth.forms import UserCreationForm from korisnici.models import CustomKorisnici from django import forms class SingUpForm(UserCreationForm): 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'})) class Meta: model = CustomKorisnici fields = ('username','first_name','last_name','email', 'password1','password2') def __init__(self,*args,**kwargs): super(SingUpForm,self).__init__(*args,**kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' self.fields['password1'].widget.attrs['class'] = 'form-control' self.fields['password2'].widget.attrs['class'] = 'form-control' -
MultiValueDictKeyError when trying to get POST charfield value using django
i have a django code which post value and retrieve it inside views.py . but when i tried to retrieve the data it is throwing me MultiValueDictkeyError . I checked whether any multiple values are passed but no where multiple values are passed . Can anyone check on this . Here is my html file . <form method="POST" enctype="multipart/form-data" >{% csrf_token %} <p> <label for="pa">App:</label> <select name = "app"> <option value = "select" selected > Select </option> {% for i in result %} <option value = "{{i.apptype}}" > {{i.apptype }} </option> {% endfor %} </select> &ensp; &ensp; &ensp; &ensp; &ensp; &ensp; &ensp; &ensp;&ensp; &ensp; &ensp; &ensp; &ensp; &ensp; &ensp; &ensp; <label for="cu">Customer:</label> <select name = "customerdrop"> <option value = "select" selected > Select </option> {% for j in result1 %} <option value = "{{j.customer}}" > {{j.customer }} </option> {% endfor %} </select> <button type="submit"style="background-color:#FFFF66;color:black;width:150px; height:40px;">Save Template</button> <input type="button" style="background-color:#FFFF66;color:black;width:150px; height:25px;" value="Save Template as :"/> <input type="text" id="fname" name="fname" value=""/><br> </form> Model.py class config(models.Model): app = models.CharField(max_length=100) customerdrop = models.CharField(max_length=100) views.py def pg2(request): conn = pyodbc.connect('Driver={SQL Server};' 'Server=abc\abc;' 'Database=UI;' 'Trusted_Connection=yes;') if request.method == 'POST': print('inside Post') print(request.POST['app']) print(request.POST['customerdrop']) so, it prints " inside Post " , and app too , but … -
How to improve count of text query for Django with Postgres
I'm having a problem when counting query results for a full-text search. I have a model where one of the fields is: search_vector = SearchVectorField(null=True) with the index: class Meta: indexes = (GinIndex(fields=["search_vector"]),) Then in the view I have the following query: query = SearchQuery(termo,config='portuguese') search_rank = SearchRank(F('search_vector'), query) entries = Article.objects.annotate(rank=search_rank).filter(search_vector=query).order_by('-rank') And now if I apply the count method to entries it takes a long time. About 2 seconds, when I have a small database with about 200k rows. -
Storing multiple values in django model field
I'm trying to build a price browser like app connected with web scrapign in django and have a problem. I've got a Product model which obviously stores the current price of said product, but also I would like to store all previous product prices for analitical reasons. What would be a better solution, creating additional model with price history and connecting it via foreign key or something else which I obviously dont know about? What would be your suggestion ? class Product(models.Model): """Product object""" CATEGORY_CHOICES = ( ('GPU', 'Graphics Card'), ('CPU', 'Processor') ) product_id = models.AutoField(primary_key=True) product_name = models.CharField(max_length=255) image = models.ImageField() link = models.URLField(max_length=255) price = models.DecimalField(decimal_places=2) #product_price_history placeholder line category = models.CharField(choices=CATEGORY_CHOICES) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.product_name -
How to make grid of video from rtsp using django?
I want to fetch video from rtsp link which are stored in database and display all video in one template but while doing that i am getting following error: NoReverseMatch at /cctv_view/ Reverse for 'livecam_feed' with arguments '('rtsp://wowzaec2demo.streamlock.net/vod/mp4:BigBuckBunny_115k.mov',)' not found. 1 pattern(s) tried: ['livecam_feed/(?P<camera_id>/rtsp.*)/$'] urls.py path('cctv_view/',views.cctv_view,name = 'cctv_view'), re_path(r'^livecam_feed/(?P<camera_id>/rtsp.*)/$' ,views.livecam_feed,name = "livecam_feed"), views.py def cctv_view(request): cttv_forms = Cttv_forms(request.POST or None,error_class = DivErrorList) ips = [ips for ips in CCTV.objects.all()] for ip in ips: ip = [re.sub(r'\([^()]*\)', '', str(ip)) ] context = { 'cttv_form' :cttv_forms, 'ips':ip, } return render(request,'cctv_view.html',context) def gen(camera): while True: frame = camera.get_frame() yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') def livecam_feed(request,camera_ip): return StreamingHttpResponse(gen(LiveWebCam(camera_ip)), content_type='multipart/x-mixed-replace; boundary=frame') template.py <div class = "row video_row" > {% for camera_id in ips %} <div class = "col-md-6 video-col"> <img src="{% url 'livecam_feed' camera_id %}" id = "vid"> </div> {% endfor %} </div> Thanks in advance -
Django Defect-dojo: LDAP integration
how can i integrate defect-dojo with LDAP all written in the documentation is this page https://django-auth-ldap.readthedocs.io/en/latest/install.html -
How to get auth_group show up on admin site with custom User-Model
In my app I got the following custom user model: class User(AbstractUser): driver_number = models.CharField(max_length=100, blank=True, null=True) hasacceptdataprivacy_timestamp = models.DateTimeField(db_column='hasAcceptDataprivacy_timestamp', blank=True, null=True) Which I registered on the admin page: class MyUserAdmin(UserAdmin): pass admin.site.register(User, MyUserAdmin) When creating a User in the adminpanel there is the option to assign him to groups, which I guess are the automatically created auth_groups created by the django authorization model. Those dont appear on my admin panel though, so that I cant create new auth_groups. What do I have to do to make them show up there? -
Utilizacion de trigers en model django
Buenas quisiera usar triggers/eventos en django con postgresql.Los triggers comunes After,Before con INSERT,UPDATE y DELETE.He estado buscando información y he encontrado: 1.- django-pgtriggers (paquete que estoy analizando) 2.- signal en django (algunos en foros y demas que no es muy recomendable,aunque igual lo he investigado un poco) 3.- modificar el metodo save(commit=false: para elegir cuando guardar) Soy nuevo en django asi que si tienen alguna sugerencia de que seria mejor para lograr mi objetivo gracias -
I tried to run "heroku run Python manage.py migrate" it throws an error ModulenotfoundError no module named django
And also it shows ImportError: Could not import django.are you sure it's installed and available on you Python path environment variable? Did you forget to activate a virtual environment? I tried all of these i check my django its working fine , if i tried "Python manage.py run server" server is running without any issues. -
How would one go about implementing a search by image function in DjangoRestFramework?
I am building an app which lets the user to upload an image to the server and the server will return the most similar image in the database. I implemented a basic algorithm to do this, but I can not figure out how to actually let the user upload the image to the server. I am using the DjangoRestFramework. I now have implemented a feature to upload an image to the database by having ViewSet with CreateModelMixin implemented. However I want to let the user upload an image, run my algorithm and then return and ID of most similar image. What function/viewset should I look into? I am beginner in REST -
Django ORM - Get distinct objects based on string
My object has this layout on mariaDB (no postgres here): +------+------------------------------+----------+---------+--------------------------------------------+ | id | created | message | from | guest_id | +------+------------------------------+----------+---------+--------------------------------------------+ | '45' | '2021-03-02 21:32:56.756966' | 'Hello ' | 'host' | 'e5b15b726e1224ca1d70ad9cf6a6e2a485de5478' | | '46' | '2021-03-02 23:32:56.756966' | 'bye' | 'guest' | 'e5b15b726e1224ca1d70ad9cf6a6e2a485de5478' | | '47' | '2021-03-02 24:32:56.756966' | 'still ' | 'guest' | 'a7c3bdf1adc0e9f821f8727e83e76ae3821cf47e' | | '48' | '2021-03-03 00:32:56.756966' | 'here ' | 'host' | 'a7c3bdf1adc0e9f821f8727e83e76ae3821cf47e' | +------+------------------------------+----------+---------+--------------------------------------------+ As you can see, i have two results for each guest_id, i'd like to have only the last one from the latest "created" resulting in: +------+------------------------------+---------+---------+--------------------------------------------+ | id | created | message | from | guest_id | +------+------------------------------+---------+---------+--------------------------------------------+ | '46' | '2021-03-02 23:32:56.756966' | 'bye' | 'guest' | 'e5b15b726e1224ca1d70ad9cf6a6e2a485de5478' | | '48' | '2021-03-03 00:32:56.756966' | 'here ' | 'host' | 'a7c3bdf1adc0e9f821f8727e83e76ae3821cf47e' | +------+------------------------------+---------+---------+--------------------------------------------+ This is what i came up with: queryaux = Message.objects.filter(guest__reservation__home=home).values('guest_id').distinct().order_by() queryset = Message.objects.filter(guest__in=queryaux).latest('created') queryaux contains the set of elements i need (no duplicates) but only the guest_id, not the full object (Because of values() ) queryset Should have the corresponding objects, but it gets only one object, the latest from the set My solution (Which uses iterators and concatenation of querysets … -
Deploy django project
Hello all I wanna to deploy a django project on my PC that is windows 10 and there is not any manage.py file in it How I can run server? following pic is the files enter image description here -
Error : Can't connect to local MySQL server through socket
I am using Ubuntu 20.04 with python3 installed in it. I am making a django project for that i have to connect to the database. I have installed XAMPP server on my Ubuntu, I start mysql service from there only. When i run... python3 manage.py makemigrations It gives this kinda error... MySQLdb._exceptions.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") I checked my.cnf file which is kept at /opt/lampp/etc, I found there socket variable like.. socket = /opt/lampp/var/mysql/mysql.sock So, As per me I think there is some mistake in socket variable in django project or in mysql but not confirmed. Can anyone tell me how to solve this error? -
Declaring foreign key in django model
i have recently started using django to read out oracle database. I am having a problem with created a model with foreign key. Here is what i have in oracle schema: CREATE TABLE MTRS_CHANNELS(ID int NOT NULL PRIMARY KEY, ALIAS VARCHAR(255) NOT NULL UNIQUE, BOARDNUMBER int, CHIPNUMBER int, CHANNELNUMBER int, TYPEID int, SYSTEMNAME VARCHAR(255)); ALTER TABLE MTRS_CHANNELS ADD CONSTRAINT uniquesensornaming UNIQUE (BOARDNUMBER , CHIPNUMBER , CHANNELNUMBER, SYSTEMNAME); CREATE TABLE MTRS_DATA(CHANNELID int NOT NULL, FLAG int, UPDATETIME TIMESTAMP, VALUE FLOAT); ALTER TABLE MTRS_DATA ADD CONSTRAINT CHANNELIDENTIFIER FOREIGN KEY (CHANNEL_ID) REFERENCES MTRS_CHANNELS(ID); Basically there are 2 tables MTRS_CHANNELS which stores channels identified by unique channelid and MTRS_DATA stores value for a channel, which is referenced by channelid as foreign key. In my models.py i have : from django.db import models class Channel(models.Model): id = models.IntegerField(primary_key=True) alias = models.CharField(max_length=256) boardnumber = models.IntegerField() chipnumber = models.IntegerField() channelnumber = models.IntegerField() typeid = models.IntegerField() systemname = models.CharField(max_length=255) class Meta: db_table = "MTRS_CHANNELS" managed = False class values(models.Model): channel = models.ForeignKey(Channel,on_delete=models.CASCADE) updatetime = models.DateTimeField() value = models.FloatField() class Meta: db_table = "MTRS_DATA" managed = False The problem is that i am trying to load data in view it complains with : ORA-00904: "MTRS_DATA"."ID": invalid identifier When i … -
Compare mutiple ids present in list of dictionaries with the ids of model django
How can i make an efficient django orm query, which will compare ids from the list of dictionaries with the ids as foreign key in other model, e.g i have two models Product: product_name=models.CharField(max_length=20) ProductOrder: order_status=models.BooleanField() product=models.ForeignKey(Product,on_delete=models.CASCADE) now i want extract every product which is present in product order. in simple query i can do this way: prod=ProductOrder.objects.all() products=Product.objects.all() for prod in prod: for products in products: if prod.product==products.id: # save product Is there any way to get this through one query or more efficiently? -
Hosting Python Django in Heroku
when I was trying to host the python, Django app in Heroku I'm facing this error the command which I used is >git push heroku master -
Automatically save list of images in ImageField after upload - django 3
Working with Django 3, I have the following model: class Case(models.Model): slug = ShortUUIDField(max_length=3) title = models.CharField(max_length=50) #.... ct = models.FileField(upload_to='files/') class ModelImages(models.Model): case = models.ForeignKey(Case, on_delete=models.CASCADE, related_name="slices_images") img = models.ImageField(upload_to='images/', editable=False) #.... position = models.PositiveSmallIntegerField(editable=False) Once 'ct' (a 3D image) is uploaded (and this works perfectly), I want to extract the slices of the 'ct' and save them as images in 'ModelImages' class. I extract the images with a function called 'get_slices(ct)' The images are hundreds for each 'ct' This should be fully automatic. How can I do it?