Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why pytest (pytest-django) doesn't have access to .env variables through decouple which regular django files access as normal?
I have a django project and I'm setting up my testing environment with pytest and pytest-django. Previously, I have set up my environment variables like DB_HOST using decouple module. These variables work fine when they are used by regular django Python files. However, when I run pytest on tests which use the same files, these variables are not found. decouple.UndefinedValueError: DB_HOST not found. Declare it as envvar or define a default value. My pytest.ini file: [pytest] DJANGO_SETTINGS_MODULE = bapi_django.settings The error suggests to declare these variables, but it seems anti-DRY to me. Is there anyway I can use my django project level env variables or do I have to redefine them from scratch? -
How should I give a id to the button which displays each button in a for loop
I'm creating a quiz application in Python Django where in the template I'm iterating through a list of questions and then iteration through a list of answers for the current question and displaying those. I have a button for each answer. When I click a answer button an ajax call is triggered which calls my view to check if the answer is correct and returns the response. As I'm iterating through the answers for-loop and displaying a button for each answer of a question how should I make the clicked answer button red or green depending on the answer I got from my view response telling me if it is right or wrong? I'm confused how to determine unique id for each button and then change the color of that button. Below is the code <div class="row"> {% for question in questions %} <div class="col-md-4" > <div class="card mb-2" id="question_counter" value="{{forloop.counter}}"> <div class="card-body" > <p>{{forloop.counter}}{{"."}}{{ question.question|safe }}</p> <br> <div class="card-body" > {% for answer in question.answers %} <li><button type="button" class="btn btn-primary display: inline-block width: auto;" name="answer" id="submit" value="{{answer}}">{{ answer|safe }}</button></li> </br> {% endfor %} </div> </p> </div> </div> </div> {% endfor %} Also I have attached a sample showing how … -
model doesn't display title Django
In the admin the content of my model doesn't show a title, now I now that I can make a field called title but then I need it to be an incrementing int, but if I do that Django tells me that that can't happen because it will get rid of the ID, is there anyway I can fix this? model: class ReviewRating(models.Model): album = models.ForeignKey(albums, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) subject = models.CharField(max_length=100, blank=True) review = models.TextField(max_length=500, blank=True) rating = models.FloatField() ip = models.CharField(max_length=20, blank=True) status = models.BooleanField(default=True) created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.subject how the admin looks if there is any information missing please let me know -
How to add value to django form template in html
I created a django form and use it in html in user profile page. {{profile_form.first_name}} how can I add form value for this column of the form I tried to add value from form widget but I need to add user data but I can only do it in html like user.first_name -
DJANGO, NGINX and WINDOWS SERVER
I have deployed a django application using nginx. These are the nginx configurations I configured. **c:/nginx/sites-available/project_nginx.conf & c:/nginx/sites-enabled/project_nginx.conf ** server { listen 80; server_name 192.168.xxx.xx; location /static { alias D:/project/apps/media; } location /media/ { alias D:/project/apps/media; } location / { proxy_pass http://localhost:8000; } } **c:/nginx/conf/nginx.conf ** events { worker_connections 1024; } http { include. mime.types; default_type application/octet-stream; include C:/nginx/conf/sites-enabled/project_nginx.conf ... I have successfully deployed it and it is running without any problem on the server but, NB: The server is a windows server the problem is that, I cannot access the software on other PCs which are on the same network. What is a possible solution to this problem? I need the application to be accessible with other PCs on the intranet. -
Using pandas in django, how to release memory?
In a django project that focuses on data analysis, I use pandas to transform the data to a required format. The process is nice and easy, but the project quickly starts using 1GB of RAM. I know that Python doesn't really free up memory in this case (https://stackoverflow.com/a/39377643/2115409) and that pandas might have an issue (https://github.com/pandas-dev/pandas/issues/2659). How do I use pandas in a django project without exploding memory? -
How to hook up two viewsets to a single django url
I hava a standard DRF viewset for a model which I hook up in my urls.py as such: router = routers.SimpleRouter() router.register("", ResourceViewSet, basename="resource") urlpatterns = [ path( "", include(router.urls), name="basic-resource-crud", ), ] Resource is the only model in the app so it is hooked up to the root. Additionally I would like to hook up the PATCH method on the root url to a bulk update view: router = routers.SimpleRouter() router.register("", ResourceViewSet, basename="notifications") urlpatterns = [ path( "", BulkResourceUpdateViewSet.as_view(), name="bulk-resource-update", ), path( "", include(router.urls), name="basic-resource-crud", ), ] The BulkResourceUpdateViewSet class only defines a patch method. However with the setup above only the first route in the urlpatterns array is taken into considereation by Django and the other is ignored. How can I achive the url structure I am looking for: GET / : ResourceViewSet PATCH / : BulkResourceUpdateViewSet.patch GET /<pk>/ : ResourceViewSet POST /<pk>/ : ResourceViewSet PATCH /<pk>/ : ResourceViewSet PUT /<pk>/ : ResourceViewSet -
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 …