Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form - Display M2M choices in multiselect check boxes' list
I'm trying to build a form where multi select checkboxes will allow user to make is choices regarding a fields linked to the form's model with M2M relation ship. I managed this but made a lot of test to display additional information, and now that I chose a solution (bases on my model's __str__() method), I'm not able to display a list of all groups where those already linked to my event are checked. Again, probably a very small detail I missed, but I do not see anything and I would appreciate some help. Some pieces of code at this stage. Models: class UserGroup(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) users = models.ManyToManyField(UserComp, verbose_name="utilisateurs", blank=True) group_name = models.CharField("nom", max_length=100) weight = models.IntegerField("poids", default=0) hidden = models.BooleanField(default=False) @property def nb_users(self): return UserComp.objects.filter(usergroup=self).count() def __str__(self): return self.group_name + " (Poids : " + str(self.weight) + " / " + str(self.nb_users) + " utilisateurs)" class Event(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, verbose_name="société" ) groups = models.ManyToManyField(UserGroup, verbose_name="groupes", blank=True) rules = [("MAJ", "Majorité"), ("PROP", "Proportionnelle")] event_name = models.CharField("nom", max_length=200) event_date = models.DateField("date de l'événement") slug = models.SlugField() current = models.BooleanField("en cours", default=False) quorum = models.IntegerField(default=33) rule = models.CharField( "mode de scrutin", max_length=5, choices=rules, … -
django.db.utils.ProgrammingError: syntax error at or near "User" LINE 1: INSERT INTO User (password, firstname, lastname, username, e
@api_view(["POST"]) @permission_classes((IsAuthenticated,)) def create_user(request): cursor = connection.cursor() email = request.data['email'] role = request.data['role'] username = request.data['email'] firstname = request.data['firstname'] lastname = request.data['lastname'] is_staff = request.data['is_staff'] password = request.data['password'] query = """INSERT INTO User (password, firstname, lastname, username, email, is_staff, role_id) VALUES (?, ?, ?, ?, ?, ?, ?)""" cursor.execute(query, (password, firstname, lastname, username, email, is_staff, role)) -
Check if foreignKey exists
I need a way to check if the record linked to the foreignKey has already been created. I have 2 models, project and fundamentals. Fundamentals has a ForeignKey to the project so that and fundamentals being added are linked to that project. class Project(models.Model): project_name = models.CharField(max_length=50, blank=False, unique=True) project_website = models.URLField(max_length=50, blank=True) project_description = models.TextField(blank=True) ckeditor_classic = models.TextField(blank=True) project_category = models.CharField(max_length=15, blank=True) def __str__(self): return str(self.project_name) class Fundamentals(models.Model): project_name = models.ForeignKey(Project, to_field='project_name', on_delete=models.CASCADE) project_roadmap = models.CharField(max_length=25, blank=True) project_tier_entry_level = models.CharField(max_length=25, blank=True) project_tier_entry_level_notes = models.CharField(max_length=25, blank=True) project_rebranded = models.CharField(max_length=25, blank=True) def __str__(self): return str(self.project_name) So in my view I'm trying to render a page based upon If the PK already exists in the fundamentals model. pk = Fundamentals.objects.filter(pk=project_id) if pk: return MyPage else: return MyPage -
I have a ML model in django and based on session id I want to save that model unique per session
Here my ML model is trained iteratively like data is provided per each iteration using a post request and ML model is trained. If two users train a ML model with different datasets simultaneously how to cache the ML model so that model for different users is of there own model and they are training the model with which they first started. Here I am not able to bifurcate the models between different users. -
Integrate WooCommerce webhooks with Django Rest Framework
I have a WordPress website that uses WooCommerce for the management of the store. I have created a Django application that has to communicate with WooCommerce, in order to be aware of the following actions: user creation user update user delete new subscription purchase subscription renewal subscription expiration product purchase (I also sell physical products) Whenever a new client is created in WooCommerce, I want to create a new user in the Django app, and update/delete it accordingly when the status in WooCommerce changes. Whenever a product is purchased in WooCommerce, it should be seen in the Django app. The same goes for subscriptions. I managed to read the POST requests WooCommerce issues for the user-related actions, with the help of Postman, but the format is different from the format accepted by the Django app, and I don't really know how to adapt the views in order to be able to use the information supplied I configured token-based authentication in Django and generated a token, which I then configured in WooCommerce but it does not seem to use it as in the WooCommerce logs the response is: [Body] => {"detail":"Authentication credentials were not provided."} I am really new to both … -
Get number of sql queries in django rest framework
Suppose @login_required() def GetFollowers(request, id): obj = Follow.objects.filter(following_id=id) serializer = SearchSerializer(obj, many=True) result = JsonResponse(serializer.data, safe=False) return result I am using django rest framework. When I hit an api endpoint suppose (localhost:8000/api/v1/myfollowers) i get a json result which is ok but not getting django-debug-toolbar. When i raise(Http404) instead of returning JSON result, django debug toolbar is visible. How do i fix this? A way i got to know was printing queries but i cant use that as i will have to add same lines to every function. Thanks in Advance! -
Communication and data sharing between two functions using django
Qui peut m’orienter comment utiliser les résultats d’une fonction comme paramètres d’entrées pour une autre fonction ? This is my code : def even_point(request): longitude=request.POST['longitude'] latitude=request.POST['latitude'] ref_location = Point(float(longitude), float(latitude)) all_evens = Even.objects.all() return render(request, 'even_map_point.html', {'all_evens': all_evens, 'longitude':longitude, 'latitude':latitude, 'ref_location':ref_location}) def EvenDataPoint(request, ref_location): name = serialize('geojson', Evenobjects.filter(geom__contains=ref_location)) return HttpResponse(name,content_type='json') I have the following error: TypeError: EvenementDataPoint() missing 1 required positional argument: 'ref_location' How do I get the second function to recognize the location value calculated in the first function? -
why is sweetalert id field not allowing me to sign into my django project
I am trying to login to my Django application but its like when I click submit, the form is not submitting. I believe the sweetalert JavaScript ID KTSigninGeneral is preventing it from submitting because I can log in without the sweetalert ID. I want to be able to log in with the sweetalert plugin. Here is the code Submit Button <!--begin::Actions--> <div class="text-center"> <!--begin::Submit button--> <button type="submit" id="kt_sign_in_submit" class="btn btn-lg btn-primary w-100 mb-5"> <span class="indicator-label">Continue</span> <span class="indicator-progress">Please wait... <span class="spinner-border spinner-border-sm align-middle ms-2"></span></span> </button> <!--end::Submit button--> </div> <!--end::Actions--> javascript "use strict"; var KTSigninGeneral = function () { var t, e, i; return { init: function () { t = document.querySelector("#kt_sign_in_form"), e = document.querySelector("#kt_sign_in_submit"), i = FormValidation.formValidation(t, { fields: { email: { validators: { notEmpty: { message: "Email address is required" }, emailAddress: { message: "The value is not a valid email address" } } }, password: { validators: { notEmpty: { message: "The password is required" } } } }, plugins: { trigger: new FormValidation.plugins.Trigger, bootstrap: new FormValidation.plugins.Bootstrap5({ rowSelector: ".fv-row" }) } }), e.addEventListener("click", (function (n) { n.preventDefault(), i.validate().then((function (i) { "Valid" == i ? (e.setAttribute("data-kt-indicator", "on"), e.disabled = !0, setTimeout((function () { e.removeAttribute("data-kt-indicator"), e.disabled = !1, Swal.fire({ text: "You … -
How to show password view page before actual view page in django?
I created a diary web app in Django. It stores all diaries encrypted. I want to ask password when a user tries to view or update or delete his/her diary. It doesn't mean a login is required. I want to ask user's password even though the user login. I tried to create a decorator for this but I couldn't complete it. I have two views: This view check to password is correct: def check_master_password_view(request): page = 'check' profile = request.user.profile if request.method == "POST": checked = check_master_password(request.POST['password'], profile.master_password) if checked: return checked # OR Redirect another page else: messages.error(request, 'You entered wrong password !') context = { 'page':page, } return render(request, 'users/create_or_check_master_password.html', context) Another view is detail view: def detail_diary_view(request, pk): profile = request.user.profile diary = profile.diary_set.get(id=pk) diary.diary = decrypt_diary(request, diary.diary) context = { 'diary': diary } return render(request, 'diary/detail_diary.html', context) When the user clicks the link to view the diary, I want to show check_master_password view. If the user enters the correct password I want to redirect to the actual page (view, update, delete pages). How can I do this? -
Django REST Framework / djoser - authentication in custom user model
I'm working on my first web-app (DRF & Vue.js). Currently I have working authorization with default User model (by username and password). I'm using djoser and restframework.authtoken. What is the best way to extend the default model by few more fields, and keep working authorization by username and pass? -
How to resolve the following error in django UndefinedValueError('{} not found. Declare it as envvar or define a default value.' .format(option))?
While making migrations I'm getting the following errors in django raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.' .format(option)) decouple.UndefinedValueError: EADDRESS not found. Declare it as envvar or define a default va lue. -
Is there any way to make django list template and use it on every object like in django admin
hi I am working on a Django project where I am creating a lot of list view I want to make a single reusable list template for listing my all model with that template but the problem is that I have to specify every field like object.subject_name is there any way to make one universal template for all models views.py from django.views.generic import ListView from .models import Subject class SubjectListView(ListView): model = Subject template_name = "subject/subject_list.html" subject/subject_list.html <div class="divider divider-success"> <div class="divider-text hvr-grow">Total {{object_list.count}} {% if object_list.count > 1 %} Subjects {% else %} Subject {% endif %} </div> </div> <!-- Striped rows start --> <div class="table-responsive"> <table class="table table-striped"> <thead> <tr> <th>Class Name</th> <th>Subject Group</th> <th>Subject Name</th> <th>Subject code</th> <th>No of periods</th> <th>Actions</th> </tr> </thead> <tbody> {% for object in object_list %} <tr id="subject-{{object.id}}"> <td> {{object.class_name}} </td> <td> {% if object.subject_group %} {{object.subject_group}} {% endif %} </td> <td> {{object.subject_name}} </td> <td> {{object.subject_code}} </td> <td> <span class="badge rounded-pill badge-light-success me-1">{{object.no_of_periods}}</span> </td> <td> <div class="dropdown"> <button type="button" class="btn btn-sm dropdown-toggle hide-arrow py-0" data-bs-toggle="dropdown"> <i data-feather="more-vertical"></i> </button> <div class="dropdown-menu dropdown-menu-end"> <a class="dropdown-item" hx-push-url="{% url 'dash:subject_change' object.id %}" hx-get="{% url 'dash:subject_change' object.id %}" hx-target="#home-justified"> <i data-feather="edit-2" class="me-50"></i> <span>Edit</span> </a> <a class="dropdown-item" hx-get="{% url … -
Mapping json data with serializer fails validation
Not able to map the json data field in serializer field. I tried with source but it seems it only works for model field. Is there any way to map this field...?? In my usecase I will be having around 10-15 fields in total to be mapped in this serializer... from rest_framework import serializers class Test(serializers.Serializer): my_field = serializers.CharField(source='myOtherField', required=True) test_data = {'myOtherField': 'test2'} test = Test(data=test_data) test.is_valid() print(test.data) Validation is failing. If I remove the validation and just pass test_data without data= like this test = Test(test_data) then it works fine. -
Reverse Foriegn Key in Django Serializers
Suppose class Post(models.Model): content = ... image = ... timestamp = ... class PostLike(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,...) post = models.ForiegnKey(Post,...) timestamp = ... and class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = ("content","image","timestamp","liked") Here liked could be true or false. It will be true if user (request.user) is in PostLike. How do i create that liked field? -
Get all appointments on the same day, same time, same seat - django
I have two models: seat model: class Seat(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() short_description = models.TextField(blank=True, null=True) created_at = models.DateField(auto_now_add=True) appointments model: class Appointment(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) seat = models.ForeignKey(Seat, on_delete=models.SET_NULL, null=True) start_appointment = models.DateTimeField(default=timezone.now, blank=True) end_appointment = models.DateTimeField(default=timezone.now, blank=True) name = models.CharField(max_length=255) I would like to get all appointments performed on the same date, same time and same seat. Lets illustrate, 28 Nov Time | Seat 1 | Seat 2 | 3:00 | Jim, John | Alex, Bean | So far i can get appointments on same date and for specific seat but i cannot figure out how can i get same time, i.e today = datetime.datetime.now() appointments_per_day = Appointment.objects.filter(start_appointment__day=today.day).filter(seat__name='Seat1').values() Any ideas? -
Sending email is not working for a django app on Digital Ocean
I am facing problem sending email on production with Digital ocean. This is my settings: MAILER_EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'Mypassword' DEFAULT_FROM_EMAIL = 'noreply<no_reply@domain.com>' All is working fine on development mode and on terminal as well When I tape ( to test) : from django.core.mail import send_mail send_mail('test email', 'hello world', 'sender@gmail.com', ['reciever@gmail.com']) I got : 550 5.4.1 All recipient addresses rejected : Access denied. AS(201806271) Please note that I authorise less secure apps on gmail account. Does any one has an idea ? Regards -
Django : One to many relationship
I have a question regarding objects modelling. Let's say we have a one to many relationship where an object A instance could have 0 to many linked objects B whereas object B could be linked to one and only one object A (note here object B cannot be created without being linked to an object B). So far I have added a foreign key to object B model, when adding that object I should select an Object A , so far so good. My question now is do I have to also add the object B to object A model on database level? Or should I just do it on API level by creating nested APIs? So that getting object B would be this way : get : http://localhost/api/objectA/objectB I hope I was clear explaining my question but to summarize I am not sure if adding a foreign key to represent a : 0.n---->1.1 is enough. It has been a long time for me that I did not design a database am I using a very old methodology? Thanks -
Can't figure out the for loop logic
I am trying to write a code where the user submits a wiki search. If the query is in the given list of entries, the user should be redirected to related entry's page. If the query doesn't match the name of an entry but is a substring of any entry, the user should be taken to a page that lists the related entries. My problem is that I couldn't figure out how to logically implement return statements. The code below works fine: def search(request): sub_list = [] entries = util.list_entries() search = request.GET.get("q") for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) elif search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, "sub_list":sub_list }) But when I try to add another condition for the case where the query doesn't match the name of an entry, either it always returns to "Not Found": for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) else: if search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, "sub_list":sub_list }) return HttpResponse("Not Found") or returns only the first substring match: for entry in entries: if search.lower() == entry.lower(): return redirect("entry", title= search) else: if search.lower() in entry.lower(): sub_list.append(entry) return render(request, "encyclopedia/search.html",{ "title":search, … -
Django c'ant runserver
my project worked but whene l added static folder withe css and js bootstrap file it crashed first sec third -
Add or Edit if already exists
I'm working on a web application that has a number of forms that allow the user to submit data to the database. The data is linked to a project, and from the project page, I have a drop-down list that allows you to select what information you want to add to the project. At the moment I have two views linked to two dropdown lists. One to add new data and one to update, but ideally, I'd like the button to either take you to the update or add a new page depending on data already being added to the database. So is there a way to have a single button that automatically takes you to the correct view? I imagine i'll need some kind of logic within the view to handle this. But im not sure what this would be? Views.py @login_required def AddFundamentals(request,project_id): project = get_object_or_404(Project, pk=project_id) if request.method == 'POST': form = AddFundamentalsForm(request.POST) if form.is_valid(): form.instance.project = project form.save() return redirect('http://127.0.0.1:8000/') else: form = AddFundamentalsForm() return render(request, 'pages/add_fundamentals.html', {'project': project, "form": form}) @login_required def UpdateFundamentals(request,project_id): project= Project.objects.get(pk=project_id) form = AddFundamentalsForm(request.POST or None, instance=project) if form.is_valid(): form.save() return redirect('dahsboard.html') return render(request, 'pages/update_fundamentals.html', {'project': project, "form": form}) HTML <div … -
create custom domain email and receive email in python
I want to receive an email on this abcd@myemail.com. I want to use python(django) in the backend, for achieve this task which libraries and steps do I have to take. -
Error trying to host my Django project on Heroku
I was creating a Django project trying to upload it to Github. When I was doing git push Heroku main it pushed most of them. Before finishing pushing all of them, this error popped up: ![remote rejected] main -> main (pre-receive hook declined) error: failed to push some refs I followed my steps on this site: https://realpython.com/django-hosting-on-heroku/#make-an-app-release -
matching query does not exist django V3.2.9
I am trying to retrieve the ID from a POST request which throws matching query does not exist when i am certain that specific ID for that customer exists because all it's information is displayed at the template table also using {{customer.id}} in the template gives an (ID) to make sure that it actually exists My views.py from .models import Customer,FilterMaintenance def index(request): if request.method == "POST": filtermaintenance_id = FilterMaintenance.objects.get(pk=request.POST.get('{{customer.id}}', False)) x = filtermaintenance_id.filter_last_due_date f = FilterMaintenance.objects.all() return render(request,'maintenance/index.html',{ "customers_maintenance":f, "test":x }) my models.py class Filter(models.Model): filter_brand= models.CharField(max_length=64) filter_interval = models.IntegerField() def __str__(self): return f"{self.id} , {self.filter_brand}" class Customer(models.Model): first_name = models.CharField(max_length=64) last_name = models.CharField(max_length=64) phone_number = models.IntegerField(blank=True) home_address = models.CharField(max_length=64,blank=True) email = models.EmailField(blank=True) notes = models.TextField(blank=True) def __str__(self): return f"{self.id}, {self.first_name}, {self.last_name}" class FilterMaintenance(models.Model): customer_info = models.ForeignKey(Customer,related_name="customer_set",on_delete = models.CASCADE) customer_filter = models.ForeignKey(Filter,related_name="filter_set",on_delete = models.CASCADE) filter_last_due_date = models.DateField() def __str__(self): return f"{self.id}, {self.customer_info}, {self.customer_filter},{self.filter_last_due_date} " my index.html {% extends "maintenance/layout.html" %} {% block body %} <div class="maintenance-container"> <h1>Section for customers ...</h1> <table class="maintenance-table"><thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone number</th> <th>Home address</th> <th>Filter brand</th> <th>Last filter change</th> <th>Next filter due date</th> <th>Filter done</th> </tr> </thead> <tbody> {% for customer in customers_maintenance %} <tr> <td>{{customer.customer_info.first_name}}</td> <td>{{customer.customer_info.last_name}}</td> <td>{{customer.customer_info.phone_number }}</td> <td>{{customer.customer_info.home_address}}</td> <td>{{customer.customer_filter.filter_brand}}</td> <td>{{customer.filter_last_due_date}}</td> … -
get current logged in user info in Django
i try to get logged in user info inside a form class in Django. class PayForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PayForm, self).__init__(*args, **kwargs) self.fields['username_id'].initial = ? #current_logged_in_user_id() -
Using Ajax call for sending sort criteria from template to a Django view
I wish to send a sort criteria from a Django template to the associated view and update the template without reloading the page. Understand that an Ajax call is the way to go, but how would I implement this? store.html {% extends 'ecomsite/main.html' %} {% load static %} {% block content %} <select class="form-control" id="sort"> <option value="default" selected="selected">Default</option> <option value="price-low">Price(lowest first)</option> <option value="product-name">Product Name</option> </select> <br> <div class="row"> {% for product in products %} <div class="col-lg-4"> <img class="thumbail" src="{{product.imageURL}}"> <div class="box-element-product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-primary add-btn update-cart">Add to Cart</button> <a href="{% url 'detail' product.id %}" class="btn btn-outline-info">View</a> <h5 style="display: inline-block; float: right"><strong>€{{product.price|floatformat:2}}</strong></h5> </div> <br> </div> {% endfor %} </div> {% endblock %} views.py def store(request): data = cartData(request) cartItems = data['cartItems'] products = Product.objects.all() context = {'products':products, 'cartItems':cartItems} return render(request, 'ecomsite/store.html', context) urls.py from django.urls import path from . import views urlpatterns = [ path('',views.store,name='store'), path('cart/',views.cart,name='cart'), path('checkout/',views.checkout,name='checkout'), path('update_item/',views.updateItem,name='update_item'), path('process_order/',views.processOrder,name='process_order'), path('getting_started/',views.HowtoView.as_view(),name='howto'), path('myorders/',views.order_list,name='list'), path('signup/',views.Signup.as_view(),name='signup'), path('thankyou/',views.thank_you,name='thank_you'), path('products/<int:id>/',views.product_detail,name='detail') ]