Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use RelatedField in Django rest framework?
I have problem with Django restframe work i have 2 table that one of them is a foreign key to another i have used RelatedField in serializer but i get an error:'Relational field must provide a queryset argument, can someone help me in this case my code is as below: class DocTable(models.Model): project = models.CharField(max_length=1000, null=True, blank=True) document_no = models.CharField(max_length=1000, null=True, blank=True) document_title = models.TextField(null=True, default='', blank=True) class PlanTable(models.Model): Document = models.ForeignKey(DocTable, on_delete=models.CASCADE, related_name='doctable') work_type = models.CharField(max_length=1000, null=True, blank=True) description_work = models.TextField(null=True, default='', blank=True) serializers.py class DocTableSerializer(serializers.ModelSerializer): doctable = serializers.RelatedField(many=True) class Meta: model = DocTable fields = ['pk', 'project', 'document_no', 'doctable'] read_only_fields = ['pk'] class PlanTableSerializer(serializers.ModelSerializer): class Meta: model = PlanTable fields = ['pk', 'doctable', 'work_type', 'description_work'] read_only_fields = ['pk'] views.py class DocTableListView(generics.ListAPIView): lookup_field = 'pk' serializer_class = DocTableSerializer def get_queryset(self): return PlanTable.objects.all() def get_object(self): pk = self.kwargs.get('pk') return PlanTable.objects.get(pk=pk) -
Migrate existing Django-Project to Apache (httpd)
There are several tutorials out there on how this is done, but I'm quite confused, some things seem to be from installation to installation different, maybe someone can clarify that. My Django-Project work/ed/s fine, I've now switched from Debug to production and need to migrate to a real Apache. I'm using Fedora in a Docker, the httpd-daemon runs and I can open the default Apache-Page. At this point I'm not starting django-admin runserver any more (is that actually correct?). I'm using monit only to start the httpd-daemon. Are there any other services to be started? Dockerfile (Installs): RUN dnf update -y \ && dnf install -y \ nmap \ vim \ ncurses-devel openssh-server httpd python3-mod_wsgi monit This guy here had the same problem: Deploy Django Application HTTPD In the solution it was referred to the file: $> sudo nano /etc/apache2/sites-enabled/000-default.conf As I'm using the httpd-package and not apache2 it's in my case under /etc/httpd - but I have no sites-enabled folder. I'm not sure if this configuration is the same: [root@9c9cdce01798 /etc/httpd]# ls conf conf.d conf.modules.d logs modules run state There's also: [root@9c9cdce01798 /]# ls /usr/share/httpd error icons noindex server-status There is also no httpd-vhosts.conf. I created the sites-enabled-folder and … -
The view ats.views.index didn't return an HttpResponse object. It returned None instead
The view ats.views.index didn't return an HttpResponse object. It returned None instead. I am trying to implement an authentication system, if I enter the password correctly I don't bump into any problems but when I enter it incorrectly I get this error. Does anyone know how I could solve this? This is my view def index(request): if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): user = form.get_user() login(request, user) return render(request, "homepage.html", context_instance=RequestContext(request)) else: form = AuthenticationForm() return render(request, "index.html", {'form': form}) This is my html {% block content %} <form class="box" method = "post"> {% csrf_token %} <h1>Ats</h1> {{ form }} <input type="submit" name="" value="Login"> </form> {% endblock %} -
How to differentiate the users and admin in the same dashboard in a django application?
I am trying a django application which is having a login and dashboard.In the dashboard I am showing the details which are selected by the user at the time of registration that is working perfect but here the problem the admin can also login to the user dashboard in the dashboard it is showing all the details as blank but I want to show the phrase as no projects This is my views.py : def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user is not None: if user.is_active: auth.login(request, user) return HttpResponseRedirect(reverse('modsy:dashboard')) else: messages.error(request,'Invalid Credentials') # return render(request,'dashboard.html') ## removed 1 # else: ## removed 2 return render(request, 'login.html') # This is a dashboard view def dashboard(request): return render(request, 'index1.html') # This is a account view def account(request): return render(request, 'dashboard.html',); # This is a logout view def logout(request): messages.error(request,'You are now logged out') return render(request, 'login.html',); dashboard.html: <div class="container20 mt-4"> <center> <h3 class="display-5 mt-2"><b>Account Details</b></h3> </center> <!--Your Account Details--> <h3 class="display-5 mt-5 ml-3"><u>Your Account Details</u></h3> <hr class="new1"> <p class="p3 ml-4 mt-4"><b>Username: </b>{{request.user.project.user}}</p> <p class="p3 ml-4 mt-4"><b>Email: </b>{{user.email}}</p> <a href="account/edit/" class="button ml-2">Edit Profile</a> <a href="/" class="button ml-2">Messages</a> <hr class="new2"> <!--Your Project--> … -
How to reset JWT token in Django after user changes password?
My problem is that I want to refresh or expire the JWT token when someone resets his or her password. My project is in Django so all I need is an example on how that will happen. warmest regards. -
Django: Want to show the url requested at the entry point of django
I have a django project i am doing lot of logging and also print statements to debug my code. Generally url is logged at the end of execution of the code Eg: [2020-01-28 11:25:16] "GET / HTTP/1.1" 200 298 I want to see my URL requested before the logging/print statements. I want it to look like below. ########################################################### URL REQUESTED: http://127.0.0.1:8000/ TYPE: GET ########################################################### . . . # My logging or print statements . [2020-01-28 11:25:16] "GET / HTTP/1.1" 200 298 So where in django should i do this. I am fine if i have to change some core django package file. -
Random string not random
I'm trying to create a random string into my DB for users. It's a part of passwordless login. So I have a field that is supposed to generate a random string. But I just found out it does not. It acctually generates same string over and over. Maybe each 5-10 min it will generate a new string for several minutes. My model looks like this. class Random(models.Model): user = models.OneToOneField('CustomUser', on_delete=models.CASCADE) random = models.CharField(max_length=25, default=uuid.uuid4().hex[:25].upper(), unique=True) created_at = models.DateTimeField(auto_now_add=True) Even though it's generating a 25 long string, it duplicates it over and over. Since I have unique true, that results in next call for creating a string is not possible, since it's not unique. How come it's creating unique each time? -
Cannot assign " "Note.user" must be a "User" instance. Django
I am getting the following error on running my django code. I am an absolute beginner and I was following a tutorial to create a crud app. On typing the information in my html form I get the following error ValueError: Cannot assign '': "Note.user" must be a "User" instance from '''form.instance.user = request.user ''' in my views.py views.py from django.shortcuts import render from django.shortcuts import render, redirect from .models import Note # Create your views here. from .forms import NoteModelForm # CRUD - create update retrieve and delete def createView(request): form = NoteModelForm(request.POST or None, request.FILES or None) if form.is_valid(): form.instance.user = request.user form.save() return redirect('/') context = { 'form': form } return render(request, "create.html", context) forms.py from django import forms from .models import Note class NoteModelForm(forms.ModelForm): class Meta: model = Note fields = ['title','url','image'] create.html <!DOCTYPE html> <html> <head> <title>CRUD APP</title> </head> <body> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <input type="submit" name="submit"> </form> </body> </html> -
Django, Apache, WSGIDaemonProcess, and threads
I'm trying to tune the performance of a Django app that's served through Apache. When doing load testing with Locust, I'm finding that latency is very high when the server is under heavy load. Right now I'm using the mpm_event_module using ThreadsPerChild=25 since that seems to be a common thing I've found in example configs. Similarly, inside my site config I have WSGIDaemonProcess ... processes=8 threads=15 python-path=... since this also matched some example. I was wondering whether the GIL in Python applies to the webserving when configured this way. If so, does that mean I need to change my config to use more processes and fewer threads to get more parallelism? When I tried doing this, my load testing reported many more failures when loading static files, so I'm not sure if it makes sense. -
how to set up a virtual environment in windows
PS C:\Users\Hennessy\Desktop\brte_project\brte_project> env\Scripts\activate env\Scripts\activate : File C:\Users\Hennessy\Desktop\brte_project\brte_project\env\Scripts\activate.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + env\Scripts\activate + ~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess every time am trying to activate the virtual environment, vs code is giving me this error.What is the solution to this? -
send parameters in url in django
I have 2 models: class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name class Question(models.Model): name = models.CharField(max_length=255) Tag_name = models.ManyToManyField(Tag) def __str__(self): return self.name urls.py urlpatterns = [ path('admin/', admin.site.urls), path('tag=<int:tag_id>/', views.QuestionList.as_view()) //this needs to be edited ] what will be the path in url.py file to send id and name parameter and fetch data like http://127.0.0.1:8000?tag=4&order_by=name so i get all questions with tag 4 and order by name ? -
How to allow/ reject api permisions based on user group in django rest framework
I have 2 groups of user Creator and viewer Creator can create,update, view , delete data while Viewer only can view data. I cant understand how to implement them easily.:Later on if Imay have to allow certain crud for different models. i feel if groups can have custom acess I will have full control , maybe a custom class I have separated the apis now need to check if group matches then allow action on the api. serializer.py from rest_framework import serializers from trackit_create.models import upload_status_image, track_info from django.contrib.auth.models import Group class StatusSerializer(serializers.ModelSerializer): class Meta: model=track_info fields = ('id','description','Manufacture','user','Cost','image') views.py has option to create data class AssetCreator(mixins.CreateModelMixin, generics.ListAPIView,mixins.ListModelMixin): serializer_class =StatusSerializer authentication_classes= [TokenAuthentication] permission_classes = [permissions.IsAuthenticated] # def get(self, request, *args, **kwags): # return self.get(request, *args, **kwags) def get_queryset(self): qs= track_info.objects.all() query= self.request.GET.get('q') if query is not None: qs=qs.filter(content__icontains=query) return qs def get_object(self): request = self.request passed_id = request.GET.get('id',None) queryset =self.get_queryset() if passed_id is not None: obj = get_object_or_404(queryset, id = passed_id) self.check_object_permissions(request, obj) return obj def post(self, request, *args, **kwags): return self.create(request, *args, **kwags) # has permision to edit, delete data based on the class StatusAPIDetailView(mixins.UpdateModelMixin, mixins.DestroyModelMixin, generics.RetrieveAPIView): serializer_class = StatusSerializer authentication_classes= [TokenAuthentication] permission_classes = [permissions.IsAuthenticated] queryset= track_info.objects.all() lookup_field ='id' … -
how do you check if a date has passed
in my views.py i want get a queryset that has all entries in a table that are older than today. i have tried to do it using the following code. today = datetime.date.today() late_books = issues.objects.filter(return_date__lt=today) but this always gives an empty set despite there being entries that should be added to late books. how do i fixs this -
How can I debug GraphQL subscriptions of a Django backend?
I'd like to add GraphQL subscriptions to a backend GraphQL API. Can I debug subscriptions with the graphene_django builtin GraphiQL? # <django-project>/settings.py ... from graphene_django.views import GraphQLView urlpatterns = [ ..., url(r'^graphql$', GraphQLView.as_view(graphiql=True)), ..., ] -
How can i add my own attribute in django as_view() method?
I want to add my own attribute 'fileName' inside method 'as_view()' path('dialogs/', CodeResponseView.as_view(fileName='Dialogs.py')), Django give's me an arror: TypeError: CodeResponseView() received an invalid keyword 'fileName'. as_view only accepts arguments that are already attributes of the class. Can you help me please? -
How can i make a file with constants in django3.0.2 python3.6 and access it in all applications . Any github repository is also useful
include( # the project different envs settings optional('envs/devel/*.py'), optional('envs/production/*.py'), optional('envs/staging/*.py'), # for any local settings optional('local_settings.py'), optional('path.py'), ) What should be the folder structure i follow to build django web application,I did not found any repo on github in which contants files are made according to the environments. As i am moving from php to python i did not found how to exactly define the constants in python so that the value of the constants will not change anywhere. print("currently i am using django-split-settings to include files") -
is there is a method in to deal with DICOM FILES in django [closed]
i want to upload DICOM FILES in form created by django i have in model.py patient class that have FileField for DICOM file model.py -
Django Setup : Offline download issue
I am trying to install django using command '''pip -install virtualenvwrapper-win''' But It is failing to connect to the download link with below error. Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by'NewConnectionError(': Failed to establish a new connection: [Errno 11004] getaddrinfo failed')': /simple/virtualenvwrapper-win/ Help me in setting up django. -
M2M field widget to add or update data as inline formset
I spent a lot of hours searching for a feature which I think should be quite a basic functionality in Django. But I just can't get it working, I am unable to find a widget which will function same as m2m widget of django, but will also create new model instance if it doesn't exists. E.g. If I had models as: class Outcome(models.Model): outcome = models.CharField(max_length=255) outcome_short_name = models.CharField(max_length=10, blank=True, null=True) class Course(models.Model): course_title = models.CharField( verbose_name=COURSE_SINGULAR + " title", max_length=200, unique=True ) course_outcome = models.ManyToManyField( Outcome, verbose_name=COURSE_SINGULAR + " outcome", blank=True ) Then I want "Outcomes" shown as this image while creating course: Image of adding new course with inline outcomes Now, If the outcomes data added by user already exists, then it should only map them to course. Otherwise it should first store outcomes into database and then map them to course. Any guidance in right direction will be highly appreciated. Thanks, -- Suraj https://hacksj4u.wordpress.com https://github.com/SurajDadral -
Connect postgresql and using virtual environment and docker on the same project
I customize the project locally to work with docker and pipenv. In settings.py, the database has changed DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ.get('POSTGRES_DB', default='postgres'), 'USER': os.environ.get('POSTGRES_USER', default='postgres'), 'PASSWORD': os.environ.get('POSTGRES_PASSWORD', default='postgres'), 'HOST': os.environ.get('POSTGRES_HOST', default='localhost'), 'PORT': "5432" } } and added in to docker-compose.yml file version: '3.7' services: web: build: . command: python /profi/manage.py runserver 0.0.0.0:8000 environment: - SECRET_KEY=dy)zvq+sf07^^456t$$6+mv*tj6#5iwyo896-z!v=h^njl9^&@q - DEBUG=1 volumes: - .:/profi ports: - 8000:8000 depends_on: - db db: image: postgres:11 volumes: - postgres_data:/var/lib/posgresql/data/ environment: POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres POSTGRES_DB: postgres POSTGRES_HOST: db ports: - "5432:5432" volumes: postgres_data: I want to be able to run the project locally in two ways: via virtual environment and via docker. But now I have error in both case using docker db_1 | db_1 | 2020-01-28 09:03:18.408 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432 db_1 | 2020-01-28 09:03:18.408 UTC [1] LOG: listening on IPv6 address "::", port 5432 db_1 | 2020-01-28 09:03:18.425 UTC [1] LOG: listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432" db_1 | 2020-01-28 09:03:18.454 UTC [64] LOG: database system was shut down at 2020-01-28 09:03:18 UTC db_1 | 2020-01-28 09:03:18.462 UTC [1] LOG: database system is ready to accept connections .... web_1 | Is the server running on … -
django-channels-graphene-ws with ASGI alongisde WSGI setup?
Let's say I've a RESTful API implemented with DRF and a GraphQL API implemented with graphene-django. Now I'd like to add GraphQL subscriptions to the GraphQL API. This requires ASGI. Is it possible to run the GraphQL API (django-channels-graphene-ws) on top of ASGI and RESTful API (DRF) on top of WSGI? -
how to embed an image with html using MultiEmailAlternatives?
Here I am trying to send image alongside with html template.For this i follow two approach 1> first approach i made logo_data() function to fetch image and I attached with msg.attach(logo_data()) after msg.attach_alternative() but this method didn't worked. 2>In second approach I send the current_site to the template through context with get_current_site() method and define image with static tag like this in the template but i didn't worked out as well. How can I send email with images also.Sending html template is working fine only the images on the template are not displaying <img src="{{site}}{% static 'dist/img/logo.png' %}" views.py def logo_data(): with open(finders.find('static/dist/img/logo.png'), 'rb') as f: logo_data = f.read() logo = MIMEImage(logo_data) logo.add_header('Content-ID', '<logo>') return logo def send_mail(request): ............. site=get_current_site(request) html_content = render_to_string('mailverification/guest_notification_after_cleaning.html',{'site':site.domain}) subject, from_email, to = 'Hello', settings.EMAIL_HOST_USER, email msg = EmailMultiAlternatives(subject, text_content, from_email, [to]) msg.attach_alternative(html_content, "text/html") msg.attach(logo_data()) msg.send() return HttpResponse('mail send') -
How to manually reset the data in a step of a formtool wizard?
I have a wizard with several steps organized as follow: 1 -> 2 -> 3 -> 4 -> 6 | ^ | | --> 5 --- where step 6 is just a review of the data in previous steps. Steps 4 and 5 are mutually exclusive. If a user travels the form 1,2,3,4,6 and then decides to use 5 instead of 4 I want to be able to reset the data in step 4. How can I manually reset the data already stored for step 4 (or any step) of the wizard? -
Retrieve and Update data in intermediate table in djnago
I want to retrieve the list of the intermediate table. here are my models with M2M relationship. class ClinicHospital(models.Model): name = models.CharField(max_length = 256) address = models.TextField() contact = models.CharField(max_length = 15) lat = models.FloatField() lon = models.FloatField() class Doctor(models.Model): name = models.CharField(max_length = 256) speciality = models.CharField(max_length = 256) contact = models.CharField(max_length = 12) speciality = models.ForeignKey(Speciality, on_delete=models.CASCADE) clinic_hospital = models.ManyToManyField(ClinicHospital, through='DoctorHospital') class DoctorHospital(models.Model): clinic = models.ForeignKey(ClinicHospital, on_delete=models.CASCADE) doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) shift = models.CharField(max_length=10) views.py class DoctorShiftListView(generic.ListView): model = DoctorHospital def get_queryset(self): return DoctorHospital.objects.all() it returns none. How could I get the list of the custom intermediate table? -
how to read POST method data in django dynamically, if the json data has multiple key values ho w to read on by one
{ "slug": { "bigbazar":[1,2,3], "paytm":[4,5,6], "wallmart":[7,8,9], "more":[10,11,12], "spencers":[14,15,16] }, "technical":{ "tech_summary":true, "marketing_summary":true, "consolidate":true }, "inspection":{ "t003":{ "download":"pdf" }, "t005":{ "download":"pdf" }, "t011":true, "consolidate":true }, "records":{ "sale_report":true, "stock_report":true, "audit_doc":{ "download":"pdf", "consolidate":true } }, "maintenance":"stacks", "contracts":{ "invoice":{ "download":"pdf" }, "unit_sum":{ "download":"pdf" }, "unit_his":{ "download":"pdf" }, "cash_flow":{ "download":"pdf" }, "BDA":{ "download":"pdf" }, "hire":true, "inv_audit":{ "download":"pdf" }, "consolidate":true } } the above json file i received through post method from front end. how to extract the code of each. I have received the data based on the category then item along with slug for common products in all the outlets from data base, now i have to read category first then read items that he wants, and based on that I will filter based on the selection, and then present the expected output document fro internal use. how can read/ extract above json data dynamically. for each slug i have to extract each category and then items in each category with expected output format.