Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to merge unrelated models and list them Django
There are two models in models.py First: class PublishedOutput(BaseModel): """Collection of generated distributions available on BigQuery""" generate_distributions = models.ManyToManyField(GeneratedImpressionDistribution) modified_by = models.ForeignKey(get_user_model(), null=True, on_delete=models.SET_NULL) updated_at = models.DateTimeField(auto_now=True) type=models.CharField(max_length=7, options=PUBLISH_TYPE_CHOICES, default=PUBLISH_TYPE_PENDING, unique=True) class meta: db_table = "collection_publish_forecast" verbose_name_plural = "active published results" protection __str__(self): return f"{self.type} publish collection" Second: class PublishedOutputHistory(BaseModel): """Historical collections only, they are no longer available in BigQuery""" # Shared fields with PublishedOutput generate_distributions = models.ManyToManyField(GeneratedImpressionDistribution) modified_by = models.ForeignKey(get_user_model(), null=True, on_delete=models.SET_NULL, related_name="modified_by") updated_at = models.DateTimeField() # field "type" without unique index type=models.CharField(max_length=7, options=PUBLISH_TYPE_CHOICES) # additional fields archived_at = models.DateTimeField(auto_now_add = True) archived_by = models.ForeignKey(get_user_model(), null=True, on_delete=models.SET_NULL, related_name="archived_by") class meta: db_table = "history_publish_forecast" order=("archived") verbose_name_plural = "historical published results" protection __str__(self): return f"Historical collection {self.type}" You are currently using two models in different lists. Is it possible to make it so that it would be displayed in one list, as in the picture? At the same time, leave filtering by type. The buttons in the picture are also tied up through admin.py. example I try to output: admin.py @admin.register (PublishedOutput) class DistributionCollectionAdmin(InlineActionsModelAdminMixin, BaseReadOnlyExceptSuperuserModelAdmin): list_display = ("__str__", "updated_at", "type") exclude = ("modified_by") readonly_fields = ("summaries", "updated_at") order=("-type") def get_queryset(self, request): # select all objects from both PublishedOutput and PublishedOutputHistory queryset1 … -
How do I deny the access to the static files of the corresponding course which is not purchased by the user? Django
I'm working on an Udemy clone. Currently I'm working on the functionality of showing the details of course to the people who didn't purchase the course and showing the details, lessons and videos to the people who purchase the course and have access to it. I have some sort of solution for that but I don't think it's the right one. My solution is storing people who has access inside a Course's foreign key field, so using that foreign key lookup on a currently logged in user I check whether a user's id is listed in that list of people who own the course. The problem of that approach is that if people who didn't purchase a course have a precise link to the video which is a part of the course, they can just type it in the searching bar and see the video, that's because this video is a media file or a static file. Here's the code that I wrote for that: Models code: class Course(models.Model): id = models.UUIDField(primary_key=True, db_index=True, default=uuid.uuid4, editable=False) author = models.ForeignKey(Author, on_delete=models.CASCADE, related_name='courses') students = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, related_name='courses', blank=True, null=True) ... class Section(models.Model): id = models.UUIDField(primary_key=True, db_index=True, default=uuid.uuid4, editable=False) course = models.ForeignKey(Course, on_delete=models.CASCADE, … -
Why does Annotate and Count in Django behave this way?
I have two models Post and Tag(given by django-taggit app). So they make use of generic foreign key concept. If i query posts like: posts = Post.objects.annotate(num_tags=Count('tags')) and try to retrieve value of num_tags for first result in queryset like: posts[0].num_tags >> 7 (which is true, there are 7 tags related with this post) Now, say if i have a post with tag ids = [4,5,6] and I query similar posts to this one like: similar_posts = Post.objects.filter(tags__in=tag_list).annotate(num_tags=Count('tags')) Now, if I try to retrieve the num tags value like: similar_posts[0].num_tags >> 1 Here 1 is referring to the number of tags that matched from the tag list. But why does Django not explain this behavior anywhere in their documentation, or am i missing some parts of documentation? Can someone please explain the actual working of 'annotate' and 'count' in different scenarios? Note: similar_posts[0] and posts[0] is the same object. I was expecting the num_tags to show 7 in both cases. However showing 1 in the latter case actually helps in my usecase. But need to know why does Count behave differently in the latter case. -
Mysql table without id field serializer unkown column id issue
I have a table data_stats without the id field that is given below. | Field | Type | Null | Key | Default | Extra +--------------+---------------+------+-----+------------------- | UUID | varchar(36) | NO | PRI | uuid()| EFAULT_GENERATED | Username | varchar(15) | YES | | NULL | | StartDate | varchar(25) | YES | | | In Serializer I am using it like class InformationSerializer(serializers.ModelSerializer): class Meta: model = data_stats fields = '__all__' And In my apiViews, I am Querying like the given below. filterObj = data_stats.objects.filter(StartDate__range = [start_date,end]) serializer = InformationSerializer(filterObj, many=True) return Response(serializer.data,status=status.HTTP_201_CREATED) I don't know what I am doing wrong here. but in my error log, I am getting the below error. [Tue Feb 28 13:29:16.277365 2023] [wsgi:error] [pid 3324135:tid 140081038006016] [client 10.223.224.12:43580] django.db.utils.OperationalError: (1054, "Unknown column 'data_stats.id' in 'field list'") Can anyone please help me how can I resolve this issue? because I don't want to add an id field in my table. when I try to debug my filter query it generates like: SELECT data_stats.id, data_stats.UUID, data_stats.Username WHERE data_stats.StartDate BETWEEN 2023-02-22 AND 2023-02-28 this data_stats.id should not be there. can anyone please help me or guide me to resolve this? thanks in advance -
'ServerRequestForm' object has no attribute 'get' on form post Django
I am trying to submit a form in django consisting of 3 models and a 3 way dependable dropdown. Every form validations and other function of dropdowns and dynamically adding teacher fields works but while submission it shows: 'ServerRequestForm' object has no attribute 'get' I have provided with views, models and forms for the problem. views.py class ServerRequestView(FormView): template_name = 'dashboard/school/request_Server_bak.html' form_class = ServerRequestForm mediator_form_class = MediatorForm teacher_form_class = TeacherForm success_url = reverse_lazy('server_request_success') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['mediator_form'] = self.mediator_form_class() context['teacher_formset'] = TeacherFormSet() return context def post(self, request, *args, **kwargs): form = self.get_form() # Check if self.request.POST is a QueryDict object if isinstance(request.POST, QueryDict): mediator_form = self.mediator_form_class(request.POST) teacher_formset = TeacherFormSet(request.POST) else: # handle the case where request.POST is not a QueryDict object # e.g. by raising an error or using a default value raise ValueError("request.POST is not a QueryDict object") if form.is_valid() and mediator_form.is_valid() and teacher_formset.is_valid(): return self.form_valid(form, mediator_form, teacher_formset) else: return self.form_invalid(form, mediator_form, teacher_formset) def form_valid(self, form, mediator_form, teacher_formset): self.object = form.save(commit=False) self.object.mediator = mediator_form.save() self.object.save() teacher_instances = teacher_formset.save(commit=False) for teacher in teacher_instances: teacher.server_request = self.object teacher.save() return super().form_valid(form) def form_invalid(self, form, mediator_form, teacher_formset): return self.render_to_response( self.get_context_data(form=form, mediator_form=mediator_form, teacher_formset=teacher_formset) ) forms.py class ServerRequestForm(forms.ModelForm): """ Server request form … -
common djngo code base for my website and use the business logic for REST API
I have my existing django web application. Now i need to expose the crud with all business validation / logic as a REST Api. e.g validate the available stock in the region before accepting the order. Simply exposing the crud operation API would not validate the underlying business logic. Did search on the forum about it and few suggested to make use of ViewSet for API and also django views. But i am still not convinced about the practicality of the solutions and how to use. What is the best solution, if i want to use my django views for regular business web application and also use the same business logic to expose with REST API. Appreciate if one can suggest with code snippet. -
Can I give parameters to AppConfig.ready() of django?
I want to get request.user.id as I have to pass it to scheduler in AppConfig.ready() but it gave an error. How can I do it ? My code is as follows: class ApiConfig(AppConfig): name = 'myapp' def ready(self, request): print('Here starting scheduler') from . import msgScheduler user_id = request.user.id msgScheduler.start(self,request, user_id) -
old value input in django model form
In Laravel, we used old('field_name') to display previous input values. How can I do this in Django form model? I mean If the validation is unsuccessful the input value will be deleted. I want its previous value to be preserved and not need to be typed. class AddMenuForm(forms.ModelForm): def __init__(self,*args,**kwargs): x=super(AddMenuForm, self).__init__(*args, **kwargs) return x class Meta: model=Menu fields="__all__" widgets = { 'title': forms.TextInput(attrs={ 'class': 'form-control', 'id':'inputname', 'placeholder': "نام آیتم" }), 'url': forms.TextInput(attrs={ 'class': 'form-control', 'id': 'inputurl', 'placeholder': " mr-keshi.ir /" }), -
upload huge file and receive that with django framework for example
I want to send huge file from http request and receive that in django application, how can I do this? please describe to me the scenario. Do I must split the file or there is some other way to solve that? i want to test that with celery... -
Django ORM - SQL part of WHERE if parameter is null
I have a problem in django trying to exclude or include part of the filter if the parameter is null. I have 4 parametros in my model. StartDate, EndDate, Severity and Source. I am trying to make a filter to a database in postgresql. The filter can have one or more of these parameters. This means that if I pass 1 of them the others could be None unless they are defined. I was able to solve my problem with query raw by doing WHERE (param IS NULL OR param=param) but I can't do the same QuerySet Any idea about this? Please help """SELECT * FROM mymanagelogs_logs WHERE (%(severity)s IS NULL OR severity=%(severity)s) AND (%(source)s IS NULL OR source=%(source)s) AND (%(start_date)s IS NULL OR timestamp >= %(start_date)s) AND (%(end_date)s IS NULL OR timestamp <= %(end_date)s)""", params={'severity': severity, 'source': source, 'start_date':start, 'end_date':end} ) With RAW Query. Trying do the same with Q objects.filter(Q(date__range=(start, end)) & (Q(severity=severity) | Q(severity=None)) -
In python , kwargs.get("somevalue") returns tuple?
I want to use a method which has not specific number of parameters , so i used kwargs for it to be able to get different parameters the problem is when I want to get the parameter by kwargs.get('candidate_email') code it returns a tuple as the answer while i expected to get sting or integer how can I get the parameter with its own type ? class TemplateCenter: def __init__(self, **kwargs): self.candidate_email: str = kwargs.get('candidate_email'), self.assessment_obj: Assessment = kwargs.get('assessment_obj'), self.company_user: User = kwargs.get('company_user'), self.template_type: int = kwargs.get('template_type'), self.text_context: str = kwargs.get('text_context'), self.subject: str = kwargs.get('subject'), def template_type_switch(self): match self.template_type: case CompanyTemplateMessage.TemplateTypeChoices.INVITATION: return self.invite_to_assessment_template( self.candidate_email, self.assessment_obj, self.company_user, self.template_type, self.text_context, self.subject, ) case CompanyTemplateMessage.TemplateTypeChoices.JOB_OFFER_ACCEPTANCE: return self.invite_to_company_template( self.candidate_email, self.assessment_obj, self.company_user, self.template_type, self.text_context, self.subject, ) def invite_to_assessment_template( self, candidate_email, assessment_obj, company_user, template_type, text_context, subject, ): pass and i called the method like this : content = TemplateCenter().template_type_switch( candidate_email=email, assessment_obj=assessment_obj, company_user=company_user, template_type=template_type, text_context=text, subject=subject, ) Is it correct or is there any better way to call a method which gets different number of variable? -
pre_save django model update fith celery shared_task
I have Project model class Project(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid4, editable=False) logo = models.ImageField(validators=[validate_image_size], blank=True, null=True, default=None) name = models.CharField(max_length=64) description = models.TextField() @transaction.atomic def save(self, *args, **kwargs): super().save(*args, **kwargs) def __str__(self): return self.name And i want to compress logo field with reciever @receiver(post_save, sender=Project) def compress_project_logo(sender, instance, **kwargs): compress_image.apply_async((instance.id,)) with shared_task @shared_task def compress_image(project_id): from api.models import Project project = get_object_or_404(Project, id=project_id) compressed_image = Image.open(project.logo) compressed_image = compressed_image.convert("RGB") compressed_image = ImageOps.exif_transpose(compressed_image) image_io = BytesIO() compressed_image.save(image_io, "JPEG", quality=70) project.logo = InMemoryUploadedFile(image_io, "ImageField", project.logo.file.name, "image/jpeg", sys.getsizeof(image_io), None) project.save() And when i'm saving Project model through django admin i take this `Traceback (most recent call last): 2023-02-28 10:27:45 File "/usr/local/lib/python3.8/site-packages/celery/app/trace.py", line 450, in trace_task R = retval = fun(*args, **kwargs) File "/usr/local/lib/python3.8/site-packages/celery/app/trace.py", line 731, in protected_call return self.run(*args, **kwargs) 2 File "/code/api/tasks/compress.py", line 14, in compress_image project = get_object_or_404(Project, id=project_id) File "/usr/local/lib/python3.8/site-packages/rest_framework/generics.py", line 19, in get_object_or_404 return _get_object_or_404(queryset, *filter_args, **filter_kwargs) File "/usr/local/lib/python3.8/site-packages/django/shortcuts.py", line 78, in get_object_or_404 2 raise Http404('No %s matches the given query.' % queryset.model._meta.object_name) django.http.response.Http404: No Project matches the given query`. -
Best library for RBAC in a model basis in Django
I have setup Django Restframework as the backend for my project. I use React as the frontend. I have various permission rules such as: Everyone can create an account. Everyone can view the accounts they are part of. Only the account admin or creator can edit the account. Etc. I have created an AccounUser model to hold this logic. However I was wondering if there is a smarter way to do this and to use a third party library? Do you guys can recommend any? Thank you ❤️ -
Stripe Authentication Error | Invalid APi
i am creating a Stripe Account when the user register himself in the E-commerece i provided the correct Secrete Key and the Publish able key. But i does not find any solution i create a customer account through signals in the django rest frame work ` stripe.api_key = settings.SECRET_KEY @receiver(post_save, sender=get_user_model()) def create_cart_for_user(sender, instance, created, **kwargs): if created: Cart.objects.create(user=instance) @receiver(post_save, sender=User) def create_stripe_customer(sender, instance, created, **kwargs): if created: customer = stripe.Customer.create(email=instance.email) instance.stripe_customer_id = customer['id'] instance.save()` Error stripe.error.AuthenticationError: Invalid API Key provided: django-i******************************************************kg%i -
razorpay supported in latest version of django 4.1.7?
When use django 4.1.7 and make payment using razorpay. it send an error, invalid callback url. i want to use razorpay payment gateway for latest version of django 4.1.7 -
How To use multiple url in the same template file in django?
I want to use 2 urls in the same template named doctors. The code of my urls.py file and doctor.html file is shown below: This is my urls.py code: path('doctors.html', views.recommend_doctors, name='recommend_doctors'), path('doctors.html',views.doctors, name = 'doctors'), This is my doctors.html file code: <!-- using this url path('doctors.html',views.doctors, name = 'doctors'), --> <div class="container"> <div class="list"> {% for row in data %} <div class="item1"> <div class="wrapper"> <div class="img-area"> <div class="inner-area"> <img src="media/female1.jpg" alt=""> </div> </div> <div class="name">{{ row.1 }}</div> <div class="speciality">{{ row.3 }}</div> <div class="hospital">{{ row.0 }}</div> <div class="social-share"> <div class="row"> <p><span>Fee</span></p> <p><span>Rs. {{ row.4 }}/-</span></p> </div> <div class="row"> <p><span>Ratings</span></p> <p><span>{{ row.2 }}</span></p> </div> </div> </div> </div> {% endfor %} </div> </div> <script> $(document).ready(function() { var showCount = 8; // number of images to show initially var $images = $('#imageTable img'); $images.slice(showCount).hide(); // hide remaining images $('#showMoreBtn').click(function() { $images.slice(showCount).show(); // show remaining images $(this).hide(); // hide the 'show more' button }); }); </script> <!-- Using this url: path('doctors.html', views.recommend_doctors, name='recommend_doctors'), --> <h1>Find Recommended Doctors</h1> <form method="POST" action="{% url 'recommend_doctors' %}"> {% csrf_token %} <label for="dept_name">Select a Department:</label> <select name="dept_name" id="dept_name"> {% for department in departments %} <option value="{{ department }}">{{ department }}</option> {% endfor %} </select> <br> <input type="submit" value="Find Doctors"> … -
Making your clone
I dont know I will need something -
How do turn text that's the result of a search into a clickable URL in Django?
I'm trying to make a search bar in Django that searches for pages by displaying the name and url of the page. Right now, I can only display the url of a page as plain text when it gets searched. I want the url to be a clickable link that leads to the page. **This is what my code looks like currently: ** The search results page search_page.html: {% extends 'contents/main.html' %} {% block content %} <center> {% if searched %} <h1>You searched for {{searched}}</h1> <br/> {% for page in pages %} {{ page }} - {{page.web}}<br/> <!-- page displays name of page and page.web displays url as text --> {% endfor %} {% else %} <h1>You forgot to search for a page</h1> {% endif %} </center> {% endblock content %} The method for search_page.html in views.py: def search_page(request): if request.method == 'POST': searched = request.POST['searched'] pages = Pages.objects.filter(name__contains=searched) return render(request, 'contents/search_page.html', {'searched':searched, 'pages':pages }) The models.py class for pages: class Pages(models.Model): name = models.CharField('Page Name', max_length=120) web = models.URLField('Page URL') <!-- this gets the url of the page --> def __str__(self): return self.name **WHAT I'VE TRIED ** I've tried turning page.web into a url but it gave me a … -
Solving 502 Bad Gateway Error for a Django Project Nginx - gunicorn - Debian
Hi I am trying to deploy my Django Project to Production for the first time using Nginx and gunicorn on linode. Currently I did not set a venv file I just downloaded all the requirements in the system as a whole. I am using Linode Server and selected Django from the market place and the set system is Debian. The project was working perfectly well with portal 8000 but now I am trying to take it to development. I have made the following steps: sudo nano /etc/systemd/system/gunicorn.service [Unit] Description=Gunicorn service for project After=network.target [Service] User=www-data Group=www-data WorkingDirectory=/var/www/DjangoApp/ ExecStart=/usr/local/bin/gunicorn --workers 3 --bind unix:/var/www/DjangoApp/project.sock project.wsgi:application [Install] WantedBy=multi-user.target I can't find the sock file in the project but this is the tree of the project if it helps cd /var/www/DjangoApp: api db.sqlite3 project manage.py media README.md requirements.txt static tac users in the /var/www/DjangoApp/project asgi.py __init__.py __pycache__ settings.py urls.py wsgi.py in my sudo nano /etc/nginx/sites-available/project server { listen 80; server_name 111.111.111.11; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /var/www/DjangoApp/; } location / { include proxy_params; proxy_pass http://unix:/var/www/DjangoApp/project.sock; } } here is the log error root@139-177-193-82:~# sudo tail -50 /var/log/nginx/error.log ......................: * connect() to unix:/var/www/DjangoApp/project.sock failed (2: No such … -
Users are not saving in ManyToMany Field drf
I am learning django rest framework and I have a field named users in my Blog Model with ManyToManyField to User and I am trying to save multiple users in .post() request. models.py class Blog(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name="users") views.py class BlogCreateView(mixins.CreateModelMixin, GenericAPIView): serializer_class = BlogSerializer queryset = Blog.objects.all() def post(self, request, pk, *args, **kwargs): try: return self.create(request, *args, **kwargs) except Exception as e: return Response({"error": "something went wrong"},) serializers.py class BlogSerializer(serializers.ModelSerializer): users = serializers.CharField() class Meta: model = Blog fields = "__all__" def create(self, validated_data): user_usernames = validated_data.pop('users', []) blog = Blog.objects.create(**validated_data) users = User.objects.filter(username__in=users) blog.tagged_users.set(users) return blog It is not saving when I pass user names string like "user1", "user2". Then I thought maybe passing username string may be antipattern then I tried to convert CharField into ListField like users = serializers.ListField(child=serializers.CharField()) but then it showed { "error": "'ManyRelatedManager' object is not iterable" } -
Django how to check if models have a field that contains substring in it
For example class A: logo_img = models.ImageField() cover_img = models.ImageField() So i want to check if model A has any field that contains 'logo' or 'cover' in it. How can i check that -
Djang-Default_storage.open() no such file or directory
I am using default_storage to store contents to a csv file on azure cloud storage. Have used default_storage.open("filepath/subfolder/subfolder1"+filename,"w") to create file. But it gives No such file or directory error when folders and subfolders in "filepath" are not present. Doesn't default_storage creates necessary folders to store a file in a folder? I tried doing same thing on local file system, through which I came to know that it requires those folders to be created at first. I solved the problem using os.mkdir(). But not sure about azure cloud storage. Also can anyone provide any other source of default storage documentation? since the original documentation is difficult to understand as a beginner for me. Thanks!! -
Vercel doesn't detect repository from Gitlab (University Gitlab)
My university has its own gitlab domain (gitlab.xyz.ac.id) and I want to deploy my university project (a django project) in my university gitlab repository, but when I tried to import gitlab repository in Vercel it didn't detect any repositories that was created in my university gitlab and it just detect the repositories that I've created in my gitlab.com (Note: Both my gitlab.com and university gitlab have the same username) I tried the import third party git repositories option in Vercel too but it still didn't workout and it still didn't detect my uni project repository from my university Gitlab. I've already tried deploying one of my django project from my own repository in gitlab.com with CI/CD and it works fine. But for this case, I need to deploy the project that is located in a repository from my university Gitlab. Does anyone have any idea how to solve this problem? Thanks -
issue installing taming-transformers into django framework(python code)
I am trying to run my dev server for django code and only "bug" left is regarding the taming-transformers module. I get this error message "from taming.modules.vqvae.quantize import VectorQuantizer2 as VectorQuantizer ModuleNotFoundError: No module named 'taming'" and I can see that the folder is there but it is not recognizing it. anyone know how to resolve this? I have tried a lot of methods and no luck so far :( here is the list of what I have tried so far to get it to work when downloading in the mac terminal: pip install taming-transformers-rom1504 pip install taming-transformers pip install -e git+https://github.com/CompVis/taming-transformers.git#egg=taming-transformers pip install -e git+https://github.com/CompVis/taming-transformers.git@master#egg=taming-transformers conda install -c conda-forge taming-transformers conda install -c conda-forge taming -
How to add support of multiple options in Django?
I created a filter to only show items with certain values. A list of social measures is displayed. There are two questions about having children and unemployment. We have or don't have children, and we are or aren't unemployed. The main problem is that the filter doesn't work correctly, due to the fact that I only add one option "no" to the entity. For example, we have a social measure "child allowance", and it's paid regardless of income. I created this measure with having children "yes" and unemployment "no". And if the user selects having children "yes" and unemployment "yes", then the page won't show this measure, although the person is entitled to it. Because only "no" was introduced into unemployment. How to enter "no" and "yes" at the same time when creating a measure? And for the site to show this measure regardless of the choice of unemployment. measure_list.html <div class="headtext"> <h3>Choose your life features</h3> </div> <form action="{% url 'filter' %}" method="get" name="filter"> <h3>Do you have children?</h3> <ul> {% for measure in view.get_children %} <li> <input type="checkbox" class="checked" name="children" value="{{ measure.children }}"> <span>{{ measure.children }}</span> </li> {% endfor %} </ul> <h3>Are you unemployed?</h3> <ul> {% for measure in view.get_income …