Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django channels changes in html appear to every client connected
Hi i have a web live chat app and i have an option for users to create a room of their own, but the problem is that i have to refresh on every other client so they can see the room and the database changes, i tried using WebSocket for the rooms lobby and on room creation recieve and send to everyone a "refresh" but i have already a socket for chat rooms and it seems like manipulating two websockets wont work, they collide on .send in the backend. Is there any option for me to make a "refresh" for all running clients upon room creation without using channels?. thank you :) this is the room creation code : html side <div class="create-room-container"> <form action'.' method='post' class="create-room-form"> {% csrf_token %} <div class="room-labels"> <label for="room-name">Room Name :</label> <input type="text" id="room-name" name="room-name" placeholder="Enter room name..."> </div> <input type="submit" value="Create Room" class="create-room-button"> </form> views.py side @login_required def rooms(request): if request.method == 'POST': room_owner = request.user room_name = request.POST['room-name'] if not Room.objects.filter(slug = room_name).exists(): if room_name == '' or room_name.isspace() or room_name.startswith(' '): messages.info(request, 'Invalid room name, spaces-only or string that starts with spaces is invalid.') else: new_room = Room(owner = room_owner,name = room_name,slug … -
Error in using crispy form in django when i created signup from
In template /home/vivekdevkar/Desktop/code/Django/social_media/socialenv/lib/python3.10/site-packages/crispy_forms/templates/bootstrap4/uni_form.html, error at line 8 -
Loading static file to a css file django-python
I have a css file and I want to link another static file to it.How can I accomplish this @font-face { font-family: 'tinymce-mobile'; font-style: normal; font-weight: normal; src: url("fonts/tinymce-mobile.woff?8x92w3") format("woff"); } how can I load this "font/static-mobile.woff" Both {% load static %} and {% load staticfiles%} are not working -
Live Data in Django - Ajax
My aim is to add data to see on the screen whithout refreshing the page. In this code I use un setInterval, but I don't like it. I want to use a method that updates data only when I add new data with the admin Django. JavaScript let tab = document.getElementById('tabella'); setInterval(function() { fetch("{% url 'ajax' %}") .then(response => response.json()) .then(result => { tab.innerHTML = ''; for(let i in result.users) { var text = `<tr><td>${result.users[i].nome}</td> <td>${result.users[i].cognome}</td> <td>${result.users[i].telefono}</td> <td>${result.users[i].email}</td></tr>`; tab.innerHTML += text; } }); }, 1000) views.py def Home(request): return render(request, 'index.html') def Ajax(request): queryset = Utenti.objects.all() return JsonResponse({'users':list(queryset.values())}) urls.py from django.urls import path from .views import Home, Ajax urlpatterns = [ path('', Home, name='index'), path('ajax', Ajax, name='ajax'), ] -
can you create a model object in a model method in Django
is something like this possible: class Comment(models.Model): video = models.ForeignKey(Video, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) text = models.TextField() def create_comment_in_template(self, video, user, text): Comment.objects.create(video=video, user=user, text=text) ///// no return -
How to send an email through Sendgrid (in django) as a reply to an email I received from let's say an end user?
So I figured out how to send single/bulk email(s) and then also how to receive emails through SendGrid. What I want to do now is to send an email which will be a reply to an email I received. So basically, I don't want to create a new conversation on let's say Gmail or Outlook, I want my email to be a reply and fall under the hood of another email that I received. -
Django on_delete=models.CASCADE not working when using related_name
I have a model named Proposal which is related to the model Customer by two different fields. I want that if any of the related users gets deleted the proposal will also get deleted. However, the on_delete=models.CASCADE is not achieving that. I guess I could use a signal to trigger this behaviour but I want to know if there is a better way to make it work in Django 4.0. class Proposal(models.Model): # foreign keys created_by_customer = models.ForeignKey(Customer, blank=False, on_delete=models.CASCADE) accepted_by_customer = models.ForeignKey(Customer, blank=True, null=True, on_delete=models.CASCADE, related_name='accepted_by_customer') This is my test with Pytest: @pytest.mark.django_db def test_delete_proposal_from_created_by_customer(): """ Deleting customer that created the proposal must delete proposal """ created_proposal = random_proposal() buyer = random_customer() created_proposal.created_by_customer = buyer created_proposal.created_by_customer.delete() -
How do i check for duplicates in django MongoDB database
I have an table in mongodb with 5000 records. I need to find the email_id field duplicate values from that table. How can i find it. -
Displaying Foreignkey table Data in Django?
I'm a Django Beginner and I was dealing with same problem as in :(How to display Foreignkey table Data in Django?) but the solution to mine was pretty simple which left me to wonder HOW? And even after I got rid of the problem I've a query . My Models were : class Customer(models.Model): name = models.CharField(max_length=64, unique=False) cust_id = models.CharField(max_length=10, unique=True) class Employee(models.Model): name = models.CharField(max_length=64, unique=False) salary = models.BigIntegerField() emp_id = models.CharField(max_length=10, unique=True) class Order(models.Model): order_id = models.CharField(max_length=64, unique=True) assigned_to = models.ForeignKey(to=Employee, on_delete=models.CASCADE) given_by = models.ForeignKey(to=Customer, on_delete=models.CASCADE) bill = models.IntegerField(null=False) As you can see my Order model contains " assigned_to " so in HTML template I wrote it as : {% for x in my_orders %} <tr> <td>{{ x.assigned_to }}</td> </tr> {% endfor %} and all I was getting a blank space I went to shell and get the queryset which showed it as "assigned_to_id" instead of "assigned_to". and then changing in HTML as : {% for x in my_orders %} <tr> <td>{{ x.assigned_to_id}}</td> </tr> {% endfor %} worked for me. Why is that? -
How to Fill Form Automatically After Fill a Value on a Form(AutoFill) Django/Ajax/Etc
Im Stuck in progress for autofill some form, I just wanna do something like this https://miro.medium.com/max/1200/0*muz52MGfi2K93nMt.gif, Here The Model Class I Have : from django.db import models class Contact(models.Model): name = models.CharField(max_length=100) email= models.EmailField() message= models.TextField() def __str__(self): return self.name Then I have Views.py Function Like This: def autofill(request): if is_ajax(request=request): term = request.GET.get('name') contact = Contact.objects.all().filter(name__icontains=term) response_content = list(contact.values()) return JsonResponse(response_content, safe=False) return render(request, 'form_autofill.html') def value_autofill(request): values = Contact.objects.values('name', 'email', 'message') data_dict = {} for dict in values: data_dict[dict['name']] = dict['email'], dict['message'] return JsonResponse(data_dict) There are two function here autofill and value_autofill. the idea is retrieve data from db then convert it into json file based on input value from the template. here the form_autofill.html code : {% block content %} <body> <h2>HTML Forms</h2> <form action="", method="GET"> {% csrf_token %} <label for="name">Name:</label><br> <input type="text" id="name" name="name"><br> <label for="email">Email:</label><br> <input type="text" id="email" name="email" ><br><br> <label for="message">Message:</label><br> <input type="text" id="message" name="message" ><br><br> <input type="submit" value="Submit"> </form> <script> $(document).ready(function() { async function getValues(event, ui) { let url = "{% url 'ajax:values' %}"; let results = await fetch(url);; let data = await results.json(); return data; }; async function AutoCompleteSelectHandler(event, ui){ let vals= await getValues(); $('#email').val(vals[ui.item.value]); }; $("#name").autocomplete({ source: "{% url 'ajax:autofill' %}", … -
How to set a custom url with "admin/" properly? (Django)
I set the custom url "admin/success/" with "admin/" as shown below: # "core/urls.py" urlpatterns = [ path("admin/", admin.site.urls), path("admin/success/", success, name='success'), # Here ] And, this is "views.py": # "core/views.py" from django.http import HttpResponse def success(request): return HttpResponse("Hello World") Then, I got "Page not found (404)" error as shown below: But, when I removed "admin/": # "core/urls.py" urlpatterns = [ # path("admin/", admin.site.urls), # Here path("admin/success/", success, name='success'), ] The custom url is displayed properly as shown below: So, are there any ways to properly set the custom url "admin/success/" with "admin/" so that the custom url is displayed properly? -
TR, TH, TD was created but TABLE NOT
i Need understand it but not be able to. My ClassForm (in view): class FormContact(forms.Form): name = forms.CharField(label='Nome', max_length=100, required=False) subject = forms.CharField(label='Assunto', max_length=100, required=False) message = forms.CharField(label='Mensagem', widget=forms.Textarea, required=False) My extended Template: {% extends 'site.html' %} {% load static %} {% block content %} <form class="contato" id="contato" action="{% url 'contato' %}" method="post"> <h1>Contato</h1> {% csrf_token %} {{ form }} <input type="submit" value="Submit"> </form> <script src="{% static 'js/form_contact.js' %}"></script> {% endblock %} Now, in the navigator (inspector -> elements) <form class="contato" id="contato" action="/contato/" method="post"> <h1>Contato</h1> <input type="hidden" name="csrfmiddlewaretoken" value="???"> <label for="id_name">Nome:</label> <input type="text" name="name" maxlength="100" id="id_name"> <label for="id_subject">Assunto:</label> <input type="text" name="subject" maxlength="100" id="id_subject"> <label for="id_message">Mensagem:</label> <textarea name="message" cols="40" rows="10" id="id_message"></textarea> <input type="submit" value="Submit"> /form> AND, in the navigator (Ctrl+U) View Code <form class="contato" id="contato" action="/contato/" method="post"> <h1>Contato</h1> <input type="hidden" name="csrfmiddlewaretoken" value="YmeKARCvhCLs1EsHedcO1h4OldOaVZ3WKiqGAVZTEJbrYq9ElBVzKQ2EWdHZPw0J"> <tr> <th><label for="id_name">Nome:</label></th> <td> <input type="text" name="name" maxlength="100" id="id_name"> </td> </tr> <tr> <th><label for="id_subject">Assunto:</label></th> <td> <input type="text" name="subject" maxlength="100" required id="id_subject"> </td> </tr> <tr> <th><label for="id_message">Mensagem:</label></th> <td> <textarea name="message" cols="40" rows="10" required id="id_message"></textarea> </td> </tr> <input type="submit" value="Submit"> </form> My doubt is: Why, in the Ctrl+U, was created the elements TR, TH and TD but TABLE not? I can't understand it It is this form same? -
Use Like on Date in sql query
SELECT survey_id, orchardist_name, village, panchayat, dev_block, tehsil, district, survey_id AS ACTION FROM hd_survey_head WHERE created_on BETWEEN '%%' AND '%%' AND dev_block='CHAUPAL' AND panchayat LIKE '%%' AND village LIKE '%%' On my live website, there is a start date and end date option which is mandatory to fill to run a query in the backend to fetch some data with other dropdowns as well. Now the problem is I want to make it optional not mandatory and still run the query is it possible if yes please tell me how to edit this query to work. -
How to aggregate sum of several previous aggregated values in django ORM
In use: django 3.2.10, postgresql 13.4 I have next query set with aggregation function Count queryset = Model.objects.all().aggregate( trues=Count('id', filter=Q(criteria=True)), falses=Count('id', filter=Q(criteria=False)), ) What I want: queryset = Model.objects.all().aggregate( trues=Count('id', filter=Q(criteria=True)), falses=Count('id', filter=Q(criteria=False)), total=trues+falses, <--------------THIS ) How to do this? -
Add column with status to csv while uploading using django
I have created a method to read and upload csv using python django. But, if i want to add a column with status to the csv getting uploaded, how to do? -
django_python3_ldap using multiple OU in LDAP_AUTH_SEARCH_BASE
need some help... i'm using django_python3_ldap and it works fine when i change settings.py for each run using different LDAP_AUTH_SEARCH_BASE . userxxx is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=xxx Accounts,OU=ZZZ,DC=domain,DC=local useryyy is logged in with LDAP_AUTH_SEARCH_BASEOU=Users,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local i have tried with LDAP_AUTH_SEARCH_BASEOU=OU=Users,OU=xxx Accounts,OU=yyy Accounts,OU=ZZZ,DC=domain,DC=local and this gives noSuchObjec ..... 0000208D: NameErr: DSID-03100241, problem 2001 (NO_OBJECT), any hint? -
Optional related form in Django
I've a Customer model and an Address model. Customer model have a not-required ForeignKey to Address. Address model have all fields required. I want to have a form to enter customers with the ability to optionally enter an address, so i make a view with a form for each and send it to the template. Now i can't subbmit the customer because the required address fields prevent me from doing so. I would like to have a link to press to bring up the form with the address -
use npm library in django template
I want to use javascript npm module in django template. In javascript document, it says npm install waveform-playlist --save on cli and to use this line in code. import WaveformPlaylist from "waveform-playlist"; So, for now I write this script in template.html <script> import WaveformPlaylist from "waveform-playlist"; </script> this error comes. Cannot use import statement outside a module (at tracks:96:5) I think some basic idea is wrong? How can I use this type of javascript? -
html form table td value is not saving in database of django
I am trying to save td value which I am getting through Js in database using django. I am specifying name to td but its not saving giving me this error. :(1048, "Column 'total' cannot be null") td is in my footer(tfoot) Why my value is not saving in database on POST : html <tfoot> <tr> <th colspan="5"></th> <th id="total">Total :</th> <td name="total" id="total_value"></td> </tr> </foot> views.py total= request.POST.get('total') or total= request.POST['total'] -
FOREIGN KEY constraint failed when any staff_user saves any object in the admin page
saving any object as admin (the first superuser i created from the cli) in the admin page works just fine. but whenever any other staff_user (whether he is a superuser or not ) tries to save any object i get an error django.db.utils.IntegrityError: FOREIGN KEY constraint failed only the admin user mentioned aboove can do so, this is the traceback Traceback (most recent call last): File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/db/backends/base/base.py", line 242, in _commit return self.connection.commit() sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 472, in thread_handler raise exc_info[1] File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/core/handlers/exception.py", line 38, in inner response = await get_response(request) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/core/handlers/base.py", line 231, in _get_response_async response = await wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 435, in __call__ ret = await asyncio.wait_for(future, timeout=None) File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for return await fut File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/asgiref/sync.py", line 476, in thread_handler return func(*args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/contrib/admin/options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/views/decorators/cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/home/bedo/RealOtakus/venv/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 233, in inner … -
Django/Python: post_save signal - expected string or bytes-like object
I have a post_save signal which is failing with 'expected string or bytes-like object'. I am not sure why, it is being caused by the call to create_user below:- This is to create a user within a tenant schema for a newly created tenant: @receiver(post_save, sender=Client) def create_user(sender, instance, created, **kwargs): if created: tenant=instance with schema_context(tenant): name = 'name' email = 'name@email.com' password = 'passwordexample' user = CustomUser.objects.create_user(name, email, password) The underlying user manager which throws the exception is def create_user(self, name, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) name = self.normalize_email(name) email = self.normalize_email(email) user = self.model(name=name, email=email, **extra_fields) user.set_password(password) user.save() return user This seems to fail on user.save() in the above manager Any help or pointers greatly appreciated Thank you -
How can i select needed db for Pytest? I have 2 - one remote, one local. I need pytest to be started on local
The default db is cloud one. And when pytest tries to create a temporary data it got permissions error. So i want to create a second database to be used with pytest. How can i select this database in pytest config? DATABASES = { 'default': { 'NAME': config['database']['name'], 'ENGINE': '...', }, 'tests_db': { "NAME": "tests_db", "ENGINE": 'django.db.backends.sqlite3', } } -
Django - showing amount of objects pointing to a key?
I have a very noob question, in fact, so noob, that despite there being multiple answers on the topic, I simply cant implement it to my project. I have a list of job offers, and my problem is to list how many offers are in each job offer. For example Offer: welder - we have 7 positions models.py from django.db import models from django.contrib.auth.models import User from django.db.models import Count STATUS = ( (0,"Inactive"), (1,"Active") ) class Offer_type(models.Model): type = models.TextField() class Meta: ordering = ['-type'] def __str__(self): return self.type class Offer_general(models.Model): offer_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) status = models.IntegerField(choices=STATUS, default=0) type = models.ForeignKey(Offer_type, on_delete= models.PROTECT) class Meta: ordering = ['-id'] def __str__(self): return self.offer_name class Offer_localization(models.Model): localization = models.TextField() class Meta: ordering = ['-localization'] def __str__(self): return self.localization class Offer_details(models.Model): slug = models.SlugField(max_length=200, unique=True) localization = models.ForeignKey(Offer_localization, on_delete= models.PROTECT, default="Opole") fk_offer_general_id = models.ForeignKey(Offer_general, on_delete= models.PROTECT) updated_on = models.DateTimeField(auto_now= True) content = models.TextField() requirements = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=0) class Meta: ordering = ['-id'] def __str__(self): return self.slug views.py from django.shortcuts import render from django.views import generic from django.db.models import Count from .models import Offer_general from .models import Offer_details # Create your views … -
find unique values in django
I am a beginner with Django. My question is, How can i retrieve all unique category name in search_result? My models.py class Category(models.Model): category_name = models.CharField(max_length=20, unique=True) logo = models.ImageField(upload_to='Category') slug = models.SlugField(unique="True") def __str__(self): return self.category_name class Product(models.Model): product_name = models.CharField(max_length=50, blank=False) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="", blank=True, related_name="Products") price = models.FloatField(blank=False, default=0.00, validators=[MinValueValidator(0.0)], help_text='Price Can not be Less than Zero.') def __str__(self): return self.product_name My views.py class SearchView(TemplateView): template_name = "productstemplate/products.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user_search = self.request.GET['product'] search_result = Product.objects.filter(Q(product_name__icontains=user_search) | Q(category__category_name__icontains=user_search)) context['products'] = search_result context['categorys'] = ===>> Here <<=== return context -
How to use the parameter queryset of model formset in ModelForm?
# this is my model class Creator(models.Model): name = models.CharField(max_length=50) class Article(models.Model): title = models.CharField(max_length=688, blank=True) creator = models.ForeignKey(Creator, on_delete=models.CASCADE) class ArticleCoAuthor(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) co_author = models.CharField(max_length=190) # code ArticleFormset = modelformset_factory(Article, form=forms.ArticleForm, extra=1, can_delete=True) article_formset = ArticleFormset( prefix="article", queryset=creator.article_set.prefetch_related("articlecoauthor_set").all() ) # this is my form class ArticleForm(forms.ModelForm): ...... I want to express all the data of the ArticleCoAuthor referenced when representing a row of Articles. How can I convey the "co_author" value, which is the result of "querieset" in "article_formset", and use it in "ArticleForm"?