Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Django Prefetch related query
I am having two models Customer and Contact where I want to add fields from Contact model to Customer model and access the values of it.How to solve it? Thanks in advance. models.py class Customer(models.Model): code = models.CharField(primary_key=True,max_length=30) name = models.CharField(max_length=200) address = models.CharField(max_length=100) class Contact(models.Model): partner_name =models.ForeignKey(Customer,blank=True,null=True,on_delete=models.CASCADE) contact_number=models.CharField(max_length=15,blank=True) email=models.EmailField(max_length=50,blank=True) I tried this query q=Customer.objects.filter(name='xxx').prefetch_related('contact_set') for i in q: print(i.contact_set) It returns partner.Contact.None partner.Contact.None partner.Contact.None -
Improve Django View with Methods
I'm looking to improve my Django web application and mainly project scripts. I'm using many times the same Python code and I would like to simplify my views.py file. For example, I have several times this part : if request.method == 'POST': form = FormBase(request.POST or None, request.FILES or None) if form.is_valid() : post = form.save() return HttpResponseRedirect(reverse('ReverseTemplate', kwargs={'id': post.id})) else : form = FormBase() form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name So, instead of copy/past this part in my different view function, I would like to set : def DjangoFormID(request, FormBase, ReverseTemplate) : if request.method == 'POST': form = FormBase(request.POST or None, request.FILES or None) if form.is_valid() : post = form.save() return HttpResponseRedirect(reverse('ReverseTemplate', kwargs={'id': post.id})) else : form = FormBase() form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name And call this function in my view : DjangoFormID(request, IndividuFormulaire, IndividuResume) I would like to know if my process is fine ? Is it a better way to programming rather than what I've done ? Then, I'm getting this error : name 'IndividuResume' is not defined How I could write my Django template inside my method ? Thank you -
Django Rest Framework overwrite serializer "to_internal_value" fucntion gets "this field is required" error with form-data, but not with json
I want my nested serializer works like primary key related field when used as input, and works as normal nested serializer when used as output. So I overwrite the to_internal_value, but it only works with application/json. When using form-data and x-www-form-urlencoded, I got a This field is required error. Here's my code for serializers. class PrimaryKeyFieldMixin(object): def to_internal_value(self, data): model = self.Meta.model try: return model.objects.get(pk=data) except ObjectDoesNotExist: self.fail('does_not_exist', pk_value=data) except (TypeError, ValueError): self.fail('incorrect_type', data_type=type(data).__name__) class PatientSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name=namespace + ':patient-detail') class Meta: model = Patient fields = '__all__' class PatientRelatedField(PrimaryKeyFieldMixin, PatientSerializer): pass class PatientRecordSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name=namespace + ':patient_records-detail') patient = PatientRelatedField() class Meta: model = PatientRecord fields = '__all__' Using with json: Request: { "patient": 1, "record_data": "some data" } Response: { "url": record_url, "patient": { "url": patient_url, "patient_data": some_data, }, "record_data": "some_data" } This works exactly as I want. But when using form-data and x-www-form-urlencoded I got a This field is required error on patient field. After using the debug in pycharm to step through the code, it looks like I need to overwrite get_value function as well, I'm not sure. -
Was i gotten a hacking?
Hello~ I've been studying Django, I've run Django Sever and I was experienced Look at this plz~ [12/Oct/2017 19:30:53] "GET /favicon.ico HTTP/1.1" 200 38 [12/Oct/2017 19:32:39] "POST /command.php HTTP/1.1" 403 1515 [12/Oct/2017 19:32:40] "GET /system.ini?loginuse&loginpas; HTTP/1.1" 200 38 [12/Oct/2017 19:32:41] "GET /upgrade_handle.php?cmd=writeuploaddir&uploaddir;=%27;echo+nuuo123456;%27 HTTP/1.1" 200 38 [12/Oct/2017 19:32:45] "GET /board.cgi?cmd=cat%20/etc/passwd HTTP/1.1" 200 38 [12/Oct/2017 19:32:49] "POST /hedwig.cgi HTTP/1.1" 403 1515 [12/Oct/2017 19:32:53] "POST /apply.cgi HTTP/1.1" 403 1515 What is this code??????? "POST /command.php, /hedwig.cgi ... I'm thinking about this code is hacking, isn't it?? -
Could not parse the remainder wtforms error
I am using django==1.11 and python3 when i use wtforms i get this error my forms.py look like from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, UserChangeForm from wtforms import Form, BooleanField, StringField, validators, PasswordField class RegistrationForm(Form): username = StringField('Username', [validators.Length(min=4, max=25)]) email = StringField('Email Address', [validators.Length(min=6, max=35)]) password = PasswordField('New Password', [ validators.DataRequired(), validators.EqualTo('confirm', message='Passwords must match') ]) confirm = PasswordField('Repeat Password') accept_tos = BooleanField('I accept the TOS', [validators.DataRequired()]) and views.py is like that def sign_up(request): form = RegistrationForm(request.POST) if request.method == 'POST' and form.validate(): user = User() user.username = form.username.data user.email = form.email.data user.password = form.password.data user.confrim = form.confirm.data user.save() redirect(reverse('accounts:home')) return render(request, 'accounts/reg_form.html', {'form': form}) and my template is like this any idea?! -
I cannot show the value in html
I cannot show the value in html. I wrote in views.py def score_test(request): results = TestScore.objects.filter(user=request.user).all() print(results) return render(request, 'score_test.html',{'results': results}) in score_test.html <div class="col-xs-12"> <h2 class="result_title">Test Score</h2> <h3>Your score is {% for result in results.all %} {% if result.score > 95 %} <h4 class="one"> {{ result.score }} </h4> {% else %} {% if result.score > 80 %} <h4 class="two"> {{ result.score }} </h4> {% else %} {% if result.score > 60 %} <h4 class="three"> {{ result.score }} </h4> {% else %} {% if result.score > 40 %} <h4 class="four"> {{ result.score }} </h4> {% else %} <h4 class="five"> {{ result.score }} </h4> {% endif %} {% endif %} {% endif %} {% endif %} {% endfor %} </h3> </div> in models.py class TestScore(models.Model): score = models.FloatField(null=True, blank=True, default=None) In print(results) of views.py,I got ,so I think I can get score of TestScore model in results.So,how can I fix this?Am I wrong to write if-else statement in template of score_test.html? -
Django - Use the given sql dump to create the other models and to populate the data
I am practising to develop a complex app, i have previously developed the same with PHP and have a sql file. i'd like to know how do i create new models and populate the data from the sql file. I have read tutorials about grabbing from JSON files, But is there any online resources for the same.