Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-q multiple clusters and tasks routing
Is it possible to have two clusters and route tasks between them? I suppose I can run two clusters using different settings files, but how to route tasks in that case? -
AttributeError: 'NoneType' object has no attribute 'lower'; password validation
When registering a User, the desired user password is checked against a list of disallowed passwords. Yet when the password is passed to a validator method, the following error is raised: AttributeError: 'NoneType' object has no attribute 'lower' Why is the validate() method being invoked as is if password is None when in fact it is truthy? from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( validate_password, CommonPasswordValidator, NumericPasswordValidator ) from rest_framework import serializers class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username = data['username'] password = data['password'] try: validate_password(password, password_validators=[ CommonPasswordValidator, NumericPasswordValidator ]) except serializers.ValidationError: if username == password: pass raise serializers.ValidationError("Invalid password") else: return data class Meta: fields = ['username', 'password'] model = User -> for validator in password_validators: (Pdb) n > \auth\password_validation.py(46)validate_password() -> try: (Pdb) n > \auth\password_validation.py(47)validate_password() -> validator.validate(password, user) (Pdb) password 'Bingo' (Pdb) user (Pdb) password 'Bingo' (Pdb) s --Call-- > \auth\password_validation.py(180)validate() -> def validate(self, password, user=None): (Pdb) password (Pdb) n > \django\contrib\auth\password_validation.py(181)validate() -> if password.lower().strip() in self.passwords: (Pdb) n AttributeError: 'NoneType' object has no attribute 'lower' -
PyTube files are in root directory not in Downloads path from user
I'm coding an video converter and everything works as expected on my localhost but now on the server my converted video gets saved in the root dir from my server and not in the Downloads path from the user. This is my code: if format == "3": messages.info(request, 'The MP3 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) new_file = base + uuid + '.mp3' os.rename(audio_file, new_file) elif format == "4": messages.info(request, 'The MP4 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) ys = yt.streams.filter(file_extension='mp4').first().download(downloads) username = request.user.username context = {'format': format, 'username': username} return render(request, 'home/videoconverter.html', context) the parameter next to .download is the path, as I already said on my localhost everything worked. So I need a way to save files in the users download dir with server. -
Reverse not working with kwargs while working in another function - why?
def test_no_errors_direct_flights_rendered_in_template(self): request = HttpRequest() response = render(request,'app1/flight-search-result.html', { 'direct_flights': [ { ---- not relevant }) self.assertContains(response, 'Direct connection') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'One change') # this assertContains will ensure that the searched word is not in the form - we don't pass # the form to the render function above self.assertContains(response, 'Venice Airport Marco Polo') self.assertContains(response, 'Dubai International Airport') # you can add more once you change the template url = reverse('app1:flight-search-detail-passenger-form', kwargs={'to_first': "VCEDXB2201040"}) ---- works! self.assertContains(response, '<a href="{}">'.format(url)) def test_no_errors_indirect_flights_rendered_in_template(self): request = HttpRequest() response = render(request, 'app1/flight-search-detail-passenger-form.html', { 'indirect_flights': [ { ----- not relevant { } ] } ] }) self.assertContains(response, 'One change') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'Direct flight') # you can add more once you change the template kwargs = {'to_first': "VCEDXB2201040"} _url = reverse('app1:flight-search-detail-passenger-form', kwargs=kwargs)------- doesn't work! self.assertContains(response, '<a href="{}">'.format(_url)) A very weird problem, but the first reverse works perfectly well while the second one throws the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'flight-search-detail-passenger-form' with arguments '('',)' not found. 2 pattern(s) tried: ['flights/detail/passenger/to=(?P<to_first>[ A-Z0-9]{13})&(?P<to_second>[A-Z0-9]{13})$', 'flights/detail/passenger/to=(?P<to_first>[A-Z0-9]{13})$'] Has someone encountered it before? How can I solve it? -
How to deploy django(back) and react(front) servers on nginx on ubuntu?
I have to to deploy web-server(django and react) on nginx server. I already have working projects, they weigh about a 2 gigabyte, there are a lot of libraries. Do I need to save them? I can't imagine how to do it in most simple way. There are information doing it using docker. Is it a common way to do it? Can you explain me how exactly a true way to do this deploying, please. -
How to send stream data using just python?
I am currently learning NodeJS and I learned a really neat way of sending big files, using streams, I already have a bit of an experience with Django but how can I do the following in Django (or python) const http = require('http') const fs = require('fs') const server = http.createServer((req, res)=>{ const fileContent = fs.createReadStream('./content/bigFile.txt', 'utf8') fileContent.on('open', ()=>{ fileContent.pipe(res) }) fileContent.on('error',(err)=>res.end(err) ) }) server.listen(5000) -
Limit amount of foreign keys in clean method Django
I'm not trying to limit amount of foreign keys on Forms or views, I'm trying to make it through the clean method on the models.py. I tried to find something about it but the thing is that when you save a model with a foreign key, the clean method don't get the new related object becouse, first, it saves the model args and then the foreign keys, so when you try to add somethings like this: class RelatedModel(models.Model): fields... def clean(self) -> None: from django.core.exceptions import ValidationError limit = 5 if self.related_name: if self.related_name.count() > limit: raise ValidationError(f"The limit of related objects is { limit }") return super().clean() class Model(models.Model): related_model = models.ForeignKey(RelatedModel, related_name="related_name") The count() is not the real one, becouse you just get an instance of the model with the previous related_models, but not with the new ones, so the you can't limit the amount like that. ¿Is there any way to achieve this? -
django: when to derive directly from View class in CBVs
I am using django 3.2. I am building a commenting system that allows users to post comments (without using a form). It is not clear from the documentation whether I should do this: class AddComment(MyMixin, View): post(request, *args, **kwargs): pass OR class AddComment(MyMixin, CreateView): post(request, *args, **kwargs): # No form .. so just deal with passed in args pass Which is the canonical way to do this? (citations please) -
From python to django [closed]
What are the Python topics that one should focus on to master and understand django? am done with the basics of python but just wanna know before moving to django. -
Queryset with collated/merged values
Let's say I have the following two models: class Parent(models.Model): name = models.CharField(max_length=48) class Child(models.Model): name = models.CharField(max_length=48) movement = models.ForeignKey(Parent, related_name='children') And I have the following DRF generics.ListAPIView where I want to be able to search/filter on Child objects but actually return the related Parent objects: class ParentSearchByChildNameView(generics.ListAPIView): """ Return a list of parents who have a child with the given name """ serializer_class = ParentSerializer def get_queryset(self): child_name = self.request.query_params.get('name') queryset = Child.objects.all() if child_name is not None: queryset = queryset.filter(name__contains=child_name) matched_parents = Parent.objects.filter(children__in=queryset).distinct() return matched_parents Now, this works well for me. If a Parent object has 3 Child objects which all match the given "name" query_param, then I only get one Parent object back, which is what I want: { "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", } ] } However, what I also want is to indicate the matched Child object IDs within the result. If I may illustrate in JSON what I want: { "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", "matched_child": [1, 3, 7] } ] } Is this something I can do with built-in tools, without expensively and repeatedly … -
Customizing UserChangeForm in django
I want to delete 'groups' field from build-in UserChangeForm and add own "Role' field. How to handle that? I created my class which inherits from UserChangeForm and went to somehow delete but no change. class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) self.exclude = ('groups',) -
Why does my column appear below my row rather than to the right?
I have a webpage at the moment with 3 cards on it which I am going to use as contact cards. To the right of that in a seperate column I want to have some text but for some reason, the text always appears directly below the cards as below. My desired outcome is to have the test text appear to the right of the cards. The html is currently formatted like this: {% extends 'base.html' %} {% block content %} <br> <div class="container"> <div class = "row-sm-1"> <div class ="col-sm-1"> <!-- Card 1 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> <!-- Card 2 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> <!-- Card 3 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> </div> <!-- Second Column --> <div class = "col-sm-2"> <h1>Test</h1> </div> </div> </div> <br><br><br> {% endblock %} Where base.html contains just basic tags like head, body, etc. This … -
Django ORM complex order_by (with CASE and WHEN by related model), DISTINCT lefting duplicates
What am i trying to do - is to create ajax datatable with serverside processing, where in first column will be keyword_name (main model), and in all others - positions ranks (related model), with ability to sort data by any column, apply search and filters. The table looks like: | Keyword_name | Position created 01.01.21, Google search engine, New-York Region | Position created 03.01.21, Yahoo Search engine, New-York Region | blablabla, all types of positions by dates,engines,regions | | |--------------|------------------------------------------------------------|---------------------------------------------------------|------------------------------------------------------------|---| | keyword 1 | rank:1 | Rank:3 | etc | | | keyword 2 | rank:5 | Rank:1 | etc | | | etc.. | | | | | My models are: class Keyword(): """Main model""" project = models.ForeignKey(Project, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(max_length=1000) <-----> created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Position(): """Model for keep keywords positions""" keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE) engine = models.ForeignKey(SearchEngine, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) rank = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) So, i dont have problem with filtering positions (getting data with simple Keyword.objects.filter("position__created_at__date_gte" = 01.01.21, "position__created_at__date_lte" = 01.02.21 etc), but the problem is when i`m trying to sort data by columns - i want to click to column … -
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!