Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am receiving recurssionError at /register/ (django rest framework)
I have create my register endpoint with DRF, so far it has been working well but since I am trying it again it is sending error. serializers.py class RegisterSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True,max_length=68,min_length=8,error_messages= {"min_length":f"Password must be longer than {MIN_LENGTH}characters"}, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True,max_length=68,min_length=8,error_messages={"min_length":f"Password must be longer than {MIN_LENGTH}characters"}, required=True) class Meta: model = User fields = ('username','phone','password','password2') extra_kwargs = { 'password': {'write_only': True}, 'password2': {'write_only': True} } def validate(self,data): if data["password"]!=data["password2"]: raise serializers.ValidationError("password does not match!") return data def create(self,validated_data): user = User.objects.create( phone=self.validated_data['phone'], username=self.validated_data['username'], ) user.set_password(validated_data['password']) user.save() return user views.py class RegisterViewSet(viewsets.ModelViewSet): http_method_names = ['post'] '''This endpoint is made to register all user with phone number and password''' queryset = User.objects.all() serializer_class = RegisterSerializer ``` -
How to restrict access to a media-File in Django?
I've an application where my users create a video-file (mp4) which is saved as a Filefield in the model. In my view I add the model to the context of a TemplateView class. In my HTML I use the video tag and use the src to add the url and to display the video. I restrict the view to the owner only. This all works fine. But now anyone can see the videos if they get the url. How can I make restrict access the the files ? -
I have created custom user using abstract user but when I am trying login its not getting log in and if user get logged in its says anonymous user
If I am not saving the password with a hash, it gets logged in. And logging in is not possible if the password is saved with a hash. -
Why i don't have have redirect in Django?
I am not able to redirect in Django. My views.py def blogpost(request, slug): blog_post = Post.objects.filter(slug=slug).first() comments = PostComment.objects.filter(post=blog_post) context = {'blog_post':blog_post, 'comments':comments, 'user': request.user} return render(request, 'blog/blogpost.html', context) def post_comment(request): if request.method == 'POST': comment = request.POST.get('comment') user = request.user post_Id = request.POST.get('post_Id') post = Post.objects.get(post_id=post_Id) comment = BlogComment(comment=comment, user=user, post=post) comment.save() messages.success(request, "Your comment has been posted successfully") return redirect(f'/blog/{post.slug}') I want to redirect (f'/blog/{post.slug}') My urls.py urlpatterns = [ path('', views.index, name='Blog_home'), path('<str:slug>', views.blogpost, name='blogpost'), path('postcomment', views.post_comment, name='post_comment'), ] But I redirect at /blog/postcomment. HTML <form action="/blog/postcomment" method="post">{% csrf_token %} <input type="text" name="comment" placeholder="Enter Comment here"> <input type="hidden" name="post_id" value="{{post.post_id}}"> <input type="submit" name="submit"> </form> Please any Devloper help me to solve this question. -
how to build query with several manyTomany relationships - Django
I really don't understand all the ways to build the right query. I have the following models in the code i'm working on. I can't change models. models/FollowUp: class FollowUp(BaseModel): name = models.CharField(max_length=256) questions = models.ManyToManyField(Question, blank=True, ) models/Survey: class Survey(BaseModel): name = models.CharField(max_length=256) followup = models.ManyToManyField( FollowUp, blank=True, help_text='questionnaires') user = models.ManyToManyField(User, blank=True, through='SurveyStatus') models/SurveyStatus: class SurveyStatus(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) survey = models.ForeignKey(Survey, on_delete=models.CASCADE) survey_status = models.CharField(max_length=10, blank=True, null=True, choices=STATUS_SURVEY_CHOICES, ) models/UserSurvey: class UserSurvey(BaseModel): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.DO_NOTHING) followups = models.ManyToManyField(FollowUp, blank=True) surveys = models.ManyToManyField(Survey, blank=True) questions = models.ManyToManyField(Question, blank=True) @classmethod def create(cls, user_id): user = User.objects.filter(pk=user_id).first() cu_quest = cls(user=user) cu_quest.save() cu_quest._get_all_active_surveys cu_quest._get_all_followups() cu_quest._get_all_questions() return cu_quest def _get_all_questions(self): [[self.questions.add(ques) for ques in qstnr.questions.all()] for qstnr in self.followups.all()] return def _get_all_followups(self): queryset = FollowUp.objects.filter(survey__user=self.user).filter(survey__user__surveystatus_survey_status='active') # queryset = self._get_all_active_surveys() [self.followups.add(quest) for quest in queryset] return @property def _get_all_active_surveys(self): queryset = Survey.objects.filter(user=self.user, surveystatus__survey_status='active') [self.surveys.add(quest) for quest in queryset] return Now my questions: my view sends to the create of the UserSurvey model in order to create a questionary. I need to get all the questions of the followup of the surveys with a survey_status = 'active' for the user (the one who clicks on a button)... I tried several … -
NoReverseMatch error when trying to go to a template page
When an item is clicked on, it should take the user to a page where there is more information about the item. However, when I click on an item, I get the error: NoReverseMatch: Reverse for 'listing' with arguments '('', '')' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/(?P<name>[^/]+)/\\Z']. This line in my HTML template is highlighted on the error page: <a href="{% url 'listing' i.pk i.name %}"> but I do not know why. The i.pk and i.name are arguments for a views.py function that is called listing that returns a page (listing.html) that has more info about the item. The url should be in the format http://127.0.0.1:8000/ID/NAME_OF_ITEM where ID is the actual id of the item and the NAME_OF_ITEM is the actual name of the item. How do I fix this? index.html: {% for i in listings %} <div class="listing"> <div class="info-container"> <div class="top-info"> <div class="listing-title"> <a href="{% url 'listing' i.pk i.name %}"> <h4>{{ i.name }}</h4> </a> </div> <div class="listing-price"> <a href="{% url 'listing' i.pk i.name %}"> <strong>£{{ i.highest_bid }}</strong> </a> </div> </div> <div class="listing-description"> <a href="{% url 'listing' i.pk i.name %}"> <p>{{ i.description }}</p> </a> </div> </div> </div> {% endfor %} views.py: def listing(request, id, name): listing = Listing.objects.get(pk=id) return … -
how to Interactive messaging through short code?
so we have a payment service and i want after every payment confirmation message to the client, it has a message at the end for instance "send the word Pay to 12344 for more information" so i want the word pay to be an identity to return some menu to the client e.g Rate us support number etc and the circles continues -
Delete expired tokens from database (Django + JWT)
Currently I am using JWT (rest_framework_simplejwt) with Django Rest Framework. The database table containing tokens got bigger and bigger. Is there any way to delete all expired access tokens from the database? I mean all expired Outstanding_Tokens and Blacklisted_Tokens related to them. I tried running the following command from django shell but didn't work: from rest_framework_simplejwt.tokens import AccessToken AccessToken.objects.filter(expires__lt=datetime.now()).delete() ==> AttributeError: type object 'AccessToken' has no attribute 'objects' Thanks a lot for your help! -
DRF ImproperlyConfigured: Could not resolve URL for hyperlinked relationship
I've searched many similar questions here on stackoverflow and tried various things but nothing helped me to fix this issue. May be someone will notice mistake in my code which I can't see. So basically I have a ModelViewSet and at first I've used ModelSerializer and it worked just fine. Then I thought it would be convenient to add a url to my serializer and so I put HyperlinkedIdentityField in my serializer and I got this error. Then I tried to switch from ModelSerializer to Hyperlinked one and still this error occurs. Here's the code: Serializer from rest_framework.serializers import HyperlinkedModelSerializer, ModelSerializer, HyperlinkedIdentityField from .models import Product, ProductCategory, Brand class ProductSerializer(HyperlinkedModelSerializer): url = HyperlinkedIdentityField(view_name='products:product-detail', lookup_field='pk') class Meta: model = Product fields = ('id', 'url', 'name', 'category', 'brand', 'price', 'units_in_stock', 'units_on_order', 'reorder_point', 'discontinued') Viewset class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer permission_classes = [permissions.IsAuthenticatedOrReadOnly] Urls from django.urls import path, include from rest_framework.routers import DefaultRouter from products import views app_name = 'products' router = DefaultRouter() router.register(r'products', views.ProductViewSet, basename='products') router.register(r'categories', views.ProductCategoryViewSet, basename='categories') router.register(r'brands', views.BrandViewSet, basename='brands') urlpatterns = [ path('', include(router.urls)), ] Model class Product(models.Model): name = models.CharField(max_length=255) category = models.ForeignKey('ProductCategory', on_delete=models.DO_NOTHING) brand = models.ForeignKey('Brand', on_delete=models.DO_NOTHING, blank=True, null=True) price = models.FloatField() units_in_stock = models.IntegerField() … -
social blog Like button
Like button is not working. here is my code please check it gives error Cannot resolve keyword 'username' into field. Choices are: id, post_id, post_id_id, user_id, user_id_id view.py def like_post(request): user_id = request.user.username post_id = request.GET.get('post_id') post = Post.objects.get(id=post_id) like_filter = LikePost.objects.filter(post_id=post_id,username=user_id).first() if like_filter == None: new_like = LikePost.objects.create(post_id=post_id, username=user_id) new_like.save() post.no_of_likes = post.no_of_likes+1 post.save() return redirect('showpost.html') else: like_filter.delete() post.no_of_likes = post.no_of_likes-1 post.save() return redirect('showpost.html') model.py class LikePost(models.Model): post_id = models.ForeignKey(Post,on_delete=models.CASCADE, null=True) user_id = models.ForeignKey(User,on_delete=models.CASCADE, null=True) -
Looking for a help Authentication of Django and Angular
I am Beginner to python Django . Here I need to communicate with frontend guys who is using angular 12. I wrote a code for signup page and i want see the output through angular but how can I see the output? -
There was an issue deploying your app. View the build log for details
-----> Building on the Heroku-20 stack -----> Using buildpack: heroku/python -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure ! Push failed -
Django filter records by field from another table
I have a "to do list" website with three tables (TDLists, Tasks, Users) and I want to display all the to do lists for a specific user with all of the tasks that are linked to that specific list. I am having trouble filtering these items in my views.py file. I have been able to get my desired results using SQL but cannot translate this into django. models.py class Users(models.Model): username = models.CharField(max_length=20) email = models.CharField(max_length=40) password = models.CharField(max_length=16) user_id = models.AutoField(primary_key=True) class TDLists(models.Model): title = models.CharField(max_length=50) date_created = models.DateField(auto_now_add=True) completed = models.BooleanField(default=False) deadline_date = models.DateField(null=True) user_id = models.ForeignKey(Users, on_delete=models.CASCADE) list_id = models.AutoField(primary_key=True) class Tasks(models.Model): description = models.CharField(max_length=120) priority = models.CharField(choices=( ("High", "high"), ("Medium", "medium"), ("Low", "low"), ),max_length=10) list_id = models.ForeignKey(TDLists, on_delete=models.CASCADE) task_id = models.AutoField(primary_key=True) SQL code that works: SELECT myApp_tasks.* FROM myApp_tasks, myApp_tdlists, myApp_users WHERE myApp_tdlists.user_id_id = myApp_users.user_id AND myApp_tasks.list_id_id = myApp_tdlists.list_id AND myApp_users.user_id = 1 output: code tried in views.py user_id = 1 user = Users.objects.filter(user_id=user_id) lists = TDLists.objects.filter(user_id=user.get(user_id=user_id)) tasks = Tasks.objects.filter(list_id=lists.get(list_id=lists.list_id)) -
Is is possible to have a static folder or directory at the root in django?
I have a python script that uses some XML files that should be available directly at the root of my Django app ( migrating from a traditional website to Django ) but since files are stored in the static folder in Django is it possible to access it directly from my view file ou to make it available at the root? -
active data in django inlineformset_factory
I have a brand table that contains active and inactive record of brand. I have created bill using inlineformset_factory that contain brand. It display both active and inactive brands in formset. I want only active brands in form. -
Fail with assignment vars when reading csv file
I cant undesrtand how to repair it to work properly, if it is possible please help me def read_from_csv(f_name: Path | str, ) -> List[Book]: if type(f_name) is str: f_name = Path(f_name) data = [] with f_name.open() as f: reader = csv.reader(f, delimiter=";") for row in reader: id, title, description, author, slug = row id = int(id) book = Book(id, title, description, author, slug) data.append(book) return data print(read_from_csv("data/data.csv")) line 59, in read_from_csv id, title, description, author, slug = row ValueError: not enough values to unpack (expected 5, got 0) -
Unable to reflect DB migrations from django application to DB in docker container running postgres DB
I have tried to do makemigrations and then migrate changes that I have made in models.py, to be accurate, I have made changes in the field type of a table, from docker interactive environment but changes are not reflected in the database. Even if I delete a table from a database and again try to migrate, the table does not appear. Is there some best practice or methods that is need to done for DB migrations for django in a docker container. -
Build Django URL for export_selected_objects. Example function out of the official django documentation
I am trying to build an URL that matches the redirect out of this function: def export_selected_objects(modeladmin, request, queryset): selected = queryset.values_list('pk', flat=True) ct = ContentType.objects.get_for_model(queryset.model) return HttpResponseRedirect('/export/?ct=%s&ids=%s' % ( ct.pk, ','.join(str(pk) for pk in selected), )) That is what I have tried: from django.urls import path, re_path from . import views urlpatterns = [ re_path(r'^export/(?P<ct>[0-9]{2})/(?P<ids>[0-9]{4})/$', views.test), path('export/<int:ct><int:ids>/', views.test), path('export/<int:ct>/<int:ids>/', views.test), path('export/<ct><ids>/', views.test), ] But none of these match. Error Message Could someone give me a hint about what I'm missing here? Thanks a lot! Sebastian -
Adding a custom header 'FOO' to Django Rest Framework APIClient
For an application that uses SSO for login I have implemented a AuthBackend with Django Rest Framework. This custom AuthBackend class checks for the X-USERID present in the headers and based on that returns the user instance. I have added permission classes to the views for verifying the authenticated users. In order to add unit tests to the code the APIClient must enable us to add custom header like {'FOO': 'BAR'} The default class seems to be APIClient I have tried the following but none of them work: class AccountsTests(APITestCase): def test_user_is_authenticated(self): ... headers = {'USERID': 'john.doe', 'FOO': 'BAR' } self.client.get(url, headers) # Doesn't work self.client.get(url, **headers) # Doesn't work self.client.headers.update(headers) # Doesn't work ... -
Hy folks! Can anyone help me out how to remove text from pdf in python
I have tried to extract text using pdf miner but not able to remove the text from pdf -
Cannot assign "<built-in function cmp_to_key>": "Foo.content_type" must be a "ContentType" instance
I am using Django 4.0.6 I have a model like this: class AnonymousInteractionMonitor(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name='%(app_label)s_%(class)s_content_types', related_query_name='%(app_label)s_%(class)s_content_type') object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') interaction_type = models.PositiveSmallIntegerField(choices=Engagement.ENGAGEMENT_TYPES, null=False) visitor_ip = models.GenericIPAddressField(db_index=True) created_at = models.DateTimeField(auto_now_add=True) In one of my views, I have the following code: ct, object_id = self._get_content_info() ip_address = get_client_ip(request_object) # expensive function, call only when needed last_visit = AnonymousInteractionMonitor.objects.filter(visitor_ip=ip_address, content_type=ct, interaction_type=interaction_type, object_id=object_id).last() I am checking the type of the variable ct before filtering - and it is indeed, an instance of a ContentType - so why is the error: Cannot assign "": "AnonymousInteractionMonitor.content_type" must be a "ContentType" instance being raised? How do I fix this? -
Avoid redirection on model
I'm fairly new in django and im building a simple web with 2 date pickers that are then used as a variable to ping the DB and populate a charfield with the result of the query. So far I've managed to render nicely the page and when the user submits the request, the query is triggered nicely and the value is fetched. The problem comes that after that, the model expects a url to redirect to but instead i want to stay on the same page and populate the result of the query into a charfield. So far this is what I got (I erased sensitive data): from django.db import models from django.forms import ValidationError import psycopg2 from django.utils import timezone class Event(models.Model): location = models.CharField(max_length=30, choices=[("us","US"), ("global","Global")]) start = models.DateTimeField(default=timezone.now) end = models.DateTimeField(default=timezone.now) # This is the field I want to fill with the output of the query. result = models.CharField(max_length=20, default=0) # def get_absolute_url(self): # I have tried just comenting this but it throws and exception # return bytes(str(self.pk), encoding='utf-8') def _do_insert(self, manager, using, fields, returning_fields, raw): query = """ """ location_value = getattr(self, fields[0].name) start_date = getattr(self, fields[1].name) end_date = getattr(self, fields[2].name) if start_date >= end_date: # … -
How to add an object field in a Django model
I would like to have a field that works as an object for one of my models, but without needing to reference it using a ForeignKey. What I'm looking for is something the field pressure here: { "professional": "d83876a6-69eb-4946-a0f7-56fd39cbd6a8", "observations": "Update", "date": "2022-03-22T21:45:37Z", "pressure": { "systolic_pressure": 0, "diastolic_pressure": 0 } I have searched a lot, but haven't found how to add a field like that one, and how to configure the model/serializer/view to be able to create/read/update/delete it. -
I have a problemem. With int 23 to convert Ienumeabable
So the quastion is about hwo two collaplse the my value of 32 integer to the ineumabable system generic. What cind of operasion can I use to get quality good result of achieving hue saturaiton faction in my Java net sharp project? -
Epoch time and daylight savings in Python/Django
I'm using a BigIntegerField to save dates (Epoch time) in a Django application. We can create single classes or courses, but let me explain the later. When creating a course, we must select the the start and end dates,the days of the week on which the event will occur and at what time. For example, we can say that a course will be from 01/09/2022 to 01/12/2022, happening on Wednesdays and Fridays at 10am. The backend receives the days and schedule of the first week. To those initial timestamps, we add milliseconds in one week to create all of the course classes. The problem is that epoch time is not aware of daylight savings, and in the example I just gave, classes until to 29/10/2022 will be schedule to 10am, but classes after 30/09/2022 will be schedule to 9am. Is there any way to be aware of the user's timezone, to detect that they have daylight savings and adjust the timestamp accordingly?