Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
POST document with Django RequestFactory instead of form data
I'd like to build a request for testing middleware, but I don't want POST requests to always assume I'm sending form data. Is there a way to set request.body on a request generated from django.test.RequestFactory? I.e., I'd like to do something like: from django.test import RequestFactory import json factory = RequestFactory(content_type='application/json') data = {'message':'A test message'} body = json.dumps(data) request = factory.post('/a/test/path/', body) # And have request.body be the encoded version of `body` The code above will fail the test because my middleware needs the data to be passed as the document in request.body not as form data in request.POST. However, RequestFactory always sends the data as form data. I can do this with django.test.Client: from django.test import Client import json client = Client() data = {'message':'A test message'} body = json.dumps(data) response = client.post('/a/test/path/', body, content_type='application/json') I'd like to do the same thing with django.test.RequestFactory. -
Django profile() missing 1 required positional argument: 'username'
I'm following the instructions from a django book, but I'm getting an error (TypeError: profile() missing 1 required positional argument: 'username') while trying to implement a profile view. What I want is to be able to see the profile of a user by going to profile/johndoe for example. Here is my view: @login_required def profile(request, username): try: user = User.objects.get(username=username) except User.DoesNotExist: return redirect('/the_pantry/home') userprofile = UserProfile.objects.get_or_create(user=user)[0] form = UserProfileForm({"name": userprofile.name, "age": userprofile.age, "bio": userprofile.bio, "picture": userprofile.picture}) if request.method == "POST": form = UserProfileForm(request.POST, request.FILES, instance=userprofile) if form.is_valid(): form.save(commit=True) return redirect("profile", user.username) else: print(form.errors) context_dict = {"userprofile": userprofile, "selecteduser": selecteduser, "form": form} return render(request, 'the_pantry/profile.html', context = context_dict) And my urlpatterns: url(r'^profile/(?P<username>[\w\-]+)/$', views.profile, name='profile'), And my UserProfile model. class UserProfile(models.Model): user = models.OneToOneField(User) name = models.CharField(max_length = 60, default = "") picture = models.ImageField(upload_to='profile_images', blank = True) age = models.IntegerField(default=0) bio = models.CharField(max_length = 500, default = "") def __str__(self): return self.user.username Additionally, I'm using django's default login and User. I have an html file for the profile (profile.html) as well. Everything is exactly like in the book. The error I'm getting is: Traceback (most recent call last): File "C:\Users\2254765p\Envs\rango\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\2254765p\Envs\rango\lib\site-packages\django\core\handlers\base.py", line … -
Passing parameters to get request in django template
I'm trying to create a link to a page in django via a GET request. But, I have to pass the value of a parameter. How do I do so? urls.py path('questions/<int:user_id>/', views.recommendationquestions,{'template_name':'questions.html'}, name = 'questions'), answers.html <a href="{% url 'questions' {{rlist.0.userId}} %}">Rate more movies</a> -
Django Administrator Theme
I'm going to develop an app using Django2.0.3 . Now it is questionable that if I can replace HTML admin with default Django admin template completely? Wouldn't be any security problem?? Please guide me to change -
How to serve staticfiles in Django 2.* when DEBUG = False?
I've stucked with deploying Django 2.* on production server. When i set DEBUG = False Styles in admin page simply stopped serving by debugger or something and i have no clue or ideas how to serve static files. My settings\actions: settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Then just python manage.py collectstatic and no styles in admin =( Will be appreciate for any help. -
Requests Sessions - Only Works First Time
I am working with Django Python. So my code generates a new 10 letter string every time the user connects to it - this acts as a unique identifier for the customer, in the wider picture. But my problem is the following.... In order to generate the random string, the user needs to be logged in. A request is then made to the random string api to generate the string, before returning it. This is the block of code (using hardcoded testing values, and removed the exact public api to minimise fake requests): ### Code To Log In s = requests.Session() credentials = {'username': 'user', 'password': 'pass'} s.post("http://XXXXXX.pythonanywhere.com/api/login/", data=credentials) ### Code to connect to Create String API, and return it as JSON r = s.post("http://XXXXXX.pythonanywhere.com/api/createstring/") results = r.json() I then parse this in my client as normal. The first time I run this code, all connections work fine and the JSON is parsed and everything works perfectly. The random string is generated and printed on the client, as it should. However, when I then run the code again, I get the status code of 500 and no connection is made. When I check the error log on my PythonAnywhere, it … -
Why a lot of ORM does not use pure python comparison in query?
A lot of ORMs (like Django ORM or MongoEngine) use "keywords magic" like id__lte=1 instead of more native Model.id <= 1 (like in SQLAlchemy). But why? It completely breaks down static analysis by IDE (refactoring, autocompletion and type checking). Maybe there are some reasons that I can't see? Or just not so many people think that Model.id <= 1 is better than id__lte=1? Example for Django ORM: Blog.objects.get(name="Cheddar Talk", user_reviews__lte=5) Example for SQLAlchemy session.query(Blog).filter(Blog.name == "Cheddar Talk", Blog.user_reviews <= 5) -
Any library for dynamic forms creation in Django
I wanted to develop a app, where users will create forms with their choice of fields, example a employer want to create a job seeker form with different fields and an other one with different fields, is there any Django library which supports this type of feature which can be used in admin and forms could be rendered at site ? I have been looking for this and found a similar one here but the issue is this is for old Django version, it doesn't work with latest (2.0.3) Appreciated. -
How to authorize only PersonalTrainers to access view but check if objects belong to current PersonalTrainer
I'm writing this django API using django-rest-framework and I'm stuck with this authorization stuff. This is my endpoint: /api/v1/personal_trainers/:id/invites/ I need to authorize only PersonalTrainers to access this view, so I have written this custom permission: personal_trainers/permissions.py class IsPersonalTrainerUser(permissions.BasePermission): """ Allows access only to personal_trainers users. """ def has_permission(self, request, view): return request.user and request.user.is_personal_trainer This is how I authorized the users to access the invites invites/views.py class InviteCreateList(mixins.CreateModelMixin, mixins.ListModelMixin, viewsets.GenericViewSet): permission_classes = (IsAuthenticated, IsPersonalTrainerUser, ) serializer_class = InviteSerializer def get_queryset(self): return get_list_or_404(Invite, personal_trainer=self.kwargs['personal_trainer_pk']) def perform_create(self, serializer): get_object_or_404(PersonalTrainer, pk=self.kwargs['personal_trainer_pk']) serializer.save(personal_trainer=self.request.user.personaltrainer) Now I need to authorize the personal_trainers to read/write ONLY their invites. I have been reading about django object permission. http://www.django-rest-framework.org/api-guide/permissions/#custom-permissions How can I do that? -
How to make a custom field with multiple db fields in Django
I have a class: class MyCustomType(object): a, b = 0, "" def __init__(self, a, b): self.a = a self.b = b I want to make a custom field class for MyCustomType. class MyCustomField(models.Field): @staticmethod def parse_value(value): # magic return MyCustomType(a, b) def from_db_value(self, value, expression, connection): if value is None: return value return self.parse_value(value) def to_python(self, value): if isinstance(value, MyCustomType) or value is None: return value return self.parse_value(value) How can I use two db fields for storing a and b data? a is an integer and b is a string? -
https facebook login automatically redirects to http
My web application (django 1.10) is currently deployed on https, however when I try logging using my social login (facebook) it takes me to http instead of https. I want the user to remain on https instead of being redirected to http. I have tried the below, If I remove my listeners on my aws load balancer listener port 80, I will get an error logging into the app using my facebook account. If I remove the http callbacks from my facebook Valid OAuth redirect URIs. It will prompt an error when I try logging in. I tried looking for the login script within my social accounts third party library, somehow my login script should be a https instead of a http but couldnt find anything resembling a http direct coe it. I am looking for suggestions on tips on how I can fix this. Thanks to anyone who has any idea in advance. -
Downloading Zip file through Django, file decompresses as cpzg
My goal is to parse a series of strings into a series of text files that are compressed as a Zip file and downloaded by a web app using Django's HTTP Response. Developing locally in PyCharm, my method outputs a Zip file called "123.zip" which contains 6 individual files named "123_1", "123_2 etc". containing the letters from my phrase with no problem. The issue is when I push the code to my web app and include the Django HTTP Response the file will download but when I go to extract it it produces "123.zip.cpzg". Extracting that in turn gives me 123.zip(1) in a frustrating infinite loop. Any suggestions where I'm going wrong? Code that works locally to produce "123.zip": def create_text_files1(): JobNumber = "123" z = zipfile.ZipFile(JobNumber +".zip", mode ="w") phrase = "A, B, C, D, EF, G" words = phrase.split(",") x =0 for word in words: word.encode(encoding="UTF-8") x = x + 1 z.writestr(JobNumber +"_" + str(x) + ".txt", word) z.close() Additional part of the method in my web app: response = HTTPResponse(z, content_type ='application/zip') response['Content-Disposition'] = "attachment; filename='" + str(jobNumber) + "_AHTextFiles.zip'" -
install ssl certificate in django on window server
How to install SSL certificate in django based web application running on windows server. one window service is running for this application and there are some other applications running under it such as nssm, nginx and apache Thanks in advance -
How to store a file in memory with Python (django)?
I have this code: NNModel.py import pickle from keras.models import load_model def load_obj(name): with open('/home/user/' + name + '.pkl', 'rb') as f: return pickle.load(f) def load_stuff(): model = load_model("/home/user/model2.h5") voc = load_obj('voc') return (model,voc) It loads my files when I use this function, I'd like to load them to some static or singleton ?class? on the first time and then access that file. How can I achieve that in Python/django? This file is fairly big and right now I belive every request loads it into memory which is not efficient I guess... -
select anwser ajax model query django
Hi i make a search field in django it's work but i want select the result of the query and put it in the fiels search fields, i already use <select> or <datalist> but it's don't work. how do it. my code: views.py: def searchPlanteur(request): if request.method == 'POST': form = PacageForm(request.POST) planteurs = "" if form.is_valid(): pacPlan = form.cleaned_data planteurSearch = pacPlan['planteurSearch'] value = request.POST['planteurSearch'] planteurs = Planteur.objects.filter(pacage__contains=value) if planteurs == None: planteurs = 'Auncun planteur ne correspond au pacage renseigner. Veuillez rentrer un pacage valide' return render(request, 'blog/ajax/ajax.html', {'planteurs' : planteurs}) def ajax_query(request): if request.method == 'POST': form = PacageForm(request.POST) if form.is_valid(): pacPlan = form.cleaned_data planteurSearch = pacPlan['planteurSearch'] value = request.POST['planteurSearch'] planteurs = Planteur.objects.objects.filter(pacage__contains=value) return HttpResponseRedirect('blog/ajax_query.html', {'planteurs': planteurs}) else: form = PacageForm() return render(request, 'blog/ajax_query.html', {'form': form}) urls.py: from django.conf.urls import url from . import views app_name ='blog' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^posts/(?P<id>[0-9]+)$', views.show, name='show'), url(r'^planteur/$', views.planteur, name='planteur'), url(r'^mouvement/$', views.mouvement, name='mouvement'), url(r'^ajax/planteur/$', views.searchPlanteur, name='searchPlanteur'), url(r'^ajax_query/$', views.ajax_query, name='ajax_query'), #url(r'^ajax_query/blog/ajax_query.html/$', views.ajax_query, name='ajax_query'), url(r'^autocomplete/$', views.autocomplete, name='autocomplete'), url(r'^get_planteurs/$', views.get_planteurs, name='get_planteurs'), forms.py: class PacageForm(forms.Form): planteurSearch = forms.CharField(label='planteurSearch', max_length=100, widget=forms.TextInput(attrs={'onkeyup': 'planteur_suggestion()', 'placeholder': 'planteur_datalist', 'list': "pacageListe",})) def clean_planteurSearch(self): try: planteurSearch = int(self.cleaned_data["planteurSearch"]) except: planteurSearch = "Auncun planteur ne correspond au pacage renseigner. Veuillez … -
Retrieve all the values of one column of Dataset in Django
class Publisher(models.Model): name = models.CharField(max_length=30) address = models.CharField(max_length=50) city = models.CharField(max_length=60) state_province = models.CharField(max_length=30) country = models.CharField(max_length=50) Suppose I have this dataset. I want to retrieve all the names of the cities in an array. Help me -
django serialize( data to convert the default serializer response to desired format)
I need to convert the response like this using serializers.py.Where id is from model Mymodel and Total_login_hours is from model class Mymodel(models.Model): status = models.CharField(max_length=50, choices=BIKER_STATUS_CHOICES, default='active') name = models.CharField(verbose_name=_('Biker Name'), max_length=254) classLoginModel(models.Model): biker = models.ForeignKey(Mymodel, db_index=True, on_delete=models.PROTECT) total_loginhrs = models.TimeField(null=True, blank=True) I have a response as shown below by using django serializer in django rest framework { "count": 1, "next": null, "previous": null, "results": [ { "id": 128, "totaldata": [ { "City": "abc", "Locality ": "def", "Biker_name": "xyz", "Total_login_hours": "00:28:41", "Date": "2018-01-13", "Sublocality": "qwe" }, { "City": "asd", "Locality ": "fgh", "Biker_name": "zxc", "Total_login_hours": "00:02:33", "Date": "2018-01-14", "Sublocality": "cvb" } ] } ] } ] } I need to convert the response like this using serializers.py Where id is from model Mymodel and Total_login_hours is from model { "count": 2, "next": null, "previous": null, "results": [ { "id": 128, "totaldata": [ { "City": "abc", "Locality ": "def", "Biker_name": "xyz", "Total_login_hours": "00:28:41", "Date": "2018-01-13", "Sublocality": "qwe" }], "id": 128, "totaldata": [ { "City": "asd", "Locality ": "fgh", "Biker_name": "zxc", "Total_login_hours": "00:02:33", "Date": "2018-01-14", "Sublocality": "cvb" } ] } ] } i am a fresher in python..can you please give me a solution for the same.How can we repeat id in … -
Django+uWSGI+nginx server configuration, no file .sock?
structure: /data # General directory for projects on the server -------- mysite # Directory for the website mysite -------- -------- conf # Configuration files for the web server mysite_nginx.conf mysite_uwsgi.ini -------- -------- project # Project code -------- -------- --------firstsite #Here settings wsgi -------- -------- venv # The directory for the virtual environment # mysite_nginx.conf # the upstream component nginx needs to connect to # Если будете настраивать несколько django сайтов - измените название upstream upstream django { server unix:///data/mysite/mysite.sock; # for a file socket } # configuration of the server server { listen 80; # порт на котором будет доступен ваш сайт server_name .example.com; # доменное имя сайта charset utf-8; client_max_body_size 75M; # max upload size # Django media location /media { alias /data/mysite/project/media; } location /static { alias /data/mysite/project/static; } location / { uwsgi_pass django; include uwsgi_params; } } # mysite_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /data/mysite/project # Django's wsgi file module = project.wsgi # the virtualenv (full path) home = /data/mysite/env/virtualenv # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket socket = /data/mysite/mysite.sock # ... with appropriate permissions - … -
Multiple Bootstrap Modals to pop on demand only, in django. I tried to separate modal and <button data-target=""> into two files which is not working
I wanted to display multiple modals on demand - pop up. Problem comes when I try to put the trigger(button or anchor tag) to pop modal and modal's html code in two separate html files.I'm not sure how to do it. This is my html file, through which I need multiple modals to pop when I click <a> tag. I have a modal in another html file, main.html: {% for pk,obj in data %}<br> <div class="col-md-6 "> {{ obj }} </div> <div class="col-md-6 "> <a href="{% url 'api-predata' %}" data-target="#{{ pk }}">Launch modal</a> </div> <br> {% endfor %} modal.html: <!-- Button trigger modal --> {% load crispy_forms_tags %} {% if data %} {% else %} <button type="button" class="btn btn-success" data-toggle="modal" data-target="#first_apc"> Create one </button> {% endif %} <!-- Modal --> <div class="modal fade bd-example-modal-lg" id="{{ pk }}" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header" align="center"> Submit Form </div> <div class="modal-body"> <div class="col-md-12"> {{ form.journalname | as_crispy_field }} </div> <div class="col-md-3 col-md-offset-2"> <button class="btn btn-primary"> Submit </button> </div> </div> </div> </div> </div> -
Strange cache bug after repreating the same task in django App
i'm about to finish my current project, i was doing repeated test to see if everything was going fine. The goal of the app is pretty simple, on the index page the user can choose to create a "movement'. When he click on the creation button, he is redirected on the creation page, fill the form and send it. A new entry is created and displayed in the index tab. When he click on the creation button, the app create an empty "movement" key in redis, fill it with the basic informations, the key is then updated with the informations submited in the form. every hit on the creation button create a new key in redis and a new entry in the database, the redirected page contain a pk in the url that correspond to the "movement" ID. at the start most of the values are set to NULL so almost every input field on the page is filled with "NULL" (all the fields are set to django tags that refer to the redis values) That mean that every creation page is full of "NULL" when the user is redirected on it, or at least it should. My current problem … -
How do I pay for a one year plan Heroku
Hello I am new here i am trying to pay heroku for my django application but i want to use the one month $7 plan for a year without having to renew every month any help would be appreciated thanks. -
Tight coupling in Django models
I have django model which contains incident_type and closed fields. Based on this fields I need to return functions that render some text. Is it okay to have such get_renderer method in models or I should move this logic somewhere else? In my understanding, this method violates single responsibility principle. class Incident(models.Model): BAD_RESPONSE = 'bad_response' SLOW_RESPONSE = 'slow_response' INCIDENT_TYPE_CHOICES = ( (BAD_RESPONSE, 'Webpage is not available'), (SLOW_RESPONSE, 'Webpage is slow'), ) incident_type = models.CharField(max_length=50, choices=INCIDENT_TYPE_CHOICES) closed = models.BooleanField() def get_renderer(self): if self.incident_type == self.BAD_RESPONSE: if self.closed: return render_page_up_screen else: return render_page_down_screen -
Docker crontab: not found
Sorry for my english. I use django-crontab in my project. Localy in my project work fine. But i want use Doker, when i run Docker i have error: /bin/sh: 1: /usr/bin/crontab: not found my docker-compose version: '2.0' services: web: build: . container_name: test_api volumes: - .:/usr/django/app/ expose: - "8000" env_file: main.env command: bash django_run.sh nginx: build: ./nginx container_name: test_ng ports: - "8000:8000" volumes: - ./nginx/api.conf:/etc/nginx/conf.d/api.conf - .:/usr/django/app/ depends_on: - web links: - web:web django_run.sh #!/usr/bin/env bash set -e if [ "$ADD_CRON" == "true" ]; then python manage.py crontab show fi if [ "$ADD_CRON" == "true" ]; then python manage.py crontab add fi if [ "$ADD_CRON" == "true" ]; then python manage.py crontab show fi if [ "$ADD_CRON" == "true" ]; then python m/usr/local/bin/gunicorn ${DJANGO_APP}.wsgi:application --timeout ${GUNICORN_TIMEOUT} --keep-alive ${GUNICORN_KKEP_ALIVE} -k gevent -w ${GUNICORN_WORKERS} --threads ${GUNICORN_THREADS} -b :${GUNICORN_PORT} my logs: test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | Currently active jobs in crontab: test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | sh: 1: /usr/bin/crontab: not found test_api | adding cronjob: (649feb1a8431f09891b644aa4ba2075b) -> ('*/1 * * * *', 'cron.cron_jubs.clear_pdf_files_scheduled_job', '>> /tmp/scheduled_job.log') test_api | /bin/sh: 1: /usr/bin/crontab: not found test_api | Currently active jobs in crontab: test_api | [2018-03-15 14:23:41 +0000] [35] … -
Django, query objects BEFORE certain id
I have encountered one interesting problem Lets say I have objects in my database likt this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Lets consider numbers as ids of these objects If I want to get two objects after 5, I need to use this query: MyObject.objects.filter(id_gt=5).order_by("id")[:2] This will return to me this result: [6, 7] Which is right result. Now I want to get two objects before object 5. I do this query: MyObject.objects.filter(id_lt=5).order_by("id")[:2] However, this returns to me this: [1, 2] instead of [3, 4] So I need to query objects starting from object of id=5 I know that there is ranged query, but it does not suit when working only with ids. Is it possible to query objects before certain id starting from this object itself? -
What do I have to do if I don't want to use basic auth on Django?
I'm new to Django. I'm working on a project, so now I'm making the login feature. And the thing I've got noticed is, when I log in, the Authorization type that I use, which is basic authentication, could be dangerous. So I thought I need to find another way to authenticate when I send a request to the server. What do I have to do if I don't want to use basic auth?