Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Python email validations no shared email between multiple users
I am needed to know what code I need to put into my models.py (validations) so that when a user goes to register for a new account, that they get an error message if that email address is already in use by another user. -
Unable to save inlineformset Django
I'm new to Django. I created a custom layout form with an inline-formset. Sadly, I can't save this form in any way and don't get any error message. The only thing I understand with the debug toolbar, no data is being posted to the order field in the order detail (child) table, which is assigned as a foreign key from the ID field of the order table (parent). My models, forms, views, and templates are given below : model.py class PurchaseOrder(models.Model): purchase_id = models.CharField(max_length=50) order_date = models.DateField(default=now) voucher = models.CharField(max_length=25, blank=True, null=True) supplier = models.ForeignKey('Supplier', blank=True, null=True, on_delete=models.SET_NULL) order_amount_usd = models.DecimalField(max_digits=10, decimal_places=2, default=0) order_amount_bdt = models.DecimalField(max_digits=10, decimal_places=2, default=0) discount_type = models.CharField(max_length=1) discount_percent = models.DecimalField(max_digits=5, decimal_places=2, default=0) discount_amount = models.DecimalField(max_digits=5, decimal_places=2, default=0) freight_charge = models.DecimalField(max_digits=10, decimal_places=2, default=0) debit_account = models.ForeignKey('Account', blank=True, null=True, related_name='debit_account', on_delete=models.SET_NULL) total_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) paid_amount = models.DecimalField(max_digits=10, decimal_places=2, default=0) credit_account = models.ForeignKey('Account', blank=True, null=True, related_name='credit_account', on_delete=models.SET_NULL) tracking = models.CharField(max_length=30, blank=True, null=True) received = models.BooleanField(default=False) status = models.CharField(max_length=25) narrations = models.CharField(max_length=100, blank=True, null=True) received_at = models.DateTimeField(blank=True, null=True) elapsed_days = models.DurationField(default=timedelta()) journal_entry = models.BooleanField(default=False) created_at = models.DateTimeField(default=now, editable=False) created_by = models.ForeignKey(User, related_name="purchaseorders", blank=True, null=True, on_delete=models.SET_NULL) class Meta: default_related_name = 'PurchaseOrder_detail' def get_absolute_url(self): return reverse('purchase-order-update', kwargs={'pk': self.pk}) def __str__(self): … -
Django equivalent to node app.get("/*" call
I am trying to replicate this node js call in Django. I am not familiar with node, but wondering how to represent /* in Django or if there is existing middleware that does the same. app.get("/*", function(req, res) { } I would appreciate any example or a pointer that I can use to help port this function. -
Django channels testing with HttpCommunicator
I have a DRF application, which also has a single websocket consumer Now I'm trying to make a test case, which inherits from a Djano 3.1 TestCase. Said test case should register a user via rest_auth registration endpoint and than connect to the channels consumer To register a user in a test case I use HttpCommunicator like so: class TestRoomWebsockets(APITestCase): async def test_connect(self): communicator = HttpCommunicator( application, "POST", reverse(UrlUtils.Users.REGISTER), body=json.dumps({"username": ..., "password1": ..., "password2": ...}).encode("utf-8") ) response = await communicator.get_response() self.assertEqual(response["status"], 200) But it fails with status code 400. The response is {'status': 400, 'headers': [(b'Content-Type', b'application/json'), (b'Vary', b'Accept'), (b'Allow', b'POST, OPTIONS'), (b'X-Frame-Options', b'DENY'), (b'Content-Length', b'120'), (b'X-Content-Type-Options', b'nosniff'), (b'Referrer-Policy', b'same-origin')], 'body': b'{"username":["This field is required."],"password1":["This field is required."],"password2":["This field is required."]}'} I have no idea, why the data is lost somewhere. Could someone please explain, what am I doing wrong? Please tell, if more details are required to solve the issue. Some additional files asgi application looks like this: application = ProtocolTypeRouter({ "http": django_asgi_app, "websocket": TokenAuthMiddlewareStack( URLRouter([ path('ws/', my_router), ]) ) }) -
filter records based on a relationship | Django
I have the following models: class PodcastPlatform(models.Model): name = models.CharField(max_length = 60) badge_path = models.FilePathField(path = settings.BADGES_DIR, unique = True) class Meta: ordering = ['name'] def __str__(self): return self.name class Podcast(models.Model): name = models.CharField(max_length = 60) description = models.CharField(max_length = 400) created = models.DateTimeField(auto_now_add = True) updated = models.DateTimeField(auto_now = True) class Meta: ordering = ['-created', '-updated'] def __str__(self): return self.name class PodcastLink(models.Model): podcast_platform = models.ForeignKey(PodcastPlatform, on_delete = models.CASCADE) podcast = models.ForeignKey(Podcast, on_delete = models.CASCADE) url = models.URLField(max_length = 400, verbose_name = 'URL') class Meta: ordering = ['podcast_platform__name'] unique_together = ['podcast_platform', 'podcast'] def __str__(self): return self.podcast_platform.name def get_badge_url(self): return static(re.search('img/.{0,}', self.podcast_platform.badge_path).group()) I want to filter the instances of the Podcast model where they have at least one link or a related instance of the PodcastLink model. To do it, I did the following: Podcast.objects.filter(podcastlink__gte = 1) Returning the following QuerySet: <QuerySet [<Podcast: Libero tenetur>, <Podcast: Libero tenetur>, <Podcast: Libero tenetur>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Assumenda iusto>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>, <Podcast: Explicabo>]> I get the expected result, but instead I notice that the instances are repeating... Try the following and in the same way I got the same result (repeated … -
Not able to maintain login in iframe for django
I am trying to maintain the login session in an iframe for a Django website. When the iframe is embedded in the same domain (example.com) the login session is maintained. But when the iframe is embedded in another domain (another.com) the login of example.com is not there, even though the src of the iframe is set to example.com. -
How to add a unique randomly generated 6 digit key stored in a model
I need each model in my database to have a unique six-digit key associated with it. For example, class Quiz(models.Model): name=models.CharField(max_length=250) randomly_generated_id=models.RandomField() #how do I generate a random key here? -
Django: Can't load JS file but all static files are rendered correctly
When I inspect I got a blank page but all static files are well loaded even CSS. My Settings STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URL = '/images/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/images') -
Postgres Syntax to DJANGO ORM Syntax
I have the following Postgres syntax, that does what I want it to do, however, I would like to implement it in the models.py tab in ORM. SELECT split_part(booking_inform, ',', 1) AS col1 , split_part(booking_inform, ',', 2) AS col2 , split_part(booking_inform, ',', 3) AS col3 , split_part(booking_inform, ',', 4) AS col4 , split_part(booking_inform, ',', 5) as col5 , split_part(booking_inform, ',', 6) as col6 FROM main_inmate; I am splitting the column "booking inform" into six new columns based on a commas. Thanks! -
Apple login in django rest framework with allauth and rest-auth
I have implemented Apple login in django with allauth and rest-auth. I implemented same way as Google login which worked perfectly. views.py class AppleLogin(SocialLoginView): adapter_class = AppleOAuth2Adapter urls.py urlpatterns = [ path("auth/apple/", AppleLogin.as_view(), name="apple-login"), ] pip versions Django==2.2.17 django-allauth==0.43.0 django-rest-auth==0.9.3 djangorestframework==3.8.2 djangorestframework-jwt==1.11.0 When I test as below I'm getting KeyError: 'id_token' and this is where error comes from: https://github.com/pennersr/django-allauth/blob/master/allauth/socialaccount/providers/apple/views.py#L92 I have no idea how to fix this error. Thank you for your help ! curl -X POST 'https://.../auth/apple/' \ -d 'access_token=AUTHENTICATION_CODE' or curl -X POST 'https://.../auth/apple/' \ -d 'id_token=ID_TOKEN' \ -d 'access_token=AUTHENTICATION_CODE' -
How to get rid of redundant elements in Django + Bootstrap4
I cannot find where to remove the unnecessary duplicate word that is above. new_entry.html: {% extends "learning_logs/base.html" %} {% load bootstrap4 %} {% block content %} <h5><a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a></h5> <form action="Topic: {% url 'learning_logs:new_entry' topic.id %}" method='post'> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button name="submit" class="btn btn-primary">Add</button> {% endbuttons %} </form> {% endblock content %} views.py: @login_required def new_entry(request, topic_id): """Добавляет новую запись по конкретной теме.""" topic = Topic.objects.get(id=topic_id) check_topic_owner(topic.owner, request.user) if request.method != 'POST': # Данные не отправлялись; создается пустая форма. form = EntryForm() else: # Отправлены данные POST; обработать данные. form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('learning_logs:topic', topic_id=topic_id) # Вывести пустую или недействительную форму. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) Perhaps I need to send something else? I don't know where the code itself is responsible for these parameters. For example, it would be interesting to find where to change the width of the form. -
Error during template rendering : NoReverseMatch at /products/product-3/
** Error ** NoReverseMatch at /products/product-3/ Reverse for 'add_to_cart' not found. 'add_to_cart' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/products/product-3/ Django Version: 3.1.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'add_to_cart' not found. 'add_to_cart' is not a valid view function or pattern name. ** products ** def single(request, slug): product = Product.objects.get(slug=slug) images = ProductImage.objects.filter(product=product) context = {'product': product, 'images': images} template = 'products/single.html' print(request) print(context) print(template) return render(request, template, context) ** urls.py in product app ** from . import views app_name = 'product_app' urlpatterns = [ path('', views.index, name='home'), path('s/', views.search), path('products/', views.all, name='products'), path('products/<slug:slug>/', views.single, name='single_product'), ] -
Are processes the same as concurrency in django-post_office?
I am using django-post_office to send c.10,000 emails in a single task each morning. It's possible to do this via the function send_queued(processes=1, log_level=None) in a celery task. I understand it's best practice to run celery with concurrency, e.g. celery -A settings worker -l info --concurrency 6 Is the processes flag in django-post_office the same as this? E.g. if I am running 6 concurrent celery processes should I have this flag also set as 6? If not, what's the difference between the two? -
ModelMultipleChoiceField returns queryset instead of object instance
Hello I have this problem with multiple checkbox select I have this form class AnswerForm(forms.ModelForm): class Meta: model = Response fields = ('answer', ) def __init__(self, *args, **kwargs): question = kwargs.pop('question') super().__init__(*args, **kwargs) self.fields['answer'].queryset = question.answers.order_by('text') if question.question_field_type == 'multiple': self.fields['answer'] = forms.ModelMultipleChoiceField( widget=forms.CheckboxSelectMultiple( attrs={'autocomplete': 'off'}), queryset=question.answers.order_by('text'), ) My problem is that on submission it raises this error "<QuerySet [<Answer: A. High School Diploma>, <Answer: B. Associate's Degree>]>": "Response.answer" must be a "Answer" instance. how do make these to return answer instance instead of a queryset. -
how can I restructure my project into a microservice architecture?
I have this example data, where I want to communicate with my main project (Django) which it will host each microservice via HTTP, RPC, and other protocols, but my issue is that flask some endpoint are slow this can be improved later, but should I paginate the data on flask or Django? 2) if the data is already paginated how can I access all data from Django to the client(react any other stack)? note: the core service behind flask uses mongo(pymongo) + redis and bson. I did a benchmark using flask + tornado / Django + REST framework, where you can see there is no difference in timing . I want to build this platform as multiple services without caring if xyz component is done by xyz stack tech , and Django will be the front of all microservices by wrapping all data from all microservices together. should I add features like throttling, auth, tokens, pagination, and more from each service or handle from Django(front backend) ?? Execution Time: 0:00:06.451492 # flask Execution Time: 0:00:06.432626 # django { "count": 152983, "matches": [ { "Modified": "2020-11-11T22:15:00", "Published": "2020-11-11T22:15:00", "access": {}, "assigner": "cve@mitre.org", "cvss": null, "cwe": "CWE-601", "id": "CVE-2020-26219", "impact": {}, "last-modified": … -
How to show in Django Admin the list of Activities a user has made
I am trying to get the most out of my Django Blog project and wanted to know how to show in the admin the activities that a user has made like making comments or giving likes to posts. I need some hints and guidance on how to add this information in the admin.py Here is the models.py in Blog App class Post(models.Model): title = models.CharField(max_length=100, unique=True) content = RichTextUploadingField(null=True, blank=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='author') date_posted = models.DateTimeField(default=timezone.now) slug = models.SlugField(blank=True, null=True, max_length=120) liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post-detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super(Post, self).save(*args, **kwargs) class Meta: verbose_name_plural = 'Blog Posts' class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) content = models.TextField(max_length=300) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-Comment No.{self.pk}" LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike') ) class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, max_length=8) created = models.DateTimeField(auto_now=True) def __str__(self): return f"{self.post}-{self.user}-{self.value}" Here is the models.py in Users App class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') This is what I have tried in the models.py in Users app … -
django api how upload multiple images
I tried many times, but I just register the last one im my model class PropertyImage(models.Model): property = models.ForeignKey(Property, default=None, on_delete=models.CASCADE,) images = models.ImageField(upload_to=upload, null=True, blank=True) def __str__(self): return str(self.images) serializer class PropertyImageSerializers (serializers.ModelSerializer): class Meta: model = PropertyImage #fields =('name','') fields = '__all__' my class view handler the post request, I tried to user method FOR to loop all images and save view def post(self, request, *args, **kwargs): for images in request.FILES.getlist('images'): serializer = PropertyImageSerializers() serializer.property(request.data['property']) serializer.images(images) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I get this error message: AttributeError: 'PropertyImageSerializers' object has no attribute 'property' but im my model you can see I have the property -
dateparser TypeError: expected string or bytes-like object
This is my Custom command and I want to convert a string from JASON like publication date: ['A week ago'] to a real date to create it in my Django database. but when I run the command I got this error. I don´t know if is for my command code or the JSON. this is my models: from django.db import models # Create your models here. class Job(models.Model): job_title = models.CharField(max_length=200) company = models.CharField(max_length=200) company_url = models.URLField(max_length=200) description = models.TextField() salary = models.CharField(max_length=200) city = models.CharField(max_length=200) district = models.CharField(max_length=200) publication_date = models.DateTimeField() job_url = models.CharField(max_length=200) job_type = models.CharField(max_length=200) def __str__(self): return self.job_title from django.core.management.base import BaseCommand from jobs.models import Job import json from datetime import datetime import dateparser class Command(BaseCommand): help = 'Set up the database' def handle(self, *args: str, **options: str): with open('static/data.json', 'r') as handle: big_json = json.loads(handle.read()) for item in big_json: #Convertir fecha publication_date = dateparser.parse('publication_date') existing_job = Job.objects.filter( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], publication_date = item['publication_date'], salary = item['salary'], city = item['city'], district = item['district'], job_url = item['job_url'], job_type = item['job_type'], ) if existing_job.exists() is False: Job.objects.create( job_title = item['job_title'], company = item['company'], company_url = item['company_url'], description = item['description'], … -
Django: How to change field name in nested serializer
Currently, I have this serializer: class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model """ user = UserDataSerializer(many=False, read_only=True) class Meta: model = TokenModel fields = ('key', 'user') And this is the response I get: { "key": "d1de7dd82f2b987a6d9f35f1d033876e164f7132", "user": { "username": "peter258", "first_name": "Peter", "last_name": "Jones", "email": "peter.jones@gmail.com" } } I would like to change the response so instead of saying "user" it says "data" but when I change the serializer to something like this, I only get the "key" in the response: class TokenSerializer(serializers.ModelSerializer): """ Serializer for Token model """ data = UserDataSerializer(many=False, read_only=True) class Meta: model = TokenModel fields = ('key', 'data') How do you properly change the name of the "user" field inside nested serializers? -
Multiple foreign key lookups
I have the following models in my app Account class Account(CommonModel): # Accounts received from Client client = models.ForeignKey('Client', on_delete=models.RESTRICT) reference = models.CharField(db_index=True, max_length=50) def __str__(self): return f"{self.client} {self.reference}" Person class Person(CommonModel): title = models.CharField(max_length=100,choices=choi.person_title()) name = models.CharField(db_index=True, max_length=100) birth_date = models.DateField() def __str__(self): return f"{self.title} {self.name}" AccountPerson class AccountPerson(CommonModel): # Account -> Person link account = models.ForeignKey("core.Account", on_delete=models.RESTRICT, related_name="accountperson_account") person = models.ForeignKey("core.Person", on_delete=models.RESTRICT, related_name="accountperson_person") contact_type = models.CharField(max_length=50, choices=choi.contact_type()) def __str__(self): return f"{self.account} - {self.person} ({self.contact_type})" The AccountPerson model holds relationships between accounts and people (one person can have multiple accounts). I'm trying to return a query set containing a list of Accounts, and the Person they're linked to (if any). My background is SQL, so I'm thinking of a query that would hit Account -> AccountPerson --> Person, but I'm stuck. I've tried prefetch_related() but I'm only returning details in the Account table - I'm unsure of how to access Person from there and put those fields into my HTML file. View def account_list(request): data = Account.objects.all().prefetch_related('accountperson_account') return render(request, 'core/account_list.html', {'data': data}) account_list.html Code condensed for readability ... {% for i in data %} <tr> <td>{{i.client}}</td> <td>{{i.reference}}</td> {% endfor %} ... I'm currently in a position where my page … -
Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|landing)/$'] [closed]
https://dpaste.org/aNOQ - кто может помочь вот ошибка Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|landing)/$'] Изменил change_form, кнопка добавилась но по пути моего приложения там где должны быть все модели выскакивает именно эта ошибка http://127.0.0.1:8000/admin/landing/ -
Django - Is there a way to validate a model with its related models before transaction commit?
Suppose I have two related models (my case is a bit more complicate, but the idea is same): class Main(models.Model): amount: int = models.IntegerField() class Child(models.Model): main: Main = models.ForeignKey(Main, on_delete=models.CASCADE) amount: int = models.IntegerField() Whenever creating or changing a Main instance, I want to make sure that it is 'valid'. In my case, a valid Main object means that the sum of all of its children amounts is equal to its own amount: def validate_main(main: Main) -> bool: children = Child.objects.filter(main=main) return sum(child.amount for child in children) == main.amount If I'm right, this creates a deadlock: I can't call validate_main before saving Main, because then I wouldn't be able to create and save the related Child instances (because Main won't have pk), so this check will fail. I can't call validate_main after saving Main, because this will enable a situation where there is an invalid state in the database (someone can create a Main without ever creating its children). I thought about validating the changes in the database just before every transaction commit, by this allowing to create both Main and its children in the same transaction.atomic context, but it seems Django doesn't have that kind of signal integration. -
Assertion failure on django project
I am new to python. I have created a Django project and I am running it locally. My python project keeps runs fine until I run a function from my main.py file. The function runs fine but then python crashes: Assertion failed: (NSViewIsCurrentlyBuildingLayerTreeForDisplay() != currentlyBuildingLayerTree), function NSViewSetCurrentlyBuildingLayerTreeForDisplay, file /AppleInternal/BuildRoot/Library/Caches/com.apple.xbs/Sources/AppKit/AppKit-1894.50.103/AppKit.subproj/NSView.m, line 13568. However I am unsure why this error is appearing. Anyone have experience in this type of error? -
Django: How to reduce size and increase cohesion of views
As my project is becoming bigger and bigger, I am starting to get very large CBVs because they are required to handle a lot of actions especially live responses through AJAX (More single page application style). For example I have class ScheduledBooking. It does everything from showing timelines of bookings, booking appointments and viewing/editing other appointments in one page. I utilise a variety of model managers for complex filtering/aggregation but not sure if it's Pythonic to extend it's role of these managers to handling booking actions such as allocating bookings, checking availability of bookings, broadcasting bookings (Even if they use other models)? To reduce size and cohesion of the view although the model manager then will just take on the workload affecting it's own level of cohesion. Or is there a better way/alternative for this? Another problem is the Live Responses from ajax. I use a large amount due to a single page application style although the action handling clogs up a lot of the view. I was wondering if there is an alternative place or way this can be handled? class ScheduledBooking(TemplateView, BetterFormsChoiceValidationMixin, SessionHandlerMixin, BookingMixin, AJAXFormSerialiserMixin): template_name = 'emissions_dashboard/booking_scheduled.html' def get_context_data(self): [... 20 lines..] return args def get(self, request, … -
How to add pagination to search view in django
could you please support adding pagination to the below search function based view, here is my code def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', weight='A') + \ SearchVector('body', weight='B') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, rank=SearchRank(search_vector, search_query) ).filter(rank__gte=0.1).order_by('-rank') return render(request, 'blog/post/search.html', {'form': form, 'query': query, 'results': results})