Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I use a variable defined in a Django method in a Django class. Both are defined in views.py
I have the following: def color(request): color = '#000000' Class Chart(otherclass): def methodchart(self): return ["one", color, "three"] So I want methodchart to return ["one", '#000000', "three"]. How do I call the variable color inside Chart Class? Is it possible? -
Could not deserialize key when sending push notification using django web push
Getting this error: ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=218542222, lib=13, reason=142, reason_text=b'error:0D06B08E:asn1 encoding routines:asn1_d2i_read_bio:not enough data')]) I am trying to use django-webpush to accept a subscription from my service worker and send a push notification to a specific user. This is what I added to my views in Django: subscription = json.loads('{"endpoint" : "https://fcm.googleapis.com/fcm/send/esP-gJr0HoE:APA91bF7swMPi7BGmzy9acg1k3lj8HAkU2BJNsDSXIWKWRdP3Dvbp5UCbfPioI78q7u9bwotaJ7Vo_6naCojdOxnbgFKsWUv7Srd5MlCFVhpBdhkFAasYRAtrh5FnbD1KF5a_xKKHPpN", "expirationTime" : null, "keys" : {"p256dh":"BNUFqA0mrtLFLHUnAhLfM9KGA63YfhrU913mOeuR3O8vNVmm65iSFJ25TIHoyUKPEAUQxQhEPaerjqCX_N9adgQ","auth":"YSorvfN6ZCW-QaJ0GJnK8g"}}') payload = {"head": "Welcome!", "body": "Hello World"} webpush_settings = getattr(settings, 'WEBPUSH_SETTINGS', {}) vapid_private_key = webpush_settings.get('VAPID_PRIVATE_KEY') vapid_admin_email = webpush_settings.get('VAPID_ADMIN_EMAIL') vapid_data = { 'vapid_private_key': vapid_private_key, 'vapid_claims': {"sub": "mailto:{}".format(vapid_admin_email)} } webpush(subscription_info=subscription, data=payload, ttl=0, **vapid_data) -
how to add two ForeignKey(User) in django model
I have a Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) and I recently added the ability for the leader to pass over their leadership to a different User. This is fine, but then I noticed that I had a created by {{group.leader} at the top of my GroupDetail template, and I figured it would be better to have a founder and a leader that way people can see which User founded the Group vs. who is currently leading it. Now what I'm struggling with is how to implement this. I assume the founder will be correlated with one User and also with the first leader of the Group. At one point both fields will be the same User. But how do I have two ForeignKeys in the same model? Or is there a better way to go about this. As of now the logic to switch leaders is as such: <form method="POST"> {% csrf_token %} {{form.as_p}} <select id="newLeaderSelect"> {% for member in group.joined.all %} {% if member != group.leader%} <option id='newLeader' value={{ member.id }}>{{ member }}</option> {% endif %} {% endfor %} </select> <button>CHANGE LEADER</button> {{form.errors}} </form> <script> let … -
Django rearrange objects inside querySet by index
In my application i have table called "Task". In this table there is a field called priority with a restricted choice of ("High", "Medium", "Low"). I have ordered these by priority which have an order of: High, Low, Medium when i would like the order to be High, Medium, Low. How could i swap Low and Medium inside the querySet around? views.py: tasks = Tasks.objects.values("priority").annotate(count=Count("priority")) output: <QuerySet [{'priority': 'High', 'count': 3}, {'priority': 'Low', 'count': 3}, {'priority': 'Medium', 'count': 3}]> desired output: <QuerySet [{'priority': 'High', 'count': 3}, {'priority': 'Medium', 'count': 3}, {'priority': 'Low', 'count': 3}]> -
Django dynamic change of models filters
I need to create a filter that offers the following filtering categories building on previous. For example, if I chose option[0][1] in first_dispute, then I would continue filtration only by option[1][1] and option[2][1] in second1_dispute. For example, if I chose option[1][1] or option[2][1] in proceeding, I can't choose any of options in second2_dispute. models.py class FirstDispute(models.Model): CHOICES=( ('1', '01 О заключении, изменении и расторжении договоров'), ('2', '02 О недействительности сделок'), ('3', '03 О неисполнении или ненадлежащем исполнении обязательств по договорам'), ... ) value = models.CharField("Категория спора (подкатегория 1):", max_length=122, choices=CHOICES, default=CHOICES[0][1]) def __str__(self): return self.value class Card(models.Model): PROCEEDING_CHOICES =( ('Административное', 'Административное'), ('Интеллектуальное', 'Интеллектуальное'), ('Экономическое', 'Экономическое'), ) SECOND1_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "01 О заключении, изменении и расторжении договоров"'), ('01.01 о понуждении к заключению договора', '01.01 о понуждении к заключению договора'), ... ) SECOND2_DISPUTE = ( ('None', 'Выбирается при значения "Подкатегория 1" - "02 О недействительности сделок"'), ('02.01 о признании сделки недействительной', '02.01 о признании сделки недействительной'), ... ) THIRD_DISPUTE = ( ('None', 'Выбирается при значениях "Подкатегория 1" - "02 О недействительности сделок" и "Подкатегория 2" - "02.03 о признании торгов недействительными"'), ('02.03.01 о признании незаконными решения и (или) действия (бездействия) организации либо членов комиссии', '02.03.01 … -
How can I see the display of a specific user?
You can see the user's home by pressing the user's photo like twitter or instagram. I want to do this with django, how do I change the url.py User urls.py urlpatterns = [ path('home/', HomeView.as_view(), name='home'), path('edit_profile/', ProfileEditView.as_view(), name='edit_profile'), # 追加 path('commnet_list_movie/', Comment_List_Movie.as_view(), name = 'comment_list_movie'), path('commnet_list_tv/', Comment_List_TV.as_view(), name = 'comment_list_tv'), path('password_change/', PasswordChange.as_view(), name='password_change'), path('password_change/done/', PasswordChangeDone.as_view(), name='password_change_done'), path('password_reset/', PasswordReset.as_view(), name='password_reset'), path('password_reset/done/', PasswordResetDone.as_view(), name='password_reset_done'), path('password_reset/confirm/<uidb64>/<token>/', PasswordResetConfirm.as_view(), name='password_reset_confirm'), path('password_reset/complete/', PasswordResetComplete.as_view(), name='password_reset_complete'), ] -
How to add custom action to Django Admin Save button
I'm trying to add a custom action to the save button in the admin interface. Basically, when the user changes the form and hits the save button, I don't want to change the default save action but I want to add custom functionality. Like; getting some or all data from the form and calling an endpoint or calling an other function. User saves -> Default save action happens -> *Custom action happens I'm aware that I can overwrite save_model of ModelAdmin with: class MyAdminView(admin.ModelAdmin): def save_model(self, request, obj, form, change): super().save_model(request, obj, form, change) # add custom feature <-- but I'm not really sure if this is the appropriate way to do this -
Running Django on Google Colab doesn't work
I tried to run a Django server in Colab as described in this question on stackoverflow. I did set ALLOWED_HOSTS = ['colab.research.google.com'] in settings.py. But when I run the server I always get "Error 403 (Forbidden)!!" when I open the link. Is it not possible anymore to run Django from Colab? -
How to get the image size in python as Megabyte or Kilobyte
I want to the image size of an image in megabyte or kilobyte. This type of question has been asked before and a solution wasn't really provided. NOTE:i'm not concerned with the image width and height, just the file size in megabyte or kilobytes because i'm working on the image for user input validation so its on the fly. -
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)