Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing Django DRF API endpoint giving an unexpected 404 with GET request
I have a DjangoRestFramework setup and it works fine, but I'm trying to wrangle it under tests. I use FactoryBoy in order to create the objects in the setUp and can confirm they exist because when I query for them they return without issue. I've written out my test like this: class AssignmentTest(APITestCase): def setUp(self): # Create the assignment from the AssignmentFactory # this works without issue f.AssignmentFactory() self.factory = APIRequestFactory() self.client = APIClient() self.url = reverse('Assignments-list') # accessing self.url in a browser shows data as expected but fails in test print(self.url) # returns: '/api/myapp/assignments' self.root = ('/api/myapp/') def test_api_endpoint_returns_200(self): """ Ensure then endpoint gives a 200 response. """ response = self.client.get(self.root) print(response) # Gives 200 and works fine other_response = self.client.get(self.url) print(other_response) # Gives 404 - but I can't figure out why self.assertEqual(other_response.status_code, 200, 'Expected Response Code 200, received {0} instead.' .format(other_response.status_code)) In my rest_api.py file in my app I have listed: router = routers.DefaultRouter() router.register(r'assignments', AssignmentViewSet, basename='Assignments') If I do python manage.py runserver and go to the API endpoint (api/myapp/assignments) it shows the results as expected. But it continuously gives me 404 in my test. Am I setting something up wrong here? The root URL works and gives … -
can we use objects.all().filter(x__lt = time or y__gt= time ), is using of OR operator inside filter() a valid approach
i have a querset: name = People.objects.all().filter(age_lt=AGE or xyz_gt=AGE) can we use the OR operator? -
How to get a second field in query_set?
I have a model called 'Report', the model has two fields 'area' connected with ForeignKey to another model called 'Area' and 'country' connected with ForeignKey to another model called 'Country'. Also I have a dropdown button, for the 'area' field and it supposed to take me to a page where the list of countries belong to the area supposed to show up from the 'country' field. My model str returns 'area' field. Because str return 'area' field my 'country' page also showing list of areas instead of list of countries. I tried 'return '{} {}'.format(self.area, self.country). When I do that my 'area' dropdown shows both area and country. Example 'NORTH AMERICA CANADA'. So tired to get 'country' field in a different way. country = Report.objects.filter(country=country). But I get error country is not defined. My models.py: class Report(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) church_name = models.CharField(max_length=255) area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True) water_baptism = models.IntegerField(default=0) holy_ghost = models.IntegerField(default=0) def __str__(self): return '%s' % self.area def get_absolute_url(self): return reverse('users:report_view') my views.py def report_list for 'areas' dropdown button @login_required def report_list(request): areas = Report.objects.all() context = { 'areas':areas, } return render(request, 'users/report_list.html', context) def report_countries for 'countries' dropdown … -
Django on Heroku - add new models to postgreSQL database
I have an Django 2.1 / Python 3.6 application running on Heroku's hobby account. The first version of this deployment went smoothly. Now I needed to add more fields to existing models and also add additional models from my local setup (which is running very smoothly with the changes) to Heroku. I do the usual git push heroku master to get the new code over to Heroku. Then I do both heroku run python manage.py makemigrations heroku run python manage.py migrate The first step gives me Running python manage.py makemigrations on ⬢ hirt-family-v4... up, run.3753 (Free) Migrations for 'users': users/migrations/0005_auto_20190425_1452.py - Create model XtraPhotos - Add field phone_number to person - Add field parent to xtraphotos which is fine, but the migrate is also coming back with the message Running python manage.py migrate on ⬢ hirt-family-v4... up, run.5929 (Free) Operations to perform: Apply all migrations: account, admin, auth, contenttypes, sessions, sites, users Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. I tried to go step by step, meaning I add … -
Django: Redirect 'Admin logout' to 'Admin login' page
In my Django App settings I've mentioned the following 2 lines in settings.py, it works fine for the normal user but is not good enough for the Admin. LOGIN_REDIRECT_URL = '/my_app/profile/' LOGOUT_REDIRECT_URL = '/my_app/login' When I log out from the Admin, it takes me to the login page of the user, as mentioned in the above LOGOUT_REDIRECT_URL. What I want is that admin logout redirect should go to the Admin login page, not the user login page. snippet from urls.py path('admin/', admin.site.urls), Can anyone suggest the best way to deal with this issue? -
Server isnt recognizing python virtualenv anymore
I have a deployed Django app on a Centos 7 server. I ran into problems when git pulling from my repository. It doesn't recognize python-home at the location where my virtualenv is anymore. When i print(sys.prefix), it shows '/usr', but when i activate my virualenv (source /path/to/virtualenv/bin/activate) it shows the correct path that is assigned to python-home in my httpd .conf file .conf file Alias /static /var/www/ek/static <Directory /var/www/ek/static> Require all granted </Directory> <Directory /var/www/ek/new> <Files wsgi.py> Require all granted </Files> </Directory> WSGIApplicationGroup %{GLOBAL} WSGIDaemonProcess ek python-path=/var/www/ek python-home= /var/www/kpi_env WSGIProcessGroup ek WSGIScriptAlias / /var/www/ek/new/wsgi.py I'm not exactly sure what the problem is, when im not in my virtualenv, should the prefix be the path to the virtualenv? Should print(sys.prefix) only show var/www/kpi_env when im in the virtualenv? Whatever it is, it doesn't recognize python-home=/var/www/kpi_env as anything anymore. When i change it to python-home = /usr it works but the application is giving me errors that i've never run into before on my server or on my workstation. This error being Permission denied is Server running on host 12.0.0.1 and accepting tcp con on port 5432 This is referring to postgresql, and i'm sure that it is running and accepting tcp … -
Using OAuth2 Gmail tokens to access protected sources
I'm having trouble figuring out how to use the tokens I got to create a new OAuth2 session and access the Gmail API. I created an app that uses the Gmail API. After the Oauth approval flow I save for each user their google user id, the access and refresh tokens, the id token and the date when the token expires. I now have a task that has to sync some data and access the Gmail api. Adding the token to the OAuthSession isn't working. import os from requests_oauthlib import OAuth2Session from oauthlib.oauth2 import TokenExpiredError def sync_gmail(user): client_id = os.getenv('CLIENT_ID') refresh_url = "www.googleapis.com/oauth2/v4/token" client_secret = os.getenv("CLIENT_SECRET") redirect_uri = os.getenv("REDIRECT_URI") authorization_base_url = "https://accounts.google.com/o/oauth2/v2/auth" token_url = "https://www.googleapis.com/oauth2/v4/token" scope = [ "https://www.googleapis.com/auth/gmail.metadata", "https://www.googleapis.com/auth/userinfo.profile" ] google_credentials = get_user_creds(user) try: client = OAuth2Session(client_id, token=google_credentials.access_token, scope=scope, redirect_uri=redirect_uri) r = client.get('https://www.googleapis.com/gmail/v1/users/' + google_credentials.google_user_id + '/profile') print(r) except TokenExpiredError as e: token = client.refresh_token(refresh_url, **extra) -
How can I get my variables in Python with Django using Javascript
Hello I have some variables in Javascript and I am using Django. I am wondering how can I get the value of my variables in Django knowing that my variables are defined in my code in javascript. Do you have a simple example on that ? Thank you very much ! -
Enumerate related objects through a many-to-many
I know that this question seem to have been answered several times, but none of the answers I found really gave me any pointer to the issue I am facing. I have 3 models into a django application: class Person(models.Model): name = model.CharField(...) interests = models.ManyToManyField(Topic, through="Interest") class Topic(models.Model): key = model.CharField(...) class Interest(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) topic = models.ForeignKey(Topic, on_delete=models.CASCADE) comment = models.CharField(...) The views.py is declared as follow: class IndexView(generic.ListView): template_name = 'index.html.j2' context_object_name = 'people_list' def get_queryset(self): return Person.objects.all() And the index.html.j2 looks as follow: {% for person in people_list %} <tr> <td>{{ person.name }}</td> <td> <ul> {% for interest in person.interests.all %} <li>{{ interest }}</li> {% empty %} No interest found {% endfor %} </ul> </td> </tr> {% endfor %} Surprisingly, the view returns 'No interest found' for every person when the admin site clearly shows interests for all persons. It looks like the Person.objects.all() in the views.py did not load the related objects from database. -
How can I use model objects as Django checkbox options and then save selections in an iterable way?
I am trying to create a scheduling site and to do that I need to allow the user to select which jobs are to be schedule. Jobs are predefined by the user and thus are already saved in my Django Model. I have been able to get the job titles to show as checkbox options but how do I save which options (when multiple have been selected) have been selected so I can use only those jobs during scheduling. I have been told to use ManyToManyField but I am unsure if I have used it correctly. class Job(models.Model): Job_Name = models.CharField(max_length=100) Completion_Time = models.IntegerField() user = models.ForeignKey(User) def __str__(self): return self.Job_Name class Selection(models.Model): selection = models.ManyToManyField(Job, blank=True) class SelectForm(forms.ModelForm): choices = forms.ModelMultipleChoiceField( queryset = Job.objects.all(), widget = forms.CheckboxSelectMultiple) class Meta: model=Selection fields=("selection",) class SelectJobView2(TemplateView): template_name="job_select.html" def post(self, request): form = SelectForm(request.POST) if form.is_valid(): meal = form.save(commit=False) meal.save() return render(request, self.template_name, {'form' : form,}) def get(self, request): form = SelectForm() return render(request, self.template_name, {'form' : form,})``` I want all of the selections to be saved in the Selection model so i can then use those the job object when scheduling. -
Reference python global variable defined in a function --> from another file
I am using django social auth pipeline to introduce a custom function during the social authentication process. I am able to parse the request parameters (eg: the facebook user token) inside this function. The parsed token will serve as input for another function located in another file and here stands the problem: I can not use it in another function I need to reference the global token variable from another function in another file. When I merge file1.py and file2.py , it works but when I want to use the parsed token from createUser(...) of file1.py in function doSomething() of file2.py, the interpreter throws an error which says that function createUser comes with arguments and I must define them , but how? # settings.py: SOCIAL_AUTH_PIPELINE = [ ... 'MyApp.file1.createUser', ... ] # file1.py : from MyApp.models import FacebookUser import file2 def createUser(backend, user, request, response, *args, **kwargs): if backend.name == 'facebook': global token token = request['token'] if request['user_type'] == "facebookUser" and not FacebookUser.objects.filter(user_id=user.id): FacebookUser.objects.create(user_id=user.id) file2.doSomething() elif FacebookUser.objects.filter(user_id=user.id): file2.doSomething() # file2.py : from file1 import createUser def doSomething(): myToken = createUser().token # <--- My problem is here. How can I access the global variable "token" from the createUser function in file1? … -
function doesn't getting call from the class from the view file in python
When i call the class from views.py it doesn't call the function of class, I am calling function latest_question_list = Question.get_poll_question() from views.py but it doesn't print in my model function, here i have added my whole code, can anyone please help me why it is not working views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Choice, Question from django.urls import reverse from django.shortcuts import get_object_or_404, render def index(request): latest_question_list = Question.get_poll_question() context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): try: question = Question.objects.get(pk=question_id) except Question.DoesNotExist: raise Http404("Question does not exist") return render(request, 'polls/detail.html', {'question': question}) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/results.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) models.py import datetime from django.utils import timezone … -
How to submit form in django at a scheduled time?
I have a typical form: class ScanForm(form.ModelForm): """ Creating a form for Scan results """ value = forms.DecimalField(widget=forms.NumberInput( attrs={ 'class': 'form-control', 'placeholder': 'Value', 'max': '500', } )) count = forms.DecimalField(widget=forms.NumberInput( attrs={ 'class': 'form-control', 'placeholder': 'Amount', 'max': '400', } )) class Meta: """ Adding choice of interval and exclude unused fields """ model = ScannedValue exclude = ('scan_date',) widgets = { 'interval': forms.Select( attrs={ 'class': 'form-control', }), } I'm rendering that form in my index.html file as usual. And it's working normally when I put all the data and pushing "Submit" button. But what I need is to automatically submit this form with filled values (let's say for 'value' = 5, 'count' = 10) at certain time, let's say 01:00pm every day. Then I need to parse all received data with function in my views after submitting the form and then save the results to database. What is the best and most right way to do this? -
Getting profile information twice displayed after query
my problem is when i try to display the profile information of a certain user i get displayed the information multiple times according to the number of created posts by the certain user. I dont know how change my query to get the profile information of an user once when i click on its name. I created a get_context_data method but i dont know how to change the query to get the user information. views.py class ProfilPostView(ListView): model=Post template_name='profile.html' #display posts created by user def get_queryset(self): return Post.objects.filter(author__username=self.kwargs['slug']).order_by('created_on') #return Post.objects.filter(author=self.request.user).order_by('created_on') #display profile information of user def get_context_data(self,**kwargs): context=super(ProfilPostView,self).get_context_data(**kwargs) context['profiles']=Post.objects.filter(author__username=self.kwargs['slug']) return context profile.html <h3 style="padding-left:40%" class="lead">Name: {{ profiles.first_name}} {{profiles.last_name}}</h3> <p class="text-muted" style="padding-left:40%">Created: {{profiles.created_time.day}}.{{profiles.created_time.month}}.{{profiles.created_time.year}}</p> <p class="text-muted" style="padding-left:40% ">Email: {{profiles.email}}</p> -
Sending table data from html form to django views
I have a html form which has a table with th,td and POST method and action is to a django view. How can I send my td,th values to the django view? I have tried using input type text and it works but I don't want to use any input type on my td,th rows. Is there a way to access td values directly from django view? htmlfile: <form method="post" action="display"> {% csrf_token %} <table name="resultsTable"> <th name="tableHeader">Name</th> <td name="tableValue">Jon</td> <button type="Submit">Display</button> </table> <form> views.py: @csrf_exempt def display(request): if request.method=='POST': print(request.POST) I want name,jon to be printed in display function -
Django deployed in IIS is not working with Selenium
I have a Django web app hosted in IIS with a function using selenium that automates the transfer of data from another application. It runs when I run it on my localhost, however with IIS it doesn't even pull up the browser. I pasted the code that pulls up a website I need: from selenium import webdriver def transfer(request): browser = webdriver.Chrome() browser.get('http://localhost/virtus#scorecard/rateteammember') browser.set_page_load_timeout(10) I am using windows 10 and IIS version 10.0.15063.0 I am also using ChromeDriver version 2.42.591088 that says 'Only local connections are allowed' which I think is the source of the problem. Can someone please advise what to do next. -
How to creat mutiple UserProfiles that inherit from AbstractUser in Django?
I want to create 3 UserProfile for 3 types of users. At first, I made a CharFiled as a mark to differentiate them, but then I realized that I have to put some ForeignKey to associate those users. As for this step, I don't know how to make it come true, please help, thanks. -
Is it possible to send action buttons to email using django?
I need to send action buttons to email. Not able to understand if actions buttons can be sent to email. If it is possible to send action buttons to django using email please provide me some sample code or links to work with -
shared libraries conflicts after installing python / django
I have this issue after installing new packages /usr/bin/ld: warning: libssl.so.1.1, needed by /usr/local/lib/libcpprest.so, may conflict with libssl.so.1.0.0 /usr/bin/ld: warning: libcrypto.so.1.1, needed by /usr/local/lib/libcpprest.so, may conflict with libcrypto.so.1.0.0 Is there 2 versions of those shared library in my system? If yes, How can I fix this warning? Thanks -
Check if element from list is inside another list in django template
I'm making a for loop through a list. For each element in this list, I would like to know if this element could be egal to one of 4 words from another list. This is my example in order to describe the situation: From my view: content = ['**Added**:\n', '* something (toto-544)\n', '\n', '**Changed**:\n', ...] operations = ['Added', 'Changed', 'Fixed', 'INTERNAL'] From my HTML file: {% for line in content %} {% if line in operations %} <tr class="table-subtitle"> <td colspan="12">{{ line }}</td> </tr> {% else %} <tr class="table-value-content"> <td colspan="12">{{ line }}</td> </tr> {% endif %} {% endfor %} It should display the first line element different than the second one (I changed color between both classes). Because line[0] is in operations and not line[1]. Do you have any idea why it doesn't work through my for loop/if statement ? -
Django Todo App data show from the user entry
I am new to Django and I'm making a todo app, almost done but can't see the user entered data. I have a program that shows TODO tasks, I can login in as any user and see anyone's tasks, but I want each user to have a diffrent tasks list as a personal todo app. I tried a lot of google search but could not find the answer. Kindly help me. Thanks I'll show you some code if you guys can help. from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class To_DO_Fun(models.Model): Task_Name = models.CharField(max_length=20, default='') Task_Text = models.TextField(max_length=450, default='') Task_Done = models.BooleanField(default=False) def __str__(self): return self.Task_Name + ' --- is --- ' + str(self.Task_Done) class user_TODO(models.Model): User_Name = models.ForeignKey(To_DO_Fun , User, on_delete=models.CASCADE) from __future__ import unicode_literals from django.shortcuts import render, redirect from .models import To_DO_Fun, user_TODO #Class Name from .forms import Form_todo, Form_Task #Form Name from django.contrib import messages from django.contrib.auth import login, logout, authenticate from django.contrib.auth.forms import UserCreationForm from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required def HomeFun(request): #To view contents of the home page return render(request, "ToDo_Files/HomePage.html") @login_required(login_url='Login-Page') def Display_Page(request, User_Name_id): if request.method == "POST": form = Form_todo(request.POST or None) if form.is_valid(): all_items … -
How to use parameterized url in django class based view?
I am using parameterized url in django rest framework based API. I am not able to pass the url parameter to Class based view pointed by that url. I am using **kwargs in the view function definition to pass the url variable but getting an error while calling the url. the url pattern is like below- url(r'product/(?P<id>\d+)/details/$', APIProductDetails.as_view()) the view look like below- class APIProductDetails(CustomAPI): permission_classes = (CustomAuthentication,) def get(self, request, **kwargs): id = kwargs.get('id',None) return Response(data={}, status=200) def post(self, request, **kwargs): return Response(data={}, status=200) While testing the url using pytest, I am getting below error- TypeError: 'id' is an invalid keyword argument for this function my pytest code is like below- response = client.get( "/api/v1/rm/product/1/details/" ) assert response.status_code == 200 The other APIs which does not contain parameters are working fine. What I am missing? -
Confusion in switching from Java Spring to Python Django framework
I have 1+ years of good experience in Core Java, JEE, Spring Framework, Hibernate. I can handle enterprise level applications as well. But from the past 3 months, I am working with Python Django(v2.2) framework and developed an application similar to Olx(buy and sell). I found it is having almost all web development components(ORM, admin, internationalization, etc.) i.e. we can say it is full-stack web development framework even support bootstrap in its core and because of python we no need to write lengthy code. Now I am in confusion that should I take a very deep dive in Django for a bright future or should come back to Java platform again? When I search for a job I found that there are fewer jobs in Python Django as compared to Java. As Django Came into the picture from 2005 and Java from 1995 so this could be the reason for more jobs in Java. Please anybody expert can guide me in this direction? -
Django decouple quotation mark
I'm trying to set key=values on .env to configure my app using django-decouple. Does anyone know how to work around values using quotation marks ( ' ) on django decouple? I've tried to set some password using these character but it's ignored -
How To allow POST and GET request only for current users's data?
I want to show only their data for each user. So one user cannot GET or POST another user's data. class FcaSet(viewsets.ModelViewSet): def get_queryset(self): return Fca.objects.filter(user_check= request.user) #user filter serializer_class = FcaSerializer permission_classes = (permissions.AllowAny,) But usually it throws error: TypeError at /api/cutarea-fca/ int() argument must be a string, a bytes-like object or a number, not 'AnonymousUser' Next I try use this: def get_queryset(self): return Fca.objects.filter(user_check= request.user) but user doesn't see no one object from this model in frontend... It is model: class Fca(models.Model): num_of_agree = models.ForeignKey(Agreement, models.DO_NOTHING, blank=True, null=True) uroch = models.TextField(blank=True, null=True) num_allot = models.ForeignKey(Allotment, models.DO_NOTHING, blank=True, null=True) num_fca = models.CharField(max_length=50, blank=True, null=True) ar_fca = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) expl_ar = models.FloatField(blank=True, null=True) cel_nazn = models.ForeignKey(ForestPurpose, on_delete=models.DO_NOTHING, verbose_name='task',blank=True, null=True) cat_zas = models.ForeignKey(ForestProtection, on_delete=models.DO_NOTHING, verbose_name='cate',blank=True, null=True ) geom = models.MultiPolygonField(geography=True, null=True, blank=True, verbose_name='ge') video_cat = models.TextField(blank=True, null=True) user_check = models.ForeignKey(User,on_delete=models.DO_NOTHING, verbose_name='user_id',blank=True, null=True ) class Meta: managed = True verbose_name = 'lek' verbose_name_plural = 'leks' There is serializer: class FcaSerializer(gis_serializers.GeoFeatureModelSerializer): class Meta: model = Fca geo_field = 'geom' fields = ('id','num_of_agree','num_allot','uroch','num_fca','ar_fca',\ 'expl_ar','cel_nazn','cat_zas','geom','video_cat','user_check') def create(self, validated_data): return Fca.objects.create(**validated_data) I hope somebody text how to solve this classic task by simple example or psedo code