Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best strategy to create an Amazon-like product search and filter with django?
I need to create a search and filter page that should work similarly to Amazon. So I search first in the search bar and then, I filter using checkboxes, dynamically, without clicking on the submit button. I have been googling for literally months and tried many things (nothing works), and I can't find a tutorial helps me doing what I want. I have been looking at: django forms django filter package django rest framework I think that django forms does not do what I need. Django filter package getting started tutorial is impenetrable for a beginner. Finally in django rest framework, many tutorial describe only how to work with the API interface, but nobody finishes by creating a dynamic filter. Can you point me to a tutorial, video or webpage that can help me? -
Using opencv to live videostream in django from android camera
hello everyone i'm using python opencv to live stream in django. Well i don't have a webcame how can i use a androidphone camera to live stream in the page. my views.py: def get_frame(): camera =cv2.VideoCapture(0) while True: _, img = camera.read() imgencode=cv2.imencode('.jpg',img)[1] stringData=imgencode.tostring() yield (b'--frame\r\n'b'Content-Type: text/plain\r\n\r\n'+stringData+b'\r\n') del(camera) def indexscreen(request): try: template = "screens.html" return render(request,template) except HttpResponseServerError: print("error") @gzip.gzip_page def dynamic_stream(request,stream_path="video"): try : return StreamingHttpResponse(get_frame(),content_type="multipart/x-mixed-replace;boundary=frame") except : return "error" my urls.py: re_path(r'^(?P<stream_path>(.*?))/$',views.dynamic_stream,name="videostream"), re_path(r'^stream/$',views.indexscreen), as i go into the stream page it just returnes a blank page its not givine any error but neither its gives anything. is there something wrong in the code? -
Django Dynamic filter over database view(virtual table)
How to query on virtual table(DataBase view) in django. there are 4 tables and i use UNION on all the certain fields. there are two field which are common in all 4 tables. what have i done so far- 1) created a migration file for this DB view CREATE VIEW `my_db_view` AS select * from table1 UNION select * from table2 .... 2) created a django class to map to this view class MyDBView(models.Model): # fields.... class Meta: managed = False 3) Quering on this model. MyDBView.objects.filter(field1=val1, field2=val2) now this is causing some performance issue as i’m filtering on db view after doing union operation. is there any way that I can dynamically pass these two fields to db view migration? using WHERE over the UNION instead of the tables, we degrade the performance. MySQL will create a temporary table containing the UNION, then query it over the WHERE clause. that we want to avoid. what i want something similar to below CREATE VIEW `my_db_view` AS select * from table1 where field1=val1, field2=val2 UNION select * from table2 where field1=val1, field2=val2 .... and pass the value of field1 and field2 from the django controller dynamically. (like mentioned in 3rd step … -
django rest framework - username field not rendering in browsable api html form
the django rest framework is not displaying username field in my browsable api html form but when i comment down the username in below code it is showing username field in my browsable api html form. I am new to django so anyone can please help me here from rest_framework import serializers from rest_framework.serializers import HyperlinkedIdentityField from .models import Note class NoteSerializer(serializers.ModelSerializer): url = HyperlinkedIdentityField(view_name='note-detail', lookup_field='pk') #username = serializers.StringRelatedField(many=False) class Meta: model = Note fields = ['url', 'id', 'username', 'note_text', 'created_date', 'updated_date'] -
question : Object of type 'datetime' is not JSON serializable
'facing this issue file quering data from database , i m not using Serializer' ''' using cursor in raw query on manager as u see''' its my view.py @login_required def index(request): if not request.user.is_superuser: raise(404) customers = Customer.objects.Customer_List() context = {'customers': json.dumps(customers)} return JsonResponse(context=context, safe=False) TypeError at /customers/ Object of type 'datetime' is not JSON serializable and here is my model.py class CustomerListManager(models.Manager): def Customer_List(self): from django.db import connection with connection.cursor() as cursor: cursor.execute(""" select customer_id ,last_30_days-perivous_30_days pace ,first_name ,last_name ,company ,tags ,date_created ,latest_order_date ,first_order_date ,customer_group ,store_type ,assigned_to ,total_orders ,days_active ,ofa ,ofaa ,total_spent ,average_order_value ,status from ( select customer_id ,last_60_days-last_30_days perivous_30_days ,last_30_days ,first_name ,last_name ,company ,tags ,date_created ,latest_order_date ,first_order_date ,customer_group ,store_type ,assigned_to ,total_orders ,days_active ,ofa ,ofaa ,total_spent ,average_order_value ,status from (select c.customer_id ,c.first_name ,c.last_name ,c.company ,c.tags ,c.date_created ,max(s.date_created) latest_order_date ,min(s.date_created) first_order_date ,g.name as customer_group ,c.store_type ,a.username assigned_to ,(select count(s1.sale_id) from sales_sale s1 where s1.customer_id =c.customer_id) total_orders --,max(s.date_created) - min(s.date_created) days_active ,( select max(s.date_created) - min(s.date_created) from sales_sale s where c.customer_id=s.customer_id ) days_active ,(select (max(s.date_created) - min(s.date_created))/count(s.sale_id) OFA from sales_sale s where s.customer_id =c.customer_id) ofa ,(select (current_date - max(s.date_created))- ( (max(s.date_created) - min(s.date_created))/count(s.sale_id) ) OFA_threshold from sales_sale s where s.customer_id =c.customer_id) ofaa ,(select sum(s1.total_inc_tax) total_spent from sales_sale s1 where s1.customer_id =c.customer_id … -
Image won't load from react app to Django server
I just started working with Django and I am trying to integrate it with my react app. I currently have everything working (set the TEMPLATES [DIRS:] to the folder containing html file in React project, and did the same for STATICFILES_DIRS), and the website is showing up properly styled and everything when I run it on the Django server, but for some reason just the images are not loading (which are stored in the public folder of my react-app). Here is an image of my directory: Let me know if any additional images/descriptions would help. -
Best practice to config the dynamically generated file
I made the file like this in views.py. csvDir = 'exportedCsv/' file_path = csvDir + 'test.csv' df.to_csv(path_or_buf=file_path,sep=',',float_format='%.2f',index=False,decimal=",",encoding='utf_8_sig') Dynamically generate file and path the filepath to html. Now there is my file in /exportedCsv/test.csv However I have no way to access this from html. My idea is basiclly wrong??? What should I do when I want to make csv file and let the user download it?? -
web hosting with python Django, Bokeh
I want to provide web application that provides data visualization. To achieve this, i use python Django and python Bokeh library to data visualization. And i tried to operate the server through pythonanywhere beginner account. But in bash, i got a response that "No module named 'bokeh'". So i entered the command "pip install bokeh". As a result, i got a response "ERROR: Could not install packages due to an EnvironmentError: [Errno 122] Disk quota exceeded". I think the reason for that response is that the private file storage provided by Pythonanywhere is 512MB in beginner account. Do you think I'm right? So what kind of web hosting service would help my application? thank you for reading it. (and sorry for my poor English.) -
How to make fields in a model unique to particular row or object in django?
class Question(models.Model): question = models.TextField() option1 = models.CharField(max_length = 20, null = False) option2 = models.CharField(max_length = 20, null = False) option3 = models.CharField(max_length = 20, null = False) option4 = models.CharField(max_length = 20, null = False) How to make all options to question should be different and unique? How to make all options of one Question object unique and different? option1 should not match with option2, option3, option4 of the same question. I have created a form to create a questions. -
How to filter price range from high to low and vice versa in django
Basically I am developing an eCommerce site where there is list of products in product listing page. And i need to show the products according to price range from high to low and vice versa. -
HTML5 player shows on webpage but, mp3 sound not playing
I'm new to programming, I'm trying to put up a mp3 file and player on a django web page the player is showing but, the song is not playing. **models.py** from django.db import models from django.contrib.auth.models import User class Song(models.Model): name = models.CharField(max_length=125) audio_file = models.FileField('media/') **audio.html** <!DOCTYPE html> <html> <body> <audio controls> <source src="JesusChrist.mp3" type="audio/mpeg"> Your browser does not support the audio element. </audio> </body> </html> **media folder** JesusChrist.mp3 **Settings.py** STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'firegod/static/media') ] STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'media') STATIC_URL = '/media/' -
ImportError: cannot import name 'render_to_response' from 'django.shortcuts'
from django.shortcuts import render_to_response ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (C:\Users\gtdra\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py) I have this error when i migrate django-chroniker into my django project , i read that render_to_response have been remove since Django 2.0 , how can i fix this error ?? thanks you -
Why to use signals in Django?
I referred to many documentation and many articles using signals in Django. but I could not understand this concept. which purpose using signals in Django? How it is work? Can please explain the signal concept and how to use it in the Django code. -
Case insensitive URLS in Django 3.0?
Is there a way to have case insensitive URLS with Django 2.0 and up syntax? For example path('profile/<str:username>/add/',views.AddFriendRedirect.as_view(),name='add_friend'), If I did profile/USERNAME, when the username is username in all lowercase, how can I make it so that it is case insensitive? So that even uSErnAmE is valid -
Django +2 ImportError: cannot import model
Hi have been working with Django and i want to have relations bettwen model i have the following structure on posts/models.py from django.db import models class Post(models.Model): (SKIP ATTRIBUTES) and then on comments/model.py from django.db import models from posts.models import Post class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') In a nutshell im trying to import posts model into comment model and i get the error that cannot import name 'Post' from 'posts.models , how should import posts model to avoid this issue ? from posts.models import Post ImportError: cannot import name 'Post' from 'posts.models -
Requiring a photo during user registration without using a custom user model in Django
So, I'm creating a dating app from scratch in Django. First project, and new to programming. I want to force a user to upload a photo during registration. I tried doing this with only extending the user model, but I looked around and tried different things but couldn't figure it out so I decided to create a custom user model. However, I am running into problems left and right, and I think that I am over contemplating things by adding a custom user model. How can I force a user to upload a photo during registration by extending the normal User model? Edit: If I am wrong, and it is indeed easier and better to keep the custom user model, please let me know and why. Models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser,BaseUserManager, User class ProfileManager(BaseUserManager): def create_user(self, username, email,description,photo, password=None): if not email: raise ValueError("You must creat an email") if not username: raise ValueError("You must create a username!") if not description: raise ValueError("You must write a description") if not photo: raise ValueError("You must upload a photo") user = self.model( email=self.normalize_email(email), username = username, description= description, photo= photo, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, username, email,description,photo, password): … -
Top-level StreamBlock within StreamField doesn't render in template
I'm attempting to use a StreamBlock like the last snippet in the section of the docs here, as the only argument to a StreamField. It's working perfectly in the Wagtail admin, but when trying to render in the template nothing appears. I tried using the default template and just include_block, but nothing is rendered. I also tried using a custom template and include_block, and the custom template is hit, but I haven't been able to render anything useful from there. I reverted to trying to use the default template in the following code. home/models.py: from django.db import models from wagtail.core.models import Page from wagtail.core.fields import StreamField from wagtail.admin.edit_handlers import StreamFieldPanel from home.blocks import HeroImageStreamBlock class HomePage(Page): hero_image = StreamField(HeroImageStreamBlock( block_counts={ 'hero_button': {'max_num': 1}, 'is_active': {'max_num': 1}, 'is_randomized': {'max_num': 1}, } ) , blank=True ) content_panels = Page.content_panels + [ StreamFieldPanel('hero_image'), ] home/blocks.py: from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock class HeroButtonBlock(blocks.StructBlock): button_text = blocks.CharBlock(required=False) button_page = blocks.PageChooserBlock(required=False) button_url = blocks.URLBlock(required=False) is_active = blocks.BooleanBlock(required=False, help_text="""When checked, this hero button is active. NOTE: Only the first active hero button will be displayed.""") class Meta: icon = "link" class HeroTextBlock(blocks.StructBlock): hero_text = blocks.CharBlock(required=False) is_active = blocks.BooleanBlock(required=False, help_text="""When checked, this hero text is … -
ModelForm with foreignkey field is not being saved
I'm trying to save a ModelForm with foreignkey field from another model. But somehow the data is not being saved. The primary key of the foreignkey field in the Problem models is from Biodata models index.html form is loaded with session['patient'] value that should be the value of the foreignkey in the Problem models upon creation of new item. Upon submitting the form, it says the new item is successfully added, but at the backend, it wasn't saved at all. Here's the code : models.py class Biodata(models.Model): lastname = models.CharField(max_length=50) firstname = models.CharField(max_length=50) dob = models.DateField() sex = models.CharField(max_length=10) address = models.CharField(max_length=100,blank=True) suburb = models.CharField(max_length=40,blank=True) state = models.CharField(max_length=50,blank=True) postcode = models.CharField(max_length=6,blank=True) def __str__(self): return self.firstname + " " + self.lastname class Problems(models.Model): biodata = models.ForeignKey(Biodata, on_delete = models.CASCADE, default=None) problem = models.CharField(max_length=200) notes = models.CharField(max_length=300) status = models.CharField(max_length=30) date = models.CharField(max_length=10) def __str__(self): return self.problem views.py def problem_add(request): patient_id = request.session['patient'] form = ProblemForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.Biodata = Biodata.objects.get(id=patient_id) instance.save messages.success(request,('Problem added')) return redirect('/crud/index/') else : messages.success(request,('There is error in the form')) return redirect('/crud/index/') forms.py class ProblemForm(forms.ModelForm): STATUS = [('S','Stable'),('U','Unstable'),('I','Inactive'),('O','Ongoing Dx.')] problem = forms.CharField(label='',max_length=50, widget=forms.TextInput(attrs={'placeholder':'Problem'})) notes = forms.CharField(label='', widget=forms.Textarea(attrs={'rows':4,'placeholder':'Notes'})) status = forms.ChoiceField(label='', widget=forms.Select(attrs={'placeholder':'Status'}), choices=STATUS) date = forms.DateField(label='', … -
Django Admin and Cloudinary : ValueError: Must supply api_key
Objective: to be able to upload files from the Django Admin, to Cloudinary I pip installed cloudinary, but don't know where to import the chunk of code below. I know how to create model class, which then in the admin, i can create instances i.e blog class, i can create blog articles, but where would I go into to handle the logic for uploading? According to the docs, I need to add this config script, in any HTTP method, but from what I know, Django Admin handles it automatically. But I know this can be done because i've checked out their tutorial and i was able to upload images from Django Admin cloudinary.config( cloud_name=os.environ.get('projname'), api_key=os.environ.get('123'), api_secret=os.environ.get('abc'), secure=True ) models.py class Media(models.Model): create_time = models.DateTimeField(auto_now_add=True) title = models.CharField("Title (optional)", max_length=200, blank=True) image = CloudinaryField('image') # Points to a Cloudinary image def __str__(self): return self.title I'm using serializer to grab endpoints in json via React with DjangoRESTframework but this shouldn't matter for now -
Autofill blank required fields in Django admin before save and before validation
I have a model 'Production' and a model 'Show'. 'Production' has a foreign key linking it to a specific show. In admin, the user has the option to fill out the title of the production. This is currently a required field. However, if the user leaves it blank I want to be able to fill it in automatically based on the title of the foreignkey Show. I have written a function that overrides save and makes this happen. However, it cannot run because if the user leaves the field blank, Django admin tells them "This field is required" before allowing the save function to run. How can I prevent this? I do not want to make the fields null=True,blank=True in the Model itself because I still want this field to always be filled. Code below (bits removed for clarity): @admin.register(Production) class ProductionAdmin(admin.ModelAdmin): inlines = [ RoleInLine, CreativeRoleInLine, ] def has_change_permission(self, request, obj=None): if request.user.is_superuser: return True if obj is not None and obj.lead_producer != request.user.profile.creative: return False return True def save_model(self, request, obj, form, change): if not obj.title: obj.title = obj.show.title + " - " + obj.theatre.city.name + " Production" obj.save() class Production(models.Model): """Model definition for MODELNAME.""" show = models.ForeignKey(Show, … -
Allowing a user to only be able to edit their own info with a custom model in Django error
I am new to development and Django. This is my first project from scratch. I decided to go with a custom user model so I could customize the registration page and require users to submit a photo during registration. I am making a tinder clone and I wanted to make sure users submitted a photo. However, as result of using a custom model, things have been more difficult. Right now, I am attempting to only allow the current logged in user to be able to edit their own info, not anyone else's. The only way I know how to do this is to create a separate model that has a foreign key to my Profile model, 'owner', and compare the two ID's when the current user try's to edit someone else's profile. However, I am having trouble adding that model to my custom model. Here is the error I am getting which I don't understand even though I tried looking it up...; django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: dating_app.Profile.owner: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. models.py from django.db import models from django.contrib.auth.models … -
Failure on git push, file not found /tmp/build/static
I am having trouble with a git push to update my Heroku app. At the end of the error log this is what comes up: remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 105, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 131, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 23, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 315, in listdir remote: for entry in os.scandir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_8e6aeb15085bd120f62a7e71199f0368/static' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. I have tried updating my gitignore, my settings static files location, and running git pull heroku master. The app works perfectly well on localhost. All help is appreciated! -
'ContactView' object has no attribute 'request'
Thanks for entertaining what is hopefully an easy fix. I have a website with a "Contact Us" page where the user can enter Name etc. and send a message. Along with this view, I collect the IP data and use MaxMind to store the geographic data of the user. I have a view that calls a function that grabs the IP and pings MaxMind to get the data. My view looks like this: class ContactView(CreateView): model = Contact template_name = "contact/contact.jinja" form_class = ContactForm success_url = "/" def __init__(self, *args, **kwargs): self.initial['ip_information'] = get_ip_data(self.request) #<< Call the IP function def form_valid(self, form): # Update Slack: first_name = form.data["first_name"] last_name = form.data["last_name"] email = form.data["email"] phone = form.data["phone"] ip_information = form.data["ip_information"] # << this is where the IP Data is stored [ ... ] return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["service_list"] = Service.objects.all().order_by("rank") context["county_list"] = County.objects.all().order_by("county") return context The function being called, which requires a request object, looks like this: def get_ip_data(request): # Get IP information # MaxMind Database for geoIP client = geoip2.webservice.Client(#####, "XXXXXXXXXXXXXXXX") x_forwarded_for = request.META.get("HTTP_X_FORWARDED_FOR") if x_forwarded_for: client_ip = x_forwarded_for.split(",")[0] else: client_ip = request.META.get("REMOTE_ADDR") ip_data = client.city(client_ip) return ip_data Unfortunately, ContactView(CreateView) does not seem to give … -
stripe-python, should it be async?
I need to integrate Stripe into a Django project and I noticed that there's a stripe-python package. This runs entirely synchronously though. Is it a bad idea to make these types of call from the main web server? Since it makes external calls, this presumably means the webserver will be blocked while we wait for a response, which seems bad. So, should I be running this from something like Celery? Or is it fine to run on the main thread? Anyone have experience with this? -
Performance Issue when saves request POST using modelformset_factory
I'm working on a project where i'm required to display 50 form per page related to specific model. I use modelformset_factory to display and edit multiple instance at once, but i faced a performance issue while saving around 50 records(50 form of same model). it makes more than 350 queries in order to save the data, I used django-debug-toolbar. to check the performance and unfortunately each record/form makes multiple queries. click to view the result from django-debug-toolbar here's snippet of the code: def offerScoring(request, offid, page): formset = modelformset_factory(Enroll, extra=0, form=Scoring) if request.POST: form = formset(data=request.POST) if form.is_valid(): form.save() messages.add_message(request, messages.INFO, "Scores are saved updated successfully") return redirect(reverse('offerScoring', kwargs={'offid': offid, 'page': page})) else: messages.add_message(request, messages.INFO, "Scores were NOT updated ") AllEnrolled = Enroll.objects.select_related('StudentID','OfferingID','OfferingID__Course').filter(OfferingID=offid) paginator = Paginator(AllEnrolled, 50) Enrolled = paginator.get_page(page) Enrolled.ordered = True if request.method == "GET": form = formset(queryset=Enrolled) return render(request, template_name='Course/templates/offerScoring.html', context={'form': form, 'Enrolled': Enrolled}) Any ideas on how to reduce the number of queries when the form is submitted?