Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
how to customize fields in nested serializer?
class ListSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = JobseekerProfile fields = ('user',) *How to modify this fields so that I can add only one field from user like user.username? * -
How to put Image reference in Character Field in Django db?
I am making an E-learning website using Django. The website would have questions along with answer options from which the user has to choose the correct answer. Most of the answer options are texts because of which I have declared the options in my model as CharField. class Question(models.Model): question = models.CharField(max_length=250) option_1 = models.CharField(max_length=50) option_2 = models.CharField(max_length=50) option_3 = models.CharField(max_length=50) option_4 = models.CharField(max_length=50) But I realized that in some questions, instead of text fields there are images as options. For example, there will be four images instead of texts and the user has to choose one answer among them. How do I include both ImageField and CharField in my model as answer choices? -
Modbus sensors in Django project
I'm working on a project in Django/Python. In one of the applications, we need to get data from the water level sensor and write it to the SQL database. Users should see the information from the sensors in one of the tables on the site. The sensors operate via the ModBus protocol. I found out that there are at least three Python libraries for working with Modbus (pymodbus, MinimalModbus, Modbus-tk), and there are also OPC servers that, as far as I understand, can read data from Modbus devices themselves and allow them to be managed, for example, via the REST API. I need advice on which software architecture is best to choose, taking into account the goal. What is better to read about possible solutions to such problems? -
Please help me with this question if anybody have a solutions
I have one model in that, I have many attributes I want to query the attributes based on the term in a search query for that I have applied Q annotate method, like below result = queryset.filter(Q(cu__icontains=term) | Q(s__icontains=term) | Q(region__icontains=term) |Q(owner__icontains=term) | Q(irr_no__icontains=term) | Q(contactperson__icontains=term) | Q(targetdate__icontains=term) | Q(briefinquirydescription__icontains=term)) Instead of this if I made a list of all attributes of my model like list = ['sdf','sf','ff','fffd','fdf','fdf','gg'] how I can query for a list of attributes of my model, any methods for this please guide or suggest other methods -
What is the best backend if front-end is React for CNN model? [closed]
I have front-end in react.js because I have expertise in it. -
Performance issue with django postgres delete
In my application I have a caching mechanism for requests to a different API. This is designed to store the request and response for 24 hours. Every-time the 24 hour limit is over the entry gets deleted from the database before creating a new request and saving the result again in the cache. It seems like there is an issue with a delete, only from time to time. Some of my delete requests take multiple minutes, even though the caching database has only around 100 entries and consists of a url, params (md5), body (md5), response and created date field. I analyse the performance through sentry. Below you can find a screenshot of the event. As you can see there is also a select beforehand that has no performance issue. Furthermore it happens that the delete has no performance issue. The database is a postgres database that runs on a different dedicated server. I already tried to recreate the database but without any success. I would assume that the ssh connection should not be the problem, because the select before the delete runs without any issue (and there are other selects beforehand as well. I also checked and debugged the … -
Make Django fail silently if an image isn't found
I'm getting a 500 error because when I run the app locally it tries to load an image that only exists on the production server. How do I make Django fail silently when this happens. I'm unable to load any page that has an image in it. -
Django User locked for 30 minutes after many attempts login failed
User will be locked out for 30min if the password is incorrect 5 times within 10min advance thanks -
Django format string based on model fields
Let's say we have a very big string with 3 parameters: "Stack Overflow is the {0} place to {1} answers from {2} problems" The parameters are based on model fields that calculated at runtime. Is it possible to store the model fields on another table? eg: | position | param | |---------------------|------------------| | 0 | modelA.field0 | | 1 | modelA.field1 | | 2 | modelB.field0 | and use them accordingly to format the above string? -
How to do Live search Using Fetch Ajax Method In Django Python?
I am getting Post.match is not a function error when i do this :( Please help, i am a newbie in JavaScript part. (I am getting back an object so have to turn it into an array but still get this error after using the Objects.values Method) My Views.py File: from django.shortcuts import render from django.http import HttpResponse, JsonResponse from .models import Post def Data(request): items = Post.objects.all() data = [] for qs in items: I = {"title":qs.title, "content": qs.content, "image": qs.image.url, } data.append(I) return JsonResponse({"data":data}) My HTML File: {% extends 'blog/base.html' %} {% load static %} {% block content %} <div class = 'w-100 text-center'> <h1>Search Results</h1> <form id = "search-form" autocomplete="off"> {% csrf_token %} <input name = 'game' type="text" id = "search-input" placeholder= "Post Search.."> </form> <div id = "results-box" class = "results-card"> </div> </div> {% endblock content %} {% block js %} <script defer src="{% static 'blog/S1.js' %}"> </script> {% endblock js %} My Java Script File: console.log('Heelowwww') const url = window.location.href const searchForm = document.getElementById("search-form") const searchInput = document.getElementById("search-input") const resultsBox = document.getElementById("results-box") const csrf = document.getElementsByName("csrfmiddlewaretoken")[0].value options = {method: "GET", headers: { Accept: "application/json" }, data:{ 'csrfmiddlewaretoken': csrf, } } const SearchPosts = async SearchIt …