Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django form class widget with drop down populated from database
I am using Django 3.2 and I am trying to create a form class that has a field (category) populated from a database model. This is a snippet of my form class: class ArticleForm(forms.ModelForm): # ... class Meta: model = Article fields = ['title', 'teaser', 'category', 'guest_author','content', 'tags', 'is_published'] categories = [] #forms.ModelChoiceField(queryset=ArticleCategory.objects.all().order_by('name')) widgets = { 'guest_author': forms.TextInput(attrs={'class': 'form-control input'}), 'title': forms.TextInput(attrs={'class': 'form-control input'}), 'teaser': forms.Textarea(attrs={'class': 'form-control input'}), 'category': forms.Select(choices=categories, attrs={'class': 'form-control input'}), 'content': forms.Textarea(attrs={'class': 'form-control input'}), 'tags': forms.TextInput(attrs={'class': 'form-control input'}), 'is_published': forms.CheckboxInput(attrs={'class': 'form-control-input'}) } I found out if I created the field as an instance attrribute like this: category = forms.ModelChoiceField(queryset=ArticleCategory.objects.all().order_by('name')) Then I am able to use the form (with no errors raised). But I want to be able to specify the widget to use for that field, using the above declaration - is there anyway to do this - or am I restricted to simply declaring the field as an instance variable of the form? -
javascript passed string itself instead of index lenght, whats wrong with my code?
I am trying to pass the item id and item id index when a button is clicked. But the code is throwing different result. For your reference, I have attached expected result and obtained result. Any help will be highly appreciated if(localStorage.getItem('cart')==null){ var cart={}; } else{ cart = JSON.parse(localStorage.getItem('cart')); } $(document).on('click','.btn-cart',function(c){ c.preventDefault(); console.log("Add to Cart Button clicked"); var item_id = this.id.toString(); console.log(item_id); if(cart[item_id]!=undefined){ cart[item_id] =cart[item_id] + 1 } else{ cart[item_id]= 1 } console.log(cart); localStorage.setItem('cart',JSON.stringify(cart)); console.log(Object.keys(cart).length); }); I am expecting this: But it happened this: -
How to implement the function, I forgot the password and send an email to change it in Django
I would like to implement a "forgot password" function, and at that point an email would be sent so that she would be able to change her own password. I have not found documentation on this. Someone could show me a way. Thanks for listening! -
Cannot install psycopg2 with Github Actions due to distutils
I am trying to setup CI/CD for my Django project on Github. I deploy it to Heroku, which requires django-heroku package, which in turn depends on the psycopg2 package. When I'm trying to run this workflow: build-django: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 with: python-version: '3.10' - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run Django Tests run: | python manage.py test I get a huge error log which culminates in this: Copying psycopg2.egg-info to /opt/hostedtoolcache/Python/3.10.1/x64/lib/python3.10/site-packages/psycopg2-2.9.2-py3.10.egg-info running install_scripts Traceback (most recent call last): <...> ModuleNotFoundError: No module named 'distutils.command.bdist_wininst' Everything checks out on my machine. Why would I get this message? The requirements.txt file is setuptools~=44.1.1 wheel~=0.37.1 django~=3.2.9 djangorestframework~=3.12.4 pip~=20.3.4 pytz~=2021.3 sqlparse~=0.4.2 asgiref~=3.4.1 h11~=0.12.0 attrs~=21.2.0 trio~=0.19.0 outcome~=1.1.0 sniffio~=1.2.0 sortedcontainers~=2.4.0 cffi~=1.15.0 idna~=3.3 six~=1.16.0 cryptography~=36.0.1 certifi~=2021.10.8 urllib3~=1.26.7 selenium~=4.1.0 pycparser~=2.21 wsproto~=1.0.0 gunicorn~=20.1.0 django-heroku -
Get the Entire Tree Data using Tree query sets and Querysets from Django
I was trying to get the data from all the tree query set and query set using django ORM and Django MPTT. The Hierarchy of the DB tables is as follows: T1 (MPTT Model) T2 (MPTT Model) T3 (Django Model) T4 (Django Model) T5 (Django Model) T6 (Django Model) I have two MPTT models from which I can get the tree Query sets using logged in user filter, however, for retrieving all the other tables data, need to evaluate from other django models. Is it Possible to get all the data in single Queryset Evaluation set so that it will reduce the load on the Request? The Required Data : { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 }, { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 }, { key1: t1.value1, key2: t2.value2, key3: t3.value1, key4: [t4.values_list], key5: [t5.values_list], key6: t6.value3 } -
reCaptcha Enterprise in django forms without django-recaptcha
How can I implement new reCaptcha Enterprise within django on the form without using old django-recaptcha? -
test complex django method containing multiple ManyToMany field using pytest
my app : account_engine has following models: class Company(models.Model): name = models.CharField(max_length=200) class Location(models.Model): name = models.CharField(max_length=200) class Client(models.Model): name = models.CharField(max_length=200) class CustomPermission(models.Model): url_name = models.CharField(max_length=200) url = models.CharField(max_length=200) class CustomRole(models.Model): name = models.CharField(max_length=200) class RoleSpecificPermission(models.Model): role = models.ForeignKey(CustomRole, on_delete=models.CASCADE) permission = models.ManyToManyField(CustomPermission, blank=True) class GroupSpecificPermission(models.Model): group = models.ForeignKey(CustomGroup, on_delete=models.CASCADE) permission = models.ManyToManyField(CustomPermission, blank=True) class UserDetail(models.Model): mobile = models.CharField(max_length=10) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) client = models.ManyToManyField(Client, blank=True) role = models.ManyToManyField(CustomRole, blank=True) group = models.ManyToManyField(CustomGroup, blank=True) special_permission = models.ManyToManyField(CustomPermission, blank=True) def get_all_permissions(self): # adding all permissions in set to remove duplicates final_set = set() role_level_prem = RoleSpecificPermission.objects.filter(role__in = list(self.role.all())) group_level_prem = GroupSpecificPermission.objects.filter(group__in = list(self.group.all())) for each_permission_set in role_level_prem: for each_permission in each_permission_set.permission.all(): final_set.add(each_permission) for each_permission_set in group_level_prem: for each_permission in each_permission_set.permission.all(): final_set.add(each_permission) for each_permission in self.special_permission.all(): final_set.add(each_permission) return list(final_set) I want to test the method get_all_permissions or model UserDetail class using pytest, pytest-django and mixer my test is as follows: class TestUserDetail: def test_method_get_all_permissions(self): roles = mixer.cycle(10).blend('account_engine.CustomRole') groups = mixer.cycle(10).blend('account_engine.CustomGroup') permissions = mixer.cycle(5).blend('account_engine.CustomPermission') special_permissions = mixer.cycle(5).blend('account_engine.CustomPermission') obj = mixer.blend('account_engine.UserDetail', role=mixer.sequence(*roles), group=mixer.sequence(*groups), permission=mixer.sequence(*permissions), special_permission=mixer.sequence(*special_permissions),) assert obj.get_all_permissions() == all_the_possible_permissions_for_which_i_need_your_inputs I'm just lost and not able to write test to verify if my method works … -
how to store a list of images in postgreSQL ArrayField (django rest)
I'm developing a project using django-rest for my backend and postgreSQL as my database. I'm using postgreSQL ArrayField in my Recipe model to store multiple images of different instructions. However when I send a POST request with a list of instructions images (instructions_image_list) I'am getting a weird error. I would really appreciate if anyone could help me solve it. thanks in advance. the error status_code 500 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte the model class Recipe(models.Model): id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False, ) author = models.ForeignKey(get_user_model() , on_delete=models.CASCADE, null=True, related_name='author') photo_main = models.ImageField(upload_to='media/', blank=True) title = models.CharField(max_length=150) instructions_text_list = ArrayField(models.CharField(max_length=100, blank=True,null=True),default=list, blank=True ,null=True,size=15,) instructions_image_list = ArrayField(models.ImageField(upload_to='media/',blank=True, null=True),default=list, blank=True ,null=True, size=15,) the view class RecipeCreate(CreateAPIView): permission_classes = (permissions.IsAuthenticated, ) queryset = Recipe.objects.all() serializer_class = RecipeCreateSerializer def perform_create(self, serializer): '''save the the current logged in user as the author of the recipe''' serializer.save(author=self.request.user) -
Should csrf_token be used when posting form data to external website/ server?
Im new to Django. Im setting up a bank payment option (banklink) to my django website. As per the banks technical docs I have to post certain key/ value data to their endpoint. Im using an html form to POST the data and Im wondering if it is needed to add the {% csrf_token %} to the form that is being posted to the bank endpoint? If I post the data to my own endpoint then the form wont even work without the csrf token, but it seems to work when POSTing to an external endpoint. I assume if the external endpoint isnt using django then the added csrf_token value in POST data wouldnt mean anything to them anyways. Or are there any other considerations I should evaluate? Thank you -
Problems with the serializer validator do not allow data to be sent
In this question, I had a problem to pass the user to the serializer, which was solved, but now I face another problem that the serializer validator stops sending user information and thinks I am going to create a new user. views.py class ProfileView(generics.RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(data=model_to_dict(request.user)) if serializer.is_valid(): return successful_response( messages=_('User Profile'), data=serializer.data ) return unsuccessful_response(errors=serializer.errors, status_code=status.HTTP_404_NOT_FOUND) My user model class: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) ..... USERNAME_FIELD = 'email' .... errors: { "errors": { "email": [ "user with this email address already exists." ] } } -
How to integrate REST API with google auth android, so that only users that are signed up on the webapp log in via their google account on android?
I have used Django Allauth for user authentication in my django webapp(used google login). I have Rest APIs for the models in my project. Made Rest API for the "User" model too containing all the user info. Used Django Rest Framework for these. How do I use these integrate REST API with google auth android, so that only users that are signed up on the webapp can only log in via their google account on android? Please do not give vague, generic answers. Please give clear directions on what to do next. I am a beginner. -
SQL / Django views conditional cumulative sum of values
Pretty new to SQL and Django, I am trying to create a query to cumulate the value of column A (integer) if the value in column B (string) is different. This cumulation should be done based on date (column C). Here is the data: Column A Column B Column C 2.0 Rock 2020-08-08 3.0 Paper 2020-09-08 1.0 Rock 2021-09-09 25.0 Rock 2021-09-09 12.0 Rock 2021-10-10 5.0 Paper 2021-11-11 Based on this data, I would like to have a third column D, which will represent the cumulative value such as follow: Column A Column B Column C Column D 2.0 Rock 2020-08-08 2.0 3.0 Paper 2020-09-08 5.0 1.0 Rock 2021-09-09 4.0 25.0 Rock 2021-09-09 28.0 12.0 Rock 2021-10-10 15.0 5.0 Paper 2021-11-11 17.0 -
What is the correct way to make an API without a model behind it?
Suppose I want to make an API that is not supported by a model. Certain fields are entered with the request, some processing is applied, and then other fields are returned. The way I usually use it is to define a simple view that instantiates a serializer to do the validation. And then I return the fields directly from the view, for example with a JSONResponse. Is this the right way to do it? Does it make sense to use a serializer for validation? Is it better to use a form? Should the response be serialized? Is it correct to process the input data in the view? -
Make file dynamically with nginx_unit and django
I am trying to make with this csv_file = 'static/result.csv' with open(csv_file,'a') as f: It works on python manage runserver However on nginx_unit there comes error like this, PermissionError: [Errno 13] Permission denied: 'result.csv' static folder is 777 already lrwxrwxrwx 1 ubuntu ubuntu 38 Dec 28 19:32 static Why this permission error happens?? in my settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATIC_ROOT = os.path.join(config("PROJ_PATH"), 'staticroot') -
How to make asynchronious django requests?
I have few GET requests which I should send to 20 http addresses The problem that's the whole pack of requests is loading very slow, I want to be able to see the result for the finished requests already and then those requests that are slow or unresponsive should be appended to the final view result later. What is the simplest method of achiving this? I have already tried asyncio From this tutorial https://betterprogramming.pub/how-to-make-parallel-async-http-requests-in-python-d0bd74780b8a but it has nothing to do with django. Here is my code https://github.com/nuriyevn/django_mine/blob/master/monitor/views.py And I get SynchronousOnlyOperation at /monitor/ You cannot call this from an async context - use a thread or sync_to_async. http://194.0.52.235:9500/monitor/ -
Filtering Foreign key choices in Django serializer
I have a Django model that looks like the code below. At the moment, when I am using django rest framework to create a new menu instance, the dish column contains options created by all users on the platform. How should I go about filtering the dish column so it only has options created by the user? Should I be doing it in the views or serializer? Thank you for the response in advance. class Dish(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=280) description = models.CharField(max_length=280) image = models.ImageField(upload_to='static/images/post_image', default='static/images/post_image/default.jpg') def __str__(self): return f'{self.title}' def get_image_url(self, obj): return obj.image.url class Menu(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(max_length=280) description = models.CharField(max_length=280) dish = models.ManyToManyField(Dish) price = models.SmallIntegerField( validators=[MinValueValidator(1), MaxValueValidator(10000)], default=None) def __str__(self): return f'{self.title}' -
how to handle multiple records in graphql django update mutation
The below method updates single emp record , how to handle the same for multiple emp recs at the same time. { (id : 1, firstName : "John", lastName: "Snow"), (id : 2, firstName : "Tryrion", lastName: "Lannister") (id : 3, firstName : "Jammie", lastName: "Lannister") } I am new to django and graphql kindly help me with code and query for the same class UpdateEmp(graphene.Mutation): emp = graphene.Field(EmployeeType) class Arguments: id = graphene.Int(required=True) first_name = graphene.String() last_name = graphene.String() @login_required def mutate(self, info,**kwargs): emp = Employee.objects.get(id=kwargs.get('id')) emp.first_name=kwargs.get('first_name') emp.last_name=kwargs.get('last_name') emp.save() return UpdateEmp(emp=emp) graphql mutation{ uopdatemp(id : 1, firstName : "john", lastName: "Snow") { Employee{ id firstName, lastName } } } -
Images got uploaded on AWS S3 bucket but it's not showing on Django heroku app
I pushed my django app on heroku and i am able to upload media files from my website admin pannel to AWS s3 bucket. But those media files doesn't render on the website. here is my settings files import os import datetime AWS_USERNAME = 'rahul' AWS_GROUP_NAME = 'new_brdy_eng_group' AWS_ACCESS_KEY_ID = os.environ.get("xxxxxxxxxx") AWS_SECRET_ACCESS_KEY = os.environ.get('xxxxxxxxxxx') AWS_PRELOAD_METADATA = True AWS_QUERYSTRING_AUTH = False AWS_S3_SIGNATURE_VERSION = "s3v4" AWS_S3_REGION_NAME = 'ap-south-1' DEFAULT_FILE_STORAGE = 'BE.aws.utils.MediaRootS3BotoStorage' STATICFILES_STORAGE = 'BE.aws.utils.StaticRootS3BotoStorage' AWS_STORAGE_BUCKET_NAME = 'brdy-engineers' S3DIRECT_REGION = 'ap-south-1' S3_URL = '//%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = '//%s.s3.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_ROOT = MEDIA_URL STATIC_URL = S3_URL + 'static/' ADMIN_MEDIA_PREFIX = STATIC_URL + 'admin/' AWS_DEFAULT_ACL = None I changed MEDIA_URL like these also MEDIA_URL = '//%s.s3-ap-south-1.amazonaws.com/media/' % AWS_STORAGE_BUCKET_NAME MEDIA_URL = 'https://brdy-engineers.s3.ap-south-1.amazonaws.com/media/' MEDIA_URL = 'https://brdy-engineers.s3.ap-south-1.amazonaws.com/media/Homefiles/reviews/' But None of these worked utils.py file from storages.backends.s3boto3 import S3Boto3Storage StaticRootS3BotoStorage = lambda: S3Boto3Storage(location='static') MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media') Bucket Policy { "Version": "2012-10-17", "Statement": [ { "Sid": "Allow All", "Effect": "Allow", "Principal": "*", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:*" ], "Resource": "arn:aws:s3:::brdy-engineers/*" } ] } Bucket CORS [ { "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [ "x-amz-server-side-encryption", "x-amz-request-id", "x-amz-id-2" ], "MaxAgeSeconds": 3000 } ] Bucket Block all public access is off … -
Expression contains mixed types: FloatField, IntegerField. You must set output_field in django annotate
I am getting this issue while using annotate.I have to calculate the counts and convert that into percentage using annotate. Also, I have to check whether the divisor shouldn't be zero. Also, I have used all the reacts in floafield. My code in view: else: articles = Articles.objects.filter(creator=user).annotate(total_reacts=Count('article_reacts')/1.0, bad_reacts=Coalesce(check(100.0*Count('article_reacts',filter=Q(article_reacts__reacts=1))/Count('article_reacts')/1.0,'total_reacts'),0.0), good_reacts=Coalesce(check(100.0*Count('article_reacts',filter=Q(article_reacts__reacts=2))/Count('article_reacts')/1.0,'total_reacts'),0.0), informative_reacts=Coalesce(check(100.0*Count('article_reacts',filter=Q(article_reacts__reacts=3))/Count('article_reacts')/1.0,'total_reacts'),0.0),) My check function is: dummy_divisor = 1.0 def check(result, divisor): return Case( When(**{ divisor: 0.0, 'then': Value(dummy_divisor, FloatField()), }), default=result, output_field=FloatField(), ) In local it is working but gets this issue on production only. Also, this is not quite correct. It also works when I put dummy_divisor = None in local, but not in prod either ways None or 1.0. I have used output field in the check function but keeps getting the same issue. -
Letters are missing when entered in custom usercreation form django
So sorry for being so brute with the question but i am currently sick and have a deadline please help As i said the letters of the username and nickname( user profile one to one display name ) are missing but the Image field email field and password field does not change when saved for example i type username as 'Baddy' but the username is saved as 'addy' please tell me how to fix it otherwise users cannot register as the username they entered is different from the one saved. models for user profile : class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) date_created = models.DateTimeField(auto_now_add=True) Nick_Name = models.CharField(default="Hey", max_length=250) Profile_pic = CloudinaryField('Profile_Pic', overwrite=True) def __str__(self): return self.user.username forms : class CreateUser(UserCreationForm): class Meta(UserCreationForm.Meta): model = User fields = ['username', 'email', 'password1', 'password2'] help_texts = { 'username': 'This is your identification value so it must be unique' } def __init__(self, *args, **kwargs): super(CreateUser, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs['class'] = 'form-control' class UserProfilePage(forms.ModelForm): class Meta: model = UserProfile fields = ['Nick_Name', 'Profile_pic'] help_texts = { 'Nick_Name': 'This will act as your display name', } def __init__(self, *args, **kwargs): super(UserProfilePage, self).__init__(*args, **kwargs) self.fields['Nick_Name'].widget.attrs['class'] = 'form-control' views : def register(request): profiles = UserProfilePage() forms = CreateUser() if … -
Supervisor not reloading Gunicorn properly with Django project
I am using Supervisor to reload Gunicorn when pushing Django project to production : Workflow : " && python manage.py migrate"\ " && python manage.py collectstatic --noinput"\ " && supervisorctl restart frontdesk-gunicorn"\ " && exit" Supervisor config : [program:project-gunicorn] command=/home/gaetangr/project/myprojectenv/bin/gunicorn config.wsgi:application user = gaetangr directory = /home/gaetangr/project autostart = true autorestart = true But most of the time, in order for all the change to propagate, I have to do a sudo : systemctl restart gunicorn From my understanding the command from supervisor should exactly the same. Any idea ? -
why swagger-UI doesn't show prameters and response?
im using django and django-rest-framwork and drf-yasg one of api in view.py @api_view(http_method_names=["GET"]) # Done def get_all__referralCodes_game(request): data = request.query_params query = GameCollection.find_one( {"_id": ObjectId(data["gameId"]), }, {"_id": 0, f"referralCodes": 1, } ) if query: return Response(data={"msg": "ok", "data": [query["referralCodes"]]}, status=http.HTTPStatus.OK) return Response(data={"msg": "not_found", "data": {}}, status=http.HTTPStatus.NOT_FOUND) and in url.py urlpatterns = [ path("referral-code/get-all", views.get_all__referralCodes_game), ] i need gameId in query_params but it can be seen there -
add static ressource to template filter function
I want to dynamically add icons from my static dir when using a template tag, but I do not want to add them in the templates HTML, but using a filter: {% for field in form %} <td>{{ field|format_ }}</td> {% endfor %} and format_ looking like this: @register.filter(name = "format_") def format_(field): if field.widget_type == "clearablefile": f = f"""{field}<button class="btn btn-danger"><img src="{{% static 'images/x-square.svg' %}}"></button>""" return mark_safe(f) return field I tried it with the same syntax I would use in the template, but just escaped: <img src="{{% static 'images/x-square.svg' %}}"> which just shows exactly that in clear text, not the icon on the template. What is the correct way here? -
Error message is not showing as form validation message in django
I have created the validation in the models itself and it's working fine for me. The problem is it is not showing in the form view instead shows as Django default error view.Here I attach the image -
Django: Revert or bypass "ValueError: Dependency on app with no migrations"
while attempting to separate the models in different apps, I bumped to an issue I would need support on: I have 2 models: class SeriesCompletion(models.Model): series = models.ForeignKey( 'Series', blank=True, null=True, on_delete=models.SET_NULL, ) user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL,) and class Series(models.Model): ... users_who_completed = models.ManyToManyField( settings.AUTH_USER_MODEL, through='app1.SeriesCompletion',) which were both located in app1 the idea (that worked well in dev environment) was to do a dumpadata, move SeriesCompletion to app2 and do the migrations, than a loaddata to repopulate properly however, when moving to prod environment, I ran the app1 migration with the Series model with a reference to app2: class Series(models.Model): ... users_who_completed = models.ManyToManyField( settings.AUTH_USER_MODEL, through='app2.SeriesCompletion',) It passed in prod, and when moving to do the makemigration for app2, it blocked because of a circular reference: ValueError: <function ManyToManyField.contribute_to_class.<locals>.resolve_through_model at 0x7f3e531f4400> contains a lazy reference to app2.seriescompletion, but app 'app2' isn't installed. I've tried a lot of things since, but I'm always blocked, and I am not able to move forwards doing a migration for app1 or for app2 ... or to move backwards returning to the previous migration with app1 I always end-up during the pre-migration/pre-makemigrations checks with the error message: ValueError: Dependency on app with …