Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Idiom for script directory in python application?
I have a python application (Django based), and I have a couple of standalone maintenance scripts that go along with the application, that I have to call every now and then. They have to import parts of my application (sub-packages). Currently, I just put them in my toplevel directory: application/ djangoproject/ djangoapp/ otherpackage/ tool1.py tool2.py Where tool1.py would do from djangoproject import wsgi from djangoapp.models import Poll I've accumulated quite some of these tools, and would like to move them to a scripts subdirectory. Then, I would like to be able to call them via python scripts/tool1.py or maybe cd scripts; python tool1.py. I understand (and sometimes lament) how Python's imports work, and I know that I can add some lines to each script to add the parent directory to PYTHONPATH. I am wondering if there is a widespread pattern to handle such a collection of assorted scripts. Maybe one could put the path manipulation into another file, and have every script start with import mainproject? I am using a virtualenv, and installing dependencies with pip. But the application itself currently doesn't use a setup.py, and I think it wouldn't help to move the scripts to a separate package installed … -
What does request_source do in a Django template
I am picking up some old Django code and am puzzled by a line in the site's master template. After a series of {% load xxx %} lines there is the line {% request_source 849051 %} I have been unsuccessful in finding any documentation for this command. Is it a standard template command? Or is it something custom to this code, and if so where would I likely find the implementation? The site was written for Django 1.5.12 if that makes a difference. -
How and where to format date in Django (Python, Ajax)?
Can I format the date in the foreach loop ? advertisements_list = [] for advertisement in advertisements: advertisements_list.append({ 'id': advertisement.id, 'description': advertisement.description, 'title': advertisement.title, 'picture_url': advertisement.image.url, 'date': advertisement.date -> format that }) In my template I would do something like {{ advertisement.date | date:"d.m.Y" }}. Is there something similiar which I can use in my foreach-loop ? I can not go the template way because it is Ajax. Is it even the right place for formatting or should I do the formatting with JavaScript/jQuery when I passed the data ? -
"utf-8" encoding works on development server but not when deployed
My django application hosted at pythonanywhere.com does not support utf-8 encoding. Characters like 'é' returns error. Views: def result_view(request): if request.method == 'POST': search= request.POST.get('textfield').encode("utf-8") print search try: try: value = wikipedia.page(search) title= value.title url=value.url print title data= wikipedia.summary(search, sentences=10) except wikipedia.exceptions.DisambiguationError as e: data = e title=search+" (Disambiguation)" u = search.replace(" ", "_") url = "https://en.wikipedia.org/wiki/"+u except: raise Http404() return render(request,"search/result.html",{'title':title,'url':url,'data':data}) else: return render(request,"search/result.html",{}) The textfield input is encoded with utf-8 and works fine in Django development server but returns 404 page in my pythonanywhere server. Template: <form name="myform" method="POST" action="{% url 'result' %}"> <div class="form-group"> <div class="input-group"> {% csrf_token %} <input type="text" class="form-control" name="textfield" placeholder="Search" required /> <div class="input-group-addon"> <span class="glyphicon glyphicon-search"></span> </div> </div> </div> <button type="submit" class="btn btn-danger btn-lg ">Search</button> </form> -
How to make django work with RTSP?
I searched everywhere but couldn't find an answer How can i make django work with RTSP. How to start the process of building an RTSP server and then connecting users to a particular stream. -
Python Django Load Images based on Tab Clicked
I am using bootstrap with nav-tabs to hopefully select filtered images based on the tab clicked. I can do an AJAX call to the view that I created that filters out the images based on category and returns an items.html template file. Is there a way to load the partial template without having to reload the entire page? Should I just do the AJAX call and it will update that partial view? -
How to upload image in react native?
Hi everyone i am trying unsuccessfully to upload image to my backend server (build with Django/python). When i try with postman it work well, but my code does not work. That is it: const data = new FormData(); data.append('id_pharma',13 ); // you can append anyone. data.append('name', { uri: this.state.photo.uri, type: 'image/png', // or photo.type filename: 'image.png' }); data.append('Content-Type', 'image/png'); fetch(config.base_url+'upload/', { method: 'post', body: data, headers: { "Content-Type": "multipart/form-data" } }).then(res => { console.log(res) }).catch((err)=> { this.setState({error_text: 'Echec de l\'ajout image', is_adding: false}) }); It is a REST API, and it is responding as django.utils.datastructures.MultiValueDictKeyError: "'name'" It seem like data is not going, please what am i doing wrong ?? (Sorry for my english) -
Best practise for package install on django server
So I'm setting up a server by myself. Now I ran into lots of different ways where to install the packages. I am thinking of the core packages like nginx, gunicorn, python3, postgresql and so on. I learned that setting up a VENV (virtual environment) is a good thing so I can have several projects running with different versions on packages. But it's a bit confusing wich ones are not going to be inside the VENV. Some install postgreSQL outside the VENV, but psycopg2 inside. Some the gunicorn inside VENV. and so on. Is there any best pratices or rules that are better safe to follow? For info. I'm setting up a Ubuntu server 16.04 with Nginx, gunicorn. PostgreSQL, psycopg2, python3 -
Which DRF generic view should be used for validating login credentials?
Just a quick question. All of my views are very redundant and just use APIView. Trying to clean it up by using generic views. Someone recommended using CreateAPIView for such things as credential verification, which didn't seem right. As expected, it tries to create the user when you provide credentials. http://www.django-rest-framework.org/api-guide/generic-views/#createapiview So just trying to find out which generic view should be used for verifying credentials passed to it from the front-end. Seems like RetrieveAPIView, but it is a get so seems like it would return the credentials which is not good. http://www.django-rest-framework.org/api-guide/generic-views/#retrieveapiview -
Can't make WhiteNoise work with Django & Heroku for production
I'm trying to reproduce a production website on Heroku, and to do that I followed step-by-step these 3 guides below: http://whitenoise.evans.io/en/stable/django.html https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Deployment devcenter.heroku.com/articles/django-assets Since I'm using Django 1.11, I don't know if I need to do something different from these guides. Part of my production.py(same as settings.py but only for production) looks like this: DEBUG = bool( os.environ.get('DJANGO_DEBUG', True) ) ALLOWED_HOSTS = ['(((MY WEBSITE))).herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And the bottom of production.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), '/var/www/static/', ] STATIC_URL = '/static/' CORS_REPLACE_HTTPS_REFERER = True HOST_SCHEME = "https://" SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True SECURE_HSTS_INCLUDE_SUBDOMAINS = True SECURE_HSTS_SECONDS = 1000000 SECURE_FRAME_DENY = True SECURE_CONTENT_TYPE_NOSNIFF = True SECURE_BROWSER_XSS_FILTER = True SECURE_HSTS_PRELOAD = True X_FRAME_OPTIONS = 'DENY' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' Everything works fine when the DEBUG = True, but when I set DEBUG = False I get a Server Error (500) meaning it's something wrong with Django and/or WhiteNoise while handling the staticfiles but I really don't know where is the problem. Other relevant files: Procfile (required for heroku) web: gunicorn … -
Changing the primary key of a model in django back to default, even when the model has dependencies with other model?
I have a django model (say model1) where I have my own primary key, but now I want to change the primary key to default id field. But the problem if I try to change is, I have another model (say model2) which has many to many dependency to the model1 and it is causing errors when I am trying to modify the field. Is there any way I can change the primary key of this model? ex: class model2(models.Model): id = .. ... model1 = models.ManyToManyField("model1", blank=True) classs model1(models.Model): Name = models.charField(primary_key=True, max_length=280) .. Now I want to change the primary key of model1 back to Id. -
Celery not detecting new tasks in django
I have a django project with the following hierarchy: . ├── api_v_1_0 ├── celery_tasks ├── db.sqlite3 ├── doc ├── manage.py ├── __pycache__ ├── rockynode ├── run.sh ├── static ├── staticfiles └── web All the celery tasks are in the celery_tasks app : celery_tasks ├── apps.py ├── emitter ├── __init__.py ├── mongo ├── __pycache__ ├── rockynodemail ├── test The test modules is a newly added module with tasks as follows: from rockynode.celerys import celery_app_basic class test: @celery_app_basic.task(queue='General') def s(x): return "{}" The test module comprises of two files mainly: celery_tasks/test ├── __init__.py └── mytest.py The content of __init__.py is as below: from .mytest import test However I cannot see the newly created task in my celery. For example if i do the following I dont see the celery_tasks.test.s task in the list: from celery.task.control import inspect i = inspect() i.registered_tasks() Am I missing something in the process? -
Invalidate cache on updation in table
Suppose, if I have a key in my redis cache or any other cache and there are a lots of GET queries for that key. The value of the key depends on the data in a model (table). Now if through some process the value associated with that key is updated in database then what are the ways in which I can invalidate the cache. -
is there an equivalent of rails try in django?
In Rails, you can call try when you're not sure if the object will exist or not. def method(foo) foo.try(:bar) end if foo exists, it will call foo.bar, and if not, it will return nil. Is there a similar mechanism in Django? -
Django-rest-framework: return Response from .dispatch
I am doing a (more-or-less) custom authentication in a django-rest-framework-based application, where I just need to call another microservice to ask it if a token is valid and what username/userid are associated with it. (I don't have a local table for users). Having found no out-of-the-box solution, I am overriding the dispatch method (I am using a APIView-based view), where I make the request to the remote service and, if the response is not 200, I want to return a 403 error. Here's my code: def dispatch(self, request, *args, **kwargs): try: user_info = user_from_token_in_request(request) return super().dispatch(*args, **kwargs) except: return Response( "No Auth Token provided or bad Auth Token" status.HTTP_403_FORBIDDEN, ) However, when I pass an invalid token, I get this error: AssertionError: .accepted_renderer not set on Response, because the response context is not initialised when the dispatch method is processed. Is there a, sort of, more proper way of doing it? -
Migrate Functions Based Views to Class Based views
According to this post, I'm trying to modify my whole script in order to get Class Based Views (CBV) in my Django application. I would like to get any help, because it's the first time I'm using CBV. My previous script function looks like this : @login_required def IdentityIndividuForm(request) : success = False query_Nom_ID = query_Prenom_ID = query_VilleNaissance_ID = None if 'recherche' in request.GET: query_Nom_ID = request.GET.get('q1NomID') query_Prenom_ID = request.GET.get('q1PrenomID') query_VilleNaissance_ID = request.GET.get('q1VilleNaissanceID') sort_params = {} lib.Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_Nom_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_Prenom_ID) lib.Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_VilleNaissance_ID) query_ID_list = Individu.objects.filter(**sort_params) else : query_ID_list = Individu.objects.none() if request.method == 'POST': form = IndividuFormulaire(request.POST or None, request.FILES or None) if form.is_valid() : post = form.save() return HttpResponseRedirect(reverse('IndividuResume', kwargs={'id': post.id})) else : form = IndividuFormulaire() form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name context = { "form" : form, "Individu" : Individu, "query_Nom_ID" : query_Nom_ID, "query_Prenom_ID" : query_Prenom_ID, "query_VilleNaissance_ID" : query_VilleNaissance_ID, "query_ID_list" : query_ID_list, } return render(request, 'Identity_Individu_Form.html', context) I had a GET part and a POST part in my function. I changed that to CBV model and my class looks like this : class IdentityIndividuFormView(CreateView) : template_name = 'Identity_Individu_Form.html' model = Individu fields = [ 'Etat', 'Civilite', 'NomJeuneFille', 'Prenom', 'Nom', 'Statut', 'Sexe', 'DateNaissance', 'VilleNaissance', … -
How to send a mail to new registered user with a link to change password?
The user submit a form with his name, email, etc. This form is submitted and it creates the user account and it sets a random password. How can I send to each new user a mail with a link to change directly the password ; I mean without the password_reset_form.html step. Put concisely, I wish to send a mail with {{ protocol }}://{{ domain }}{% url 'password_reset_confirm' uidb64=uid token=token %} but I get this : django.urls.exceptions.NoReverseMatch: Reverse for 'password_reset_confirm' with keyword arguments '{'uidb64': '', 'token': ''}' not found. 1 pattern(s) tried: ['accounts/reset/(?P<uidb64>[0-9A-Za-z_\\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] -
KeyError at /partners/create/ 'name'
I have a model Partner that is related to Product by a one to many relationships. I am using inlineformsets for the Product and I am gettig the following error which I don't understand:"KeyError at /partners/create/ 'name'" my views are as follows: def partner_create(request): if not request.user.is_staff or not request.user.is_superuser: raise Http404 ProductFormSet = inlineformset_factory(Partner, Product, form=ProductForm, extra=3, min_num=1) if request.method == 'POST': partnerForm = PartnerForm(request.POST or None, request.FILES or None) formset = ProductFormSet(request.POST, request.FILES, queryset=Product.objects.none()) if partnerForm.is_valid() and formset.is_valid(): instance = partnerForm.save(commit=False) instance.save() for form in formset.cleaned_data: name = form["name"] description = form["description"] price = form["price"] image = form["image"] product = Product(partner=instance, name=name, description=description, price=price, product_image=image) product.save() messages.success(request, "Partner Successfully Created") else: print partnerForm.errors, formset.errors else: partnerForm = PartnerForm() formset = ProductFormSet(queryset=Product.objects.none()) return render(request, "partner_form.html", {"partnerForm": partnerForm, "formset": formset}) my forms.py are as follows: class PartnerForm(forms.ModelForm): mission = forms.CharField(widget=PagedownWidget(show_preview=False)) vision = forms.CharField(widget=PagedownWidget(show_preview=False)) # publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Partner fields = [ "name", "logo", "banner_image", "mission", "vision", "website_link", "fb_link", "twitter_link", "ig_link", ] class ProductForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Product fields = [ "partner", "name", "description", "price", "image", ] My models.py are as follows: class Partner(models.Model): name = models.CharField(max_length=120) logo = models.ImageField(upload_to=upload_location, null=True, blank=True, width_field="width_field", … -
Hiding ModelMultipleChoiceField on template for custom input
I want the user to select a number of elements belonging to a certain model. I don't want to use the default 'ctrl+click' input of django forms, but create a table of checkboxes myself. For that reason I hide the ModelMultipleChoiceField by defining the widget: field = forms.ModelMultipleChoiceField(..., widget=forms.MultipleHiddenInput()) Then I add the form element into the template as follows: <form method="POST" class="locklist-form" id="locklist-form">{% csrf_token %} {{ form.field }} </form> At this step, I expect the select-option elements to be added to HTML page (as hidden), so that I can reach to element options and modify them with javascript. However, it doesn't add anything to the HTML page. I use this approach with other type of form fieds. For a TextField HTML page have a hidden element as shown: Why doesn't it work with ModelMultipleChoiceField? How can I modify the choices of this field with Javascript? Edit: MultipleHiddenInput renders only if with initial data is a similar question. But applying it doesn't lead to the expected solution. In this question, it is expected to render the following as hidden: But following the MultipleHiddenInput renders only if with initial data, when I modify the form constructor as: form = MyForm(initial={'field':MyModel.objects.all()}) Rendered … -
Hosting Django on Google cloud 502 error
Good day. I'm a newbie to GCP. I followed the steps on the site on how to host a Python app using the app engine. However when I try to access the site on myfirstestever.appspot.com, it returns a 502 error. I dont know what is wrong or what to do about it. I'm a newbie. How can I solve this? Thanks. Note: the app is written using Python 3.5 and Django 1.10 -
django two foreign key for same model
my model User = models.ForeignKey(User,related_name='User') AssignedUser = models.ForeignKey(User, related_name='AssignedUser') i just want to give a 2 foreign key this my model but error is AssertionError: ForeignKey() is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' -
How to get input either from a form or as uploaded input file in Django?
I have write a view which takes input either from a form where you can past your data directly or you can upload a ".csv" file like this given bellow: views.py def Some_view(request): if request.method == 'POST': form = My_form(request.POST) else: request.method == 'POST' and request.FILES['myfile'] myfile = request.FILES['myfile'] fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'myapp/des.html') return render(request, 'myapp/des.html', {'form': form}) html template: des.html is like this: {% extends 'protocol/base.html' %} {% load staticfiles %} <!DOCTYPE html> <html> <head> <title></title> <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> </head> {% block content %} <body> <div class="container"> <div style="width:30%"> <form action="/result_view/" method="post"> {%csrf_token%} {% for error in form.non_field_errors %} <div class="form-group has-errors text-danger small"> {{error}} </div> {% endfor %} {% for field in form %} <div class="form-group has-errors text-danger small"> {{field.errors}} </div> <div class="form-group has-errors text-danger small"> </div> {% endfor %} <div class="form-group"> {{form.AA}} </div> <div class="form-group"> <button class="btn btn-primary" style="width:100%; margin-bottom: 30px ">Submit</button> </div> <h2> or <h2> <style type="text/css"> .button { background-color: #ff9800; /* Green */ border: none; color: black; padding: 10px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin-top: 10px; margin-bottom: 30px; } </style> <form method="post" enctype="multipart/form-data"> <div class="heading"> </h4> </div> {% csrf_token %} … -
Stripe Connect Python
Trying to clean this question up a little, everything works in the stripe connect callback function and I can save stripe user id againt my user, Id like to save the stripe user id againt a related profile model but not sure how to get that model from user=request.user. Any suggestions would be a big help. def stripe_callback(request): client_secret = STRIPE_API_KEY user = request.user code = request.GET.get('code', '') data = { 'grant_type': 'authorization_code', 'client_secret': 'sk_test_5SLLtqWFDTqzdbYmBz4XZpSX', 'client_id': 'ca_ANdfv3rlKvpOU3rDglk6qoXuBYqGYiq5', 'code': code, } url = 'https://connect.stripe.com/oauth/token' resp= requests.post(url, params=data) stripe_payload = json.loads(resp.text) stripe_user_id = stripe_payload['stripe_user_id'] user.stripe_user_id = stripe_user_id user.save() -
Django - How to redirect to a different view without returning a redirect HTTP response? (e.g. .NET's Server.Transfer)
I'm working on an application where in a certain circumstance a redirect must take place, but the necessary querystring parameters are extremely large and at risk of not working in certain browsers / HTTP proxies. In the past when working with .NET, I could do a Server.Transfer to perform a redirect without sending anything to the client. Is there a similar capability or pattern I can use in Django to accomplish this? Some things I've considered are: Transferring the parameters out of the querystring and into Session (or other server-side) state, and doing a normal 302 redirect Having the first view function directly call the second view function Neither of these approaches feels right; what other possibilities should I consider? -
Github not detecting language used for django python
I recently added a django repository to github but the language used is displaying javascript instead of python