Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Avoid Google oauth redirect to localhost on call from public server with nginx reverse proxy + docker setup
I am setting up a technical blog with the following infrastructure: Client <---domain.tld:80---> Nginx Reverse Proxy <---localhost:8001---> Docker container with Django web app I am using Gunicorn as WSGI web server within my container. The problem I am facing is that when I want to include Google authentication for my comment section and call my corresponding URI for authentication (which is http://domain.tld/auth/login/google-oauth2/), I get the following error from google: The redirect URI in the request, http://localhost:8001/auth/complete/google-oauth2/, does not match the ones authorized for the OAuth client. So the main problem is that google thinks I want the redirect host to be localhost, because my app is deployed on localhost (and only served via my reverse proxy to the internet), but of course I need it to be domain.tld instead. I didn't found an option were I can explicitly tell google were the traffic should be redirected to, I only can authorize URIs. Of course I tried to allow localhost redirect access, but obviously this doesn't help because google redirects to the localhost URI. My code is mainly based on this blog post and this stackoverflow question. As this is mainly a link call to a URL from my server, I … -
How to get values from input field without form tag in django views for database?
<div class="product_quantity_container"> <div class="product_quantity clearfix"> <span>Qty</span> <input id="quantity_input" type="text" pattern="[0-9]*" value="1" name="quantity"> <div class="quantity_buttons"> <div id="quantity_inc_button" class="quantity_inc quantity_control"><i class="fa fa-chevron-up" aria-hidden="true"></i></div> <div id="quantity_dec_button" class="quantity_dec quantity_control"><i class="fa fa-chevron-down" aria-hidden="true"></i></div> </div> </div> <div class="button cart_button"><a type="submit" href="{% url 'online:cartitemcreate' pk=prod.pk %}">Add to cart</a></div> </div this is template. I want to get the input field in django views for store in database. -
Coverage shows too less percentage for Django test
i'm currently testing my django (2.1.0) application with some api-unit-tests. I used the django rest framework(3.9.0) to build a login. For this i use code like this: '''python class LogoutTest(APITestCase): def test_login_post_unauth(self): response = requests.post('http://127.0.0.1:8000/myapp/user_info/') self.assertEqual(response.status_code, 401) def test_login_put_auth(self): token = auth() payload = {'Authorization': 'Token '+token} response = requests.put('http://127.0.0.1:8000/myapp/user_info/', headers=payload) self.assertEqual(response.status_code, 405) def test_login_delete_auth(self): token = auth() payload = {'Authorization': 'Token '+token} response = requests.delete('http://127.0.0.1:8000/myapp/user_info/', headers=payload) self.assertEqual(response.status_code, 405) ''' The tests are running when i use: coverage run --source='.' manage.py test myapp like you see: Creating test database for alias 'default'... System check identified no issues (0 silenced). .................................... Ran 36 tests in 5.082s OK Destroying test database for alias 'default'... But when i do coverage report i just get myapp/auth.py 72 46 36% Despite the fact my api test uses the code in my auth.py. My auth.py looks like this: ''' def logout(request): if request.method == 'GET': request.user.auth_token.delete() return JsonResponse({'message':'You are sucessfully logged out'}, status=200) return JsonResponse({'error': 'Other Methods than GET not allowed'}, status=405) ''' But coverage says '''return JsonResponse({'error': 'Other Methods than GET not allowed'}, status=405)''' will never be used. Do you have an idea? -
Store a CharFiled with a value, how can I get another value when read it?
The CharFiled saved with a value, but I want to make some modifications with the stored value when reading it, but the value in db doesn't change. How should I do ? -
Django usage of ManyToManyField between 2 different applications
Let's say we got 2 applications, games and streamers. Both applications got their own views, models, templates etc. In application streamers we got model Streamer with field games = models.ManyToManyField('games.Game') and we are importing model Game from application games. Now after migrations, adding some content we can create object Streamer and assign to him games that he is playing. But when it comes to display all games that selected Streamer is playing by adding to template tag {{ streamer.games }} we are getting on template string games.Game.None so something causes it and we don't know yet what exactly. We have created views for games, streamers, templates, urls and everything works fine because we are getting data like streamer's nick, or streamer's links to YouTube/Twitch etc. but if we want in our Application streamers be allowed to display games assigned to streamers should we import views and models from streamers and games? Or should we change in app streamers/views.py any view and there place games imported from app games? I know how I could do this in single application with models and relation ManyToMany because I had already chance (with StackOverFlow help) to do something like this. But know I'm doing … -
pass variables from template to views in django
On clicking on each location I have to fetch a text file from there. I need to pass these locations to the views.py to render the files. template: if(data.columns[j]=="outputFilePath"){ var op = JSON.stringify(data.tableData[i][j]); op=op.substring(1,op.length-1) row.append("<td><a href='/dhl/outputDir'>"+op+"</a></td>")} views. py: def outputDir(request,location): text_data = open("location/stdout", "rb").read() return HttpResponse(text_data, content_type="text/plain") urls.py url(r'^dhl/outputDir',views.outputDir), -
Django - Caching a InMemoryUploadedFile (request.FILES['file'])
Is there a way to cache request.FILES['file'] to use it in a second request. I am trying to confirm a file upload. Therefore I have two forms. One to upload the file to the server and one to confirm the upload. However in the second form the request.FILES['file'] of course, is empty because it is a new request. How can I cache the file to use it in the second request. Here is my views.py def file_upload(request): save = False if request.method == "POST": form = UploadFileForm(request.POST, request.FILES) # In form2 the request.FILES should contain the file I selected in the UploadFileForm form2 = ConfirmationForm(request.POST, request.FILES) if not form2: save = True elif form.is_valid(): save = False print("request.POST: ", request.POST) print("request.FILES: ", request.FILES) # empty print("save: ", save) #false print("form: ", form) print("form2: ", form2) # empty if not request.FILES: print("empty") else: print("not empty") updated_obj = 0 created_obj = 0 duplicate_obj = 0 count = 0 # Prüfen ob CSV Datei valide ist (keine doppelten Datensätze) if form.is_valid(): csv_file = request.FILES['file'] print("csv_file: ", csv_file) rs1 = list() rs2 = list() d_list1 = list() d_list2 = list() file = csv_file.read().decode('utf-8').splitlines() reader_orig = csv.reader(file) for row in reader_orig: try: row_set1 = [row[0], … -
Dropdown Option Value not saving
Hej, I have multiple options created by an SQL Select, one Example looks like this: <option value="1" selected="">Westcoast Computer</option> You can see value is correct the ID of this Company, the problem is if I click on save its not saving. But if I change my queryset that the output looks like: <option value="1" selected="">1</option> then it's saving fine. But this looks not user-friendly. Why is Django try to save the text behind the value and not the value? My view looks like this (is working for other forms but without this options field. def addKunder(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = AddKunder(request.user.id, request.POST) # check whether it's valid: if form.is_valid(): form.save() return HttpResponseRedirect('/pyOekonomi/kunder/') # if a GET (or any other method) we'll create a blank form else: print ('somethin goes wrong') form = AddKunder(request.user.id) return render(request, 'pyOekonomi/modules/kunder/add.html', {'form': form}) Forms look like: class AddKunder(forms.ModelForm): Firma = forms.CharField(widget=forms.TextInput(attrs={'class': 'input_app', 'autofocus': True}), label='Firma', required=False) Adresse = forms.CharField(widget=forms.TextInput(attrs={'class': 'input_app'}),label='Adresse', required=False) Postnummer = forms.IntegerField(widget=forms.TextInput(attrs={'class': 'input_app'}),label='Postcode', required=False) Byen = forms.CharField(widget=forms.TextInput(attrs={'class': 'input_app'}),label='By', required=False) Land = forms.ModelChoiceField(widget=forms.Select(attrs={'class': 'countryselectbox'}),queryset=CountryList.objects.values_list('countryname', flat=True).order_by('code'), … -
django rest framework - foreign key fields are read only
The model: class Item(models.Model): company = models.ForeignKey(Company, on_delete=models.CASCADE) item_num = models.IntegerField() # other fields... class Meta: unique_together = [('company', 'item_num') ] Serializer: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('company_id', 'item_num', ) The problem is that django rest framework generates a ReadOnlyField() for the company_id field, so this field is not editable when I create a new instance in view code like this: s = ItemSerializer(data=request.POST) s.save() I also lose the default UniqueTogetherValidator that is defined in the model. Though, if I change the serializer field name from 'company_id' to 'company', I do get the validator, as drf will generate PrimaryKeyRelatedField so it will be editable. How can I still name my foreign key objects like 'company_id', because I do prefer naming them like this, and still get the default validation and saving behavior? Preferably without adding to much code to the serializer. -
Django rest framework RecursionError during dispatch
From time to time, a RecursionError error gets triggered on my website. Unfortunately, the error log is not helpful. One thing that strikes me as weird is that the response = self.handle_exception(exc) in the except is being called, but after that, the code continues from the line above at response = handler(request, *args, **kwargs) def dispatch(self, request, *args, **kwargs): """ `.dispatch()` is pretty much the same as Django's regular dispatch, but with extra hooks for startup, finalize, and exception handling. """ self.args = args self.kwargs = kwargs request = self.initialize_request(request, *args, **kwargs) self.request = request self.headers = self.default_response_headers # deprecate? try: self.initial(request, *args, **kwargs) # Get the appropriate handler method if request.method.lower() in self.http_method_names: handler = getattr(self, request.method.lower(), self.http_method_not_allowed) else: handler = self.http_method_not_allowed response = handler(request, *args, **kwargs) except Exception as exc: response = self.handle_exception(exc) self.response = self.finalize_response(request, response, *args, **kwargs) return self.response Should the code jump out of the try block when a exception occurs? The traceback Traceback: File "/path/to/webapp/venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/path/to/webapp/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/path/to/webapp/venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/path/to/webapp/venv/lib/python3.6/site-packages/django/views/decorators/csrf.py" in wrapped_view 54. return view_func(*args, **kwargs) File "/path/to/webapp/venv/lib/python3.6/site-packages/rest_framework/viewsets.py" in view 116. return … -
Django query with two foreign-keys
I'm trying to create an application page. On this page, I show application name. Now, I want to show, if it exists, the DRP application. The models are like that : class Application(models.Model): application_name = models.CharField(max_length=64) def __str__(self): return self.application_name class Drp_Application(models.Model): application_prod = models.ForeignKey(Application, related_name='drp_application_prod', on_delete=models.CASCADE) application_drp = models.ForeignKey(Application, related_name='drp_application_drp', on_delete=models.CASCADE) def __str__(self): return str(self.application_prod) + " -> " + str(self.application_drp) Drp_Application model contains the link between the production application and the DRP application. My current page is like that : def application(request, application_id): application = get_object_or_404(Application, pk=application_id) context = { 'application': application } return render(request, 'application.html', context) How should be my request to get the DRP application model from the application_prod ? Thanks for your help -
AUTH_USER_MODEL refers to model 'base.User' that has not been installed for custom auth backend
I'm trying to customize auth backend while customized auth model but keep facing this error because i'm using get_user_model() function. django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'base.User' that has not been installed INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'base.apps.BaseConfig', 'core.apps.AccountsConfig', 'system.apps.SystemConfig', ] -
choosing between inheritence and type field
I don't know if this is the right place to post this question, but here it is: I have an Answer object, an Answer can have multiple types (image, article, map, ..), each type has a form to show to the user so he can insert his answer. I'm confused between these 2 options: 1- create a class answer and class type, answer class has many fields, and I create many forms, a form for each type of answer, and call the form when a user selects a specific type. class answer(models.Model): name = fields.CharField(...) type = fields.ForeignKey(Type,...) 2- create a class answer, and a class for each type of answer that inherit from answer class. What is the optimal way for MVC architecture and for the database? I'm using MongoDB as a database. Thanks. -
How to render an editable table in Django and update the edits in the database?
So, I want to render a table with three columns. The first column contains the items like Name, Place etc. The second column contains the actual names and the third column is empty where the user can fill in some data. This table is unique to each user. I want this table to get updated in the database. How to accomplish this? (forgive the noob lingo) -
Couldn't Import GroupRequiredMixin
I want to check users if they are in a specific user group. If they are in that group they can view the "create product" page. Saw that documentation on web but couldn't use it properly by now. https://django-braces.readthedocs.io/en/latest/access.html#grouprequiredmixin I'm trying to use django-braces > GroupRequiredMixin but when I try to run my server I'm getting that error: File "C:\market\src\products\views.py", line 7, in <module> from django.contrib.auth.mixins import GroupRequiredMixin ImportError: cannot import name 'GroupRequiredMixin' from 'django.contrib.auth.mixins' (C:\market\lib\site-packages\django\contrib\auth\mixins.py) My views.py looks like this: from django.http import Http404 from django.shortcuts import render, get_object_or_404 from django.views.generic import TemplateView from django.views.generic.edit import CreateView, UpdateView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.contrib.auth.mixins import GroupRequiredMixin from .forms import ProductModelForm, CategoryModelForm from .models import Product, Category, Stocks class ProductCreateView(GroupRequiredMixin, SubmitBtnMixin, CreateView): model = Product template_name = "form.html" form_class = ProductModelForm submit_btn = "Ürünü Kaydet" group_required = u"sellers" pip freeze: Django==2.1.5 django-braces==1.13.0 django-polymorphic==2.0.3 pytz==2018.9 Thank you for your time in advance. -
is there any solution for importing request library in django using python?
Question: I'm trying to link my python code in Django and as I'm using an API for weather and using it to extract the data for any country. problem 1: I want to use a location, date, format and tp from the API link. the problem is that I don't know how to extract that 4 four things particular from the same link. It showing me this: Traceback (most recent call last): File "C:\Users\Muahr\source\repos\RCAI-Project\Pest\api.py", line 14, in url=int(api_address+city+24+date_time) TypeError: must be str, not int Problem 2: at the same time, I'm integrating this whole code into the Django and it's giving me an error that request isn't defined. Kindly help me through this. Thank you in advance! Original Code: import requests import simplejson import time from daytime import DateTime api_address='http://api.worldweatheronline.com/premium/v1/past-weather.ashx?key=0532bdcbc963417092c74946192203&q=&format=json&date=&tp=24' city=input("enter\n") ask=input("enter date\n") date_format = "%Y-%m-%d" date_time = datetime.strptime(ask, date_format) url=int(api_address+city+24+date_time) json_data=requests.get(url).json() formatted_data=json_data['data'] print(json_data) -
Django user permision on Update object
The work flow is listed below user post something. the initial status of the post is unpublished(is_published=False) admin approve the post. so post status is published(is_published= True) when the post status is published(is_published= True) user is not able to edit post. user to be able to edit, the post need to be unpublished(is_published=False). Then user is able to edit post. Require admin approval again. def edit_post(request, post_id): if request.method == 'POST': # adminn start here if request.user.is_staff or request.user.is_superuser: form = PostForm(request.POST, request.FILES, instance=obj) if form.is_valid(): post = form.save(commit=False) post.submitted = obj.submitted post.save() return redirect(approved_post) else: print("form invalid. post. admin") # admin end here #user star here else: obj = post.objects.get(pk=post_id) form = PostForm(request.POST, request.FILES, instance=obj) # check post status. if published cant edit if obj.is_published: print("no permission . user") return redirect(approved_post) # error page here else: if form.is_valid(): post = form.save(commit=False) post.submitted = request.user post.save() return redirect(approved_post) else: print("form invalid. post. user") # GET else: obj = post.objects.get(pk=post_id) # checking is user is admin or normal user if not request.user.is_staff or not request.user.is_superuser: #checking if post is belong to the logged in user if obj.submitted == request.user: form = PostForm(instance=obj) else: print("not your object") else: form = PostForm(instance=obj) return … -
How to link my price field with my website image field as i am developing a price comparison website using python and django
I am currently working on a project that shows us prices of a particular phone from multiple websites. So there are in total 3 websites, so I want to link the price field of website 1 to image field of website 1 and likewise others. How can I do that using django that price from a particular website should be shown next to that particular website image. A demo of that is shown in an image below.enter image description here -
UnicodeDecodeError Error charmap' codec can't decode byte 0x81 in position 250:
class ProductDownloadlView(MultiSlugMixin,DetailView): model=Product def get(self,request,*args,**kwargs): obj=self.get_object() filepath = os.path.join(settings.PROTECTED_ROOT,obj.media.path) guessed_type = guess_type(filepath)[0] wrapper=FileWrapper(open(filepath)) mimetype = 'application/force-download' if guessed_type: mimetype=guessed_type response = HttpResponse(wrapper,content_type=mimetype) if request.GET.get("preview"): response["Content-Disposition"]="attachment; filename=%s" %(obj.media.name) response["X-SendFile"]=str(obj.media.name) return response am using python 3.7 and django 1.8.6 trying to download files like .txt works fine and .md files but i have tried an image file and it gives the error charmap' codec can't decode byte 0x81 in position 250: character maps to from the template list products {% extends "base.html" %} {% block Content %} <h1>Products</h1> <p>{{object.title}} </p> <p>{{object.description}} </p> <p>{{object.price}}</p> {% if object.media %} <p>{{ object.media }}</p> <p><a href="{{ object.get_download }}">Download</a></p> <p><a href="{{ object.get_download }}?preview=True">Preview</a></p> {% endif %} {% endblock Content %} -
Django entering args for call_command for custom datadump
I am trying to make a custom datadump for Django fixtures so I don't dump everything into one file. here is my code that throws an error: extract.py def create_fixture( filename, *app_name): # buffer buf = StringIO() # unpacks args to list of db tables apps = ','.join(map(str, app_name)) # calls dump data and adds db table to call command call_command('dumpdata', apps, indent=2, format='json', stdout=buf) # Write to file buf.seek(0) with open(Path.cwd().joinpath('main', 'fixtures', filename), 'w') as f: f.write(buf.read()) class Command(BaseCommand): help = 'Dumps database file to fixtures' def handle(self, *args, **kwargs): #calls function create_fixture('country.json','main.Country','main.Cities') #prints to console if successful self.stdout.write("Dumped Country data!") If I run python manage.py extract in the console I get the following message: CommandError: No installed app with label 'main.Country,main.Cities' But if I write the code like this it works fine but does not use a function: class Command(BaseCommand): help = 'Dumps database file to fixtures' def handle(self, *args, **kwargs): buf = StringIO() call_command('dumpdata', 'main.Country', 'main.Cities',indent=2, format='json', stdout=buf) buf.seek(0) with open(Path.cwd().joinpath('main', 'fixtures', 'country.json'), 'w') as f: f.write(buf.read()) self.stdout.write("Dumped Country data") Not sure how to unpack the args correctly and put them into the call_command function -
There's something like Django apps in Spring (Boot)?
Dango framework has the possibility to divide your site into independent and reutilizable apps. The app is like a package that you can import. Is there something similar in Spring or Spring Boot? -
Connection Refused Error Actively Refused? SMTP django Don't understand why
I'm trying to test out sending email using django. After running this through python manage.py shell. it throws a connection refused error. Same problem when using smtplib less secure app access is already turned on for the gmail account I use for testing from django.core.mail import send_mail send_mail('subject','message', 'thisisadummyusername@gmail.com', ['thisisadummyusername@gmail.com']) import smtplib smtpserver = smtplib.SMTP('smtp.gmail.com', 587) -
Getting all values of 2 columns
I am looking for appropriate elasticsearch query for, SELECT col1,col2 FROM myTable WHERE col1="value1" AND col2 = "value2" -
I want a make Notepad like Google keep features. Can anyone help me? For reference I am attaching a screenshot
I want a notebox like this..please have a look -
PermissionError at /download/
when i try to download the file it says PermissionError at /download/ views.py def download(request, path): file_path = os.path.join(settings.MEDIA_ROOT, path) if os.path.exists(file_path): with open(file_path, 'rb') as f: response = HttpResponse(f.read(), content_type="application/vnd.ms-excel") response['Content-Disposition'] = 'inline; filename=' + os.path.basename(file_path) return response raise Http404 urls.py re_path(r'^download/(?P<path>.*)$', views.download) in html templates <a href="/download">Download</a> i have tried everything such as moved project folder to another directory or run it as admin etc but it says Internal Server Error: /download/ Traceback (most recent call last): File "C:\Users\Zako5\.virtualenvs\jurnal-6LxuXEYu\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Zako5\.virtualenvs\jurnal-6LxuXEYu\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Zako5\.virtualenvs\jurnal-6LxuXEYu\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Zako5\PycharmProjects\jurnal\jurnal_app\views.py", line 40, in download with open(file_path, 'rb') as fh: PermissionError: [Errno 13] Permission denied: 'C:\\Users\\Zako5\\PycharmProjects\\jurnal\\media/' [27/Mar/2019 10:56:09] "GET /download/ HTTP/1.1" 500 66483 any help would be appreciated) this problem has been pissing me off for a week