Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a class attribute to a queryset field on ModelForm
So I'm trying to add a class attribute to this field on my ModelForm to allow for Bootstrap styling: category = forms.ModelChoiceField(queryset=Category.objects.all()) I tried this: category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) and got this error: TypeError: __init__() missing 1 required positional argument: 'queryset' My complete ModelForm: class NewListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "start_price", "image", "category"] title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) start_price = forms.DecimalField(label='Starting Bid Price (£)', widget=forms.NumberInput(attrs={'class':'form-control'})) image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off', 'class':'form-control'})) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) (I was going to do the fields = [] labels={} widgets={} format but I couldn't work out how to do that with a queryset field) -
How to add new values to Many2Many field Django
I'm currently working on a small Django project and I'm having an issue setting a many2many field's value. in my models I have something like : class Operation(models.Model): day = models.DateField() realized_by = models.ManyToManyField(User, related_name="consumer", blank = True) ... in my views.py I want to check: if there is an Operation instance that happened today, then add request.user to the relized_by users list else, create an Operation instance and make request.user the first element of realized_by users list Thank you for your answers in advance. -
Why am I getting a NOT NULL constraint failed when submitting my django form?
I am trying to add comments to my post model in django but when I try to submit a form it throws a NOT NULL constraint failed error because it cannot find a post even though it is being assigned in the view when saving the form. here are my models: class Post(models.Model): title = models.TextField('Title', max_length=300) slug = models.SlugField('Link') created_on = models.DateTimeField('Creation date', auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField('Content', max_length=2000, default='!') class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comment_author') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) then this is my form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['user', 'body'] if I add the 'post' field to fields it displays it as a dropdown and adds the comment to the correct post even if the dropdown option points it to a different one but I don't want it to display the 'post' field in the form at all and this is the view: def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.all() new_comment = None … -
How to get Django model id in views.py
I know Django automatically create a unique id for every model created. For example like this fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.EmailField(max_length=50)), ('language', models.CharField(choices=[('ur-PK', 'Urdu'), ('en-US', 'English')], max_length=15)), ], But I want to get this id in views.py file. How can I do this? I am using django model forms to enter data -
Unit tests for OrderingFilter DRF
I have a model: class Trade(models.Model): name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField('Active', default=True) is_deleted = models.BooleanField('Deleted', default=False) and views.py class TradeViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = TradeSerializer filter_backends = [ DjangoFilterBackend, CaseInsensitiveOrderingFilter, SearchFilter ] filter CaseInsensitiveOrderingFilter class CaseInsensitiveOrderingFilter(OrderingFilter): """ Custom filter to order case insensitive fields as CharField and TextField. To define filter it's needed to add char or text fields to list: ordering_case_insensitive_fields = ["field"] """ def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ()) if ordering: new_ordering = [] for field in ordering: if field.lstrip('-') in insensitive_ordering: if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) else: new_ordering.append(field) return queryset.order_by(*new_ordering) return queryset And simple serializer class TradeSerializer(serializers.ModelSerializer): class Meta: model = models.Trade fields = ( 'id', 'name', 'is_active', 'is_deleted', ) read_only_fields = ('is_deleted', 'id') my tests.py class TradeAPITest(BaseAPITestCaseSetup): data = { 'name': 'Trade Name 012000', 'is_active': True, } def setUp(self): super().setUp() self.trade = Trade.objects.create(**self.data) factories.TradeFactory.create_batch(10) self.test_data = { 'name': 'Trade Name 2', 'is_active': True, } def test_ordering_by_name_ascending(self): url = reverse('trades-list') + '?ordering=name' response = self.client.get(url) response_results = response.json().get('results') expected_result = sorted(response_results, key=lambda i: i['name'].lower()) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response_results, expected_result) def test_ordering_by_name_descending(self): url = reverse('trades-list') + '?ordering=-name' response = self.client.get(url) response_results = response.json().get('results') expected_result … -
Django - Email confirmation - recommendation on what service to use
I want to configure email responses for my Django app (registration, password reset, email confirmation etc) I did filled setting.py with my gmail account credentials while developing, but I don't want get banned if I will use this email after app deployment on server. May you please recommend any service that offers email address for automatic letters? EMAIL_HOST_USER = '' EMAIL_HOST = '' EMAIL_PORT = EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '' -
Django don't refresh site when form is invalid
I am currently developing a website for which I use a lot of modals with forms in them. The thing is, every time I enter invalid information in a form field and press the submit button, the modal just closes and there is no indication that the form was invalid. I already know that there is the possibility of making an ajax request which sends the form data to another view which then responds with a JSONResponse that contains errors which can then be displayed. That would work but by doing that I would lose all benefits of django forms. Because I have to submit the form data as JSON, I cant use functions like form.is_valid. So my question is: Is there a way to not refresh the site when a invalid form is submitted and displaying errors without having to send the data via JSON? -
How to Bind form action in Python Variable?
i am Sending html form via email using Django.When user submits Form i want to call view function Written in my views.py file.Here is my Code. subject,from_email,to = 'Varification link', 'kishan@lucsoninfotech.com',''+userdata['user_email']+'' text_content = 'Please Varify your email here' html_content = '<form method="POST" action=""><input type="text" name="username"><input type="submit" name="varify" value="varify"></form>' #Here is the issue msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content,"text/html") msg.send() I am Using above code for sending email.You can see here Form action is blank. i Want to give form action here.so that i Can call View Function . here is my Views.py def varifyemail(request): return HttpResponse('hello') i Want To call 'varifyemail' function from form action.I dont Know how to do that.I will be thankful if anyone can help me. -
Django invitation
I want people who have the correct invite code to access the signup form.So, whenever a user goes to a signup page, they are first redirected to Invite Code Page where the Invite Code form is displayed, once the user enters the correct Invite Code, the user is promoted back to the SignUp Page. I have made Invite Code Model to store the invite codes.But how can I implement the above functionality in django? -
field.value_to_string returns integer for ForeignKey django
I have a models A, B. class A(models.Model): a_field = CharField(max_length=100, verbose_name='alpha') b = ForeignKey('B', verbose_name='beta') ..... z = CharField(max_length=10, verbose_name='zeta') def get_fields_pair(self): return [(field.verbose_name, field.value_to_string(self)) for field in A._meta.fields] class B(models.Model): name = CharField(max_length=100) In template I want to display all pairs of verbose_name field value. I tried like below in views.py @login_required def myview(request, arg): a = get_object_or_404(A, a_field=arg) ... return render(request, 'mypage.html', {'a':a}) and template below: <table> <tbody> {% for k,v in a.get_fields_pair %} <tr><th>{{ k }}</th><td>{{ v }}</td></tr> {% endfor %} </tbody> </table> {% endfor %} However I see integer for b field value, even though when I put a.b in template it returns string, and I have no clue as to why. Could someone shed some hints on it? Thanks in advance. -
how to filter models on django-admin
I have two models: class Contrato(models.Model): active= models.BooleanField(default=False, verbose_name="Activo?") ..... def __str__(self,): return str(self.id) + '- ' + str(self.forcenedor) class Fatura(models.Model): contrato = models.ForeignKey(Contrato, on_delete=models.CASCADE,verbose_name="Contrato") designação = models. CharField(verbose_name="Designação",max_length=30) .............. def __str__(self,): return str(self.id) When I'm adding a new "Fatura" in my django-admin , i want to only show the "Contrato" that is true on "active" This type of filter , do i need to do in my admin file or i can do here directly on my models files? and how can i do it ? -
How to secure sensitive informations in settings.py
I have some sensitive information about MySql, celery, and redis in my settings.py. I read that its better to keep them in an .env file with python-dotenv or keep them in the linux's environment variables. But I am confused in this point. Even if they are in a separate file like .env or in environment variables they are still plain text. Is there way to keep them encrypted in a file or environment variable and make django possible to read them ? I don't want them to be plain text in somewhere. -
module 'qrcode' has no attribute 'make'
While integrating python library qrcode==6.1 with django==3.1.2. I have been trying to generate a qrcode which will contain the URL links for my other websites. Models.py from django.db import models import qrcode from io import BytesIO from django.core.files import File from PIL import Image, ImageDraw # Create your models here. class Website(models.Model): name = models.CharField(max_length=200) qr_code = models.ImageField(upload_to='qr_codes', blank=True) def __str__(self): return str(self.name) def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.name) canvas = Image.new('RGB', (290,290), 'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = f'qr_code_{self.name}.png' buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) But It always display an error saying that module 'qrcode' doesnot contain any attribute named 'make()'. I want to know how to resolve this? -
Django AWS Code Deploy - Deployment Failed
I am deploying Django app in AWS code deploy, which is connecting to RDS Postgres DB. It stuck into start_server event and i get below logs only. System check identified 5 issues (0 silenced). I googled it and find some DB related issue , but all the DB security and hosts are fine. Anyone can suggest any comments.. please -
Django - prepare_database_save() missing 1 required positional argument: 'field' save()
It's my first question here, but i will try my best do give you all details. I need to create a watch list for some page, the user should be able to "add" item to watchlist. ERROR Exception Type: TypeError Exception Value: prepare_database_save() missing 1 required positional argument: 'field' I have no idea why, can you tell me what does 'field' means, I don t even have that name of field in my code. And I am unable to save object to my db. And Also C:\auctions\views.py, line 46, in watchlist_add watchlist.save() Models class WatchList(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user") auctions = models.ManyToManyField(Auction, related_name="auctions", blank=True) def __str__(self): return f"{self.user}'s watchlist'" My URLs urlpatterns = [ path("", views.index, name="index"), path("watchList/<int:auction_id>", views.watchlist_add, name="watchlist_add"), ] and Views.py def getLastPk(obj): if(obj.objects.first() is None): return 1 else: get_pk = obj.objects.order_by('-pk')[0] last_pk = get_pk.pk +1 return last_pk def watchlist_add(request, auction_id): auction_to_save = Auction.objects.get(pk=auction_id) watchlist = WatchList(getLastPk(WatchList),User) watchlist.save() watchlist.auctions.add(auction_to_save) watchlist.save() return render(request, "auctions/watchlist.html",{ "watch_list" : watchlist.auctions.all(), }) In html i call this function by: {% if user.is_authenticated %} <a href="{% url 'watchlist_add' listing.id %}">Add to Watch List</a> {% endif %} Thank you for any help :) -
why django rest framework wants auth token for every request
I just started using django rest framework. I tested a single view function and it worked. @api_view(['GET', ]) def test_api(request): if request.method == 'GET': data = {} data['response'] = 'Test!' return Response(data=data) after that I tested registration view and in it worked too. @api_view(['POST', ]) def doctor_registration_view(request): if request.method == 'POST': serializer = DoctorRegistrationSerializer(data=request.data) data = {} if serializer.is_valid(): doctor = serializer.save() data['response'] = 'successfully registered.' data['email'] = doctor.user.email data['first_name'] = doctor.user.first_name data['last_name'] = doctor.user.last_name data['phone_number'] = doctor.user.phone_number data['social_id'] = doctor.user.social_id data['mc_code'] = doctor.mc_code token = Token.objects.get(user=doctor.user).key data['token'] = token else: data = serializer.errors return Response(data) class RegistrationSerializer(serializers.ModelSerializer): password2 = serializers.CharField(style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = ['email', 'first_name', 'last_name', 'phone_number', 'social_id', 'password', 'password2'] extra_kwargs = { 'password': {'write_only': True} } def save(self): user = User( email=self.validated_data['email'], first_name = self.validated_data['first_name'], last_name=self.validated_data['last_name'], phone_number=self.validated_data['phone_number'], social_id=self.validated_data['social_id'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': 'Passwords do not match.'}) user.set_password(password) user.save() return user after this I tested token authenication for logging in with obtain_auth_token view urlpatterns = [ path('test/', test_api, name='test-api'), path('register', registration_view, name='register'), path('login', obtain_auth_token, name='login'), ] Now when I request for test_api it says {"detail": "Authentication credentials were not provided."} While I did not … -
Integrate django filer in django tinymce image selector
I'm trying to integrate django filer in django tinymce image selector but kinda lost. I've implemented this with django ckeditor but I like Tinymce better. My tinymce config now in settings.py file is below - TINYMCE_DEFAULT_CONFIG = { 'theme': 'silver', 'height': 700, 'width': '100%', 'menubar': True, 'plugins': 'advlist,autolink,lists,link,image,charmap,print,preview,anchor,' 'searchreplace,visualblocks,code,fullscreen,insertdatetime,media,' 'table,paste,code,help,wordcount', 'toolbar': 'undo redo | formatselect | bold italic backcolor | ' 'alignleft aligncenter alignright alignjustify | ' 'bullist numlist outdent indent | removeformat | link image | help ', 'image_title': True, 'automatic_uploads': True, 'file_picker_types': 'image', 'file_picker_callback': "function (cb, value, meta) {" "var input = document.createElement('input');" "input.setAttribute('type', 'file');" "input.setAttribute('accept', 'image/*');" "input.onchange = function(){" "var file = this.files[0];" "var reader = new FileReader();" "reader.onload=function(){" "var id = 'blobid' + (new Date()).getTime();" "var blobCache = tinymce.activeEditor.editorUpload.blobCache;" "var base64 = reader.result.split(',')[1];" "var blobInfo = blobCache.create(id, file, base64);" "blobCache.add(blobInfo);" "cb(blobInfo.blobUri(), { title: file.name });" "};" "reader.readAsDataURL(file);};" "input.click();" "}" } as you can see, right now it pops up the image chooser and save the image as blob file in database table by file picker callback. Can anybody help me build a callback function to pop up django filer and show the selected image? Thanks in advance! BTW, I'm using all latest versions. Django v3.1 -
Django rest framework sorting in ascending and descending order
This is my view code class BlogListSerializerView(generics.ListAPIView): model = Blog serializer_class = BlogSerializer pagination_class = CustomPagination for sorting the client side request comes with two parameters, 'sorters[0][field]' and 'sorters[0][dir]'. I could add the first parameter in settings as follows REST_FRAMEWORK = { 'ORDERING_PARAM': 'sorters[0][field]' } and I have added ordering filter and ordering filter as follows to the view filter_backends = [filters.OrderingFilter] ordering_fields = ['category'] ordering = ['-id'] Now it sorts the table but only in one direction, how can I sort it in ascending and descending order, any help will be appreciated. -
I want to covert a custom Django view to an Django-Rest_framework Endpoint
I am new to Django Rest framework, I would like to convert my Payment view in Django which uses an external endpoint(flutterwave endpoint) to an endpoint. I have gone through the official Django Rest Framework documentation, but most of the example there uses models inclusive to make list, detail, delete and update endpoint. I would be glad if I can get a solution to my problem. P.S: I have removed my secret key Views.py from django.shortcuts import render import requests # Create your views here. # PAYSTACK VERIFICATION def verify_paystack_payment(request): url = "https://api.paystack.co/transaction/verify/262762380" payload = { "email": "myemail@yahoo.com", "amount": "10000", "currency": "NGN", "reference": "262762380", "metadata": { "custom_fields": [ { "display_name": "Mobile Number", "variable_name": "mobile_number", "value": "+2348012345678" } ] } } files = {} # The Bearer can either be an account or sub-account, but the default is account headers = { 'Authorization': 'Bearer {{SECRET_KEY}}', 'Content-Type': 'application/json' } response = requests.request("GET", url, headers=headers, data= payload, files=files) print(response.text.encode('utf8')) return render(request, "transaction/pay.html") -
How to overcome the resolve the error "Please verify that the package.json has a valid "main" entry " while trying to login to heroku on Windows
I am having trouble trying to deploy my Django app to Heroku. I am using visual studio code IDE on Windows 10. I have installed Heroku CLI but seems it's not pointing to the Heroku PATH or maybe something now set right. I am unable to login. All my search results are suggesting solutions around Node JS yet am not using Node.js.Here is the error message. -
AttributeError: 'NoneType' object has no attribute 'split' in django
I have created nested comment system using django-mptt.(Addding comment,reply to a certain comment,deleting a comment) these functionalities are working fine.But when I am trying to edit particular comment,after editing comment it is not reloading to detail page.In console it showing "AttributeError: 'NoneType' object has no attribute 'split' ". During this error another error is occuring -> TypeError: 'NoneType' object is not subscriptable.Here is my code: models.py: class Comment(MPTTModel): video = models.ForeignKey(Video, on_delete=models.CASCADE, related_name = 'comments') parent = TreeForeignKey('self',on_delete=models.SET_NULL, null=True, blank=True, related_name='children') reply_to = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='replayers') user = models.ForeignKey(User, on_delete= models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) class MPTTMeta: order_insertion_by = ['created'] def __str__(self): return f'{self.content[:20]} by {self.user}' views.py: def edit_comment(request, video_id, comment_id): video = get_object_or_404 (Video, id=video_id) comment = Comment.objects.get(id=comment_id) print(comment) if request.method == 'POST': edit_form = CommentUpdateForm(request.POST,instance=comment) print(edit_form) if edit_form.is_valid(): edit_form.save() messages.success(request, f'Your comment has been updated!') return HttpResponse("") else: return HttpResponse( "The content of the form is incorrect, please fill in again.") else: edit_form = CommentUpdateForm(instance=comment) print(edit_form) context = { 'edit_form': edit_form, 'video_id' : video_id, 'comment_id': comment_id, } return render(request,'comment/edit_comment.html',context=context) main urls.py: urlpatterns = [ path('comment/',include('comment.urls')), ] comment urls.py: from django.urls import path from comment import views app_name = 'comment' urlpatterns = … -
Django Translation Framework and formatted string literals
In the Django Documentation regarding the translation framework, all examples make use of the old style string interpolation: from django.utils.translation import gettext as _ my_string = _('This month has the name %(month)s.') % {'month': get_current_month_name()} Is it also possible to use the newer syntax like f-strings and str.format()-syntax with djangos gettext()? -
How to add a logo to the site index bar using django
Can anyone help me on how to add a logo to the index bar in Django-admin site? -
I am try to implement test series but stuck on add and updating question option
option is depend on question type{Single choice,Multiple choice and file or text options} I have used class based for create question Createview and update question by UpdateView. I Can create question successfully but my data is not render in formsets.Please give you suggestion so i can fixed it. class Questions(models.Model): ques_type = ( ('SCQ', 'Single choice questions'), ('MCQ', 'Multiple choice questions'), ('DQ', 'Descriptive'), ) title = models.TextField(_("Question Title"),null=False,blank=False) file = models.FileField( _("Image / Video"), upload_to='question/file/%Y/%m/%d', null=True, blank=True, help_text='Please upload single video [max 10 mb/ mp4, m4a, m4v, mov]') difficulty_level = models.ForeignKey("DifficultyManager.Difficulty", verbose_name=_( "Difficulty Level"), on_delete=models.SET_NULL, null=True) topics = models.ForeignKey("TopicManager.Topic", verbose_name=_( "Topic"), on_delete=models.SET_NULL, null=True) ques_type = models.CharField( _("Question Type"), max_length=4, choices=ques_type) is_delete = models.BooleanField(_("Delete"), default=False) created_by = models.ForeignKey(User, related_name="questions", blank=True, null=True, on_delete=models.SET_NULL) status = models.BooleanField(_("Status")) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) objects = QuestionsManager() filetype = models.BooleanField(_("Video"), help_text='if video available',default=False) imagetype = models.BooleanField( _("Image"), help_text='if image available', default=False) def __str__(self): return self.title class QuestionOption(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions")) option = models.CharField(_("Option"), max_length=255) is_right = models.BooleanField(_("Right"), default=False) create_date = models.DateTimeField( _("Created timestamp"), auto_now_add=True) update_date = models.DateTimeField( _("Last update timestamp"), auto_now=True) def __str__(self): return self.question.title class QuestionFile(models.Model): question = models.ForeignKey( "Questions", on_delete=models.CASCADE, verbose_name=_("questions"), null=True) … -
What do I need to do to a function in views.py works?
I'm working on a API and I need to create a function to don't allow the same post format in less than 10 minutes, but i'm just trying to print something in the terminal if the user use the "GET" request method, but it's not working. urls.py: from django.urls import include, path from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(r'products',views.ProductsViewSet) router.register(r'product-images',views.ProductImagesViewSet) #router.register(r'^products/', views.testIt, basename="TestIt") urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('products/', views.testIt, name = "testIt"), ] views.py: from rest_framework import viewsets from .serializers import ProductsSerializers from .serializers import ProductImagesSerializers from .models import Products from .models import ProductImages from rest_framework import status from rest_framework.throttling import UserRateThrottle from rest_framework.views import APIView from rest_framework.response import Response from rest_framework.decorators import api_view from django.http import JsonResponse class ProductsViewSet(viewsets.ModelViewSet, APIView): queryset = Products.objects.all().order_by('id') serializer_class = ProductsSerializers def testIt(self, request, pk=None): if request.method == 'GET': print('Testando') return Response('Teste!', status = status.HTTP_400_NOT_FOUND) class ProductImagesViewSet(viewsets.ModelViewSet): queryset = ProductImages.objects.all().order_by('id') serializer_class = ProductImagesSerializers I still see the data but it's not returning any message or printing anything when I use the get method. Thank you in advance!!