Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get image based on category django drf
i want to fetch image on particular category like if i make get request localhost/api/image/3/ i get 3rd category image view.py: class ImageView(generics.ListCreateAPIView): authentication_classes = [] permission_classes = [] pagination_class = None queryset = Image.objects.all() serializer_class = ImageSerializer api output: [ { "title": "aka", "category": 5, "image": "http://localhost:8000/media/home/tboss/Desktop/image/logo.png" }, { "title": "aka", "category": 7, "image": "http://localhost:8000/media/home/tboss/Desktop/image/DSC_9314.JPG" }, { "title": "test", "category": 3, "image": "http://localhost:8000/media/home/tboss/Desktop/image/Pillars_Outdoor_OR_RD_50003619_1280x640_DQMyGuR.jpg" } ] -
django filter returns infinite loop
When I filter the storehouses of a company, it returns the error: RecursionError: maximum recursion depth exceeded in comparison def destroy(self, request, *args, **kwargs): company = Company.objects.get(owner=self.request.user) stores = Store.objects.filter(company=company.id) if len(stores) <= 1: return Response(data={'detail': 'At least one storehouse is required'}, status=status.HTTP_400_BAD_REQUEST) return self.delete(request, *args,**kwargs) -
Blank input, hide next form-group
i have problem with JS/Jquery I will make hide .form-group in form when previous input field is empty and show show .form-group when input field have some text. I have problem with .parents(), this is not possible to use in my case pls help -
django.core.exceptions.ImproperlyConfigured: WSGI application 'auth.wsgi.application' could not be loaded; Error importing module
import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'auth.settings') application = get_wsgi_application() that is the wsgi file that think results in the error above -
The class fuction to retrive photolist not working . Event the print statement is not working or logging in console
class BasicUploadView(LoginRequiredMixin,TemplateView): login_url = 'accounts/login/' redirect_field_name = 'redirect_to' def get(self, request, **kwargs): photos_list = Photo.objects.all().count() print('done') return render(request, 'upload/doc_upload.html',context= {'photos': photos_list}) def post(self, request): form = PhotoForm(self.request.POST, self.request.FILES) if form.is_valid(): photo = form.save() data = {'is_valid': True, 'name': photo.file.name, 'url': photo.file.url} else: data = {'is_valid': False} return JsonResponse(data) -
Django - Using function in template
I'm trying to figure out how to create a progress tracker for my users so they can see how many % of the form they have filled out. I'm stuck not sure how to create the function and then use it / call it in the template. Views - calculate progress function My function within my class currently looks like this (I've deliberately excluded the form in the class to avoid cluttering): class OpdaterEvalView(ModelFormMixin, DetailView): template_name = 'evalsys/evalueringer/evaluering_forside.html' model = Evaluation form_class = OpdaterEvalForm def calculate_progress(self, evaluation=None): value = [evaluation.communication, evaluation.motivate_others, evaluation.development, evaluation.cooperation] count = 0 if value[0]: count += 1 if value[1]: count += 1 if value[2]: count += 1 if value[3]: count += 1 return count * 25 The idea is that it will check the array for which values exist in the database and if 0,1,2,3 values exist it will show 25%, 50%, 75%, 100%. I just don't really know how to make this function work in my template? How do I call it? And maybe the function be outside the class? But how do I then target the specific pk of the evaluation. -
Execute Django custom command from django admin dashboard
I was wondering that if its possible to run custom django commands like startapp sampleapp from admin dashboard. I have a app registered in my project and i created the management and commands folder in that app and run want to know that how i pro-grammatically create the another app by going into django dashboard and in specific app. Something like trigger functionality like on button, when button click it execute the command which create the another djangoapp. Your suggestions are appreciated. -
DRF: Create instances of ManyToMany Relations
My models: class Order(models.Model): order_items = models.ManyToManyField('Product', through='OrderItem') class OrderItem(models.Model): order = models.ForeignKey('Order', null=True, on_delete=SET_NULL) product = models.ForeignKey('Product', null=True, on_delete=SET_NULL) class Product(models.Model): title = models.CharField(max_length=1000) The corresponding serializers: class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = ('id', 'product', 'order', ) class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(source='orderitem_set', many=True, read_only=True) class Meta: model = Order fields = ('id', 'order_items') When I perform a GET-request I get the following result. Every order contains an array order_items which has a relation to a product and an order which is fine. "results": [ { "id": 1, "order_items": [ { "id": 1, "product_variation": 1, "order": 1 } ], }, ] However, I have problems creating a new order. I tried to overwrite the create method from my OrderSerializer but order_items is not in the validated data. What would be a good and appropriate way to solve this / what am I doing wrong? -
Selenium with Python- Message: 'operadriver' executable needs to be in PATH
for checking whether a website loads in opera using selenium with python, using the code def test_opera_compatability(self): driver = webdriver.Opera("functional_tests/operadriver") driver.get("https://www.google.com/") driver.quit() It returns the following error Message: 'operadriver' executable needs to be in PATH. -
Admin user is still using "old" authentication even if this one is override - Django 2.2.6
I would like to know if there is a way to persist a user in my django website. I am using SAML authentication in order to authenticate my users and make sure they have access to this application using Centrify (this is maybe too much details...) I have a custom authenticate backend which is returning a user or creating one if it does not exists (for now as a super user): def authenticate(self, request, username=None): if request.user and request.user.is_authenticated: return request.user saml_user_email = None if username: saml_user_email = username elif 'samlNameId' in request.session: saml_user_email = request.session['samlNameId'] try: user = User.objects.get(username=saml_user_email) except: if saml_user_email: user = User.objects.create_superuser(username=saml_user_email, password='simplePassword', email=saml_user_email) else: user = None request.user = user return user I know I can override the admin login page and make one. But do you know why the admin page still use the "old" authentication process even if in my settings.py I have specify AUTHENTICATION_BACKENDS = [ 'project.authentication.saml.SamlAuthentication'] . I was thinking that the admin page should be using my authentication process. Currently, when I try to connect to the admin page, I am getting redirected to the login page (which I also removed...) Is there a way for me to make sure … -
Django output csv file, filename is not setting as the value of Content-Disposition
I want to download a csv file with custom filename in a django project, but somehow the downloaded filename just display as "download.csv" instead of using the value of filename in Content-Disposition. And I also tried to print it out, but getting a very strange string =?utf-8?b?YXR0YWNobWVudDsgZmlsZW5hbWU9Iuivvueoi+aKpeWQjeaDheWGtV8yMDE5MTEyODA3NDI0Ny5jc3Yi?= the code snippet is : @action(detail=False, methods=['GET']) def download(self, request): registrations = self.filter_queryset(self.get_queryset()) csv_response = HttpResponse(content_type='text/csv') csv_response['Content-Disposition'] = 'attachment; filename="some_custom_name_{time}.csv"'.format( time=time.strftime("%Y%m%d%H%M%S", time.localtime()) ) print("asas",csv_response['Content-Disposition']) writer = csv.writer(csv_response) writer.writerow([ some content, ]) for registration in registrations: term_title = '{order} th'.format(order=registration.term.order) course_title = registration.course.title writer.writerow([ registration.user.email, course_title, term_title, str(registration.confirmation_code), str(registration.payment_due), str(registration.payment_paid), str(registration.source), str(registration.created_at), str(registration.updated_at), str(registration.payment_source), ]) return csv_response the django I am using is 2.2 any ideas why this is happening? I am a newb. Thx in advance -
corss domain login problem sessionid cookie not set in a django-graphql backend api on aws eb
I have setup a django-graphene application on aws eb successfully but there are authentication problems from cross domain. Logins are working on same domain but when trying to login from cross domain it do not work. Using session based authentication (Cookies) My django-graphql api is on a url something like: http://foo.bar.elasticbeanstalk.com/graphql/ When I login from Insomnia (similar to postman) the login works. This is the response I receive Date: Thu, 28 Nov 2019 06:36:39 GMT Server: Apache/2.4.41 (Amazon) mod_wsgi/3.5 Python/3.6.8 Vary: Cookie,Origin X-Frame-Options: SAMEORIGIN Set-Cookie: csrftoken=1FTnBwp8b3OlVVf1NXZqZtWBoZkA1xh4ihryPtvZeTRZj3od5mHn3tDxFhgFvGl9; expires=Thu, 26 Nov 2020 06:36:39 GMT; Max-Age=31449600; Path=/; SameSite=Lax Set-Cookie: sessionid=vv9e1o2m92ekwcaq8xhzoedf9uhues4u; expires=Thu, 12 Dec 2019 06:36:39 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax Content-Length: 190 Content-Type: application/json In insomnia it works the user is logged in. On the frontend I am using gatsby and apollo. The front end is currently running on http://localhost:3000. This is my Apollo client: import ApolloClient from "apollo-boost" import { fetch } from "isomorphic-fetch" const client = new ApolloClient({ uri: "http://foo.bar.elasticbeanstalk.com/graphql/", credentials: "include", fetch, }) export default client When I perform the login mutation no sessionid cookie is set. There is also no csrftoken. Login mutation response: Access-Control-Allow-Credentials: true Access-Control-Allow-Origin: http://localhost:3000 Connection: Keep-Alive Content-Length: 271 Content-Type: application/json Date: Thu, 28 Nov 2019 … -
How to filter a nested serializer's field in Django DRF
I have two models named 'School' and 'Student'. I've created each's serializers and the nested serializer for School having a student serializer as a nested field. Here I want to apply filters on the fields of the serializers using 'django-filters' and it is almost working, BUT ...the problem is that when I filter the nested field, i-e 'students's field' , It doesn't show me the required result. My models are : class School(models.Model): name = models.CharField(max_length=256) principal = models.CharField(max_length=256) location = models.CharField(max_length=256) is_government = models.BooleanField(default=True) def __str__(self): return self.name class Student(models.Model): name = models.CharField(max_length=256) age = models.PositiveIntegerField() school = models.ForeignKey(School,related_name='students',on_delete = models.CASCADE) is_adult = models.BooleanField(default=True) def __str__(self): return self.name and my serializers are: class SchoolSerializer(serializers.ModelSerializer): def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass # Instantiate the superclass normally super(SchoolSerializer, self).__init__(*args, **kwargs) allow_students = self.context.get("allow_students",None) if allow_students: self.fields['students'] = StudentSerializer(many=True, context=kwargs['context'], fields=['name','age','is_adult']) class Meta(): model = School fields = '__all__' class StudentSerializer(DynamicFieldsModelSerializer): class Meta(): model = Student fields = '__all__' and these are the filters that i am using in my views: from django_filters.rest_framework import DjangoFilterBackend from django_filters import FilterSet from django_filters import rest_framework as filters class SchoolStudentAPIView(generics.ListAPIView, mixins.CreateModelMixin): queryset = School.objects.all() serializer_class = SchoolSerializer … -
AuthenticationForm valid Unknown every time in DJANGO
VIEWS.py: def login_user(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): return redirect(user_details) else: form = AuthenticationForm() return render(request, 'django_app/loginuser.html', {'form': form}) `` `please see the below screenshot for the code execution `please see the below screenshot for the code execution i am unable to login with my crdentials -
After Django page refresh Seaborn plot legend have been copy and append
I am try to use Django with Seaborn. First time plot is show perfact but after page refresh plot is ok but same legend copy. I have attached my output image. My code is def complete_application(request, *agrs, **kwargs): sns.countplot(x='licensefor', hue='licensestatus', data=licenses_complete) plt.legend(bbox_to_anchor=(1, 1), loc=2, borderaxespad=0.) plt.tight_layout() figfile = BytesIO() plt.savefig(figfile, format='png') figfile.seek(0) # rewind to beginning of file figdata_png = base64.b64encode(figfile.getvalue()) content_data = { 'result':figdata_png.decode('utf8'), } return render(request, 'complete_application.html', content_data) I have find solution in stackoverflow but i can not get any answer related to this. Thanks -
makemigrations for a model that is created via inspectdb
I have a database in microsoft sql server. I created tables and views in it. I ran py manage.py inspetdb view_Name > Models.py and populated my models.py file with managed=false. I also dont want my model to alter my database. I just want it for data retrieval. After inspectdb should i apply makemigrations on my app or is just migrate enough? And also what are the points to remember while using inspectdb on an existing database. Also I have something like the below in my models.py file for all columns created = models.DateTimeField(db_column='Created', blank=True, null=True) # Field name made lowercase Is having the fieldname in lowercase safe ? Or should I change it as it is in my column? And what are those db_column='Created', blank=True, null=True fields. Not all my views have such fields. Only a few have such values. -
Django _mysql.connection.query(self, query) django.db.utils.OperationalError: (1050, "Table 'gaur' already exists")
I don't want to use Fake app migrate option for the solution Please suggest any other method for this problem Do check my code Models - from django.db import models from mptt.models import MPTTModel, TreeForeignKey class Delhi(models.Model): account_id = models.IntegerField() type_code = models.CharField(max_length=200) sub_type_code = models.CharField(max_length=200) name = models.CharField(max_length=200) credit_amount = models.IntegerField() debit_amount = models.IntegerField() # parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE) class Meta: managed = True db_table = 'gaur' def __str__(self): return self.type_code class Ranchi(MPTTModel): node_name = models.CharField(max_length = 100) parent = TreeForeignKey('self', null = True, related_name = 'strctr', on_delete = models.CASCADE) def __str__(self): return self.name Serializer - from rest_framework import serializers from .models import Delhi, Ranchi class DelhiSerializer(serializers.ModelSerializer): class Meta: model = Delhi fields = "__all__" class RanchiSerializer(serializers.ModelSerializer): class Meta: model = Ranchi fields = "__all__" View - from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import generics from rest_framework import status class CreateView(generics.ListCreateAPIView): """This class defines the create behavior of our rest api.""" queryset = Delhi.objects.all() serializer_class = DelhiSerializer def perform_create(self, serializer): """Save the post data when creating a new bucketlist.""" serializer.save() class DetailsView(generics.RetrieveUpdateDestroyAPIView): """This class handles the http GET, PUT and DELETE requests.""" queryset = Delhi.objects.all() serializer_class = … -
How can I deploy my django website on multiple server, that is how can I make it distributed?
I have my django website, which I want to make distributed, I know all the concept of system design and distributed system but still cannot figure out how can I serve it using multiple server. Can someone suggest how to make my system distributed. How can I install load balancer and direct the request to my servers. I cannot find any resource to learn about making my django website distributed and install various distributed system software concept on it? How can I make my django website serve from different server with a centralised database. Can someone explain me the steps to do so? Or point me to any learning material cuz I can't find any resource online. -
How to edit default django home page and new page
I am beginner to Django. I just install the django & there is default home page appearing. I want to edit the default home page content & create new extra pages. Please can any one help me how to add the new pages with using the template. -
How join annotate value of QuerySet and property field of Model to one logic in Django?
I have this situation. I calculate a diameter in two ways: annotate of QuerySet and property in Model. class CircleQuerySet(models.QuerySet): def annotate_diameter(self): return self.annotate(diameter=models.F('radius')*2) class Circle(models.Model): radius = models.DecimalField(max_digits=11, decimal_places=2) objects = CircleQuerySet.as_manager() @property def diameter(self): return self.radius * 2 How can I join this two ways to one? Is it exists? -
Django - how to perform delete object using a view
This is my code in my html {% for summary in psummary %} <tr> <td colspan="3" class="tdcell">{{summary.Description}}</td> <td colspan="2" class="tdcell">{{summary.Start_Grading_Period}}</td> <td colspan="2" class="tdcell">{{summary.End_Grading_Period}}</td> <td colspan="2" class="tdcell">{{summary.Method}}</td> <td colspan="3" class="tdcell"><span style="text-align: right;font-weight: 600;" class="close" onclick="deleteRow(this)"><a href="url:delete_view">&times;</a></span></td> </tr> {% endfor %} this is how it looks like this is my views.py def function(request,part_id =None): object = gradingPeriodsSummary.objects.get(id=part_id) object.delete() print(object) return render(request, 'admin/Homepage/view.html') urls.py path('delete/(?P<part_id>[0-9]+)/$', Homepage.views.function, name='delete_view'), i just want that if the teacher click the close button it will delete the record in the database i followed the instruction here, but its not working Django - How to delete a object directly from a button in a table -
How to handling "We are unable to register the default service worker" when already using https?
I have a project using django and firebase. I need notification feature of firebase so that I create a service worker file in templates folder and my view.py like : ... class ServiceWorkerView(View): def get(self, request, *args, **kwargs): return render(request, 'whizper_apps/firebase-messaging-sw.js', content_type="application/x-javascript") my urls.py like : url(r'firebase-messaging-sw.js', views.ServiceWorkerView.as_view(), name='service_worker') When I running my project from localhost, it work fine. I get the token and can get notification. Then, I'm trying deploy my project to server using gunicorn, supervisor, nginx and using https (the documentation to set up https in nginx : https://www.linode.com/docs/web-servers/nginx/enable-tls-on-nginx-for-https-connections/#configure-the-http-block). When I run my project, i get error like this I follow https://jee-appy.blogspot.com/2017/01/deply-django-with-nginx.html as documentation to deploy my project. What I have to do so the service worker can work and I get the notification token. Thank's before. -
MarkItUp Supports Alignment Option or Not
I am using Django_Markdown app for my project. I just wanted to know whether Markitup supports Alignment options or not? If not, then how can i add this alignment tool in my text body? I have tried writing the text under the tag but it's not working. Thanks in advance. -
Best way to pass variable to remote (Golang) app from Django View
I'm creating a web application where a server will register itself via curl to the rest framework. When the POST is executed in the view.py of the django app it'll will kick off a remote command to a Golang app that'll change the server's port VLAN and start a Docker container. That piece I can figure out, but the execution from POST to ensure the Golang is handling this participial server I'm not sure on. My thought is to use a option parser because the payload from the server will have server serial, mac, ip info that'll be saved in the database. When the Golang app runs, something like <Go app> -s <serial Number> will then perform a GET call based on the provided serial number then start doing its thing. Would that be the best way to get this done or is there a better way? -
Error: failure to route to my newly created app
So I'm following the django tutorial at https://docs.djangoproject.com/en/2.2/topics/http/urls/ i reached the point where i should be able to navigate to the polls url instead I get a 404 error Page not found (404) Request Method: GET Request URL: http://localhost:8000/polls/ Using the URLconf defined in mysite.urls, Django tried these URL patterns, in this order: admin/ The current path, polls/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. my folder structure is D:. | db.sqlite3 | manage.py | +---mysite | | settings.py | | urls.py | | wsgi.py | | __init__.py | | | \---__pycache__ | settings.cpython-37.pyc | urls.cpython-37.pyc | wsgi.cpython-37.pyc | __init__.cpython-37.pyc | \---polls | admin.py | apps.py | models.py | tests.py | urls.py | views.py | __init__.py | \---migrations __init__.py I have modified the mysite/urls.py as from django.contrib import admin from django.urls import path, include urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] added a urls.py file inside polls folder and filled it with from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index') ] and finally adjusted the polls/views.py file to …