Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Suspicious activity on Django
I was running a django server on my aws instance for testing and these requests popped, showing bad requests from an unknown ip with a link of russia. I am unsure what is it and is this a major security threat. Can anyone explain what does this means ? -
Django application level wsgi setting
My django project has three apps as shown. /project/ -/project/ - settings.py - wsgi.py - urls.py -/auth/ -/app1/ -/app2/ Here app1 and app2 are independent of each other (use different models and views) but share same auth. Is it possible to have separate app level WSGI file rather than project level so that the apps can be well isolated ? -
How to write a condition, that the function is not executed, if there is data in the database? Django
Every time a run my Django app, the same data is inserted into database. I only want to include data the first time, when there are no values in base(table). I am getting my data from API and Json. view.py from django.shortcuts import render, HttpResponse from .models import Brands import requests def get_brends(request): all_brands = {} url ='http://makeup-api.herokuapp.com/api/v1/products.json?brand' response = requests.get(url) data = response.json() for result in data: brand_data = Brands( name=result['name'], price=result['price'], image_link=result['image_link'], brand=result['brand'], category=result['category'], product_type=result['product_type'], description=result['description'], ) brand_data.save() all_brands=Brands.object.all().order_by('-id') return render(request, 'brands_makeup/brands.html', { "all_brands":all_brands}) model.py class Brands(models.Model): name = models.CharField(max_length=100, default="None") price = models.DecimalField(decimal_places=3,max_digits=4,null=True,blank=True) image_link = models.CharField( max_length=50, blank = True, null = True) brand = models.CharField( max_length=150, blank = True, null = True) category = models.CharField( max_length=150, blank = True, null = True) product_type = models.CharField( max_length=150, blank = True, null = True) description = models.CharField( max_length=1500, blank = True, null = True) def __str__(self): return self.name , self.price , self.category , self.brand I am only trying to include JSON once in my database when a database is empty. -
Call a separate http request from django view and return response as view response
I need to call Microsoft graph API from front end. I have designed the flow like this: Ajax Call --> Django View --> Microsoft Graph API --> Return response of graph api from django view I am sending an ajax call from front end to a django view. In view i am using concurrent module to initiate a new thread for http request(calling Microsoft graph API). I have followed this answer. Issue is the http request that i have initiated for Microsoft Graph API is getting timed out. If i initiate the request stand alone from python manage.py shell then it is working fine probably because it is an independent process. class MicrosoftSubscriptionList(LoginRequiredMixin, ListView): model = ApiSubscription template_name = "ReportingWebapp/microsoft_api_subscriptions.html" def post(self, request): action = request.POST.get("action", None) if action == 'create_presence_subscription': try: with concurrent.futures.ThreadPoolExecutor() as executor: # create_presence_subscription function will call graph api future = executor.submit(create_presence_subscription) api_response = future.result() return HttpResponse(api_response.text) except Exception as e: log.exception(e) return HttpResponse("Internal Error") Microsoft graph api error that i am getting "message":"Subscription validation request timed out." -
changing django admin panel interface
here is the Django default admin panel I want to keep the functionality (like accessing users table and buttons) but change the interface. I don't want to write Django and It is also hard and needs much time to style this panel again. I want exactly the default admin panel but with an attractive style and appearance. I saw Django admin dashboard templates but it did not have the functionality, for example a button that when you click you can see users table and you can add or edit user. Is there any quick way (like templates or a stylesheet) to achieve this goal? -
issues in django REST framework custom user registration,login and login with separate profile for each role
I am beginner to Django and try to implement custom user model and providing functionality for registration, login with separate profile for each role. for application I am trying to develop there us 3 users roles 1) student 2) Teacher 3) Institute so I am trying to address following broad level requirement a) need separate registration REST API URL for student, Teacher and Institute b) registration REST API URL for student, Teacher and Institute should require only unique email address and password. username may derived internally based on users email Address c) After registration of student/teacher/institute it should create blank profile and separate REST API be provided for updating Profile of student, teacher and institute. field of profile of student , teacher and institute are different as shown in content of model.py my current code as shown below does not work as expected and gives many errors a) python manage.py createsuperuser command gives error File "D:\djangoprojects\hellodjangousers\venv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' b) after commenting some code and creating super user errors occurs for creating profile of user c) url http://127.0.0.1:8000/api/v1/rest-auth/registration/ when posted shows error TypeError at /api/v1/rest-auth/registration/ save() takes 1 positional argument … -
How to store API data in variable/Memory in Python or django and reuse it when required without calling API again?
How to store API data in variable/Memory in Python or django and reuse it when required without calling API again? without storing data in any file. -
Unique single comment like and dislike for each user
My comments model: class Comment(models.Model): product = models.ForeignKey(Product ,on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User ,on_delete=models.CASCADE, max_length=80, related_name='comments_user') body = models.TextField() subject = models.CharField(max_length=255, default="") created_on = jmodels.jDateField(auto_now_add=True) created_on_time = models.TimeField(auto_now_add=True,null=True) active = models.BooleanField(default=False) like = models.IntegerField(default=0) dislike = models.IntegerField(default=0) And my like and dislike views: def like(request,product_id,comment_id): product = get_object_or_404(Product, id=product_id) comment = get_object_or_404(Comment, product=product, id=comment_id) comment.like = comment.like + 1 comment.save() return redirect("/products/category/"+str(product.product_category.category_url)+"/"+str(product.product_subcategory.subcategory_url)+"/"+str(product.product_url)+"/") def dislike(request,product_id,comment_id): product = get_object_or_404(Product, id=product_id) comment = get_object_or_404(Comment, product=product, id=comment_id) comment.dislike = comment.dislike + 1 comment.save() return redirect("/products/category/"+str(product.product_category.category_url)+"/"+str(product.product_subcategory.subcategory_url)+"/"+str(product.product_url)+"/") I want each user only like or dislike the specific comment. and then if that user changed the opinion and wanted to dislike it, the like would be remove and add 1 more to dislike. and also one comment just can get one like or dislike from one user. -
render_to_string doesn't render image
I have this Market Application where cashier can print receipts via website. I render an html document and order printer to print. But it seems that it doesn't render/find images. Here is my code: context = { 'order': order, 'item': item } html = render_to_string('receipt.html', context) And my html : {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Use PyQt5 to print thermal receipts</title> </head> <body> <img src=' {% static "images/favicon.png" %} ' style="align-items: center;" width="130" height="130"/> <div id="capture"> <div class="print_container"> <h3>Market Name</h3> <span>---------------------------------------</span> <br> <span>Order number: {{ order.code }} </span> <br> <br> <span>Order time: {{ order.created }}</span> <br> <br> <span>Cashier: {{ order.waiter }}</span> <br> <!--- and so on ---> It's my first project using render_to_string function so any help would appreciated. -
Django: Reverse for ‘topic_posts’ with arguments ‘(3, ”)’ not found
The reverse of '‘topic_posts’ works fine in other places. But it doesn’t work here. HTML file <td class="align-middle"> {% with post=board.get_last_post %} <small> <a href="{% url 'topic_posts' board.id post.topic.id %}"> By {{ post.created_by.username }} at {{ post.created_at }} id - {{ board.id }} {{ post.topic.id }} </a> </small> {% endwith %} </td> url setting path('boards/<int:board_id>/topics/<int:topic_id>/', views.topic_posts, name='topic_posts'), topic = get_object_or_404(Topic, board_id=board_id, id=topic_id) return render(request, 'topic_posts.html', {'topic': topic}) When I changed the board.id and post.topic.id to integer value , for exmaple 1 and 24, the web would render. I commented <a href="{% url 'topic_posts' board.id post.topic.id %}"> and added {{ board.id }} {{ post.topic.id }} to see if there is an error with the query, turned out there is no problem, it would render 1, 24 on the webpage. Then I tried <a href="{% url 'topic_posts' board.id 24 %}"> It worked fine, but <a href="{% url 'topic_posts' board.id post.topic.id %}"> still won’t work. Thanks for reading! -
ENVIAR MENSAJE A UN USER ESPECIFICO QUE SE LE PASA POR URL DJANGO POSTMAN
A partir de la pagina de detalle de un anuncio, envio por la url el usuario que ha subido el anuncio, para enviarle un mensaje. Necesito que el campo de destinatario en el formulario del mensaje se muestre este usuario y no tenga yo que buscarlo manualmente. El sistema de mensajes es con Postman y Django. [Formulario mensaje][1] [1]: https://i.stack.imgur.com/No9c7.png <form action="{% if next_url %}?next={{ next_url|urlencode }}{% endif %}" method="post">{% csrf_token %} <table> {% block pm_write_recipient %}{% endblock %} {% comment %} {{ form.as_table }} {% endcomment %} <p> <label>Destinatario: </label> <input type="text" name="recipients" id="recipients" > </p> <p> <label>Asunto: </label> <input type="text" name="subject" id="subject" > </p> <p> <label>Contenido: </label> <textarea name="body" rows="3" id="body" ></textarea> </p> </table> Arriba se ve que le paso el usuario marta, este usuario debe aparecerme en el campo destinario. urls.py (postman): views.py (postman): class WriteView(ComposeMixin, FormView): """ Display a form to compose a message. Optional URLconf name-based argument: ``recipients``: a colon-separated list of usernames Optional attributes: ``form_classes``: a 2-tuple of form classes ``autocomplete_channels``: a channel name or a 2-tuple of names ``template_name``: the name of the template to use + those of ComposeMixin """ form_classes = (WriteForm, AnonymousWriteForm) autocomplete_channels = None template_name = 'postman/write.html' @sensitive_post_parameters_m @never_cache_m … -
DJANGO : how to run API-request in the background so my users experience no delay?
I've a script that get's data from an API. The API needs some time to calculate and return the values. This means that my my user experiences a lot of delay (9sec) to go to the next page, until the API has returned the values. Is there a way to run the script with the API in the background? So the user can continue their experience without any hinder ? (I wonder if async functions can help?) the code I use to run the API: import requests body = {...} headers = { 'Accept': 'application/json, application/geo+json, application/gpx+xml, img/png; charset=utf-8', 'Authorization': '...', 'Content-Type': 'application/json; charset=utf-8' } call = requests.post('https://api....', json=body, headers=headers) print(call.status_code, call.reason) print(call.text) -
How to use multiple lookup fields in Django Rest framework in a class based view?
I literally searched similar questions but didn't a answer that solves my question Here i want a functionality like a question can have multiplt answers my models.py class QuestionModel(models.Model): question = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) doubt_class_id = models.ForeignKey(DoubtClasses, on_delete=models.CASCADE) conceptual_class_id = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE, null=True, blank=True) status = models.BooleanField(default=False) mentor = models.ForeignKey(Mentor, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.question def clean(self): if self.doubt_class_id and self.conceptual_class_id : raise ValidationError("only one field can be set") class AnswersModel(models.Model): answer = models.TextField() question_id = models.ForeignKey(QuestionModel, on_delete=models.CASCADE) my urls.py path('questions/', views.QuestionModelView.as_view()), path('questions/<int:id>/', views.QuestionModelViewID.as_view()), path('questions/<int:id>/answer/', views.AnswerModel.as_view()), my views.py # Create your views here. class QuestionModelView(mixins.ListModelMixin, mixins.CreateModelMixin,GenericAPIView): queryset = models.QuestionModel.objects.all() serializer_class = serializers.QuestionModel_serializer permission_classes = [IsAuthenticated] def get(self, request): return self.list(request) def post(self, request): return self.create(request) class QuestionModelViewID(mixins.ListModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, mixins.DestroyModelMixin,GenericAPIView): queryset = models.QuestionModel.objects.all() serializer_class = serializers.QuestionModel_serializer permission_classes = [IsAuthenticated] lookup_field = 'id' def get(self, request, id=None): if id: return self.retrieve(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) def put(self, request, id=None): if int(request.POST.get('author')) != self.request.user.id: return Response("you cannot edit othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if id: return self.update(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) def delete(self, request, id=None): if int(request.POST.get('author')) != self.request.user.id: return Response("you cannot destroy othe user question", status=status.HTTP_405_METHOD_NOT_ALLOWED) if id: return self.delete(request, id) else: return Response(status=status.HTTP_204_NO_CONTENT) class AnswerModel(mixins.ListModelMixin, mixins.CreateModelMixin, GenericAPIView): … -
Django Rest Framework: consuming external API's
I'm practicing my Django by building app that consume API's from several sport sites, what I want to achieve is a single API endpoint that works as a search engine and return all possible results with pagination of 10 results per request. What is the best approach for building app like this? How to avoid being blocked by making too many requests per minute, is it a good idea to store all the requested data in local cache/db ? -
'super' object has no attribute 'set_context'
I upgrade Django version from 1.11 to 3.2 and upgrade the installed python. I am facing an error at this line super().set_context(serializer_field) Below is the Full class code. '''' class UniqueForProjectValidator(UniqueValidator): """ Validates uniqueness of field within project Context of parent serializer must contain 'project' key Model must have project field """ def set_context(self, serializer_field): super().set_context(serializer_field) self.project = serializer_field.parent.context['project'] def filter_queryset(self, value, queryset): queryset = queryset.filter(project=self.project) return super().filter_queryset(value, queryset) '''' -
How can I delete all child objects of a parent object without deleting parent object with Django
I have two models that use the same class as foreign key. I don't want to delete the parent model (which is being used as foreign key) but delete the child models that are associated with the parent model. class A(models.Model): pass class B(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, default=None) class C(models.Model): a = models.ForeignKey(A, on_delete=models.CASCADE, default=None) Now I am deleting them separately as below : b_list = B.objects.filter(a = A) for b_list_item in b_list: b_list_item.delete() c_list = C.objects.filter(a = A) for c_list_item in c_list: c_list_item.delete() How can I delete them all together with a single command ? -
the short links doesn't redirects to the original link using pyshorteners
I am trying to achieve that the short links redirects to the original link using pyshorteners library. Below i have attached the files to help know. Views.py contains the function from which the individual products and short link being created and rendered to the template. Urls.py shows the url patterns for these functions only. And following Images are showing how it has been working till now. I am not using form to accept any url, instead i am creating short links for every products page and every page has its unique shortlink Please help as I am stuck in this part for a while now. Views.py #Display individual product and render short links for all using pyshorteners def link_view(request, uid): results = AffProduct.objects.get(uid=uid) slink = request.get_full_path() shortener = pyshorteners.Shortener() short_link = shortener.tinyurl.short(slink) return render(request, 'link.html', {"results": results, "short_link": short_link}) Urls.py urlpatterns = [ path('link/', views.link, name='link'), path('link/<int:uid>/', views.link_view, name='link_view') ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This image is of the HTML template , where both current link and short link has been rendered. This image is when i copy the shortlink and search it on the browser, the host is not been applied to the short link. Hence, the short links are not linking … -
How Django prints SQL statements even when unit testing
You can have Django output SQL statements corresponding to ORM operations during non-unit tests by configuring them as follows. LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level': 'DEBUG', }, } } But the above configuration does not print SQL when it comes to unit tests, what should I do to output SQL statements corresponding to ORM operations in unit tests? Translated with www.DeepL.com/Translator (free version) -
Django POST or GET
I have a page for teachers to input the marks and registration number of the students.. After input, it gets stored in the database and the students can fill a form which asks for D.O.B and registration number and get's the marks based on that particular registration from the database.. But when I use post request for the students, it shows form is invalid and says that, the registration number already exists.. My views.py: from django.shortcuts import render from django.views.generic.list import ListView from django.views.generic.edit import CreateView from django.urls import reverse_lazy from .models import Mark from django.contrib.auth.views import LoginView from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic.edit import FormView from .forms import ViewResultForm, AddResultForm from django.contrib import messages class ViewResultFormView(FormView): template_name = 'main/home.html' form_class = ViewResultForm success_url= 'result' def form_valid(self, form): global registration_number global dob registration_number = form.cleaned_data['registration_number'] dob = form.cleaned_data['dob'] return super(ViewResultFormView, self).form_valid(form) class MarkListView(ListView): model = Mark template_name = "main/result.html" context_object_name = 'result' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['result'] = context['result'].get(registration_number=registration_number, dob=dob) return context class MarkCreateView(LoginRequiredMixin, CreateView): model = Mark template_name = "main/add.html" form_class = AddResultForm def form_valid(self, form): total_10th = ((form.cleaned_data['class_10_sub_1'] + form.cleaned_data['class_10_sub_2'] + form.cleaned_data['class_10_sub_3'])/300)*30 total_11th = ((form.cleaned_data['class_11_English'] + form.cleaned_data['class_11_Maths'] +form.cleaned_data['class_11_Physics'] +form.cleaned_data['class_11_Chemistry'] +form.cleaned_data['class_11_Comp_Bio'])/500) * 30 total_12th = ((form.cleaned_data['class_12_English'] + … -
How to convert django complete app to an iOS app
I already see this link and some how I understand how to setup my project backend with REST api and restive data from my django and I find out I have to use react for my front end (please current me if I’m wrong) then I wonder how can I transfer my layout in HTML and is of my website to order to make it work in iOS The website I made is a social network and base on user make question and answer and upload it to a server after upload it’s work like a flash card, front side is question and when user click on image your text will flip and show the answer behinds well please tell should I make all of my HTML and is again or I can use those code I have no idea about how its can work Please kindly just tell what material should I study to deploy my django project to iOS app and android as well Please tell me the fastest and easiest way Until now I find out I should use REST API and what else should I do to make my app work with lowest code writing as … -
Django changing uploaded image path
I am uploading images with labels and saving them in folders according to their labels. I have a function to change the labels of the image. after which I can move the images from the old label folder to the new one. But How do I change the path of the image in the database? Because class-based list view is still looking for images at old path(updated while uploading) I tried doing d.image.url = 'new_path' but it didnt work: AttributeError: can't set attribute. Is there any other way to update the URL/path in the database. -
How to check whether the checkbox is checked in Django?
I have a Task class which contains a boolean attribute called 'complete', which stores the information wheter a task is completed or not. Now in my task list, I would like to have a checkbox to change the Task.complete to True if checkbox is checked. <div class="task-list-wrapper"> {% for task in task_list %} <div class="task-wrapper"> {% if task.complete %} <div class="task-title"> <div class="task-complete-icon"></div> <i><s><a href="{% url 'task-update' task.id %}">{{task}}</a></s></i> </div> <a class="delete-link" href="{% url 'task-delete' task.id %}">&#128465</a> {% else %} <div class="task-title"> <div class="task-incomplete-icon"></div> <a href="{% url 'task-update' task.id %}">{{task}}</a> </div> <a class="delete-link" href="{% url 'task-delete' task.id %}">&#128465</a> {% endif %} </div> {% empty %} <h3>No items in list</h3> {% endfor %} </div> Assuming that each 'task' in 'task_list' will have own <input type="checkbox" name="task-status" value="Mark as complete"> how do I assign the task.complete = True? -
Django saving overriden user fails when ModelForm.save is done running
Context I override AbstractBaseUser in order to provide it with extra fields I needed. I can create a User no problem, and I can use my User objects to connect to my app. My issue starts when I try to modify an existing user from the admin view. In my admin view for the User model, I show an inline for a Permission model related to my users and I use an override of ModelForm specific to my Model. Here is its code : from django.contrib.auth import get_user_model class CustomUserAdminForm(forms.ModelForm): """ Comment """ class Meta: model = User fields = [ "email", "password", "is_admin" ] def save(self, commit=True): """ Save override. """ # Raise in case of errors. if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, "created" if self.instance._state.adding else "changed", ) ) # Get custom User model. my_user_model = get_user_model() # Find user if the object exists. try: self.instance = my_user_model.objects.get(email=self.cleaned_data["email"]) except my_user_model.DoesNotExist: self.instance = my_user_model() self.instance.email = self.cleaned_data["email"] self.instance.is_admin = self.cleaned_data["is_admin"] # Saving the hash of the password. if not self.cleaned_data["password"].startswith("pbkdf2_sha256$"): self.instance.set_password(self.cleaned_data["password"]) if commit: # Copied from BaseModelForm. # https://github.com/django/django/blob/master/django/forms/models.py # If committing, save the instance and the … -
In Django, how to make files downloadable for production environment?
I've been working on a Django project, in which I would take in user files and encrypt/decrypt the file as the output. Hence, I'd also provided the option to download the encrypted/decrypted file. This all in the local server by adding static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in the application's urls.py Now, I would like to publish the website. In fact, I'd configured the Heroku settings as well. But the problem is - it is not wise to use serve media in a production environment. And I can't figure out how to design a download function for the files on the production website. Below is the download.html template (Which displays the download link for the local server) {% if var.function == 'ENCRYPT' %} <a href="{{ var.encryptedfile.url }}" class="btn btn-success">Download</a> {% else %} <a href="{{ var.decryptedfile.url }}" class="btn btn-success">Download</a> {% endif %} Here, var is the queryset object, retrieved from the database. Application-level urls.py urlpatterns = [ path('', MainpageView.as_view(), name='home'), path('download/', DownloadpageView.as_view(), name='download'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I cannot understand that how to modify the views.py or urls.py or download.py so that the files can be downloaded from the published website? Many Thanks! -
Poting a working Django project to Passenger
I developed my Django project and its applications using PyDev, it works well with the integrated server and also published on a local server running Apache and Django. Now I want to move/port the project and its applications to a shared web server (on ifastnet.com) running Passenger. The main difference I see, it is the passenger_wsgi.py file. I changed it to run my applications but it does not work also giving no so much information about errors. I suppose many others had this problem so I want to learn how to solve it. Thanks, Massimo