Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django verification email
I have a Django app deployed on Pythonanywhere. Everything works as expected except for the verification emails.When a new user registers, he should receive a verification email, but Django doesn't send it until the admin panel is reloaded. All other emails(welcome emails, contact form emails) are sent without issue. When I test locally on my laptop verification emails are sent instantly. I am using django-email-verification and emails are sent through gmail. views.py class RegisterView(CreateView): form_class = RegisterForm template_name = 'common/register.html' success_url = reverse_lazy('login') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.save(commit=False) user_email = form.cleaned_data['email'] user_username = form.cleaned_data['username'] user_password = form.cleaned_data['password1'] user = UserModel.objects.create_user(username=user_username, email=user_email, password=user_password) user.is_active = False send_email(user) return HttpResponseRedirect(reverse('email sent')) def form_invalid(self, form): return super().form_invalid(form) -
Django admin: group two fields in a section without having to specify every other field as well?
I have a Django model with a whole bunch of fields. In the Admin UI I want to group two of these fields in their own little section, but as far as I know that means I now have to specify every single model field in the fieldsets config: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): fieldsets = ( ( None, { "fields": ("field_1", "field_2", "field_3") # etc etc } ), ( "My special section", { "fields": ("field_11", "field_12") } ) ) It's annoying to copy and paste so many field names, but worse: if I add a new field to the model I have to remember to add it to the fieldsets config as well. So my question is: is there no way to have some kind of "the rest of the fields go here" section? Or another way to only change the section of a subset of fields while leaving the rest alone? -
i am trying to run manage.py runserver on pycharm and an attribute error is returned
File "C:\Users\user\PycharmProjects\Diabetes Prediction\Diabetes_prediction\Diabetes_Prediction\urls.py", line 23, in path("", views.home), ^^^^^^^^^^ AttributeError: module 'Diabetes_Prediction.views' has no attribute 'home' I expected the project to run -
How to get Page no of pdf and assign to a table in ReportLab, Python
I'm working on a PDF generation script using ReportLab in Python. The script generates a PDF with a client table and some additional information. I have implemented a custom PageNumCanvas class to handle page numbering.(PageNumCanvas is from https://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/) this is the PageNumCanvas. I override(in save method) the first page to add the page no on a fixed location. But i need to load the page_count dynamically, in the client table. class PageNumCanvas(canvas.Canvas): """ http://code.activestate.com/recipes/546511-page-x-of-y-with-reportlab/ http://code.activestate.com/recipes/576832/ This below code is taken from the https://www.blog.pythonlibrary.org/2013/08/12/reportlab-how-to-add-page-numbers/ """ #---------------------------------------------------------------------- def __init__(self, *args, **kwargs): """Constructor""" canvas.Canvas.__init__(self, *args, **kwargs) self.pages = [] #---------------------------------------------------------------------- def showPage(self): """ On a page break, add information to the list """ self.pages.append(dict(self.__dict__)) self._startPage() #---------------------------------------------------------------------- def save(self): """ Add the page number to each page (page x of y) """ page_count = len(self.pages) self.__dict__.update(self.pages[0]) self.setFont("Helvetica", 9) self.drawRightString(270, 679, str(page_count)) for page in self.pages: self.__dict__.update(page) self.draw_page_number(page_count) canvas.Canvas.showPage(self) canvas.Canvas.save(self) #---------------------------------------------------------------------- def draw_page_number(self, page_count): """ Add the page number """ page = "Page %s of %s" % (self._pageNumber, page_count) self.setFont("Helvetica", 9) self.drawRightString(200*mm, 20*mm, page) class YourPdfClass: def __init__(self): pass def header(self, canvas, doc): pass def write_pdf_lines(self, columns_fields, file_path): pdf_filename = file_path pdf_document = SimpleDocTemplate(pdf_filename, pagesize=letter ) # Calculate the available width within the margins available_width … -
How to add value into a form before saving in Django
I want the user to fill some form, then add the user's id and user's branch(from another table, by releation) to add to the form data before saving it. the form has other fields like {type, serialno, model, date}, after it is submitted i want to add userid and branchid to that form value and submit it to database This is my view.py enter image description here I tried to overide the form data as you can see in the picture. But, it keeps showing me an error message of "TypeError" -
Incorporating Slack-bolt django example in my app
I have incorporated slack-bolt Django example in my Django project. I can successfully install the app using /slack/install. However, I have challenges with customisation. My app is initialised as in the django example app = App( signing_secret=signing_secret, oauth_settings=OAuthSettings( client_id=client_id, client_secret=client_secret, scopes=scopes, user_scopes=user_scopes, # If you want to test token rotation, enabling the following line will make it easy # token_rotation_expiration_minutes=1000000, installation_store=DjangoInstallationStore( client_id=client_id, logger=logger, ), state_store=DjangoOAuthStateStore( expiration_seconds=120, logger=logger, ), ), ) Challenge 1: I would like the installation flow to be triggered from the /profile page of my app. I generated the Slack install button and placed it inside of my app /profile page. Please note that the profile page is available to the user after authentication to the django project. When the user gets redirected, the Slack page shows up, user clicks Allow and is redirected back to the /slack/oauth_redirect The error shows up with information that Slack installation was triggered from a different URL than /slack/install. I tried to set the installation_url in my app as follows app.oauth_flow.install_path = '/profile' app.oauth_flow.settings.install_path = '/profile' but it didn't work The only way I could make it work was to disable the state validation app.oauth_flow.settings.state_validation_enabled = False Question 1: How do I … -
Issues while using related names
This is the Course and LearnerCourse model: class Course(BaseModel, Timestamps, SoftDelete): name = models.TextField(_("Course Name"), max_length=100, blank=True, null=True, unique=False) description = models.TextField( _("Course Description"), blank=True, null=True) course_number = models.CharField( max_length=15, null=True, blank=True, unique=True).... class LearnerCourse(BaseModel, Timestamps, SoftDelete): course = models.ForeignKey(Course, verbose_name=_("Course"), on_delete=models.CASCADE, db_index=True, related_name='course_learner_courses') learner = models.ForeignKey(Learner, verbose_name=_("Learner Course"), on_delete=models.CASCADE, db_index=True) course_subscription = models.ForeignKey(CourseSubscription, null=True, on_delete=models.CASCADE, db_index=True) enroll_date = models.DateTimeField(verbose_name=_("Course Enroll Date")) is_favourite = models.BooleanField(default=False) in LearnerCourse used the related name for the course field, after that When used like this details = LearnerCourse.objects.filter(learner=learner_id).all().order_by('-datetime_created') print("details", details) courses = details.course_learner_courses.all() print("courses", courses) which causes an error 'SafeDeleteQueryset' object has no attribute 'course_learner_courses' Please give me some suggestions to fix this problem. -
Tried to live the server using ngrok but ending up getting error
i have created a django crud application website and i want to live it using ngrok server once i tried to login using the link the ngrok given im getting this error [09/Jan/2024 13:21:36] "GET /static/img/login.png HTTP/1.1" 200 1543188 Forbidden (Origin checking failed - https://4407-2001-d08-2901-3214-a5a4-7e36-5645-47c1.ngrok-free.app does not match any trusted origins.): /login/ , i have put the link on allowed host and CORS_ALLOWED_ORIGINS as well. -
TypeError: RocCurveDisplay.__init__() takes 1 positional argument but 4 were given [closed]
from sklearn.metrics import confusion_matrix from sklearn.metrics import classification_report, roc_curve, RocCurveDisplay print('----- confusion matrix ------') print(confusion_matrix(y_test, y_pred_nb)) print('----- classification report -----') print(classification_report(y_test, y_pred_nb)) RocCurveDisplay(nb, X_test, y_test) TypeError: RocCurveDisplay.__init__() takes 1 positional argument but 4 were given how to fix this error? i use sklearn 1.2 -
Runtime error while using post methord in forms submision
Title: Getting Runtime Error (Append Slash) on Submit Button Click Description: I'm encountering a runtime error when I click the submit button on my form. The error mentions something about appending a slash. I've tried to understand it, but I'm stuck. Can someone please help me figure out what's causing this error and how to resolve it? I'm using python with django for my project. Additional Information: [Provide relevant code snippets if possible] [Any error messages received] <form action="register" method="POST" onsubmit="register"> {% csrf_token %} <h3>my information</h3> <h4>Contact us today, and get reply with in 24 hours!</h4> <style> fieldset { border: medium none !important; text-emphasis-color:black; margin: 0 0 10px; min-width: 100%; padding: 0; width: 100%; } </style> <fieldset> <input placeholder="Your name" type="text" tabindex="1" style="background-color:black;" required autofocus> </fieldset><br> <fieldset> <input placeholder="Your Email Address" type="email" tabindex="2" style="background-color:black;" required> </fieldset><br> <fieldset> <input placeholder="Your Phone Number" type="tel" tabindex="3" style="background-color:black;" required> </fieldset><br> <fieldset> <label for="account">Choose a account:</label> <select name="account" id="name"> <option value="netflix">netflix</option> <option value="amazone prime">amazone</option> <option value="disney plus hotstar">hotstar</option> </select> <style> #nname { padding: 5px; color: #f7f7f8; font-size: 12px; background: black; appearance: none; } </style> </fieldset><br> <fieldset> <textarea placeholder="Type your Message Here...." tabindex="5" style="background-color:black;" required></textarea> </fieldset><br> <fieldset> <button name="submit" type="submit" id="contact-submit" style="background-color:rgb(23, 12, 12);" data-submit="...Sending" value="submit">Submit</button> … -
Django . password and phone number is not storing in admin page
[enter image description here](https://i.stack.imgur.com/xuuor.png)enter image description here I was making a project and the data of customers are not being added to the admin page. the First name last name and email shoes up after the signup but the phone number and password dont show up. How do i fix it? -
chrome not saving httponly refresh token on incognito mode django react jwt auth
I am building an app using django and react. Im using JWT auth, and access refresh tokens for auth. ive deployed it in heroku, connected my domain, now it works on regular browsing but on incognito it doesnt work, meaning when i log in the user, in incognito mode the refresh token doesnt get saved, so it cannot reauthenticate. ive read that its good to send the refresh token through httponly, so thats what im doing, but it deosnt get saved in the incognito but it does on regular. I tried to understand it using chatgpt but it says there isnt much i can do then swithcing to another auth method, but there should be a way, if httponly refresh token is the secure way of doing it there should be a way to make it work. here is my website:http://www.chronocraftusa.com/ git:https://github.com/ashgharibyan/ChronoCraft settings.py """ Django settings for backend project. Generated by 'django-admin startproject' using Django 4.2.1. For more information on this file, see https://docs.djangoproject.com/en/4.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.2/ref/settings/ """ from pathlib import Path from datetime import timedelta from environs import Env import os env = Env() env.read_env() # Build paths inside the project … -
how to store and manage the access_token and refresh_token for Oauth2 (React JS)?
I have an API Rest created in Django and Django Rest Framework. I implemented the Oauth2 protocol using the OAuth Toolkit library. The backend is built and working. I have questions about how to maintain and manage tokens in the front-end made in React. The access_token expires every 10 days, so I need to make a request to renew the access_token using refresh_token. The big issue is that when creating the React build, even using environment variables, with each token renewal, I will have to generate the build again. Is there any way to do this differently, without having to generate a new build every time the token is renewed? -
How to makemigrations django 2.2.9 multiple DB
So I am working in a legacy project with a Django 2.2.9 and here we have 3 DBs, nobody migrated on two additional databases ever, and now its time to do it, but nobody knows how to do it on django 2.2.9 on a database that is not default... I tried writing migration manually and running it - didnt help python manage.py makemigrations No changes detected Any help? -
Array of dictionaries in Django models and forms
I'm working on a static routes plugin for the Netbox project. For my static route object, I need a property, qualified_next_hops, which is a list of dictionary objects. Each item in the list field would have a few keys: next_hop_address, next_hop_interface, admin_distance, route_metric, route_tag. In my model and forms, what field can I use for this list of dictionaries? I've used ArrayField elsewhere, but I don't know how to use a dictionary object as the base field. Any advice? -
Object of type (serializer name) is not JSON serializable
I have a legacy system and a new one for classes (the kind you teach). In this part of the project I am trying to bring items from the old into the new but I keep running into "Object of type ThingOldClassSerializer is not JSON serializable" and I have yet to figure out why. There are no NULLs in the data. Some code: models.py class OldTemp(models.Model): legacy_user_id = models.PositiveIntegerField() legacy_title = models.CharField(max_length=250,) legacy_material_limit = models.PositiveIntegerField() legacy_handout_limit = models.PositiveIntegerField() legacy_handout_fee = models.FloatField() legacy_material_fee = models.FloatField() legacy_duration = models.FloatField() legacy_culture = models.CharField(max_length=250) legacy_topic = models.CharField(max_length=250) legacy_adult_only = models.BooleanField() legacy_heat_source = models.BooleanField() legacy_year = models.PositiveIntegerField() legacy_private_camp = models.BooleanField() legacy_active = models.BooleanField(default=True) instructor = models.CharField(default='') def __str__(self): return self.legacy_title serializers.py class ThingOldClassSerializer(serializers.ModelSerializer): class Meta: model = OldTemp exclude = ['legacy_user_id', 'legacy_active'] views.py class ThingOldToNewView(generics.CreateAPIView): queryset = OldTemp.objects.all serializer_class = ThingOldClassSerializer def get(self, request, pk, curr_old): oldclass = get_object_or_404(OldTemp, pk=pk) serializer = ThingOldClassSerializer(oldclass) return Response({'serializer': serializer, 'thingcurrentclass': oldclass}) def post(self, request, pk, curr_old): oldclass = get_object_or_404(OldTemp, pk=pk) serializer = ThingOldClassSerializer(oldclass, data=request.data) if serializer.is_valid(): self.check_object_permissions(request, oldclass) serializer.save(legacy_active=False) return redirect('home_page') return Response({'serializer': serializer, 'thingcurrentclass': oldclass}) The item displays just fine, but when I click a button to move the it into the new system (POST action) I … -
Permutation feature importance with multi-class classification problem
I am wondering if we can do Permutation feature importance for multi-class classification problem? from sklearn.inspection import permutation_importance metrics = ['balanced_accuracy', 'recall'] pfi_scores = {} for metric in metrics: print('Computing permutation importance with {0}...'.format(metric)) pfi_scores[metric] = permutation_importance(xgb, Xtst, ytst, scoring=metric, n_repeats=30, random_state=7) Cell In[5], line 10 8 for metric in metrics: 9 print('Computing permutation importance with {0}...'.format(metric)) ---> 10 pfi_scores[metric] = permutation_importance(xgb, Xtst, ytst, scoring=metric, n_repeats=30, random_state=7) File c:\ProgramData\anaconda_envs\dash2\lib\site-packages\sklearn\utils\_param_validation.py:214, in validate_params.<locals>.decorator.<locals>.wrapper(*args, **kwargs) 208 try: 209 with config_context( 210 skip_parameter_validation=( 211 prefer_skip_nested_validation or global_skip_validation 212 ) 213 ): --> 214 return func(*args, **kwargs) 215 except InvalidParameterError as e: 216 # When the function is just a wrapper around an estimator, we allow 217 # the function to delegate validation to the estimator, but we replace 218 # the name of the estimator by the name of the function in the error 219 # message to avoid confusion. 220 msg = re.sub( 221 r"parameter of \w+ must be", 222 f"parameter of {func.__qualname__} must be", 223 str(e), 224 ) ... (...) 1528 UserWarning, 1529 ) ValueError: Target is multiclass but average='binary'. Please choose another average setting, one of [None, 'micro', 'macro', 'weighted']. Then I tried to use average='weighted', then I still got an … -
Recursion error in django model when setting constraints
Im trying to create an app to keep track of matches however I keep getting an error when trying to create add to my match model. I want to make sure that team 1 and team 2 dont have the same players, is this the correct way to do so? How do i resolve my error? team1_names = set([player.playerName for player in self.team1.all()]) ^^^^^^^^^^ … Local vars Variable Value self Error in formatting: RecursionError: maximum recursion depth exceeded while calling a Python object class player(models.Model): playerName = models.CharField(max_length = 255,primary_key = True) club = models.ForeignKey(club,on_delete=models.CASCADE) inGameFlag = models.BooleanField(default = False) elo = models.IntegerField(default = 1200) class session(models.Model): sessionID = models.AutoField(primary_key=True) club = models.ForeignKey(club,on_delete=models.CASCADE) date = models.DateField(default = get_today) players = models.ManyToManyField(player) def __str__(self): return str(self.date) class Meta: constraints = [ models.UniqueConstraint(fields=['sessionID', 'club'], name='unique_session') ] class match(models.Model): matchID = models.AutoField(primary_key=True) session = models.ForeignKey(session,on_delete=models.CASCADE) team1 = models.ManyToManyField(player, related_name='team1') team2 = models.ManyToManyField(player, related_name='team2') score = models.CharField(max_length = 255, default = '00-00') completed = models.BooleanField(default=False) def clean(self): team1_names = set([player.playerName for player in self.team1.all()]) team2_names = set([player.playerName for player in self.team2.all()]) common_players = team1_names.intersection(team2_names) if common_players: raise ValidationError({'team1': 'Players cannot be in both team1 and team2.'}) if self.team1.count() > 2 or self.team2.count() > 2: … -
django-admin: redirecting after object save
I have an "edit" button in the detailed view for one of my Django models. This button sends the user to the admin panel. Example for the "project" model: /admin/<app_name>/project/3108/change/ Once the user finishes making changes and hits "Save", they are redirected back to the main admin panel. Is it possible, instead, to send them back to the detailed view in the app? -
ValueError at /pharmcare/patients-create/: "needs to have a value for field "id" before this many-to-many relationship can be used."
Please help me with the Django app I am creating called pharmcare on the issue I am having. I have been stuck on this value-error for 2 days now, and I had researched how to sort it out when using the ManyToMany relationship including reading the Django docs. Still, I ended up getting None as total payment in the patients http://127.0.0.1:8000/pharmcare/patient-list/ which is kind of weird in my second solution, and I believe I am missing something on my second solution. Please, I do want the total to be saved dynamically once the pharmacist has added the discount price and if there is no discount which I set to null and blank=True, I would want the previous total to be saved as well on pharmaceutical_care_plan table of my PostgreSQL. Here is my model: class PharmaceuticalCarePlan(models.Model): class Meta: ordering = ['id'] user = models.ForeignKey('songs.User', on_delete=models.CASCADE) pharmacist = models.ForeignKey( "Pharmacist", on_delete=models.SET_NULL, null=True, blank=True) organization = models.ForeignKey( 'leads.UserProfile', on_delete=models.CASCADE) patients = models.ManyToManyField('Patient') patient_unique_code = models.CharField( max_length=20, null=True, blank=True) total_payment = models.PositiveBigIntegerField(null=True, blank=True) discount = models\ .PositiveBigIntegerField(null=True, blank=True, help_text="discount given to patient,\ perhaps due to his/her consistent loyalty strictly authorized by \ management (if any).") # other codes slug = models.SlugField(null=True, blank=True) date_created = … -
Django project not working on my friends device
I created a a small website using django. I can host it locally and can interact all the buttons like sign up page and login page. but when my friend tried to run project then they can able to start django server but can't able to interact with sign up page and login page! He can see the server syntax on html page like {% csrf_token %}. Please help!!!!!!!!!!!!!!!! -
Best Practice for Django Mixins?
I'm working on a Django project and creating a custom mixin, specifically a MessagesMixin for handling success and error messages. I'm using it with CreateView and UpdateView. I'm wondering about the best practice regarding the mixin's dependency on the view it is mixed into??. I have created a two version of MessagesMixin, which one is the correct answer ??? Version 1: class MessagesMixin: success_message = None fail_message = None fail_redirect_url = None def form_valid(self, form): response = super().form_valid(form) if self.success_message: messages.success(self.request, self.success_message.format(self.object)) return response def form_invalid(self, form): super().form_invalid(form) if self.success_message: messages.error(self.request, self.fail_message.format(self.object)) return redirect(self.fail_redirect_url) Version 2: class MessagesMixin(ModelFormMixin, View): success_message = None fail_message = None fail_redirect_url = None def form_valid(self, form): response = super().form_valid(form) if self.success_message: messages.success(self.request, self.success_message.format(self.object)) return response def form_invalid(self, form): super().form_invalid(form) if self.success_message: messages.error(self.request, self.fail_message.format(self.object)) return redirect(self.fail_redirect_url) -
Why no junction table for ForeignKey in Django Model? How prefetch_related works under the hood
I am trying to understand the difference between select_related and prefetch_related in Django. More specifically, how do both of them work under the hood. My understanding of select_related is clear but I am confused about prefetch_related. Here is my sample Django model. class Club(models.Model): name = models.CharField(max_length=100) class Teacher(models.Model): name = models.CharField(max_length=100) class Student(models.Model): name = models.CharField(max_length=100) teachers = models.ManyToManyField('Teacher') club = models.ForeignKey('Club', null=True, blank=True, on_delete=models.SET_NULL) When I see the db.sqlite3 through an extension, I can see following tables - club, student, teacher, and student_teachers which is the junction table that stores the relationship. Why is there no club_teachers? I understand there is no need for a junction table for OneToOne but for 1:N/ForeignKey, how do we access them? I guess it has something to do with this part in official documentation. prefetch_related, on the other hand, does a separate lookup for each relationship, and does the ‘joining’ in Python How does prefetch_related help with the N+1 problem if it does a "separate lookup for each relationship, and does the ‘joining’ in Python"? I understand the difference between select_related and prefetch_related is that select_related is for single-valued relationships but then how does the reverse relationship for Club work? -
Django Foreign Key To Any Subclass of Abstract Model
I have an abstract Django model with two concrete implementations. E.g. class Animal(models.Model): name = models.CharField("name", max_length=100) class Meta: abstract = True class Dog(Animal): ... class Cat(Animal): ... And then I want to create a generic foreign key that points to a Dog or a Cat. From the documentation about GenericForeignKeys I know that I can do something like from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class Appointment(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() patient = GenericForeignKey("content_type", "object_id") But I have to do this for every model that can point to a Dog or a Cat. It doesn't enforce that the foreign key actual points to an Animal. Is there a way to set up my Animal model such that in the Appointment model I can just do class Apointment(models.Model): patient = GenericRelation(Animal) -
Django : Login/authentication function is not working
im trying to write a login function code in my django app everything seems to be fine but still everytime i try to login to an account in that application it seems to return me back to the the same page here is my views.py code def admin(request): if request.user.is_authenticated: return redirect("/admin_home") else: if request.method == "POST": uname = request.POST.get("uname") pas = request.POST.get("psw") use = authenticate(username=uname , password=pas) login(request,use) return render(request,"admin_login.html") Html Code here <!DOCTYPE html> {% load static %} <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> {% for message in messages %} <div style="background-color:lime;position:fixed;top:0%; width:90%; height:5%; font-size:25px; font-family:sans-serif; left:5%; border-radius:11px; text-align:center; line-height:2;"><b>{{ message }}</b></div> {%endfor%} <h2 style="margin-left:20%;">Login</h2> <link rel="stylesheet" href="{% static 'login.css' %}"> <div style="height:70%; width:60%; margin-left:20%;"> <form method="POST"> <div class="imgcontainer"> <img src="https://cdn-icons-png.flaticon.com/512/21/21104.png" alt="Avatar" class="avatar" style="height:30%; width:30%;"> </div> <div class="container"> <label for="uname"><b>Username</b></label> <input type="text" placeholder="Enter Username" name="uname" id="uname" required> {% csrf_token %} <label for="psw"><b>Password</b></label> <input type="password" placeholder="Enter Password" name="psw" id="psw" required> <button type="submit">Login</button> </div> <div class="container" style="background-color:#f1f1f1"> <button type="button" class="cancelbtn">Cancel</button> </div> </form> </div> </body> </html> ive tried every possible thing in my knowledge and im stuck on this part so please help me