Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting Django to AWS MySQL Database
I am having an issue allowing my Django project connect to my AWS MySQL RDS instance. I keep getting the error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2005, "Unknown MySQL server host 'cropdrone.cp1xd7eoed6m.us-east-2.rds.amazonaws.com' (11001)") So then nothing happens. I deleted all my security groups and opened all IPv4 and v6 ports to the database. I tried doing an EC2 method but that was all local. The goal is for me to make a website that uses this database then can pull images and GPS coordinates a partner of mine uploads to the database. Here is my settings.py image displaying the database connection I have set up. Here is another question I have been asking myself and would like to know from anyone willing to help. Should I scratch the MySQL option and do PostgreSQL? I see many many many tutorials showing how to connect Django to it and I'm so at a loss I'm willing to change databases. I don't have data stored in my instance yet so it won't be much of a change anyway. -
Pyperclip wont let me copy things
If I try to copy things with pyperlclip this error appears: Pyperclip could not find a copy/paste mechanism for your system. On this site: https://pyperclip.readthedocs.io/en/latest/index.html#not-implemented-error they said I have to install things that it will work and I did that but it still wont work, also if I just type in the name of the installed thing there comes an error named Error: No display: (null) But the thing is installed, I know that because if I do it again it says that its already installed. Please help -
How could I display parent object attribute in Django Admin?
At the moment I'm working on an e-commerce application. It contains a sub-app called "blog". The idea is that the superuser creates an account for the *Trainer. And yeah, I already created a new AbstractUser Trainer logins into his account and creates Post I logged in here using my Trainer`s credentials After I want the superuser to see WHO created post, but DjangoAdmin displays me admin`s email How could I display the email of the 'creator' of the post in Django admin? Code: #models.py class UserTrainer(AbstractUser): email = models.EmailField(verbose_name='email', max_length=100, unique=True) age = models.PositiveIntegerField(null=True) info = RichTextField(blank=True, null=True) image = models.ImageField(upload_to='media/stuff_images') inst = models.URLField(blank=True) REQUIRED_FIELDS = ['email', ] def __str__(self): return self.email def get_email(self): return self.object.email class Post(models.Model): DEFAULT_TRAINER_ID = 1 article = models.CharField(max_length=50, default='Article text') slug = models.SlugField(max_length=30) keywords = models.CharField(max_length=100) text = RichTextField(blank=True, null=True) trainer = models.ForeignKey(UserTrainer, on_delete=models.CASCADE, null=False, default=1) def __str__(self): return self.article class Meta: verbose_name = 'Post' verbose_name_plural = 'Posts' #admin.py class CustomUserAdmin(UserAdmin): model = UserTrainer add_form = CustomUserCreationForm fieldsets = ( *UserAdmin.fieldsets, ( 'TrainerInfo', { 'fields': ( 'age', 'info', 'image', 'inst', ) } ) ) admin.site.register(UserTrainer, CustomUserAdmin) @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ('article', 'slug','trainer') list_display_links = ('article',) fields = ('article', 'slug', 'keywords', 'text',) readonly_fields = … -
'UNIQUE constraint failed: main_chatroom.admin_id' when creating new object in django
it only happens when I create new chatroom with the same admin this is what I wrote in my models.py class ChatRoom(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, null=False, blank=True) users = models.ManyToManyField(User, through='Membership') admin = models.ForeignKey( User, null=False, blank=False, on_delete=models.CASCADE, related_name='admin') date_created = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Membership(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) user = models.ForeignKey(User, on_delete=models.CASCADE) chatroom = models.ForeignKey(ChatRoom, on_delete=models.CASCADE) date_joined = models.DateTimeField(auto_now=True, null=False, blank=False) def __str__(self): return self.user class Meta: unique_together = [['user', 'chatroom']] when i write this: from .main.models import ChatRoom,Membership from django.contrib.auth.models import User user = User.objects.get(username = 'someone') chatroom = ChatRoom(admin = user, name = 'something') chatroom.save() chatroom2 = ChatRoom(admin = user, name = 'somethingElse') chatroom2.save() after i save chatroom2 i get this error : django.db.utils.IntegrityError: UNIQUE constraint failed: main_chatroom.admin_id can anyone help me? -
Django password reset link
I am trying to make a password reset system with Django (for learning purposes) and I want to use the built-in password reset system(django.contrib.auth.PasswordReset...) except sending the password reset link via email. Instead of sending this link via email, I want to send it the way I want, and to achieve that I need to get this link in Python code (maybe in views.py). My question: How can I get the password reset link in Python code? I am using Django 3.2.6 -
Override min_value and max_value in IntegerField Django
class A: min_v = 1 max_v = 15 number1 = IntegerField(min_value=min_v, max_value=max_v) class B(A): number2 = IntegerField(min_value=A.min_v, max_value=A.max_v) class C(B): min_v = 2 max_v = 20 How to make both number1 and number2 to be in range from 2 to 20 in class C? I'm thinking about two ways: In __init__ redeclare self.fields['number1'] like IntegerField(min_value=self.min_v) Set self.fields['number1'].min_value=self.min_v in __init__ and override setattr() to add validator. What is the best and the cleanest way? -
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