Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to update/delete related model in the save() method of a model
I have two Django models: from django.db import models class Policy(models.Model): status = models.IntegerField() def save(self, *args, **kwargs): quote = self.documents.get(document_type=DocumentType.quote) if self.status = "X": quote.delete() elif self.status == "Y": new_quote_content = create_new_quote() quote.s3_file.save(quote.name, File(new_quote_content)) super().save(*args, *kwargs) class Document(models.Model): policy = models.ForeignKey( to=Policy, null=True, blank=True, on_delete=models.CASCADE, related_name="documents", ) s3_file = models.FileField( storage=S3Storage(aws_s3_bucket_name="policy-documents"), upload_to=get_document_s3_key, max_length=255, ) I want to delete/update the document when the policy status is updated and I've overriden the save() method in Policy to do it. However, neither the doc deletion nor the doc's FieldFile update works in the save() method. If I move them to outside the save() method, everything works. Does someone understand what's the issue here? -
Object of type ImageForm is not JSON serializable
I wanted to post image processing from views to celery, but it shows me a JSON-related problem "Object of type ImageForm is not JSON serializable" Here the code from models.py class ImageModel(models.Model): title = models.CharField(max_length=20, null=True) sec_title = models.CharField(max_length=20, null=True) img = models.ImageField(upload_to='upload_p/', blank=False) slug = models.SlugField(max_length=250, null=True) def delete(self, *args, **kwargs): self.img.delete() super().delete(*args, **kwargs) forms.py class ImageForm(forms.ModelForm): class Meta: model = ImageModel fields = ('title', 'img', 'sec_title') views.py def upload_image(request): if request.method == 'POST': form_w = ImageForm(request.POST, request.FILES) if form_w.is_valid(): water_mark.delay(form_w) else: form = ImageForm() return render(request, 'Luki/upload_img.html', { 'form': form, }) tasks.py @shared_task def water_mark(form_w): instance = form_w.save(commit=False) cd = form_w.cleaned_data['img'] if instance.img: im = Image.open(instance.img) width, height = im.size draw = ImageDraw.Draw(im) text = "TEST WATERMARK" font = ImageFont.truetype('arial.ttf', 36) textwidth, textheight = draw.textsize(text, font) # calculate the x,y coordinates of the text margin = 10 x = width - textwidth - margin y = height - textheight - margin draw.text((x, y), text, font=font) thumb_io = BytesIO() print('BYTES IO: ', thumb_io) im.save(thumb_io, im.format, quality=100) instance.img.save(str(cd), ContentFile(thumb_io.getvalue()), save=False) instance.save() return redirect('Luki:gallery') Of course, all the libraries are imported and the code from the views without celera is executed and it looks like this. This works so that the … -
Running sever but throwing an "Exception has occured" eccured. Django python
this server breaks when I enter my login details and this is where the system breaks. -
Unable to deploy Django app to heroku using heroku local
Novice here. Trying to deploy my Django app to Heroku and I get an Unable to connect from the Firefox browser (I tried Chrome as well with similar results). I'm having a lot of trouble troubleshooting where exactly the problem is? Heroku local? Gunicorn? Browser Firewall? Django Settings? What I have done. Added the django_heroku import to settings.py Tried to ensure My browser(Firefox) is not blocking pop-ups etc. Firefox -> settings-> Privacy and security -> permissions-> Uncheck Block pop-up windows Ensured my app works on with just gunicorn I run gunicorn project3.wsgi in my terminal (project3 is the directory for my wsgi file) which works I have the same command in my Procfile, uppercase 'P' (web: gunicorn project3.wsgi). However when I run the command 'heroku local' The browser opens up on clicking the link, but I get an error. Any assistance would be appreciated. I am running commands using windows WSL -
Server Response Time is Much Longer Than Expected
I have an Django application which runs on my localhost currently. Some of the pages take much longer time, so for debugging reasons I calculated the time spend in one of the class based views with this simple code: class DiscoverView(LoginRequiredMixin, ListView): model = MyModel template_name = "app1/discover.html" context_object_name = 'influencers' # not necessary, default is object_list def get_context_data(self, **kwargs): start_time = time.time() # ... # Some tasks which I tought they are the reasons of long response time # ... print(time.time() - start_time, "seconds took to complete...") return context After the experiments I saw that this view takes 0.01 seconds to complete, while the page is loading in nearly ~5 seconds. For further debugging I dig into Chrome Dev Toools. There in network tab 'Finish' time of the page is 5.86 seconds. I also runned Lighthouse test, which says that servers initial response time is ~2 seconds. I can't understand why this 0.01 seconds becomes 2 seconds, I also used django-debug-toolbar in order to inspect database query times, which are not that long. My application is also living on production (Heroku), the loading times are much worse there of course but I feel like I need to fix that … -
Django Postgres - violates foreign key constraint (deleting post with comments)
I just implemented a comment feature into my blog app. The issue I am facing is if I try to delete a blog post that has comments I get the postgres error If I understand this error correctly I cant delete the post because the comment is referencing the post id. To solve this issue I figured I would just add on_delete=models.CASCADE to the model. Unfortunately this did not resolve the issue. I was under the impression that with the CASCADE it would delete the entire model if the FK was deleted. the two models. class Post(models.Model): title = models.CharField(max_length=100) image = models.ImageField(default='default.jpg', upload_to='hero_car_image') aspiration = models.CharField(max_length=55, choices=ASPIRATION) content = RichTextUploadingField(blank=True, null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) manufacture = models.ForeignKey(Manufactures, on_delete=models.CASCADE) model = models.ForeignKey(Models, on_delete=models.CASCADE) class Comment(models.Model): comment = models.TextField() created_on = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey('Post', on_delete=models.CASCADE) -
Change the score value of all users in a single query to 100 (one hundred)
class CUser(User): score = models.IntegerField() Change the score value of all users in a single query to 100 (one hundred) -
django ContentType select model and instance
I have 3 models in my geometry app: Square_section, T_section, Double_T_section I want to create a model: beam with 2 fields one to select the model in my geometry app and another field to select an instance from a list of all instances of that specific model, will something like this work? : from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.db import models class beam (models.Model): slug = models.SlugField() content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) content_object = GenericForeignKey('content_type') def __str__(self): return self.slug -
Django Dictionary/Tuple iteration
I am working on a project for school, and am having a lot of trouble with Templates in Django. My code is below, the first block is Python in a function, bear in mind I removed a lot for easy viewing. amounts = [('None ',), ('1 1/2 oz',), ('1 oz',), ('1/2 oz',), ('1/2 ml ',), ('15 ml',), ('35 ml',), ('splash',), ('6 splashes',), ('10 dashes',), ('25 ml',), ('3 slices',)] data = { 'amounts': amounts, 'ingredients': ingredients, } amount1 = request.GET.get('amount1') print(amount1) return render(request, 'addcocktail.html', {'data': data}) This block is my HTML file: <select name="amount1" id="amount1"> {% for key, value in data.items %} {% if key == 'amounts' %} {% for amount in value %} <option value = {{amount}}> {{ amount.0 }}</option> {% endfor %} {% endif %} {% endfor %} </select> When select 1 oz on the website, amount1 is printed as: 1 which is the first half of the string in the tuple: '1 oz'. I was wondering if anyone knew what the problem here is. -
How can I add additional data to a Django DeleteView POST request?
I'm deleting an item from my template and need to add some extra data, which I tried to do by adding a hidden input field: <form action="{% url 'MyDeleteView' pk=object.id %}"method=POST> {% csrf_token %} <input type="hidden" value="some value"> ... </form> How can I access this hidden input value in MyDeleteView? I tried accessing it in my request.POST but it's not there. def delete(self, request, *args, **kwargs): print(request.POST) # No hidden input value Or is there another way? -
How to create specific view?
models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) students = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py class CreateStudent(LoginRequiredMixin, CreateView): # … def form_valid(self, form): self.object = form.save(commit=False) self.object.save() for student in form.cleaned_data['name']: connect = Connect() connect.student = self.object connect.course = Course.objects.get(name='math') connect.save() return super(ModelFormMixin, self).form_valid(form) How to create view , using this view user must be able to specify which instances of model Course are used for default relation when no relation to Course was chosen by the user. Using this view user must be able to select or unselect some instances of model Course as a default ones. By “default Course“ it is meant that when user creates or some other service creates instance of model Student and saves it to database these default B are used to create matching relations between that instance of Student and these “default” instances of Course. hmp -
Is there any other chances to resolve this issue
Admin Login Error : DJANGO I have created a django super user for admin. I have added AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) in settings.py file but when I enter the same credentials it is showing the below erro: ** django admin showing username and password incorrect.both fields are case insensitive ** -
django redirect after form save
I have a detail view with 2 forms and here I provide code for only one of them. The form is located in a modal on user detailed view and I need to redirect the client to that detail view in which the form is. In the post method the request.GET['user'] returns the user id so I have everything needed to achieve this. I have tried the reverse and redirect, nothing worked I guess because of wrong code. Should I provide a get_success_url() to do that? model = TbUser def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['entrance_rights_form'] = TbPeopleEntranceRightForm( user=self.object, initial={'user': self.object}) return context class TbPeopleEntranceRightFormView(FormView): form_class = TbPeopleEntranceRightForm template_name = 'users/create_entrance_permission_modal.html' def post(self, request, *args, **kwargs): print(request.POST['user']) # returns user id entrance_rights_form = self.form_class( user=None, data=request.POST) terminal_permissions_form = TbTerminalPermissionForm(user=None) if entrance_rights_form.is_valid(): entrance_rights_form.save() return redirect('user-detail', args=(request.POST['user'],)) else: return redirect('users-list') urlpatterns = [ path('users-list/', UsersListView.as_view(), name='users-list'), path('user-detail/<str:pk>/', UserDetailView.as_view(), name='user-detail'), path('tb-entrance-right-form/submit', TbPeopleEntranceRightFormView.as_view(), name='tb-entrance-right-form'), ] -
django admin list data using default filter
i have model like this ### models.py class Pizza(models.Model): name = models.CharField() price = models.IntegerField() have_recipe = models.BooleanField() ### admin.py admin.register(Pizza) class PizzaAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'price') exclude = ('have_recipe',) when I enter localhost:8000/admin/pizza i can see all of pizza objects, but, I want to make admin pizza list show only have_recipe=True objects and nobody can't control this filter in admin page is there any solution?? -
AM PM not working in django html template
I am getting Enter a valid date/time. error when trying use AM and PM. Without AM PM I am not getting any error. I am using bootstrap datetimepicker in my html template. here is my code: froms.py class BlogForm(ModelForm): class Meta: model = Blog fields = ['title','body','published'] widgets = { 'title': forms.TextInput(attrs={'class':'form-control','placeholder': 'Title'}), 'published': forms.DateTimeInput(format=['%Y-%m-%d %I:%M %p']) } #html <form method="POST" enctype="multipart/form-data"> {{from}} </form> <script> $(function () { $("#datetimepicker1").datetimepicker({ format: 'YYYY-MM-DD hh:mm:ss a', }); }); </script> -
How to idealy setup Model For default items in Djaago
I have a Django application, where the business can add items in Item Model. Also, some of the common items should be there in the database which is provided by the admins(me) which will be shown to the users and they can add that if they want. If the select that item a new item will be created in the database with values from the selected item and the user field in the item model will point to the user who created it. From that instant, the user has a copy of that item under their control. They can edit values if they want. How to implement this system. I have two options Adding the common items in the item model itself with user field equals to null, and maybe add another field to identify it is added bt admin. Create a separate model for default Items. Which is the ideal method? Or is there an alternate method? -
How to return values without breaking a function [duplicate]
I'm generating an html file to print in a thermal printer. But since I can't use django template tags I'm generating it on the views.py. Since I can't predict the item number, I was using a loop. def total(): for ordered_item in ordered_items: title = ordered_item.food.title['tm'] price = ordered_item.food_size.price quantity = ordered_item.quantity return str(title),str(price),str(quantity) And I'm using that here: html=""" <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use PyQt5 to print thermal receipts</title> </head> <body> <img src='http://c.biancheng.net/cpp/templets/new/images/logo.jpg?v=3.994' style="align-items: center;" width="130" height="130"/> <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: """ + str(order.code) + """ </span> <br> <br> <span>Order time: """ + str(order.created) + """</span> <br> <br> <span>Cashier: """ + str(order.waiter) + """</span> <br> <span>---------------------------------------</span> <div class="section4"> <div> <table> <thead> <tr> <th width="110">Product name</th> <th width="80">Unit price</th> <th width="30">Quantity</th> </tr> </thead> <tbody> <tr> <td>""" + str(total()) + """</td> </tr> </tbody> </table> </div> <br> <span>---------------------------------------</span> <br> <div class="total"> <span>Total : """ + str(order.total_cost) + """</span> <br><br> <span>Paid : """ + str(order.paid) + """ </span> <br><br> <span>Change : """ + str(change) + """ </span> </div> <br> <span>---------------------------------------</span> </div> <div class="section5"> <span>Thank you for your patronage! </span> </div> </div> </div> </body> </html> """ But my function exits after the first loop. Is … -
Why can't select one object in django
I'm creating a ecommerce store using django And tried s many things to do this.index page is working pretty well but I want select specific product when I click .ex: when I click a shoe I want to enter shoe detail page with shoe image and all the necessary details.Here is my home page.And also I highly recommend to check my all code because you can't get any idea with only this code.github source code here.thanks dinindu {% extends 'store/main.html'%} {% load static %} {% block content %} <style> img:hover{ opacity: 0.5; } </style> <div class="row"> {% for product in products %} <div class="col-lg-4"> <a href="{% url 'productDetail' Product.name %}"><img class="thumbnail" src="{{product.imageURL}}"></a> <div class="box-element product"> <h6><strong>{{product.name}}</strong></h6> <hr> <button data-product="{{product.id}}" data-action="add" class="btn btn-outline-secondary add-btn update-cart">Add to Cart</button> <h4 style="display: inline-block; float: right"><strong>Rs {{product.price}}</strong></h4> </div> </div> {% endfor %} </div> {% endblock content %} -
Error 0 connecting to localhost:6379. Error
Got strange redis error Error 0 connecting to localhost:6379. Error. It comes time to time but it's not permanent or reproduceable. I'm using redis-server v3.0.6 and redis==3.5.3, channels_redis==2.4.2 python packages for client connection alongside with django framework. -
Django login state isn't saving
I'm using Django and React to create a login page. When the user clicks on the submit button, I send an Axios POST request to my Django server to authenticate and login. In the login function, printing request.user works as intended. But as soon as the scope of the function is left, printing request.user prints AnonymousUser. I've talked to some people about it and they seem to think it's because cookies aren't persisting, but we haven't been able to solve the problem. Any guidance would be appreciated. // REACT FORM function submitHandler(event) { event.preventDefault(); const state = login ? "login" : "signup"; axios .post(`http://localhost:8000/auth/${state}`, { username: username, password: password, }) .then((response) => { setRedirectMessage(response.data); axios .post("http://localhost:8000/auth/user") }) .catch((err) => alert(err.response.data)); } # LOGIN REQUEST (/auth/login) @require_POST @csrf_exempt def auth_login(request): if request.user.is_authenticated: return HttpResponseBadRequest("You are already logged in") username, password = get_credentials(request) user = authenticate(username=username, password=password) if user is None: return HttpResponseBadRequest("Those credentials do not exist") login(request, user) print(user) # PRINTS CORRECTLY print(request.user) # PRINTS CORRECTLY return HttpResponse("You have successfully logged in with username " + username) # GET REQUEST TO CHECK LOGIN STATE (auth/user) @csrf_exempt def get_user(request): print(request.user) return HttpResponse("Hey there") -
How to connect to a signal while some method calls?
For example I have the model below. class MyModel(models.Model): ........ def some_method(self): .... At some point I will call this method somewhere in the view. Whenever this method gets called I want to call a django signal. How can I do this ? -
save() prohibited to prevent data loss due to unsaved related object 'student'?
There is m2m relationship models.py: class Student(models.Model): name = models.CharField(max_length=249) class Course(models.Model): name = models.CharField(max_length=249) students = models.ManyToManyField(Student, through='Connect') class Connect(models.Model): student = models.ForeignKey(Student, on_delete=models.SET_NULL, null=True) course = models.ForeignKey(Course, on_delete=models.SET_NULL, null=True) views.py: class CreateStudent(LoginRequiredMixin, CreateView): login_url = '/admin/' redirect_field_name = 'index' template_name = 'app/create_student.html' model = Student fields = ('name',) def form_valid(self, form): self.object = form.save(commit=False) for student in form.cleaned_data['name']: connect = Connect() connect.student = self.object connect.course__name = 'math' connect.save() return super(ModelFormMixin, self).form_valid(form) how to do what when creating a Student instance the default value was automatically added Course instance And how create in view method to define default Group p r -
Accessing a cookie set in template using document.cookie in a django View
I'm trying to use a cookie to store an integer value which will then be used to determine the range of data to be displayed on the next page. I am currently using the function document.cookie="name=tom" I've checked my browser storage and the cookie is stored there. And trying to access the cookie via a django view using request.COOKIES['name'] which is unsuccessful. I'm new to django so any info on why this doesn't work and best practice ways of managing variables between js and Python would be really helpful. Thanks! -
Django - TypeError - quote_from_bytes() expected bytes
I'm getting started with Django. I created a Create View for one of my models and got this Error message. I had the following output on my Django-server-website: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/blog/create/ Django Version: 2.0.7 Python Version: 3.8.5 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'products', 'pages', 'blog'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/base.py" in view 69. return self.dispatch(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/base.py" in dispatch 89. return handler(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in post 172. return super().post(request, *args, **kwargs) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in post 142. return self.form_valid(form) File "/home/mau/Dev/tryDjango/src/blog/views.py" in form_valid 23. return super().form_valid(form) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in form_valid 126. return super().form_valid(form) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/views/generic/edit.py" in form_valid 57. return HttpResponseRedirect(self.get_success_url()) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/http/response.py" in init 407. self['Location'] = iri_to_uri(redirect_to) File "/home/mau/Dev/tryDjango/lib/python3.8/site-packages/django/utils/encoding.py" in iri_to_uri 151. return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") File "/usr/lib/python3.8/urllib/parse.py" in quote 839. return quote_from_bytes(string, safe) File "/usr/lib/python3.8/urllib/parse.py" in quote_from_bytes 864. raise TypeError("quote_from_bytes() expected bytes") Exception Type: TypeError at /blog/create/ Exception Value: quote_from_bytes() expected bytes Can anyone tell me what is wrong? -
Check permissions for serialized child objects using Guardian
I have three models where one Document has many Blocks and one Block has many Comments. class Document(models.Model): name = models.Charfield() class Block(models.Model): document = models.ForeignKey(to=Document) class Comment block = models.ForgeinKey(to=Block) Users can have permissions for Document which allows them to see all Blocks in it. Users can also add Comments to any Block which they can share if other users. I use django-guardian to manage object-based permissions. I have created a RetrieveAPIView using Django Rest Framework to make the Document available. class DocumentDetailView(PermissionRequiredMixin, RetrieveAPIView): serializer_class = DocumentSerializer permission_required = "document.view_document" To include all blocks and their comments in that view, I use the following serializers (omitted class Meta for brevity): class DocumentSerializer(serializers.ModelSerializer): blocks = BlockSerializer(many=True, source="block_set") class BlockSerializer(serializers.ModelSerializer): comments = serializers.CommentSerializer(many=True, source="comment_set") class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment I would like to restrict the comments included in DocumentDetailView to those to which a user has permissions. Following the logic of django-guardian I would use get_objects_for_users(), to filter down the QuerySet of Block.comment_set.all(). Yet, I don't know where to do this. I guess to restrict the comments to those available to request.user, the permission-based filtering should be done in the DocumentDetailView, but I don't see how to do this …