Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I render and extract assets (3D) in browser?
I have a simple app created in Django and my problem is that I need to extract 3D assets from engine (like Unity), this are just files that contains 3D game characters and I need to render them in the browser, is there a Python library that can be integrated under a django web project and no other external web framework library like three.js? -
Image Update is happening in Django
I had used code to update the image in Django, but it doesn't resulted as expected. if request.method == "POST": data = ImageModel.objects.get(pk=id) pid = customer.objects.get(pk=id) fm = CustomerRegisteration(request.POST, request.FILES, instance=pid) if fm.is_valid(): data.image_document.delete() fm.save() This code doesn't work -
file cannot be uploaded and gone (not move to local storage) - DJANGO FORMS
i don't use models form but only form. so when i clicked button upload, the file just gone and not uploaded to my local storage. i don't know why. please help me. this is my code : def homepage(request): if request.method == "POST": form = Audio_store(request.POST, request.FILES) # form = AudioForm(request.POST, request.FILES) if form.is_valid(): handle_uploaded_file(request.FILES['record']) return render(request, "homepage.html", {'form': form}) else: return render(request, "homepage.html") def handle_uploaded_file(f): with open('mp3', 'wb+') as destination: for chunk in f.chunks(): destination.write(chunk) forms.py : from django import forms class Audio_store(forms.Form): record=forms.FileField() urls.py : urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^decode/$', views.decode), path("", views.homepage, name="upload") ] if settings.DEBUG: #add this urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) terminal my folder: -
How to render specific template if two app have same template name?
How can I render a specific template in Django? I have created three apps for my project. Each app contains a templates folder. The project structure is as follows: ├───Project ├───app1 │ ├───templates ├───app2 │ ├───templates ├───app3 │ ├───templates In my app2 and app3, I have templates with the same name. I want to render the template from app3 but the template is rendering from app2. I am using the following code. In app3.views.py return render(request, "template_name.html") -
Django System in another Project that is not web application [closed]
I am new to using Django, and I like it. I was working before with python on another project connected to Database and used CURD Methods and JSON format. My Question now can I use Django System (Models and Serializer) in this project? I think it will be better than cursor() and execute() -
how to add second page reportlab in django
my goal is to write the data in the models to a pdf file so that if it doesn't fit on the first page, it will automatically continue on to the second page. is writing me a card again and again on a sheet of code pls help me from django.shortcuts import render from django.http import HttpResponse,HttpResponseRedirect # Create your views here. from .forms import VenueForm from .models import * from django.http import FileResponse import io from reportlab.platypus import PageBreak from reportlab.pdfgen import canvas from reportlab.lib.pagesizes import inch from reportlab.lib.pagesizes import letter def venue_pdf(request): buf = io.BytesIO() c = canvas.Canvas(buf,pagesize=letter,bottomup=0) textob=c.beginText() textob.setTextOrigin(inch,inch) textob.setFont("Helvetica",14) venues = Venue.objects.all() l = [] for i in venues: l.append(i.lname) l.append(i.fname) l.append(i.fan) l.append(i.address) l.append(i.phone) l.append(" ===================================================== ") l.append(" ") for j in range(len(l)//36+1): c.drawText(textob) c.showPage() c.save() buf.seek(0) return FileResponse(buf,as_attachment=True,filena me='east_ariza.pdf') -
Retrieve specific objects from prefetch_related query
I'm working on twitter like app and I have home view which displays tweets and retweets by current user and users who follow that user. I want to show info who retweeted this tweet for all retweets. In retweeted_by column I receive user id. Queryset for this view: def get_queryset(self): user = self.request.user tweets = Tweet.objects.filter(Q(user=user) | Q(user__in=user.followees.all())). \ annotate(action_time=F('pub_date'), retweeted_by=Value(0, output_field=BigIntegerField())). \ select_related('user').prefetch_related('likes', 'retweets', 'children', 'mentioned_users') retweets = Tweet.objects.filter(Q(tweetretweet__user=user) | Q(tweetretweet__user__in=user.followees.all())). \ annotate(action_time=F('tweetretweet__timestamp'), retweeted_by=F('tweetretweet__user')). \ select_related('user').prefetch_related('likes', 'retweets', 'children', 'mentioned_users') return tweets.union(retweets).order_by('-action_time') Template for this view renders all tweets in queryset with inclusion tag: @register.inclusion_tag('tweets/short_tweet_snippet.html', takes_context=True) def render_short_tweet(context, tweet): var_dict = { 'request': context['view'].request, 'tweet': tweet, } # Check if queryset has retweeted_by column # (i have a lot of views which display tweets, but only some show retweet info) try: retweeted_by = tweet.retweeted_by except AttributeError: return var_dict # If retweeted_by value not equal 0 if retweeted_by: # user = tweet.retweets.filter(pk=retweeted_by).get() (hits the db) # user = tweet.retweets.get(pk=retweeted_by) (hits the db) # Doesn't hits the db, but not optimized solution for user in tweet.retweets.all(): if user.pk == retweeted_by: retweeted_user = user var_dict.update(retweeted_user=retweeted_user) return var_dict The problem is when i want to get user object who retweeted specific tweet django makes … -
Django Postgresql annotate group_by (annotate) not working?
I want to query for product with details but currently i am not getting results as I want. class Product(models.Model): . . . price = models.DecimalField() url = models.URLField(max_length=255, null=True, unique=True) merchant = models.ForeignKey(Merchant, on_delete=models.DO_NOTHING) class ProductVariant(models.Model): sku = models.CharField(max_length=255) product = models.ForeignKey(Product, on_delete=models.DO_NOTHING) Query: class Detail(DetailView): model = ProductVariant template_name = "products/cpus_detail.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['cpu'] = CPU.objects.filter( model__iexact=context['object'].sku).first() merchant_products = ProductVariant.objects.filter(sku__iregex=rf"\y{context['object'].sku}\y").values('product__merchant').annotate(merchant=Count('product__merchant')) Output of the above query is: <QuerySet [{'product__merchant': 1, 'merchant': 1}, {'product__merchant': 2, 'merchant': 2}]> in above query product is grouped by merchant. And if I want to include other fields of product model: <QuerySet [{'product__merchant': 1, 'product__url': 'some url 1', 'merchant': 1}, {'product__merchant': 2, 'product__url': 'some url 2', 'merchant': 1}, {'product__merchant': 2, 'product__url': 'some url 3', 'merchant': 1}]> now in above query product is no longer grouped by merchant (3 records are returned instead of 2, even though 2 records have product__merchant: 2) what i want is: query that returns grouped records based on merchant (with product fields) -
How to get the related models first objects in a single query in Django?
class Product(models.Model): category = models.ForeignKey(Category, related_name="products_category", null=True, on_delete=models.CASCADE) sku = models.CharField(max_length=200, blank=True, null=True) class ProductVariants(DateTimeModel): name = models.CharField(max_length=200, blank=True, null=True) product = models.ForeignKey(Product, related_name="products_variants", null=True, on_delete=models.CASCADE) products = Product.objects.select_related().all() how to get all the parent model objects with their related model's first object in a single query. [0] and first() is not working. how to fetch that? -
Makemigrations/migrate in django
Could anyone help me solve this problem? I want to add data and time models in Django, but after makemigration, I got this. **You are trying to add a non-nullable field 'MeterReading_DateTime' to mdm_api without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: Provide a one-off default now (will be set on all existing rows with a null value for this column) Quit, and let me add a default in models.py Select an option:** -
How to export data from front Web to CSV files using jquery?
I'm practiced Python+Django edited Web, followed sample trying to export from db data into front Web and I want download CSV file. Here is my whole function. Its download a file, but it shows the for the title and not any data out. Thanks all. Views: sid search funtion def search_by_sid(request,pk=1): sdepartments = Department.objects.all() cdepartments = CDepartment.objects.all() ssid = CourseData.objects.all() if request.method == "POST": sid = request.POST.get("sid").strip() if "," in sid: course = CourseData.objects.filter(sid="NA") sids = sid.split(",") for n in sids: courses = CourseData.objects.filter(sid = n.strip()) course =course | courses else: course = CourseData.objects.filter(sid=sid).order_by("teacher") num = len(course) return render(request, "list.html") return redirect("/") donwload file function: def down_file(request): sdepartments = Department.objects.all() cdepartments = CDepartment.objects.all() ssid = CourseData.objects.all() if request.method == "POST": sid = request.POST.get("sid") dfs = CourseData.objects.filter(sid__in=['sid']).values_list("sid","name","phone","email","sdept") response = HttpResponse(content_type="text/csv") response.write(codecs.BOM_UTF8) response['Content-Disposition'] = 'attachment; filename = "Report.csv"' writer = csv.writer(response) print(writer) writer.writerow(["sid","name","phone","email","sdept"]) for sop in dfs: writer.writerow(sop) return response Templates: button function <form id="sid" action="/bysid/" method="post"> {% csrf_token %} Search:<input name="sid" size="50" placeholder="Search"> <input type="submit" value="Go Search"> <input id="btnType" type="" value="Search"> <button type="button" id="down_file" >Download Files</button> </form> js funtion: $(document).ready(function(){ $("#down_file").click(function(){ $("#btnType").val('accpeted'); <!--Why Null ?!--> $("#sid").submit(); }); }); -
How to get count of more than one field from a table using Django queryset
here is my queryset queryset = (PrathamTeamMembers.objects. select_related('state', 'district', 'block', 'personnel_type'). filter(is_active=1). annotate(total_state=Count('state', distinct=True), total_district=Count('district', distinct=True))) I am expecting result similar to { "total_state": 10 "total_district": 60 } But it is not aggregating instead it is grouping by table PrathamTeamMembers primary key. which I want to avoid. Since it is grouping on table primary key so my queryset giving result simlary to .. [{ "total_state": 1, "total_district": 1 }, { "total_state": 1, "total_district": 1 }, { "total_state": 1, "total_district": 1 } ] -
JSON field sometimes contains string, sometimes object
I'm using Django rest framework to validate JSON received from a banking API (webhook) that sends financial transactions. The serializer has been working for a few years now. The merchant field in the JSON would always contain the merchant as a nested object with the merchant's ID, name etc. But now I am sometimes receiving just the merchant's ID as a string and the JSON now fails validation. How do I set up my serializer to allow eith string or object in the merchant field? serializers.py class MerchantSerializer(serializers.Serializer): id = serializers.CharField(required=True, max_length=50) name = serializers.CharField(required=True, max_length=100) atm = serializers.BooleanField(required=False, allow_null=True) address = AddressSerializer(required=False, allow_null=True) logo = serializers.URLField(required=False, allow_null=True, max_length=500, min_length=None, allow_blank=True) class DataSerializer(serializers.Serializer): account_id = serializers.CharField(required=True, max_length=50) amount = serializers.IntegerField(required=True) created = serializers.DateTimeField() currency = serializers.CharField(required=True, max_length=3) description = serializers.CharField(required=True, max_length=250) id = serializers.CharField(required=True, max_length=50) category = serializers.CharField(required=True, max_length=100) decline_reason = serializers.CharField(required=False, allow_null=True, allow_blank=True, max_length=100) merchant = MerchantSerializer(required=False, allow_null=True) counterparty = CounterpartySerializer(required=False, allow_null=True) metadata = MetadataSerializer(required=False, allow_null=True) -
Handling upload of many files in django
Im trying to upload many image files at once to my django website. The images are put into an html form and the post request is sent with all these images (thousands). My problem is that once the images reach my server, the app crashes because too many files are open. I'm not sure how to correctly handle the post request - I'm thinking there must be a way to iterate through all the images and save and close them instead of having them all open at one time. Here is my upload method in views.py: def upload(request): if request.method == 'POST': username = request.user dataset_access = DatasetAccess.objects.get(user=username) dataset_name = request.POST['dataset_name'] if '-' in dataset_name: messages.error(request, 'Invalid Character: \' - \' ') return redirect('upload') if Dataset.objects.all().filter(title=dataset_name): messages.error(request, 'A Dataset by this name already exists!') return redirect('upload') else: notes = request.POST.get("notes") dataset = Dataset.objects.create( title = dataset_name, num_datapoints = 0, owner = username, notes = notes, ) dataset_access.dataset.add(dataset) dataset_access.save() images = request.FILES.getlist('images') dataset.create_datapoints(images,xmls,jsons,username) messages.success(request, "Dataset uploaded successfully!") return redirect('manage', dataset.title) return render(request, 'datasets/upload.html') -
How to configure SSL(HTTPS) Elasticbeanstalk
Hello Im trying to use HTTPS in ELasticBeanstalk, I already Have an SSL Certificate in certificate manager Note: My certificate status in Certificate Manager is "okay" Note: HTTP I can access my aplication I will send the link: my site in http Note: even if I configured the certificate in loadbalancer when I enter my domain it's like my EB aplication it's not being linked dont get any error: I put the SSL certificate in LoadBalancer( I used 2018, any earlier fail to deploy) I get this error on my aplication: Now I will send Prints of my LoadBalancer: Note: I also tried to get my EC2 LoadBalancer and add as a dns in my domain when I try to access it I get the error Bad Gateway 400 -
Upload issue Geonode
I am working on a website based on opensource Geonode. While extending the upload document section - (Hidden field permissions) This field is required. shows up. I didnt touch the geonode code. just added header and footer of personal choice. -
password_reset_confirm.html and password_reser_complete.html in not rendering in django
I have implemented password reset functionality in Django it working fine but when I open account recovery link from the Gmail browser redirects me to Django's built-in password_reset_confirm page I want it to redirect me to my custom password_reset_confirm.html urls.py code app_name="accounts" urlpatterns=[ path('password_reset/',auth_views.PasswordResetView.as_view( template_name='password_reset.html', success_url=reverse_lazy('accounts:password_reset_done')),name='password_reset'), path('password_reset_done/', auth_views.PasswordResetDoneView.as_view(template_name='password_reset_done.html'), name='password_reset_done'), path('password_reset_confirm/<uidb64>/<token>/',auth_views.PasswordResetConfirmView.as_view(template_name='password_reset_confirm.html',success_url=reverse_lazy('accounts:password_reset_complete')),name='password_reset_confirm.html'), path('password_reset_complete/', auth_views.PasswordResetCompleteView.as_view(template_name='password_reset_complete.html'), name='password_reset_complete'), ] I also want to check while entering email into the input field to send the email. if the user's entered email-id does not exist then it should show a message "this email does not exist" -
This was likely an oversight when migrating to django.urls.path()
So hello guys, I am new to this django and i have encountered this type of error enter image description here while this if my url.py from unicodedata import name from django.urls import path from Project.views import viewAppointment, addDiagnosis from . import views app_name = "Project" urlpatterns = [ path('', views.index , name='index'), path('counter', views.counter, name='counter'), path('Register', views.Register, name= 'Register'), path('login', views.login, name='login'), path('logout', views.logout, name = 'logout'), path('post/str:pk', views.post, name = 'post'), path('profile', views.profile, name='profile'), path(r'^appointment/appointment=(?P<appointment_id>[0- 100]+)', viewAppointment, name='appointment'), path(r'^appointment/appointment=(?P<appointment_id>[0- 100]+)/AddDiagnonsis', addDiagnosis, name='AddDiagnosis') ] meanwhile this is my views.py def viewAppointment(request, appointment_id): appointment = Appointment.objects.filter(id=appointment_id) return render(request, 'appointment_form.html', {'Appointment': appointment}) def addDiagnosis(request): return True -
Validate forms.TimeField() in Django
I am quite new in Django world. I was working on forms.TimeField() validation (image below) but can not find solution yet :( Whenever user enters "letters" or extra "number" form field should raise ValidationError(_('Please follow the right format')) like this image below I tried with def clean_max_check_out_time(self): cleaned_data = super().clean() default_check_out_time = cleaned_data['default_check_out_time'] if type(default_check_out_time) is not datetime.time: raise ValidationError(_('Please follow the right format')) return default_check_out_time and def clean_max_check_out_time(self): testtime = '00:00:00' if(default_check_out_time >= testtime): raise ValidationError(_('Please follow the right format')) With these codes when I click submit Button it gives me KeyError How can I fix this. Thank you for your help in advance -
show text as it is entered in input box
I have created a Q&A website in Django I want to print text in the same format as it entered This is the text This is on a new line It should print in this format as it is entered but it prints like this This is the text This is on a new line my forum.html code <div class="card-body cardbody"> <p>{{post.post_content|truncatewords:"10"|linebreaks}}</p>{% if post.post_content|length|get_digit:"-1" > 50 %} <a href="/discussion/{{post.id}}" data-abc="true"><button class="btn btn-light" style="color:blue; font-size: 13px;">Show more </button> </a> {% endif %} </div> please help me to do this -
Is Django unchained, in any way related to the Django framework
I Have not watched the movie Django unchained but I was wondering whether it takes any inspiration from the website creating framework. -
How can i send data to two different column from the same form field?
In my project i am using Django 1.11.10 and postgresql for database. When someone enters data to 'order_id' field i want to send it a item_barcode column whether its first 2 character is letters. How can I do that? models.py from django.db import models class Customer(models.Model): item_barcode = models.TextField(max_length=50,unique=True,null=True) order_id = models.TextField(max_length=50,unique=True,null=True) full_name = models.TextField(max_length=50) company = models.TextField(max_length=60,blank=True) email = models.EmailField(max_length=40) phone_number = models.TextField(max_length=17) note = models.TextField(max_length=256,blank=True) def __str__(self): return self.order_id forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = ( 'order_id','full_name','company','email', 'phone_number','note') views.py def guaform(request): form = CustomerForm() if request.method == "POST": form = CustomerForm(request.POST) if form.is_valid(): form.save(commit=True) else: HttpResponse("Error from invalid") return render(request,'customer_form.html',{'form':form}) *My database columns is same of the models.py -
Django app with celery, tasks are always "PENDING". How can I fix this bug?
I have following celery settings in settings.py CELERY_BROKER_URL = "amqp://admin:admin2017@localhost" CELERY_IMPORTS = ("web.task",) When I use the form to submit a task to celery I see state is always pending enter image description here the following code is used in models: class AnaysisStatus(models.IntegerChoices): #TODO PENDING = 1 COMPLETED = 2 FAILED = 0 class Analysis(models.Model): STATUS_CHOICES = ((1,"PENDING"),(2,"COMPLETED"),(0,"FAILED")) user = models.ForeignKey(User,on_delete=models.CASCADE) status = models.IntegerField(choices=AnaysisStatus.choices,null= True) created_at = models.DateTimeField(auto_now_add=True,null=True) file = models.FileField(null=True) data = models.JSONField(null=True) I'm very new to celery and django so any help is greatly appreciated. Note: I'm not even sure if I need to install broker locally at this point amqp looks like RabitMQ? If so I plan on deploying this to Google Cloud without having to use google tasks if that is relevant. -
Django: how to filter form field based off of many to many relationship?
Currently, when a user creates a task, they can assign it to all users. I only want them to be able to assign a task based on the members of the project. I feel like the concept I have right now works but I need to replace the ????. projects/models.py class Project(models.Model): name = models.CharField(max_length=200) description = models.TextField() members = models.ManyToManyField(USER_MODEL, related_name="projects") tasks/models.py class Task(models.Model): name = models.CharField(max_length=200) start_date = models.DateTimeField() due_date = models.DateTimeField() is_completed = models.BooleanField(default=False) project = models.ForeignKey( "projects.Project", related_name="tasks", on_delete=models.CASCADE ) assignee = models.ForeignKey( USER_MODEL, null=True, related_name="tasks", on_delete=models.SET_NULL ) tasks/views.py class TaskCreateView(LoginRequiredMixin, CreateView): model = Task template_name = "tasks/create.html" # fields = ["name", "start_date", "due_date", "project", "assignee"] form_class = TaskForm def get_form_kwargs(self): kwargs = super(TaskCreateView, self).get_form_kwargs() kwargs["user"] = self.request.user kwargs["project_members"] = ?????????? return kwargs tasks/forms.py class TaskForm(ModelForm): class Meta: model = Task fields = ["name", "start_date", "due_date", "project", "assignee"] def __init__(self, *args, **kwargs): user = kwargs.pop("user") project_members = kwargs.pop("project_members") super(TaskForm, self).__init__(*args, **kwargs) self.fields["project"].queryset = Project.objects.filter(members=user) self.fields["assignee"].queryset = Project.objects.filter( members=????????? ) -
what is the best way to refresh a page automatically?
I am trying to create a simple movie list app with django.I have two page. One for users nad one for movies' list table.Users can add items to the list on their own page and list should be update after every single request. though I know that i can refresh the list page rapidly I was wondering is there another and better way to do this?