Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Carousel in modal Django
Hello I am trying to put a carousel in my modal. everything was working fine until I put it. can someone please tell me what's wrong? gallery.html {% for photo in gallery %} × <div id="carouselExampleControls" class="carousel slide" data-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item"> <img src="{{photo.imageURL}}" alt="First slide"> </div> </div> <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> {% endfor %} </div> </div> </div> -
Pass my df from panddf function,pass it as paramater to graphview function
In this code i reutrned pie chart for all my data in database.. Now I have filtered my data using pandas df in panddf funtion and I need to pass my df into grpahview function to get pie chart only for my filtered dataframe from django.http import JsonResponse from django.shortcuts import render from board.models import userboard from.utils import get_plot import pandas as pd from sqlalchemy import create_engine def graphview(request): qs =userboard.obects.all() x=[x.Month for x in qs] y=[y.Bp_Values for y in qs] chart = get_plot(x,y) return render(request, 'piechart.html' ,{'chart':chart}) def panddf(request): username = None if request.user.is_authenticated: username = request.user.username print(username) engine=create_engine('postgresql+psycopg2://postgres:#24May@2002@localhost/bhavesh') df = pd.read_sql_query('SELECT * FROM public."board_userboard"',con=engine) filt = (df['User_name'] == username) print(df[filt]) df1 = (df[filt]) return render(request, 'abc.html') -
Updating Django model field in template without page refresh using UpdateView
How can I update a model field in my template without page refresh? I am using UpdateView. I have considered using Ajax, but I have no idea how to implement this. Can you help me to how I can update the following TextField description in the template without need to refresh the page? models.py: class Measurement(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) description = models.TextField(blank=True, default="", max_length=1200) views.py: class MeasurementView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Measurement template_name = 'ergolab/measurement.html' form_class = forms.MeasurementCreate def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): measurement = self.get_object() if self.request.user == measurement.author: return True return False template.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <fieldset class="form-group"> {{ form.description|as_crispy_field }} </fieldset> </form> -
Serializer field with source is not present in validated_data
I have added a field in serializer with source, Its validate function is being called, but its value is not present in validated_data. class MySerializer(serializers.ModelSerializer): # some fields new_name_field = serializers.CharField(source='model_field', required=False) # I have renamed this because I need "new_name_field" on my frontend. def validate_new_name_field(self, value): # do validations return value def validate(self, attrs): attrs = super().validate(attrs) print(attrs['new_name_field']) # This throws KeyError What am I doing wrong and How do I get the value of new_name_field in my validate function? -
How to prefetch_related fields for a related field in Django
I have seem some examples of how to prefetch_related fields in a forward and backward relationship in Django, but I have doubts about how can this be applied if we want to prefetch all the fields of a related model. For instance if I want to fetch all content from the following models, using the most optimized query: class HealthCheck(models.Model): id = models.Integer() person = models.ForeignKey('Person') class Person(models.Model): profile = models.ForeignKey('Profile') vaccines = models.ManyToManyField('vaccines', through='PersonVaccines') class Profile(models.Model): name = models.CharField(max_length=16) class PersonVaccines(models.Model): person = models.ForeignKey(Person) vaccine = models.ForeignKey('Vaccine') class Vaccine(models.Model): name = models.CharField(max_length=16) I have tried something like this but doesn't seems to work: from django.db.models import Prefetch HealthCheck.objects.filter(id=1).prefetch_related( Prefetch( 'person__vaccines', queryset=PersonVaccines.objects.select_related('person', 'person__profile', 'vaccine') ) ) How can I prefetch all the related content? -
Python, Django: Limit IntegerField inside models.py
I would like to ask, if it's possible to limit one IntegerField inside my model-class in comparison to another one!? For example: models.py class Example(models.Model): name = models.CharField(max_length=50, null=False, blank=False, unique=True) ports = models.IntegerField(default=1, validators=[MinValueValidator(1), MaxValueValidator(50)]) ports_active = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(50)]) As you may see, the ports_active are related to ports!? Is it possible to limit the ports_active-field, so that it can only be less or equal, but never greater than ports? Thanks for your help and have a great day! -
My plugin adding functionality was missing after publishing the page
What could be the reason of empty structure but previously successfully added plugin to the page. Actually I published the page then, I entered the edit mode where the plugin option was missing and the previously added plugin option was still available? -
Get the Top 5 users in each month for the last three months Django
I have this query Post.objects.filter(issued_at__isnull=False, issued_at__gte=three_months_ago).annotate( month=TruncMonth('issued_at'))[:5].values('month').annotate(num_of_posts=Sum('number_of_posts')).values( 'month', 'user__name', 'num_of_posts').order_by('-num_of_posts')[:15] All I need right now is getting only the top 5 users of each month (so in total 15 users are going to be returned). As you can see I tried to slice 5 after the annotate but a AssertionError: Cannot reorder a query once a slice has been taken. error rises. Also, I tried slicing 15 users but that didn't work because the wrong users are being returned. -
Looking for assistance in eliminating duplication in the python code related to django
Hi can someone please help me in reducing the complexity of the below mentioned code as I am new to this I need it to reduce the amount of code and improve the code and to improve simplicity and reduce duplications in the overall coding any any help in this regard can be of great help and thanks in advance for your time and consideration in helping me in this regard. ''' def update(self, instance, validated_data): for key, value in validated_data.items(): if hasattr(instance, key): if key == "email_embedd": # special case instance.email_embedd = json.dumps(value) else: setattr(instance, key, value) # instance.ef_underwriter_decision = validated_data.get('ef_underwriter_decision', # instance.ef_underwriter_decision) # instance.ef_feedback = validated_data.get('ef_feedback', instance.ef_feedback) # NBI USE CASE if instance.ef_underwriter_decision == configur.get('decisions', 'non_binding_indication'): # enquiry Log dict_obj = temp_dict() # Update Submission table based on underwriter decision submission.objects.filter(email_id=instance.email_id).update(email_status='active') submission.objects.filter(email_id=instance.email_id).update( email_uwriter_decision=instance.ef_underwriter_decision) submission.objects.filter(email_id=instance.email_id).update( email_today_mail=configur.get('mailstatus', 'nbi_mail_type')) instance.email_today_mail = configur.get('mailstatus', 'nbi_mail_type') # setting email_today maio to 0 for submission fields # CR7.1 Changes (FROM COMPLETED TAB TO PROCESSED TAB) submission.objects.filter(email_id=instance.email_id).update( email_deleted=configur.get('mailstatus', 'nbi_mail_type')) temp_email_table = submission.objects.filter(email_id=instance.email_id).values( 'email_id', 'enquiry_id', 'email_sender', 'email_subject', 'email_broker', 'email_outlook_date', 'email_today_mail', 'email_assigned_user', 'email_deleted') for today in temp_email_table: for t in today: dict_obj.add(t, today[t]) if len(validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) == 0: dict_obj.add('ef_insured_name', not_avbl) else: dict_obj.add('ef_insured_name', validated_data.get('ef_insured_name', instance.ef_insured_name)['name']) if len(validated_data.get('ef_obligor_name', instance.ef_obligor_name)['name']) == … -
Django Message Inbox
I'm pretty new on Django. I'm just trying to create a messaging app and i want to make a conversation inbox. To explain a little more there are two users like user1 and user2. I need to classify conversation between user1 and user2 also user2 and user3. Then I can get conversations with DRF to React. I looked up this article but I'm so confused. I think on generate conversation ID for this. But I don't know how to do this. models.py class Message(models.Model): sender = models.ForeignKey(User, related_name="sender", on_delete=models.CASCADE, related_query_name='s') reciever = models.ForeignKey(User, related_name="reciever", on_delete=models.CASCADE, related_query_name='r') msg_content = models.TextField(max_length=500, blank=True) sendtime = models.DateTimeField(auto_now_add=True) views.py class MessagesViewSet(viewsets.ModelViewSet): serializer_class = MessageSerializer authentication_classes = (JSONWebTokenAuthentication,) permission_classes = (IsAuthenticated,) def get_queryset(self): connected_user = self.request.user queryset = Message.objects.filter(reciever=connected_user) return queryset serializers.py class MessageSerializer(serializers.ModelSerializer): class Meta: model = Message fields = ('sender','reciever','msg_content','sendtime') -
How to define a class in Django use for loop?
I create a model. It let people create objects, if people create an objects, it would creates more model to let people create objects. How to do this? -
Is there a way to set the acks_late config in Celery?
For my Django project, I am using Celery with Redis, registering the tasks on runtime using the celery_app.tasks.register method. I want to retrigger a task in case of some failure, I have set the acks_late config param using task_acks_late=True on the app level while instantiating celery itself. I have also set task_reject_on_worker_lost=True. However, the tasks aren't being received back by celery no matter what. Is there any other way? -
Django gives me 'image' attribute has no file associated with it. error
I hope you can help me with my Django project. I am able to upload an images under a media_cdn folder, inside a folder based on the name of the slug. The problem occurs when I try to display the image inside my post list and post. It gives an error when I go to the home page Here is my code settings.py /my_site STATICFILES_DIRS=[ Path(BASE_DIR,'static'), Path(BASE_DIR,'media') ] STATIC_URL = '/static/' MEDIA_URL ='/media/' STATIC_ROOT=Path(BASE_DIR,'static_cdn') MEDIA_ROOT=Path(BASE_DIR,'media_cdn') models.py/blog def upload_location(instance, filename): file_path = 'blog/{author_id}/{title}-{filename}'.format( author_id=str(instance.author.id),title=str(instance.title), filename=filename) return file_path class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) image = models.ImageField(upload_to=upload_location, null=True, blank=True) date_published = models.DateTimeField(auto_now_add=True, verbose_name="date published") date_updated = models.DateTimeField(auto_now=True, verbose_name="date updated") author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) def __str__(self): return self.title @receiver(post_delete, sender=BlogPost) def submission_delete(sender, instance, **kwargs): instance.image.delete(False) def pre_save_blog_post_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = slugify(instance.author.username + "-" + instance.title) pre_save.connect(pre_save_blog_post_receiver, sender=BlogPost) blog_post_snip.html {% if blog_post %} <a href="{% url 'blog:detail' post.slug %}"> <img class="card-img-top" src="{{blog_post.image.url}}"> </a> ... {% else %} <div class="container"> <div class="row"> <div class="card m-auto"> <div class="card-body mt-2 mb-2"> <h2 class="card-title">No results</h2> <p class="card-text">There were no results matching the search: "{{query}}"</p> </div> </div> </div> </div> {% endif %} url.py from … -
What do the symbols in the api endpoint mean?
I am new to backend development and got confused about the syntax. Using django routers I got the below set of API endpoints. Please help me understanding the symbols/syntax of the below API endpoints. Where can I learn about these symbols and syntax? 1) domain.com/myuser/ ^users/$ [name='myuser-list'] 2) domain.com/myuser/ ^users.(?P[a-z0-9]+)/?$ [name='myuser-list'] 3) domain.com/myuser/ ^users/(?P[^/.]+)/$ [name='myuser-detail'] 4) domain.com/myuser/ ^users/(?P[^/.]+).(?P[a-z0-9]+)/?$ [name='myuser-detail'] 5) domain.com/myuser/ ^$ [name='api-root'] 6) domain.com/myuser/ ^.(?P[a-z0-9]+)/?$ [name='api-root'] -
what does this mean? and what is cause of this problem?
[Vuetify] [UPGRADE] 'v-content' is deprecated, use 'v-main' instead. console.ts:34 found in ---> VMain VApp App Root POST 'http://ec2-50-18-81-3.us-west-1.compute.amazonaws.com:8000/SkdevsecProduct/item_list' xhr.js:177 !net::ERR_CONNECTION_REFUSED! !Uncaught (in promise) Error:Network Error createError.js:16 at t.exports (createError.js:16) at XMLHttpRequest.d.onerror (xhr.js:84) ! POST 'http://ec2-50-18-81-3.us-west-1.compute.amazonaws.com:8000/SkdevsecBag/bag_count' xhr.js:177 net::ERR_CONNECTION_REFUSED Uncaught (in promise) Error: Network Error createError.js:16 \at t.exports (createError.js:16)\ \at XMLHttpRequest.d.onerror (xhr.js:84) \ -
'AllauthResetpasswordForm' object has no attribute 'save'
I have installed allauth package and i need to add recaptcha field to my reset password form! i am very new to the concept of init and super() so i googled and found this code : class AllauthResetpasswordForm(forms.Form): def __init__(self, *args, **kwargs): super(AllauthResetpasswordForm, self).__init__(*args, **kwargs) ## here i add the new fields that i need self.fields["captcha"] = ReCaptchaField() self.fields["email"] = forms.EmailField() and in settings.py : ACCOUNT_FORMS = {'reset_password':'meeting.forms.AllauthResetpasswordForm'} and when i enter email address i get this error : AttributeError at /accounts/password/reset/ 'AllauthResetpasswordForm' object has no attribute 'save' Traceback Switch to copy-and-paste view /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/exception.py, line 47, in inner response = get_response(request) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/core/handlers/base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 70, in view return self.dispatch(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/django/views/generic/base.py, line 98, in dispatch return handler(request, *args, **kwargs) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 102, in post response = self.form_valid(form) … ▶ Local vars /home/admin1/envs/myvenv/lib/python3.8/site-packages/allauth/account/views.py, line 690, in form_valid form.save(self.request) … ▶ Local vars -
How to accept a list of integers as input and create an object for each item in the list in django rest framework?
I have to pass a request body as shown below. { "user_id": 1, "skill": [ { "id":1 }, { "id":2 }, { "id":3 } ] } Models looks like this: class UserSkill(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) skill = models.ForeignKey(Skills, on_delete=models.CASCADE) class Meta: db_table = "user_skill" Serializer looks like : class UserSkillSerializer(serializers.ModelSerializer): class Meta: model = UserSkill fields = ['user', 'skill'] Viewset is done like: class UserSkillViewSet(viewsets.ModelViewSet): queryset = UserSkill.objects.all() serializer_class = UserSkillSerializer I have to pass the above mentioned request body to this api and for each element in "skill", I have to create an object for the model "UserSkill". Some one please help me with the changes I have to make to get this api working. Thanks -
how to pass field to get_queryset method in django manager?
i want create the Hierarchy user system and i want implement with group concept in django. in function get_subgroup give user(admin) and return list of subgroup later in django manager with get_queryset().filter(groups__in=self.subgroup) filter users in subgroups and return. but i do not know how pass subgroup field in get_queryset in user manager?? class MyUserManager(UserManager): def get_queryset(self): return super().get_queryset().filter(groups__in=self.subgroup) i can not use another manager method except get_queryset. i view several other question but i do not result. i can handle this system in api(in view with filter_backends) but that does not solve my problem. class IsManagerOrInSubGroupsForViewUsers(BaseFilterBackend): """ if manager send request for view users just view users in Subgroups or be sysadmin view all user in system. """ def filter_queryset(self, request, queryset, view): if request.user.has_perm("is_sysadmin"): return queryset subgroup = get_subgroups(manager=request.user) return queryset.filter(groups__in=subgroup) -
Django order a query by instance of ManyToMany
I have a model A with a ForeignKey to B: class A(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) A ManyToMany relationship with an extra field that weight any B and C relation: class B2C(models.Model): b = models.ForeignKey(B, on_delete=models.CASCADE) c = models.ForeignKey(C, on_delete=models.CASCADE) weight = models.IntegerField(default=0) And I need to order the A model (A.objects.filter(...)) using the weight of B2C for a given instance of C. For only one A instance I can do : # Example of C instance c = C.objects.get(pk=1) # Single instance of A a = A.objects.get(pk=1) # Getting the weight for this instance # A => B => B2C WHERE metier=metier weight = a.b.b2c_set.get(c=c) But I don't know how to do apply this on a queryset (like using it in a annotate). During my research I've found theses F(), ExpressionWrapper, SubQuery, annotate but I can't figure out how to use them for my problem. Thanks for reading :) -
Generate Qrcode images from data and make all Qrcode images to single PDF in Django/Python
I need to generate Qrcode images from database objects and make all QRcode images as single pdf in one request in Django. View Code: @csrf_exempt @login_required(login_url='/login/') def qrCodeGenerator(request,pk): if request.method == "POST": imgAll = [] first = None allData = CsvFileData.objects.filter(file_id=pk) for i in allData: qrFile = dataQrCodes.objects.create( file_id=pk, data_id=i.data_id ) qrFile.save() img = Image.open(requests.get(f"http://127.0.0.1:8000{qrFile.qrcode_image.url}", stream=True).raw) if first is None: first = img.convert('RGB') else: img = img.convert('RGB') imgAll.append(img) fileName = f"{MEDIA_ROOT}/{pk}_qrcodes.pdf" first.save(fileName,save_all=True,append_images=imgAll) filename = fileName response = FileResponse(open(filename, 'rb')) return response return None While creating objects it will create Qrimage in the Save method. Code: class dataQrCodes(models.Model): file_id = models.CharField(max_length=200) data_id = models.CharField(max_length=200) qrcode_image = models.ImageField(upload_to='qrImages',blank=True) def __str__(self): return f"Data_id : {self.data_id} | {self.id} | File_id : {self.file_id}" def save(self, *args, **kwargs): if dataQrCodes.objects.filter(data_id=self.data_id).exists(): return False qrcode_image = qrcode.make(self.data_id) canvas = Image.new('RGB', (qrcode_image.pixel_size, qrcode_image.pixel_size), 'white') canvas.paste(qrcode_image) fname = f'qr_code-{self.data_id}.png' buffer = BytesIO() canvas.save(buffer,'PNG') self.qrcode_image.save(fname, File(buffer), save=False) canvas.close() super().save(*args, **kwargs) The problem here is it, creates multiple objects instead of one object for a single Id in for loop. I attached the image here: But in pdf, it only attaches one time and it returned response correctly. After creating all objects it shows some error in the terminal that is in … -
Build a Python app that calls Microsoft Project Online API endpoints to GET project data and save its response in CSV format
I want to fetch Microsoft Project with API endpoint. But I am getting the 404 Not found error while I am hitting the following endpoint https://myprojects.sharepoint.com/teams/gpols/_api/ProjectData. This endpoint will return me an xml file with project Id that I will pass to next two endpoints which are: https://myprojects.sharepoint.com/teams/gpols/_api/ProjectData/Projects(guid'%3CProjectID%3E')/Assignments https://myprojects.sharepoint.com/teams/gpols/_api/ProjectData/Projects(guid'')/Tasks I have done some R&D. It seems like that I need some authentications? Let me know how I can get response of this endpoint. Thanks in advance for correcting me. -
I can not get into posts in django admin
Once I click the posts in django admin then this message pops up ValueError at /admin/blog/post/ invalid literal for int() with base 10: b'27th June' yes, I put wrong form of data in DateField. I wanted to remove this data. that's why I tried to get into posts in django admin. is there anyway to fix this problem? models.py class Post(models.Model): flight_date = models.DateField(blank=False) -
Call my view from celery task which will hit the third party API and save data into database
I want to call my view from celery task which will hit the API and save the respective data into database. def test_task(): # view_url = "domain/api/v1/id/connection" objects = Model.objects.all() for ob in objects: # get the id and for each id calll the test view def testView(request): instance = self.self.get_object() #do the task This is my celery task and view that I want to access from that celery task ** My thought** I thought of making url and just adding id to the url and then using the request module to make the request on that view. example : def test_task(): objects = Model.objects.all() for ob in objects: view_url = "domain/api/v1/%s/connection" % ob.id request.get(view_url) ``` -
update_or_create how to filter
class ModelAnswer(models.Model): question_id = models.ForeignKey( Questions, on_delete=models.CASCADE, db_column="question_id" ) answer_id= models.AutoField(primary_key=True) answer_mark = models.FloatField() model_ans = models.TextField(unique=True) class Meta: db_table = 'MODEL_ANSWER' @require_http_methods(["POST"]) @login_required def edit_guided_answer(request): req = json.loads(request.body) question_no = req["question_no"] qn_total_mark = req["qn_total_mark"] guided_answers = req["guided_answer"] models.Questions.objects.filter(pk=question_no).update( qn_total_mark=qn_total_mark, updated_by=request.user.username, ) for guided_answer in guided_answers: for guided_answer in guided_answers: models.ModelAnswer.objects.update_or_create( question_id=models.Questions.objects.get(pk=question_no), model_ans= guided_answer["model_ans"], answer_mark=guided_answer["answer_mark"], defaults={ "model_ans": guided_answer["model_ans"], 'answer_mark':guided_answer["answer_mark"], } ) return success({"res": True}) I know that this might be a duplicate question but i am genuinely confunsed about how the filter works.Whenever i try to change the value of an existing field,it does not get updated instead,the updated existing field is seen as an entirely new item and is created and put into the database.Putting a unique into model_Ans does not seem to work either.Why does it happen? -
How to render data vertically in table in dajngo?
How can I render data in the table in the vertical table? Is there any plugin in jquery.I want to export vertical data in pdf format also