Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bonsoir j'ai un problème j'essai de démarrer mon server django mais sa ne marche pas et sa le donne des erreurs
ImportError: cannot import name 'django' enter code herefrom 'myblog' (C:\Users\HIPMAN\Desktop\Myblog\myblog\myblog_init_.py)enter code here -
How to handle empty argument value in python function of Django views?
I have an application that passes the user name from the HTML template to the URL and functions in the views. views.py def cv_detail_view(request, username): if username=='': return redirect("accounts:login") else: user = get_object_or_404(User, username=username) try: personal_info = PersonalInfo.objects.get(user=user) except PersonalInfo.DoesNotExist: # if personal info doesn't exist redirect to create or 404 page. if user == request.user: return redirect("cvs:create_personal_info") else: raise Http404("CV Does Not Exist.") work_experience = WorkExperience.objects.filter(user=user) education = Education.objects.filter(user=user) context = { "personal_info": personal_info, "work_experience": work_experience, "education": education, } return render(request, "detail.html", context) Html snippet: <li><a class="nav-link" href="{% url 'cvs:cv_detail' user.username %}">Use templates</a></li> ursl.py path(r'^(?P<username>[\w._-]+)/$',views.cv_detail_view,name='cv_detail'), My idea is to redirect users to login page if the parameter username is empty i.e, if the user is not logged in. However, I get the following error: NoReverseMatch at / Reverse for 'cv_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['cvs/templates\\Z'] Request Method: GET Request URL: http://127.0.0.1:9090/ Django Version: 4.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'cv_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['cvs/templates\\Z'] Is there any way to handle the empty value in function arguments? -
Django send_mail dont sending non ascii symbols (cyrillic)
I'm trying to send like this: send_mail(u'Тема', u'Тело письма', EMAIL_HOST_USER, ['EMAIL_RECIPIENT']) But got smthing like this: "Sубьект" as subject. And "Тело РїРёСЃСЊРјР°" as body of message. How can I fix this problem. Help please. -
Get Context Data on Attribute within Model in Django DetailView
I am trying to filter all reviews that correspond to listings created by a certain viewer. The purpose is to put all the reviews someone has received on their listings on a profile page. I am able to use get_context_data to pull in the listing reviews, but I want to filter on a relationship within the listing itself. Views.py class ProfileDetailView(DetailView): model = Profile template_name = 'account/profile_detail.html' context_object_name = 'profile_detail' def get_object(self): return self.request.user.profile def get_context_data(self, **kwargs): context = super(ProfileDetailView, self).get_context_data(**kwargs) context['reviews'] = RentalListingReviews.objects.filter(RentalListing.lender = self.request.user) return context Models.py class RentalListing(models.Model): item_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) lender = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, ) item_name = models.CharField(max_length=200) def __str__(self): return self.item_name def get_absolute_url(self): return reverse('rental_listing_detail', args=[str(self.item_id)]) class RentalListingReviews(models.Model): listing = models.ForeignKey( RentalListing, on_delete = models.PROTECT, related_name = 'listing_reviews', ) review = models.TextField(max_length = 1000) author = models.ForeignKey( get_user_model(), on_delete = models.PROTECT, ) def __str__(self): return self.review def get_absolute_url(self): return reverse('rental_listing_detail', args=[str(self.listing.item_id)]) -
conditional querysets Django
I'm trying to show the server to the user only if the user is a moderator or the creator of the server. so i wrote this code: class ServerModeratingView(LoginRequiredMixin, View): def get(self, request, server_tag): moderator = ServerModerator.objects.get(user=request.user) server = Server.objects.get(Q(tag=server_tag), Q(creator=request.user) | Q(moderators=moderator)) ... I thought Q object will make this code conditional like if the request.user is not the creator then user is a moderator this works fine if the user is a moderator of the server but the creator(creator is not one of the moderators so moderator queryset will be empty) shows this error: ServerModerator matching query does not exist. models.py: class Server(models.Model): ... tag = models.CharField(max_length=50, unique=True) moderators = models.ManyToManyField('ServerModerator', related_name='server') ... class ServerModerator(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='moderator_of') allow_create_tag = models.BooleanField(default=True) allow_create_rule = models.BooleanField(default=False) allow_remove_user = models.BooleanField(default=True) allow_remove_moderator = models.BooleanField(default=False) allow_delete_post = models.BooleanField(default=False) -
Django dynamic reverse url
Im using detailview to view user data as staff, and I also want to edit it. How do I approach the reverse url. Right now it reverses me on my staff pk but the goal is to reverse back to the user view page the update view class SVAVerwaltung(LoginRequiredMixin, UpdateView): model = SchulverzeichnisTabelle fields = ['Konto', 'S_Form', 'Schulname', 'SAB', 'GL', 'Zuege', 'Teilstandort', 'IH', 'SSt_OGS', 'OGS_Grp', 'VK', 'Z_SW', 'Z_besG', 'U_Ausf', 'U_Org', 'Schulleitung_Vorname', 'Schulleitung_Nachname', 'Lehrer_FK', 'GL_Lehrer_FK'] template_name = 'SCHUK/SVAVerwaltung.html' context_object_name = 'SVAVerwaltung' def get_success_url(self): return reverse('Ansicht', kwargs={'pk': self.object.pk}) the detail view from django.shortcuts import get_object_or_404 class Dashboard (AdminStaffRequiredMixin, LoginRequiredMixin, ListView): model = User template_name = 'SCHUK/Dashboard.html' context_object_name = 'Dashboard' def ansicht(request, pk): user = get_object_or_404(User, pk=pk) return render(request, 'SCHUK/Ansicht.html', context={'user': user}) class Ansicht(AdminStaffRequiredMixin, LoginRequiredMixin, DetailView): model = User template_name = 'SCHUK/Ansicht.html' context_object_name = 'Ansicht' def get_success_url(self): return reverse('Ansicht') ``` urls path('', Dashboard.as_view(), name="Dashboard"), path('Ansicht/<int:pk>', Ansicht.as_view(), name='Ansicht'), path('SVAVerwaltung/<int:pk>', SVAVerwaltung.as_view(success_url="Ansicht/<int:pk>"), name='SVAVerwaltung'), -
What will be the future of these Django vs React vs Flask framework?
I need suggestions about these web frameworks. I am confused which to choose for my carrier. -
Adding Alpine attributes to Django's form fields
I'm rendering django template form fields this way : <div x-data="{ amount: 0 }"> {% render_field field class=class %} </div> I want to add to the input : x-on:input.change="console.log('test');" How can I add this to render_field ? In forms.py as widgets = { 'amount': forms.TextInput(attrs={'x-on:input.change': "console.log('test');" }) } the only way ? Is there a way to add x-on:input.change via JavaScript ? -
How to make the ForeignKey either one of two models
I'm trying to make a social media web application using Django, I made a user model and a page model that can be managed by multiple users now I'm trying to make Posts model, Posts should be able to be posted by either users or pages, It's something like that: posted_by = models.ForeignKey(("accounts.User" or "accounts.Page"), verbose_name=_(""), on_delete=models.CASCADE) Can anyone help? -
problem with Django prepopulated.fields ModelAdmin option version(4.1)
hi guys i have simple model in django I have class model below: class Book(models.Model): title = models.CharField(max_length=75) author = models.CharField(max_length=75) rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) best_selling = models.BooleanField(null=False, default=False) slug = models.SlugField(default='', null=False, db_index=True, blank=True) I made admin page modification with below code: class BookAdmin(admin.ModelAdmin): prepopulated_fields = {"slug": ("title",)} admin.site.register(Book) but problem is prepopulated_fields won't work not in database not in admin page in database I get blank as slug column can anyone help me with this issue thank you. -
Django Models - Form saves but model is blank
Not sure my title is fully representing my problem. I thought I would put a screenshot of the problem (admin panel), so it's clearer for everyone It looks like the form is savings, but nothing goes inside. Here is the models code: class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) address = models.CharField(verbose_name="Address",max_length=100, null=True, blank=True) town = models.CharField(verbose_name="Town",max_length=100, null=True, blank=True) county = models.CharField(verbose_name="County",max_length=100, null=True, blank=True) post_code = models.CharField(verbose_name="Post Code",max_length=8, null=True, blank=True) country = models.CharField(verbose_name="Country",max_length=100, null=True, blank=True) longitude = models.CharField(verbose_name="Longitude",max_length=50, null=True, blank=True) latitude = models.CharField(verbose_name="Latitude",max_length=50, null=True, blank=True) city = models.CharField(max_length=120) def __str__(self): return str(self.name) if self.name else '' Obviously, I am aware I have asked to return '' if self.name wasnt there. The reason why I did it, is because initially, the models was visible on the admin panel under "-" but was throwing an error message when clicking on it. Considering I am working with a form, here is the form code: class VenueForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) address = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) town = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) county = forms.CharField(max_length=100, required=True, widget = forms.HiddenInput()) post_code = forms.CharField(max_length=8, required=True, widget = forms.HiddenInput()) country = forms.CharField(max_length=40, required=True, widget = forms.HiddenInput()) longitude = forms.CharField(max_length=50, required=True, widget … -
Cannot migrate in django using mysql
I'm trying to migrate my data from sqlite to mysql database but when I'm migrating the models, i'm getting the following error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") django.db.utils.OperationalError: (2059, "Plugin http could not be loaded: The specified module could not be found. Library path is 'http.dll'") what can be the problem? I'm using Django 4.0.5, python 3.10.2, mysqlclient 2.1.1 -
Django signals: why create and save profile on 2 different functions?
I noticed from many django tutorials that Profiles are created and/or saved upon User post_save signal. Most codes go like this: from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() My question is, why do they use 2 functions instead of just one like this? @receiver(post_save, sender=User) def save_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) instance.profile.save() To my understanding, (1) when a new user is created, a new profile will also be created and saved thereafter; and (2) when a user is updated, its profile will also be updated but not created. Am I missing something? -
How do I convert this postgresql code to Django code?
This is my code in Postgresql -- create CREATE TABLE EMPLOYEE ( empId INTEGER PRIMARY KEY, username TEXT NOT NULL, userrole TEXT NOT NULL, roles TEXT NOT NULL, accesses TEXT NOT NULL ); -- insert INSERT INTO EMPLOYEE VALUES (0001, 'Clark','President', 'Admin','privileged'); INSERT INTO EMPLOYEE VALUES (0002, 'Dave','sales rep', 'Operational role','not privileged'); INSERT INTO EMPLOYEE VALUES (0003, 'Ava','finance manager', 'Managerial role','privileged'); -- fetch SELECT * FROM EMPLOYEE; SELECT *, CASE WHEN (roles, accesses) IN ( ('Admin','privileged'), ('Operational role','not privileged'), ('Managerial role','not privileged') ) THEN 'GRANTED' ELSE 'REVOKED' END AS permissions FROM employee; -
Helping with models in DjangoREST
I am making API in Django rest and I am not sure what to do with groupID. I have just 1 model - countries. I have assigned request and response. Request for POST is : {"name": "Czech Republic","countryCode": "CZ"} Response is: { "name": "Czech Republic","countryCode": "CZ","id": 123,"createdAt": "2022-08-21T11:49:39.239Z", "groupId": 123 } And I am supposed to create API for that. I am not sure what to do with groupI in model. class Countries(models.Model): name = models.CharField(unique=True, max_length=100) countryCode = models.CharField(unique=True, max_length=100) createdAt = models.DateTimeField(auto_now=True) groupId = models.CharField(unique=True, max_length=100) def __str__(self):return self.name -
Passing Information from Another Django Model Createview - Listing and Reviews
I have two Django apps, one with listings and another for accounts. Within the accounts app, I have a reviews model attached to the account, and I want users to have the ability to create a review for a listing that ultimately attaches to the account, not the listing, that way any listing reviews under a particular account are attached to the account itself, not necessarily the listing. Part of the reviews model is the listing and listing_author fields, that way I can filter on these fields later on. From the listing detail page, I want users to be able to click "Create Review" and create a review for a listing that is under the profile. I am running into an issue where I cannot pass the user_id and listing_id in the CBV CreateView, as the information from the listing_detail page (including these two fields) is not passed. Accounts Models.py class ProfileReviews(models.Model): user = models.ForeignKey( get_user_model(), on_delete = models.CASCADE, related_name = 'reviews' ) listing_item_id = models.UUIDField() review = models.TextField(max_length = 1000) rating = models.IntegerField() reviewer = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) def __str__(self): return self.review Listings Model.py class Listing(models.Model): item_id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False ) lender = models.ForeignKey( get_user_model(), on_delete … -
How to prevent multiple login for a jwt token based authentication in django rest-framework?
https://dev.to/fleepgeek/prevent-multiple-sessions-for-a-user-in-your-django-application-13oo i have followed the above article for achieving preventing multiple login. But the above process is not working and it does not through any errors. What i have done to test after copying above code> I have loged in with user credentials in postman. I have collected the jwt token which is a response. I have stored the first jwt token in notepad. next i have loged again. Now i have used old jwt token ( i mean first token) to get some data and i am able to access it. What i am expecting here is. I don't want first token to be working anymore. Please help me. Thanks in advance. -
Creating a model with a ManyToMany relationship to users, how to extend Users information
I am trying to create a model that has (perhaps several) ManyToMany relationships with users. Basically the model is suppose to hold an event (Madklub) in which users can join. Now this I already successfully implemented, however now I want to make the users be able to bring guests (Users not registered), now this simply need to be a number on how many guests a specific user is bringing, but the amount of guests needs to be tied to the user somehow, so that in case the user leaves the event then the guests are also decremented from the total amount of guests. The following is my current model, DIET_OPTIONS = ( ('vegan', 'Vegan'), ('vegetarian', 'Vegetarian'), ('meat', 'Meat') ) class Madklub(models.Model): owner = models.ForeignKey(MyUser, related_name="owner", null=False, blank=False, on_delete=models.CASCADE) dish = models.CharField(max_length=100, null=True, blank=True) date = models.DateField(null=False, blank=False, unique=True) guests = ??? active = models.BooleanField(default=True) vegan_participants = models.ManyToManyField(MyUser, related_name="vegan_participants", blank=True) vegetarian_participants = models.ManyToManyField(MyUser, related_name="vegetarian_participants", blank=True) meat_participants = models.ManyToManyField(MyUser, related_name="meat_participants", blank=True) diet = ArrayField( models.CharField(choices=DIET_OPTIONS, max_length=10, default="vegetarian") ) class Meta: ordering = ('date',) class GuestInfo(models.Model): ??? So right now I have it so that when a user joins the Madklub (event) they choose one of three options (meat, vegetarian, vegan). And depending … -
How display django models with datetime field in chart using chartjs
Hi everyone I am stuck on a problem, I have a django model which is called ScanBatch, now that Scan batch is made up of fields like the timestamp (datetime field), domain (char field) and total ids found (integer field) My chart code is : const ctx = document.getElementById('myChart').getContext('2d'); const myChart = new Chart(ctx, { type: 'bar', data: { labels: [], datasets: [] }, options: { scales: { yAxes: [{ id: 'A', type: 'linear', position: 'left', }, { id: 'B', type: 'linear', position: 'right', ticks: { max: 1, min: 0 } }] } } }); models code is class ScanBatch(models.Model): domain = models.CharField(max_length=255) timestamp = models.DateTimeField(auto_now_add=True) valid_ids_found = models.IntegerField(default=0) the trick question is how do I make the chart show the batch data historically from django and then output it to the chart I want to show the batches historically by date and also group by domain -
Giving an error messagebox for the submission of a form : Django
i was following a tutorial and after finishing it i came across and error which should only be shown if the form i have submitted is invalid. I am using recaptcha and several other apis these are few of my functions result = "Error" message = "There was an error, please try again" class AccountView(TemplateView): ''' Generic FormView with our mixin to display user account page ''' template_name = "users/account.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == 'XMLHttpRequest' def profile_view(request): ''' function view to allow users to update their profile ''' user = request.user up = user.userprofile form = UserProfileForm(instance = up) if request.is_ajax(): form = UserProfileForm(data = request.POST, instance = up) if form.is_valid(): obj = form.save() obj.has_profile = True obj.save() result = "Success" message = "Your profile has been updated" else: message = FormErrors(form) data = {'result': result, 'message': message} return JsonResponse(data) else: context = {'form': form} context['google_api_key'] = settings.GOOGLE_API_KEY context['base_country'] = settings.BASE_COUNTRY return render(request, 'users/profile.html', context) class SignUpView(AjaxFormMixin, FormView): ''' Generic FormView with our mixin for user sign-up with reCAPTURE security ''' template_name = "C:/Users/adity\OneDrive/Documents/Coding/python/py_tutorial/djangotutorial/googleapi project/googapiproj/templates/users/sign_up.html" form_class = UserForm success_url = "/" #reCAPTURE key required in context def is_ajax(request): return request.META.get('HTTP_X_REQUESTED_WITH') == … -
Session variable not getting updated during session in django
I'm new to web development and trying to create an auction website as a course project. I'm trying to create a user-specific watchlist. It's able to add a product to the watchlist but when I go to delete an item from the watchlist it doesn't get deleted until I log out and log in again. Here is my code: views.py: def watchlist(request, item_id=None): if request.method == "POST": for item in request.session["watchlist"]: if item["id"] == item_id: ind = request.session["watchlist"].index(item) modified = request.session["watchlist"][:ind] + request.session["watchlist"][ind + 1:] request.session["watchlist"] = modified break data = request.session["watchlist"] return render(request, "auctions/watchlist.html", { "data": data }) watchlist.html: {% block body %} {% if user.is_authenticated %} <h2>Watchlist</h2> <ol> {% for item in data %} <li> <div style="display: flex;"> <div> <img src="{{ item.image_url }}" alt="No image"> </div> <div> <a href="{% url 'listing' item.id %}"><h4>{{ item.title }}</h4></a> </div> <div> Current Price: {{ item.current_price }} </div> <div> <form action="{% url 'watchlist_del' item.id %}" action="post"> <input type="submit" value="Delete"> </form> </div> </div> <div style="border-bottom: 1px solid black;"></div> </li> {% empty %} <h1>No items in watchlist</h1> {% endfor %} </ol> {% endif %} {% endblock %} I checked session data through Django-admin and found that even after deleting an item, its data was not … -
Python Django: ImportError: cannot import name '...' from partially initialized module '...' (most likely due to a circular import) (......)
In a Django project, I need to import class-A from file-1 in file-2. and import class-B from file-2 in file-1. These classes have their unique methods, and I want to use these methods within another file (like description above). I'm working with: Python 3.8.10 (within a virtual environment) Windows 10 - 64 bit (latest build) Django 4.0.4 When I runpython manage.py runserver, I see errors below: (my_ea_proj) PS F:\my_ea_proj\ea_proj> python.exe .\manage.py runserver Traceback (most recent call last): File ".\manage.py", line 30, in <module> main() File ".\manage.py", line 13, in main django.setup() File "F:\my_ea_proj\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "F:\my_ea_proj\lib\site-packages\django\apps\registry.py", line 116, in populate app_config.import_models() File "F:\my_ea_proj\lib\site-packages\django\apps\config.py", line 304, in import_models self.models_module = import_module(models_module_name) File "C:\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "F:\my_ea_proj\ea_proj\ea_app\models.py", line 16, in <module> from .login_request_based import full_request File "F:\my_ea_proj\ea_proj\ea_app\login_request_based.py", line 10, in <module> from ea_app.all_utils.ea_utils import ea_utils_class File "F:\my_ea_proj\ea_proj\ea_app\all_utils\ea_utils.py", line 10, in <module> from ea_app.login_request_based import full_request ImportError: cannot import name … -
Django DeleteView not make delete
I want to convert user deletion from FBV to CBV My FBV def delete_student(request, pk): student = get_object_or_404(Student, pk=pk) student.delete() return HttpResponseRedirect(reverse("students:get_students")) My CBV class DeleteStudentView(DeleteView): model = Student form_class = StudentForm template_name = "students/students_list.html" success_url = reverse_lazy("students:get_students") student_list.html <td><a type="button" class="btn btn-danger" href="{% url 'students:delete_student' student.pk %}">Delete</a> </td> There is no error, but no selection occurs. What could be the problem? -
Create object using django POST method
I have a question regarding Djanog views I have to Create a Task object using the string(the object)that I am getting from POST method. This string is equal to the name field in the Task object. the POST request contains : task \ username. the page is in this url: http://localhost:8000/tasks/ after adding the task the user should see something like this : Task Created: 'Task_Name_Here' this was my code and i know its not correct: def list_create_tasks(request): if request.method == 'POST': task_name = request.POST.get('task_name') task = Task.objects.create(name=task_name) return HttpResponse(f"Task Created: '{task}'") thanks for helping. -
Trying to use whois in python but getting file not found error in windows
I am trying to use whois but getting this error: I have also installed https://docs.microsoft.com/en-us/sysinternals/downloads/whois and it is working fine in my cmd but when I try it with python it shows the above error. I have installed both python-whois and whois using the below commands but still getting the same error. pip install python-whois pip install whois