Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to retrieve colors all variants of a product are available in, alot of queries are made. Optimization possible?
Here's my models: https://pastebin.com/qCMypxwz the query executed creates many duplicated queries according to the debug tool. Is there a way to optimize this? Fairly new to django so I am not sure if I am doing the querying right. What I want to do is get the details of the first variant of a product but the colors key of the dictionary must have all the colors the variants are available in. My view: productList = Products.objects.prefetch_related('category', 'variants_set__color_id', 'variants_set__image') for productName in productList: products = dict() prod_id = productName.variants_set.all()[0].id products['id'] = prod_id products['category'] = productName.category.category_name products['prod_name'] = productName.prod_name products['brand'] = productName.brand prod_colors = productName.variants_set.all().values_list('color_id__name', flat=True) #THIS QUERY LOOKS LIKE THE PROBLEM prod_images = list(productName.variants_set.all()[0].image.all()) image_list = list() for image in prod_images: image_list.append(image.image_url) products['image'] = image_list products['colors'] = list(prod_colors) price = productName.variants_set.all()[0].price products['price'] = price createdAt = productName.variants_set.all()[0].createdAt products['createdAt'] = createdAt productListDict.append(products) -
How to add the form to many to many field in Django?
caffeinated_form = CaffeinatedForm() if request.method == 'POST': caffeinated_form = CaffeinatedForm(request.POST) if caffeinated_form.is_valid(): instance = caffeinated_form.save(commit=False) instance.user = request.user instance.item = item instance.hot_or_cold = caffeinated_form.cleaned_data['hot_or_cold'] instance.hot_cold = caffeinated_form.cleaned_data['hot_or_cold'] order = Order.objects.create(user=request.user, ordered=False) order.items.add(instance) instance.save() I want to add my caffeinated_form to ManyToMany field called items. -
Automatically add HStore extension Django
I'm developing on a django app that has a directory like so: App: manage.py --App1: -models.py -etc. --App2: -models.py -etc. --App3: -models.py -etc. Many of them use HStore field(s) in the model definition file and when I go to migrate them each time I have to do this sequence: run python manage.py makemigrations {app 1,2,3 and so on here} Add HStoreExtension() to operations=[] in the first migration file like: 0001_initial.py It becomes tedious to do that when there's a ton of migrations for one app. I realize there may be better ways to structure the application but that's how it was built. Is there any way to avoid having to "makemigrations" then add the hstore extension to the operations each time? I don't want to create a lot of manual work for others to spin up the app. I know there are similar questions where the solution is to run a query to the database to add the extension. In this multiple subdirectory apps situation would I just include that in the top level application init file? -
Is there any Solution for this Login syntax>?
Ive this Django Login and Registration form but the registration form is fetching in database auth_user but not in helloworld_register This is my Registration code def Register(request): if request.method =='POST': username=request.POST['username'] email=request.POST['email'] first_name=request.POST['first_name'] last_name=request.POST['last_name'] password1=request.POST['password1'] password2=request.POST['password2'] if User.objects.filter(email=email).exists(): messages.info(request, 'uh oh..:( This Email is Already Taken ') print('emailtaken') return redirect('/Register') elif User.objects.filter(first_name=first_name).exists(): messages.info(request, 'uh oh..:( This Name is Already Taken ') print('Name taken') return redirect('/Register') user=User.objects.create_user(username=username, email=email,first_name=first_name,last_name=last_name,password=password1) user.save(); messages.info(request, 'Registration complete Login to continue ..:)') print('user created') return redirect('/LOGIN') return render(request, 'Register.html') And this is my Login Code def LOGIN(request): if request.method=='POST': email=request.POST['email'] password1=request.POST['password1'] user=auth.authenticate(email=email,password1=password1) #user.save(); if user is not None: auth.LOGIN(request,user) return redirect('LOGIN') else: messages.info(request, 'mmm :( Invalid Credentials ') return redirect('LOGIN') Even though if i try Logging in with registered credentilals im unable to login -
How can I paginate list of dictionaries in django
I am working on Django pagination and trying to paginate my data which is in the form of dictionaries inside a list, I tried function based approach as per documentation class MyUserData(TemplateView): template_name = "myuserdata.html" form = "userform" def listing(request): contact_list = Contact.objects.all() paginator = Paginator(contact_list, 25) # Show 25 contacts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) return render(request, 'list.html', {'page_obj': page_obj}) I am writing above function inside my class which is inheriting (TemplateView) now the problem is that it is reducing the number of results to 25 but when i click on next it doesn't show next page <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ page_obj.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">next</a> <a href="?page={{ page_obj.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> Flow is like this the user will come and enter the start date and end date and click on submit and get's his history of data and the issue is user gets all his history if he selects longer date range which I want to paginate this is how data is coming … -
Django AWS S3 some media images not showing up
The user uploaded images show up (ex: profile pics) but not my 'static' images (logos). They are both in the same bucket. (Folder -> profile-pics, Folder -> static-images). Heroku production urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py DEBUG = False MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME') AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None AWS_S3_REGION_NAME = 'us-west-1' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_S3_ADDRESSING_STYLE = "virtual" DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' some template. below isn't loading.. <img src="/media/signin_buttons/btn_google_signin_dark_normal_web.png"> but for example, user uploaded images load up from S3 {{ user.profile_pic.url }} pip list asgiref==3.5.2 boto3==1.25.2 botocore==1.28.2 certifi==2021.10.8 cffi==1.15.0 charset-normalizer==2.0.7 cryptography==36.0.0 defusedxml==0.7.1 dj-database-url==1.0.0 Django==3.2.15 django-allauth==0.46.0 django-cleanup==5.2.0 django-crispy-forms==1.12.0 django-heroku==0.3.1 django-storages==1.13.1 gunicorn==20.1.0 idna==3.3 jmespath==1.0.1 oauthlib==3.1.1 Pillow==8.3.2 psycopg2==2.9.5 pycparser==2.21 PyJWT==2.3.0 python-dateutil==2.8.2 python3-openid==3.2.0 pytz==2021.1 requests==2.26.0 requests-oauthlib==1.3.0 s3transfer==0.6.0 six==1.16.0 sqlparse==0.4.3 urllib3==1.26.12 whitenoise==6.2.0 -
How to make many to many query set
Here My Branch table and Store Table How many branch record available in store table and count. I'm try it but can't get it. class Branch(models.Model): # Branch Master status_type = ( ("a",'Active'), ("d",'Deactive'), ) name = models.CharField(max_length=100, unique=True) suffix = models.CharField(max_length=8, unique=True) Remark = models.CharField(max_length=200, null=True, blank=True) created_by = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) status = models.CharField(max_length=1, choices = status_type, default = 'a') def __str__(self): return self.name class Store(models.Model): status_type = ( ("y",'Yes'), ("n","No") ) branch = models.ManyToManyField(Branch) asset = models.ForeignKey(Asset,on_delete=models.CASCADE) asset_code = models.CharField(max_length=100, null=True, blank=True, unique = True) model = models.CharField(max_length=250) serial_no = models.CharField(max_length=200) vendor = models.ForeignKey(Vendor,on_delete=models.CASCADE) invoice_no = models.CharField(max_length=50) purchase_date = models.DateField() store_status = models.CharField(max_length=1, choices = status_type, default = "y", blank = True) store_date = models.DateTimeField(null = True, blank = True) assige = models.CharField(max_length=1, choices = status_type, default = "n", blank = True) assige_date = models.DateTimeField(null = True, blank = True) scrap = models.CharField(max_length=1, choices = status_type, default = "n", blank = True) scrap_date = models.DateTimeField(null = True, blank = True) created_by = models.ForeignKey(User, on_delete=models.CASCADE) create_at = models.DateTimeField(auto_now_add=True) update_at = models.DateTimeField(auto_now=True) Query get store object store_obj = Store.objects.get( id= 5) try to get count of branch record tempcount = Store.objects.filter( branch = … -
Django Nginx Reverse Proxy CSRF Cookie Not Set
The Setup Using docker compose, I have the following: Nginx Reverse Proxy <> Docker Django Application with React pages (:8000) In my Nginx Reverse Proxy, the configuration under conf.d is as follows: server { listen 80; server_name localhost; location / { proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header Cookie $http_cookie; proxy_pass http://frontend:8000; } } In my Django Application, I have a view that sets a CSRF token as follows in views.py: @method_decorator(ensure_csrf_cookie, name='dispatch')` class GetCSRFToken(APIView): ... And on my Django app's react pages, I use Axios to call: axios.get('http://localhost:8000/csrf_cookie').then(...) This gets my CSRF token and saves it as a cookie on the React page. The Problem Before deploying the nginx reverse proxy, while accessing the app via localhost:8000, CSRF token is set when I make the axios call to the above view and everything works. However, after deploying the nginx reverse proxy, while accessing the app via localhost, the CSRF token is not set when I call the above view. Another observation is that, with the nginx reverse proxy set up, if I visit localhost:8000 directly, and call axios from there, the CSRF token is set. It seems to be a issue with the … -
jQuery attr() Method add html tag
I have a search input tag, and I wanted to set a placeholder. In place holder I need to keep a magnify icon, how to do it in jquery? below is the code I tried $('.gridjs-head .gridjs-search .gridjs-search-input').attr("placeholder", "<i class='mdi mdi-magnify'></i>&nbsp;Search...") I needed to use this path because I'm using grid.js to render table in my django project -
Missing double authentication with User Models in Django
I want to make my first student's project in Django and I am trying to make a management system that has two authentications from one site. I want to have a staff sign-up form and a customer sign-up form if it's possible. I made one AppBaseUser Model, which inherits AbstractUser, and two other models - one for customers, and one for staff, witch will I make it in forms in the template. They inherit AppBaseUser and extend it. Everything is working, but I don't have a double password authentication and the password is in plain text not in a hash in DB. class AppBaseUser(AbstractUser): MIN_LEN_FIRST_NAME = 2 MAX_LEN_FIRST_NAME = 40 MIN_LEN_LAST_NAME = 2 MAX_LEN_LAST_NAME = 40 first_name = models.CharField( max_length=MAX_LEN_FIRST_NAME, null=False, blank=False, validators=[ validators.MinLengthValidator(MIN_LEN_FIRST_NAME), validate_only_letters, ] ) last_name = models.CharField( max_length=MAX_LEN_LAST_NAME, null=False, blank=False, validators=[ validators.MinLengthValidator(MIN_LEN_LAST_NAME), validate_only_letters, ] ) email = models.EmailField( unique=True, null=False, blank=False, ) class AppCustomerUser(AppBaseUser): MAX_LEN_PHONE_NUMBER = len('+359-888-88-88-88') MIN_LEN_PHONE_NUMBER = len('+359888888888') # TODO Make it with enumerate! GENDER_CHOICES = [('Male', 'Male'), ('Female', 'Female'), ('Do not show', 'Do not show'),] MAX_LEN_GENDER = len('Do not show') HAIR_TYPES_CHOICES = [ ('Straight hair', 'Straight hair'), ('Wavy hair', 'Wavy hair'), ('Curly hair', 'Curly hair'), ('Kinky hair', 'Kinky hair'), ('I am not sure', 'I … -
DRF Foreign Key from reverse lookup
Using django rest framework, I'm after this output: slides = [ { "id": "1", "sentence": "The person is in the house.", "sentence-type": "simple", "clauses": { "type": "independent clause", "description": "An independent clause has a subject and a verb. An independent clause expresses a complete thought." }, "wordlist": [ { "pos": "article", "pos_description": "An article modifies a noun like an adjective does and are considered necessary to provide proper syntax to a sentence.", "colour": "21 128 61", "word": "the" }, Here are my models: class Sentence(models.Model): sentence = models.CharField(max_length=500) class Word(models.Model): word = models.CharField(max_length=255) part_of_sentence = models.ForeignKey(PartOfSentence, related_name='pos_word', on_delete=models.CASCADE, blank=True, null=True) words = models.ForeignKey(Sentence, related_name='sentence_word', on_delete=models.CASCADE, blank=True, null=True) class PartOfSentence(models.Model): part_of_sentence = models.CharField(max_length=20) pos_colour = models.CharField(max_length=20) pos_description = models.CharField(max_length=512) class Clause(models.Model): TYPES = ( ('NONE', 'None'), ('INDEPENDENT', 'Independent'), ('DEPENDENT', 'Dependent'), ('COORDINATING_CONJUNCTION', 'Coordinating-Conjunction'), ('SUBORDINATING_CONJUNCTION', 'Subordinating-Conjunction') ) clause = models.CharField(choices=TYPES, max_length=40, default='None') And the serializer: class SentenceSerializer(serializers.ModelSerializer): clause = ClauseSerializer() words = serializers.SlugRelatedField( source='sentence_word', slug_field='word', many=True, read_only=True ) class Meta: model = Sentence fields = ('sentence', 'sentence_type', 'clause', 'words', 'part_of_sentence') Which results in: [ { "sentence": "the person is in the house", "sentence_type": "SIMPLE", "clause": { "clause": "INDEPENDENT" }, "words": [ "the", "person", "is" ] } ] Which isn't perfect, i.e. the keys … -
Convert Jpg image to heice in python
Hey folks i need to Convert Jpg image to heic in python, any lead will be appreciateble I try pillow but not supporting extension. It showing error of unknown file extension: .heic -
User objects has no attribute profile
Can anybody explain me why am in getting this error. I have two models User and Profile with OnetoOne relations. models.py class User(AbstractBaseUser): phone_number = models.IntegerField(unique=True, verbose_name='phone number') email = models.EmailField() class Profile(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) first_name = models.CharField(max_length=25) last_name = models.CharField(max_length=25) and here's the serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields =["first_name", "last_name"] class UserSerializer(serializers.ModelSerializer): profile = ProfileSerializer() class Meta: model = User fields = ["id", "phone_number", "email", "profile",] Views.py class UserDetailsView(generics.RetrieveUpdateAPIView): serializer_class = UserSerializer def get_queryset(self): return User.objects.filter(pk=self.kwargs['pk']) -
Employee Leave types conditions in DJango rest framework
I'm working on Hrms application in django rest framework. I've created employee details module now next part is leave management system. Actually my company policy has different leave policies like cl,sl,ml,compo off, and permissions.I'm unable to understand how to make the logic for it and and don't know where to write the logic in serializers or views? Since a newbee i find somewhat difficult. Also when a employee apply a leave it should be requested to T.L. and then should be visible to hr and manager. T.l would give permission and it all should be in application and also in email process. How to make request and approval in rest api also how to send mail using django rest api? Can anyone guide me. If employee select Cl, he got total 12 cl and he can avail monthly once and cl can carryforward upto 3 leaves after that it will expire, then sl means quarterly 2 available, then half day leaves, what will be the logic here and how should i progress? class LeaveType(models.Model): Leave_type = ( ('CL', 'Casual Leave'), ('SL', 'Sick Leave'), ('ML', 'Medical Leave'), ('Comp Off', 'Compensation'), ('L.O.P', 'Loss of Pay') ) Leave_Choice = ( ('Full Day', 'Full … -
docker forgets to install dependency from requirements file
I am trying to troubleshoot a tutorial on udemy on Windows 10 but when I run my containers the django app does not seem to want to load celery as a module. I tried a few different versions but still get the same error message. The celery worker seems fine. Does anyone here see my issue and help me understand what is happening? The tutorial's original code is here on his github but most of my code is a straight copy from him. Here is a link to the repo of what I have covered so far. error message: postgres | 2022-11-14 03:17:27.850 UTC [1] LOG: database system is ready to accept connections flower | PostgreSQL is ready!!!!.....:-) celery_worker | PostgreSQL is ready!!!!.....:-) django-api | PostgreSQL is ready!!!!.....:-) django-api | Traceback (most recent call last): django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 354, in run_from_argv django-api | self.execute(*args, **cmd_options) django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 398, in execute django-api | output = self.handle(*args, **options) django-api | File "/usr/local/lib/python3.9/site-packages/django/core/management/base.py", line 86, in wrapped django-api | saved_locale = translation.get_language() django-api | File "/usr/local/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 254, in get_language django-api | return _trans.get_language() django-api | File "/usr/local/lib/python3.9/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ django-api | if settings.USE_I18N: django-api | … -
django rest_framework with basic auth, how to consume api with django
I created an API with basic authentication and I was wondering how can i consume it with an username and password this is my endpoint http://127.0.0.1:8000/Clerk/ I try to consume it by def display_clerk_view(request): displaytable = requests.get('http://127.0.0.1:8000/Clerk/') jsonobj = displaytable.json() return render(request, 'clearance/clerk_view.html', {"ClerkClearanceItems": jsonobj}) this block of code and it's giving me error Unauthorized: /Clerk/ I'm planning to use django all-auth with google as provider but for now I want to know how consuming api with authentication works -
django summernote to aws3 connection problem
django summernote can be uploaded and shown locally, but if i connect summernote aws s3, it will be uploaded, but the image cannot be imported. Does anyone know? -
Filter dropdown in django forms
In forms, I am trying to filter marketplace drop down field that belong to the logged in user based on its group. Its listing all the dropdown field items. I tried below but I think something is wrong with the filter part. class InfringementForm(ModelForm): def __init__(self, user, *args, **kwargs): super(InfringementForm,self).__init__(*args, **kwargs) self.fields['marketplace'].queryset = Marketplace.objects.filter(groups__user=self.user) class Meta: model = Infringement class Meta: ordering = ['-updated', '-created'] def __str__(self): return self.name fields = ['name', 'link', 'infringer', 'player', 'remove', 'status', 'screenshot','marketplace'] models.py class Marketplace (models.Model): name = models.CharField(max_length=100) updated = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) groups = models.ForeignKey(Group, on_delete=models.CASCADE,default=1) -
django deply support LANGUAGES (local vs host)
I was programming my Django site normally .. and I set some data in the database in the Arabic language it was work find in my locl pc useing pycharm editer On my local pc its looks like this: photo 1 and then I buy sharing host on Namecheap and deploy my site after entering some data into my database in the Arabic language I find it like this! photo 2 It looks like the system Namecheap does not support the language or what! -
Control the order of the database columns before proceeding to makemigrations in Django
Is there a way to control the database column ordering, directly within a Django model? I know I can manually edit the migration file after makemigrations to adapt it to my needs, but is there a way to do so, prior to the makemigrations call? This can be especially useful when initializing the database. -
I'm building a expense tracker app following a guide and the Pipenv shell command will not work!!! Python 3.11, Windows 10
As I've said I'm building a expense tracker web app. This is for my university course. I found a video series that builds one step by step. I wanted to follow this video to get a nice walk through to help me understand how to approach this task. https://www.youtube.com/watch?v=tYPx-fcICts&list=PLx-q4INfd95G-wrEjKDAcTB1K-8n1sIiz&index=2 (Link for the video for context). Anyways the video wants you to use Django and to install it I must first create a virtual environment using pipenv. I installed it and everything checked to make sure it was actually installed. But when i went to create the enviorment in the folder of the project using the "pipenv shell" command it give me an error which is "PermissionError: [WinError 5] Access is denied". For the life of me I cannot figure this out. I've been at it for hours. Please i need help on how to get this fixed as this video series is perfect for my project. I'm using python 3.11 and I'm on windows 10. I also followed the steps in the video exactly so that should give you some context. Honestly I just started coding so i really don't know what to even try. I've tried finding answers online … -
I get this error :[Errno 2] No such file or directory: 'ffprobe'
I have installed ffmpeg as a dependency in my conda env but still get this error. Can anyone help pls ? -
Create custom discord user django allauth
How can I add an element to user in the database, like when a user signs up with discord OAuth2 the database saves so little information. I want to add multiple fields to the User module in the db, but I don't want to give the user the option to input this info, like I don't want the user to give me his discord id, I want to get it from discord directly and save it to the user db Currently allauth only saves creation date, last login date, first name, username, email. I want to a lot more, I want to add discord access token, id, and much more, is there a way to add these fields to the User directly instead of creating a new module that copies User and adds the id and other fields? I have searched a lot but I couldn't really figure a way out -
React and Django: CSRF Token is not set on production, and especially for create method
on development, the csrf cookie used to be set normally if it is not in available in application tab in dev tool, however on production, whenever i try to create a new post, it tells me " CSRF Failed: CSRF token from the 'X-Csrftoken' HTTP header has incorrect length." however, the plot-twist here, is that with other post requests such as when you login, or signup, it works perfectly and fine, so i figured it seems to be a problem with create method in django (BUT with login , even though login works perfectly fine, and that i am logged in using session based authentication, it seem like session_id and csrf are invisible in application tab? I assume it is because the website is on production and for security reasons, it wont show the session_id there. However, whenever i try to look at network tab after i try to create a post and fail, it looks like x-csrftoken is undefined but, there is another key called cookie which includes both csrftoken and session_id please note that this only occur on production, i never faced such issue on development server, and look at settings.py code after the view code for more … -
How to exclude null values in queryset for charts.js
I am trying to get the count of infringements in the market place for the logged in user. The logged user is part of a group. The problem I am having is its still counting values for marketplace items that doesn't belong to the group. It adds 0 in the queryset breaking my charts, u = request.user.groups.all()[0].id mar_count = > Marketplace.objects.annotate(infringement_count=Count('infringement', filter=Q(groups=u))) The result 'Ebay','Amazon','Facebook','Wallmart', '0','0','0','0','1','1','1','1', I should be getting 'Ebay','Amazon','Facebook','Wallmart', '1','1','1','1', How do I exclude counting the marketplace when its no part of the logged in users group? I am new. Thanks