Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
How to add extra command line arguments to createsuperuser - Django?
I have UserManager class below: class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) In the create_superuser function, i would like to add one more field to set tenant_id. This has to be taken from the command line, when using python manage.py createsuperuser. If i add tenant_id in create_superuser function like this create_superuser(self, email, password, tenant_id,**extra_fields), i'm getting the following error UserManager.create_superuser() missing 1 required positional argument: 'tenant_id'. Is there any way i can pass tenant_id from command line? -
How to get ceiling of seconds in a timedelta object
I'm working with Django and I fall into a problem that blocked me. I write this method to perform a duration as a difference between "end_time" and "start_time", the result is a timedelta object. @property def start_dt(self): if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty(): try: return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.min()) except BaseException: return None else: intervals = self.get_datetime_intervals() return intervals.min() @property def end_dt(self): if self.track and self.track.dt > 0 and not self.sample_intervals.is_empty(): try: return self.track.timestamp + datetime.timedelta(seconds=self.track.dt * self.sample_intervals.max()) except BaseException: return None else: intervals = self.get_datetime_intervals() return intervals.max() @property def duration(self): return self.end_dt - self.start_dt It works well, but if I have, for example, 00:32:55.765000, the result is approximated down and I obtain 00:32:55 instead of 00:32:56. How can I approximate up or down depending on duration's microseconds? -
Run Command Line Inside Virtual Environment Using Python
I have a Django App running in a virtual environment on Windows 10. I am trying to create a Scheduled Job that allows to automatically start the Server when Windows Start. What I need to be done is the following command lines to be executed in this order: cd Django\project-name\ Scripts\activate.bat \\30 Seconds Later cd app-name\ python manage.py runserver 0.0.0.0:8000 What is the simplest way to do this ? Thanks -
how to serialize current user in django rest framework?
I wrote a custom user and defined the serializer for it, and now I have an endpoint that the user sent the get request. He should get the user information in json format. And since my response format is as follows { 'messages': msg, 'data': data } I do not know how to serialize the user or which generic view to use my code: class ProfileView(generics.RetrieveAPIView): permission_classes = (IsAuthenticated,) serializer_class = UserSerializer def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(data=request.user) if serializer.is_valid(): return successful_response( messages=_('User Profile'), data=serializer.data ) return unsuccessful_response(serializer.errors) and the error I get: { "errors": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got User." ] } } Anyone have an idea? -
How to restart Django-react frontend
Made a few changes in the jsx files on the frontend. The server uses django, react, apache2, python Now that i made a few change in the frontend, it wont show up in the website, untill i restart react How do I do? I tried. systemctl restart apache2 reboot . venv/bin/activate python ./manage.py runserver Server Files structure /var/www/backend /vaw/www/frontend -
do we need query set in CreateAPIView?
My question is quite straight forward. I'm actually not sure that queryset is required need for CreateAPIView or not.. ? class CreateNotificationAPIView(generics.CreateAPIView): """This endpoint allows for creation of a notification""" queryset = Notification.objects.all() #can we remove it, if we do so, will we face any issue in future ? serializer_class = serializers.NotificationSerializer -
Django Celery vs Django-Q
I'm relatively new into backend engineering (still learning). So, I have a question for which I didn't find any reliable answer searching on the internet. I wanna create a web-app with django. But I understand there is a need of task queuing system or similar worker tool for it. So I searched on the internet and found django-q, which I think would be easier to implement than django-celery (honestly I don't know much about any of them). But at the same time, I can see, most of the django developers are actually using django-celery. So my questions is, which one should I choose? Should I go with django-celery or django-q? And is there any key differences between them which should be considered? (or Am i asking the wrong question?) -
django: get HTML form value in view.py failed with empty <QueryDict: {}> and None value
I am new to django and follow the djangogirls tutorial. With a few modifications, I am trying to get the value from the form text field and print it in view.py and then display this value again in another "result" field in the html page. html: <!DOCTYPE html> <html> <body> <form> <div> <label>num_1:</label> <input type = "text" name="num_1" value = "1" placeholder="Enter value"> </div> <div> <label>num_2:</label> <input type = "text" name="num_2" value = "2" placeholder="Enter value"> </div> </form> <div> <label>result:</label> {{ result }} </div> <br> </body> </html> view.py: def post_list(request): # posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') num1 = request.POST.get('num_1') num2 = request.POST.get('num_2') result = int(num1)+int(num2) print(request.POST) print("num1 ", num1) # return render(request, 'blog/post_list.html', {'posts': posts}) return render(request, 'blog/post_list.html', {'result': result}) when I activate the local server, I got: Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. <QueryDict: {}> num1 None -
How to load an image file from my local hard drive to html page using python?
I want to load an image (.png file) from my local system to html page using python. -
Django Invalid Form
I have a modal with a form in it. The issue is that on invalid form it does return the form errors but it also closes the modal dialog box by rendering the home page again. It is also the home page so the return render is needed for the logging in. How would I just return to the screen if the post fails. def index(request): context = {} if request.method == "POST": print(request.POST) form = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if form.is_valid(): form.save() return redirect('home') else: form = UserProfileForm() context['form']= form return render(request, "home.html", context) modal {% block content %} <div class="modal fade" id="editProfile" tabindex="-1" role="dialog" aria-labelledby="editProfilelCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-dialog-centered" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="editProfileLongTtitle">Edit Profile</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> {% include 'form.html' %} </div> </div> </div> </div> {% endblock %} -
How to create get or create object from serializer data
I'm passing two serializer with one view. On creating object I want to first create CaseId object which is why I'm poping out CaseObject from validated data. I want to get or create an object with the given data. Because I want to pass that to the CaseMessage object as a reference. class CaseMessageSerializer(serializers.ModelSerializer): case_id = serializers.IntegerField(required=False) case_object = CaseIdSerializer(required=False) message_type = ChoicesFieldSerializer(choices=CaseMessage.MESSAGE_TYPE) body_format = ChoicesFieldSerializer(choices=CaseMessage.BODY_FORMAT) class Meta: model = CaseMessage fields = "__all__" depth = 1 def create(self, validated_data): raw_case_object = validated_data.pop('case_object', None) # Not Getting or creating object with the given data. case = CaseId.objects.get_or_create(**raw_case_object) case_message = CaseMessage(**validated_data) case_message.caseid = case case_message.save() if not CaseAudience.objects.filter(case_id=case).exists(): case_audiance = CaseAudience( case_id = case, source_message = case_message, ) case_audiance.save() return validated_data The Errors are as follows: