Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
FOREIGN KEY constraint failed djnago
I get the error FOREIGN KEY constraint failed. I'm trying to return the average of comments and ratings in a model Class Movie, but I get the error FOREIGN KEY constraint failed. How can I fix it? class Movie(models.Model): def get_comments(self): return Comment.objects.filter(movie_id=self.id) def average_stars(self): comments = self.get_comments() n_comments = comments.count() if n_comments == 0: return 0 else: return sum([comment.stars for comment in comments]) / n_comments class Comment(models.Model): comment = models.TextField(max_length=1000) stars = models.FloatField( blank=False, null=False, default=0, validators=[MinValueValidator(0.0), MaxValueValidator(10.0)] ) user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,) movie = models.ForeignKey(Movie, on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(auto_now=True) def view_movie_detail(request, movie_id): if request.method == "POST": user = request.user comment = request.POST.get("comment") stars = request.POST.get("stars") if not request.user.is_authenticated: user = User.objects.get(id=1) Comment(comment=comment, stars = stars, user=user,movie_id=movie_id).save() return redirect(f"/movie/{movie_id}/") else: data = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}?api_key={TMDB_API_KEY}&language=en-US") recommendations = requests.get(f"https://api.themoviedb.org/3/movie/{movie_id}/recommendations?api_key={TMDB_API_KEY}&language=en-US") comments = reversed(Movie().get_comments()) average = Movie().average_stars() return render(request, "Movie/movie_detail.html", { "data": data.json(), "recommendations": recommendations.json(), "type": "movie", "comments": comments, "average" : average, }) I get the error FOREIGN KEY constraint failed. I'm trying to return the average of comments and ratings in a model Class Movie, but I get the error FOREIGN KEY constraint failed. How can I fix it? -
Can we import JSON file in Django and then save it in postgresql?
I have a JSON file for now which needs to be stored in Postgresql. I don't want to directly import JSON into postgres. How do I go about that? -
Django xhtml2pdf | How to move a long word to the next line in a PDF file
How to move a long word to the next line in a PDF file in Django xhtml2pdf? This style word-break: break-all; doesn't work Example: <table cellpadding="0" cellspacing="0" width="100%"> <tr> <td>LooooooooooooongWooooooooooooooord</td> </tr> </table> -
How to avoid timeout making large CSV with python?
For a project I need to implement a CSV export of large DB. My Django project is hosted on Azure and I get a timeout error each time... I think I need to implement async function or something like this. I've tried async_to_sync and sync_to_async, start with Daphne server, StreamingHttpResponse... Here is the code: class Echo: """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value @api_view(['POST']) @permission_classes((permissions.IsAuthenticated,)) def export_csv(request): try: # long task first_item, second_item, third_item = my_function(request.data) csv_tab = [] csv_tab.append(build_headers()) # long task for item in first_item: csv_tab.extend(build_lines(item, second_item, third_item)) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer, delimiter=';') response = StreamingHttpResponse( (writer.writerow(line) for line in csv_tab), content_type='text/csv', headers={ 'Content-Disposition': 'attachment; filename="somefilename.csv"'}, ) return response except Exception as identifier: LOGGER.exception(identifier) current = { 'state': "failure", 'reason': "server error", } print(identifier) return HttpResponse(json.dumps(current), status=500) -
Use order by in pagination result Django
I want do order by only pagination result for example in first page i get two product(the meaning of this mehsul is product) and when i get ordering i want order this two product. Who can halp me. def animal(request,slug): mehsul=Product.objects.filter(animal_type=slug) animal_count=2 paginator=Paginator(mehsul,animal_count) page_number=request.GET.get('page') page_obj = paginator.get_page(page_number) ordering = request.GET.get('ordering') if ordering: mehsul = Product.objects.filter(animal_type=slug) paginator=Paginator(mehsul,animal_count) page_number=request.GET.get('page') page_obj=paginator.get_page(page_number) return render(request,'animal.html',context={'mehsullar':page_obj}) -
How to filter objects whose created_date exceeds 30 days
Here,I have model from django.db import models class Product(models.Model): name=models.CharField(max_length=100) created_at=models.DateTimeField(auto_now_add=True) I want to get all those objects that date exceeds 30 days from creation,by like this but this doesnot work. Is there any way to hack this scenario from django.db.models import F from django.utils import timezone Product.objects.annotate(diff_date=(timezone.now()-F('created_at'))).filter(diff_date__days__gte=30) -
download video from server
I,m trying to download a video from my server,and wrote a code for it but don't work and download everything can any one help me for my problem? class VideoDownloadView(viewsets.ModelViewSet): queryset = Video.objects.all() def get_serializer_class(self): if self.action == 'retrieve': return VideoSerializer @action(detail=True, methods=['get'], name='Videos_download') def download(self, request, pk): video = self.get_object() file_handle = video.video_file.open() return FileResponse(file_handle,) model: class Video(models.Model): course = models.ForeignKey(Courses, on_delete=models.CASCADE, related_name='course_videos') video_file = models.FileField(upload_to='deploy/video/', blank=True, null=True, verbose_name='video')- -
django migrations always run twice for unit tests
I have a django project with some unit tests. When I run the tests, I usually skip migrations, because they take a lot of time. I use the the keep argument of the django test runner: manage.py test --keep This works fine. When I need to run migrations, I use: manage.py test --noinput This runs migrations as I would expect. However, when I now run manage.py test --keep it runs the migrations for the second time as if ignoring the keep argument. The third and subsequent commands work again correctly skipping the migrations. I tested this behavior on two different projects and it is the same. Is it default django behavior? Can it be somehow avoided? I don't need the second migration. -
Very slow CSV import in Django
I have a working function in my views.py to import a uploaded csv-file in my database (sqlite). The csv-file has a size of about 760kb and about 2.1k lines of data. It takes me about 9 minutes to import that data with the following simplyfied code. Is there any faster method? for row in reader: item.objects.update_or_create( sn = row[0], defaults={ "field_a": row[1], "field_b": row[2], "field_c": row[3], "field_d": row[4], } )``` Thank you for your help! -
An Unexpected Error while trying to delete data
I am doing CRUD using serializers and foreign key as tasked,the problem is that when I am trying to delete a data,an error which is completely unexpected has come. this error should not be coming as I am not missing the id in the below functions and html code NOTE : I am doing soft delete hence the parameter 'isactive' is there delete function def delete(request,id): deleteclothes = Products.objects.all(id=id) delclothes = {} delclothes['isactive']=False form = POLLSerializer(deleteclothes,data=delclothes) if form.is_valid(): print("error of form when valid:",form.errors) form.save() return redirect('polls:show') else: print("error of form when not valid:",form.errors) return redirect('polls:show') html code of product_list <td> <a href="/delete/{{result.id}}/" onclick="return confirm('Are You Sure you want to delete?')"> <button class="btn btn-danger"> Delete </button> </a> </td> where am I going wrong in the code? -
Updating id of models without deleting objects in it in Django
I am studiying the bases of django by watching courses of "Tech with Tim" https://www.youtube.com/watch?v=sm1mokevMWk&t=2912s I deleted objects in models and my id always incremented instead of making reset. How can I reset my id? enter image description here from typing import Text from django.db import models class ToDoList (models.Model): name = models.CharField(max_length = 200) def __str__(self): return self.name class Item(models.Model): todolist = models.ForeignKey(ToDoList, on_delete = models.CASCADE) text = models.CharField(max_length=300) complete = models.BooleanField() def __str__(self): return self.text -
Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)/\\Z']
get the following error when adding a go back link in my comment_delete.html: Reverse for 'post_detail' with arguments '('',)' not found. 1 pattern(s) tried: ['(?P[-a-zA-Z0-9_]+)/\Z'] Everything works without the go back link (deleting a comment). Would like to know what I'm doing wrong in my comment_delete (href="{% url 'post_detail' post.slug %}") Go back Thank you :) models.py: class Post(models.Model): title = models.CharField( max_length=200, unique=True, default=str(f'Fishing {datetime.today()}')[:24] ) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey( User, on_delete=models.CASCADE, related_name='blog_posts' ) featured_image = CloudinaryField('image', default='placeholder') excerpt = models.TextField(blank=True) updated_on = models.DateTimeField(auto_now=True) content = models.TextField() created_on = models.DateTimeField(auto_now_add=True) status = models.IntegerField(choices=STATUS, default=1) likes = models.ManyToManyField( User, related_name='blogpost_like', blank=True) class Meta: ordering = ['-created_on'] def __str__(self): return self.title def number_of_likes(self): return self.likes.count() def get_absolute_url(self): return reverse('post_detail', kwargs={'slug': self.slug}) def save(self, *args, **kwargs): self.slug = slugify(self.title) return super().save(*args, **kwargs) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_comments') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) approved = models.BooleanField(default=True) class Meta: ordering = ['created_on'] def __str__(self): return f'Comment {self.body} by {self.author}' views.py class CommentDelete(LoginRequiredMixin, SuccessMessageMixin, UserPassesTestMixin, generic.DeleteView): model = Comment template_name = 'comment_delete.html' success_message = "Comment Deleted" def get_success_url(self): slug = self.kwargs['slug'] return reverse_lazy('post_detail', kwargs={'slug': slug}) def delete(self, request, *args, **kwargs): messages.success(self.request, self.success_message) return super(CommentDelete, … -
Where shall I put sub-domain routing? Front-end (React) or Back-end (Django+zappa) in a Serverless multi-tenant application?
So, we have a multi-tenant application in which sub-domain routing is handled by backend (django+zappa) and now we're moving to Serverless for back-end. Hence, we need to seperate our React and Django code. So, my question is where shall I put the subdomain routing on react side or on django side. -
Where should I store the Django media files so that I can have the same functionality as the Lynda site?
I built a Django website that works like Lynda's tutorial. Now my question is, where should I save my video files so that they are only accessible to users who are allowed to download them? Does saving files on object space give me such a feature? Or where should I live my website to have such a feature? Or if I save on vps servers where my Django app is live, will it affect the speed of my app? Please guide. -
Accessing reverse relation in django, Django restframework
I want to get all the students/learners that are enrolled in a course, This is my course model, this is my courseenrollement model -
How do I change dynamically one form value based-on other form value on Django?
I am trying set dynamically a value from form value A to the form value B (his default) Value on form A: A = models.IntegerField(XXX) Value on form B: ### if A is 1900, B default value is years ago B = models.IntegerField(XXX, default=value_from_A_+_1000) what is the best way to manage it? Thank you -
I am trying to create a review form. but I am having difficulties with the submit_review form. Many errors due to Service ID
I believe my issue is stemming from the views.py file. I dont believe I have it correctly laid out. The idea is for the user to review a service that has been purchased only. The link to the review form is in the purchase order history view so when they click on review service that service description would automatically transfer to the submit_review form. Model: class ReviewRating(models.Model): service = models.ForeignKey(Service, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, null=True, blank=True) review = models.TextField(max_length=500, null=True, blank=True) rating = models.FloatField() status = models.BooleanField(default=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.subject I believe the problem to be here in the view Views: def submit_review(request, service_id): service = get_object_or_404(Service, pk=service_id) if request.method == 'POST': form = ReviewRatingForm(request.POST) if form.is_valid(): review_form = form.save(commit=False) review_form.service = service_id form.save() messages.success(request, 'Review submitted succeffully!') return redirect(reverse('useraccount')) else: messages.error(request, 'Failed to submit review. Please ensure the form is valid.') else: form = ReviewRatingForm() template = 'useraccount/submit_review.html' context = { 'form': form, 'service': service, } return render(request, template, context) URLs: from django.urls import path from . import views urlpatterns = [ path('', views.useraccount, name='useraccount'), path('purchase_history/<order_number>', views.purchase_history, name='purchase_history'), path('submit_review/<service_id>', views.submit_review, name='submit_review'), ] template form: <form class="reviews-form" method="POST" action=""> … -
Make a relative url go one step back
I have a url: http://test.com/test1/test2/ Is there a way to make a relative url from test2 to test1? Like just one step back? Without Javascript. The /test1/ part may change, that's why I need to go from /test/2 just one step back to /test1/ (or changed url) -
Not able to save and retain the selected option in dropdown
I am performing CRUD using foreign keys and serializers,and I am having difficulty in doing the update operation. the problem is that I am unable to retain the selected option in dropdown. for example in categories column,I have selected 'Bridal wear' and then when I try to edit it,in the edit page the value saved appears as '9-6wear' instead as shown below in below images the selected categories is 9-6wear below are the models and serializers class CategoriesSerializer(serializers.ModelSerializer): class Meta: model = Categories fields = "__all__" extra_kwargs = {'category_name': {'required': False}} class ColorsSerializer(serializers.ModelSerializer): class Meta: model = Colors fields = "__all__" class POLLSerializer(serializers.ModelSerializer): # categories = serializers.StringRelatedField(many=False) # sub_categories = serializers.StringRelatedField(many=False) # color = serializers.StringRelatedField(many=False) # size = serializers.StringRelatedField(many=False) class Meta: model = Products fields = "__all__" class SizeSerializer(serializers.ModelSerializer): class Meta: model = Size fields = "__all__" class SUBCategoriesSerializer(serializers.ModelSerializer): class Meta: model = SUBCategories fields = "__all__" models class Products(models.Model): categories = models.ForeignKey(Categories,on_delete=models.CASCADE) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE) color = models.ForeignKey(Colors,on_delete=models.CASCADE) size = models.ForeignKey(Size,on_delete=models.CASCADE) # image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) product_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) class Categories(models.Model): #made changes to category_name for null and blank category_name = models.CharField(max_length=20) category_description … -
404 (Not Found) error on ajax post request
Good morning Sirs, this code is meant to get data from a form and request a Django view to create an account in a database and respond with an instant of the account created, back to the template.html which made the previous request. The form is created using django-crispy-forms form.html -
Set personalized body for sending mail in django
I want to send a message with personalized SMTP mail-in Django. Where I want to send Name, email, and contact information with the dynamic text input value. Here is my code if request.method == 'POST': name = request.POST.get('name') email = request.POST.get('email') contact = request.POST.get('contactnum') textmess = request.POST.get('textarea') allinfo = "Name : " + name, "E-Mail" + email, "Contact:" + contact, textmess print (allinfo) subject = 'From MBS Project(Contact Us)' email_from = settings.EMAIL_HOST_USER mailto:recipents_list=['abc@gmail.com'] if allinfo: sendMail = send_mail(subject, allinfo, email_from, recipents_list) messages.success(request, 'Message Send Successfully...') return HttpResponseRedirect('contactus', {'sendMail': sendMail}) else: messages.error(request, 'error during send!!, Please Try Again..') return render(request, 'contactus.html', {}) else: return render(request, 'contactus.html', {}) -
Display popup information beside map in a table when I click a marker with leaflet/django
I am using Leaflet JS and Django to create a map website. I have markers on the map showing correctly and I'm trying to display a table in a seperate div beside the map displaying information that would be in the popup. I am also using a Django REST api to store marker data such as lat & long, names etc. My api returns this: [ { "id": 2, "cube": "Industrial Cube North", "cubeurl": "https://dcwppntise010.edc.nam.gm.com/admin/login.jsp", "hostname": "acrptisepsn01", "domain": "nam", "personas": "Policy Service", "ip": "10.36.139.120", "structurename": "Rochester COMP", "streetaddress": "1000 Lexington Ave", "latitude": 43.18226, "longitude": -77.65599 }, I fetch data from my API like: {% for item in data %} var marker = L.marker([{{item.latitude}},{{item.longitude}}]).bindPopup("<strong>{{item.hostname}}</strong><br/>{{item.personas}}").addTo(map).on('popupopen', function (e) { console.log(e.popup.getContent()) });; {% endfor %} It logs the content in the console but don't know how to dynamically change info in the table for each marker (they have different info & locations) I have seen examples such as: http://www.gistechsolutions.com/leaflet/DEMO/baseball/BaseballPanel.html That uses GeoJson and I'm not sure how to apply the same logic to my setup. Thank you! I need a table like this: -
Django rest framework sql raw query from another host
I have two database with different connection, 1st is the default database and 2nd is for data only. 1st DB: Host:0.0.0.0 port:5822 dbname:DBone user:postgres password:user:postgres 2nd DB: Host:0.0.0.0 port:5842 dbname:DBtwo user:postgres password:user:postgres 1st database the main database, I want to query data from 2nd database under views.py (request) Im using Django RestFrameworks now. I want to raw query from another host connection, how to do that? @api_view(['GET']) def get_data(request): data = DBtwo.objects.raw(SELECT current from DBtwo WHERE name ='Test' AND gender ='M' AND age ='20') -
serve static and media files in django when debug=False
I want to publish my django project but when is change my settings.py "debug = False" static files are not loaded ! here is my settings.py MEDIA_URL = '/media_files/' STATIC_URL = '/static_files/' MEDIA_ROOT = '/home/domain/public_html/static_cdn/media_root' STATIC_ROOT = '/home/domain/public_html/static_cdn/static_root' also I used "python manage.py collectstatic" command and it created folder for example when I put "https://domain/static_cdn/static_root/admin/css/base.css" I can see the files without error -
How shall I make this form automatically identify the user who is logged in as author
class ArticleCreateView(CreateView): model=Post form_class=PostForm template_name='add_post.html' from operator import mod from turtle import title from django import forms from .models import Post class PostForm(forms.ModelForm): class Meta: model=Post fields=['title','body','author','category']