Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django model - object attribute update after creation
I am working on some Django project (first time) and after lot of searching i have no clue how to proper update object attribute after creation. I have sucha models.py from django.db import models import os # Create your models here. class Place(models.Model): # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Add templates folder for dynamic usage, os independent TEMPLATE_DIR = os.path.join(BASE_DIR, "templates/places") name = models.CharField(max_length=100, unique=True) display_name = models.CharField(max_length=100) floor = models.DecimalField(max_digits=3, decimal_places=0) template = models.FilePathField(path=TEMPLATE_DIR, match=".*html") url = models.URLField(unique=True) # Display name of object in object list view def __str__(self): return self.name Question is how to update url attribute after object creation of url to this particular object, it should be something like (base url + object_id i know object_id is created after object creation) but after searching documentation i dont have ideas how to do this properly. I tried get_absolute_path but with no success. Maybe some kind post_save method override ? -
Django website : make the url adress unchangeable
I would like to get your advices in order to block the url modification by my clients. For example, I have a client in my website and he will redirect to his own page after the log process. His homepage url looks like : http://mywebsite/client/ with client replaced by his name. For example : http://mywebsite/csa with csais the client's name. But, in the url bar, if my client writes : http://mywebsite/aboproject he will be redirected to aboproject's homepage and I don't want this possibility. My question is : How I can implement some rules, functions, or anything else in order to set unchangeable the url adress ? Client couldn't change the url and see the homepage which make reference to another client ? Thank you -
How to create Id based PUT/POST but details in the response in DRF?
I have a situation where a model has a foreign key with details. Ex. there are two models class Person(models): country = models.ForeignKey(Country) class Country(models): name = models.CharField(max_length=100) Assume countries have been created beforehand. Now, I want the APIs for Person to take only country Id in POST/PUT requests but return the details of that country instead of only Id. Request { "id": 1, "country": 9 } Response { "id": 1, "country": { "id": 9, "name": "Some Country" } } I'm using Django Rest Framework. (I can write serializers which either take id in both read and write APIs or take the entire country object) -
Twitter account authenetication in python with access token
I have a Web Api project that I have already configured to use Facebook & Google authentication. Facebook and Google both have a way of verifying the access token given on authentication step. Facebook: https://graph.facebook.com/debug_token?input_token={0}&access_token={1}", accessToken, appToken These return the app_id or consumer key for my applications. What is the process for Twitter? The documentation I have read isn't very clear and what I have tried fails and returns a 404. -
not null constraint failed error in recommendation system
I tried to add image in reviews page of my project.The image was updated however, I get the error as sqlite3.IntegrityError: NOT NULL constraint failed: reviews_review.pub_date my models.py looks like this: class Review(models.Model): RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) wine = models.ForeignKey(Wine) pub_date = models.DateTimeField('date published') user_name = models.CharField(max_length=100) comment = models.CharField(max_length=200) rating = models.IntegerField(choices=RATING_CHOICES) images = models.ImageField(null = True, blank=True) the code for reviews_list looks like this: {% extends 'base.html' %} {% block title %} <h2>Latest reviews</h2> {% load static %} {% endblock %} {% block content %} {% if latest_review_list %} <div class="row"> {% for review in latest_review_list %} <div class="col-xs-6 col-lg-4"> <h4><a href="{% url 'reviews:review_detail' review.id %}"> {{ review.wine.name }} </a></h4> <br> <a><img src="{% static wine.images.url %}" height="200"></a> <h6>rated {{ review.rating }} of 5 by <a href="{% url 'reviews:user_review_list' review.user_name %}" >{{ review.user_name }}</a></h6> <p>{{ review.comment }}</p> </div> {% endfor %} </div> {% else %} <p>No reviews are available.</p> {% endif %} {% endblock %} -
Django url expression variable is returning the remainder of the url
In my urls.py I have a url expression where I need to get the name of the subject in the view. url(r'^notebook/(?P<subject>.+?)/new/entry/$', view, name) However this returns not only the subject but also the following url. IE: chemistry/new/entry How would I get it to return just chemistry? -
Javascript XMLHttpRequest with Django
I'm trying to send some photos with fetch using React JS to Django. And then I want to save those photos to the database using Django. The React JS function to handle sending photos is as follows: handleAdd(e){ e.preventDefault(); let data = this.state.data; let pictures = this.state.pictures; let body = new FormData(); body.append('data', JSON.stringify(data)); if (pictures.length > 0){ _.each(pictures, (picture, i) => { body.append('pictures', picture); }); } let xhr = new XMLHttpRequest(); xhr.open('POST', `http://localhost:8000/master/api/add-inspection/`); xhr.setRequestHeader("Authorization", "Token vEdD9t701LtDaCZYrSEutHKSNnAuUFAV"); xhr.onload = e => { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log("Status 200"); } else { console.log("Error"); } } }; xhr.onerror = e => { console.log("Error " + e); }; xhr.send(body); } And then Django. In settings.py I have MEDIA_ROOT and MEDIA_URL MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'), STATICFILES_DIRS = (os.path.join(BASE_DIR, 'master/static/master/img/inspection_pictures'),) The add_inspection view is as follows: @token_required @transaction.atomic def add_inspection(request): if request.method == "POST": data = json.loads(request.POST.get('data')) pictures = request.FILES n_inspection = Inspection() n_inspection.user_id = data['user']['id'] n_inspection.data = json.dumps(data) n_inspection.save() save_pictures(n_inspection, pictures) return HttpResponse("Its ok.", status=200) else: return HttpResponse("Something went wrong.", status=400) Where the save_pictures function is as follows: def save_pictures(inspection, pictures): print(pictures) // Gives me <MultiValueDict: {'pictures': [<InMemoryUploadedFile: samsung-s8.png (image/png)>, <InMemoryUploadedFile: Simulator Screen Shot 6 … -
What's more efficient? Read and Write If... or always write to db?
I have a database table, that has a column, which is being updated frequently (relatively). The question is: Is it more efficient to avoid always writing to the database, by reading the object first (SELECT ... WHERE), and comparing the values, to determine if an update is even necessary or always just issue an update (UPDATE ... WHERE) without checking what's the current state. I think that the first approach would be more hassle, as it consists of two DB operations, instead of just one, but we could also avoid an unnecessary write. I also question if we should even think about this, as our db will most likely not reach the 100k records in this table anytime soon, so even if the update would be more costly, it wouldn't be an issue, but please correct me if I'm wrong. The database is PostgreSQL 9.6 -
Django not serving every static files when DEBUG=True
It is really weird that code works fine on Mac and PC with docker. But when i uploaded code to cloud server, it got 404 with some static files and 200 with the others. bootstrap.min.css 200 stylesheet (index) 119 KB 50 ms dataTables.bootstrap.min.css 404 stylesheet (index) 126 B 164 ms buttons.bootstrap.min.css 404 stylesheet (index) 126 B 165 ms Here is my settings.py ... DEBUG = True # still on develop ... STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static") ] ... Maybe something wrong with templates or host ip: Templates I put some basic css/js in base.html. this bootstrap css works fine. <!DOCTYPE html> <html lang="en"> <head> {% block head_meta %} <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> {% endblock head_meta %} <title>{% block head_title %}{% endblock head_title %}</title> <!-- Bootstrap core CSS --> <link href="/static/vendors/bootstrap-3.3.7-dist/css/bootstrap.min.css" rel="stylesheet"> {% block head_link %} <!-- HERE I PUT EXTENDED CSS/JS --> {% endblock head_link %} <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]--> </head> ... </html> And i extend some css/js when i used in some.html. these Datatables css/js got 404. {% extends "base.html" %} … -
Django reverse url with ID
I would like to use HttpResponseRedirect(reverse()) when my client is logged in my application in order to redirect him to his own client page. Each client has a page like this : http://localhost:8000/Identity/Contrat/Societe/4/ The number (4 in this case) corresponds to the client ID in my database and each number redirects to a single page. In my url.py file, I have : url(r'^Contrat/Societe/(?P<id>\d+)/$', views.Identity_Contrat, name="Contrat"), In my log application, I have : def connexion(request): error = False if request.method == "POST": form = ConnexionForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(username=username, password=password) if user: login(request, user) if user == 'Admin' : return HttpResponseRedirect(reverse('accueil')) elif user == 'client4' : return HttpResponseRedirect(reverse('Contrat')) else : error = True else: form = ConnexionForm() return render(request, 'connexion.html', locals()) For example, I would like to redirect my client (client4) to his own page (http://localhost:8000/Identity/Contrat/Societe/4/). And make this process for each client. Do you have any solution to make this process ? Then, I have to restrict access for each client in order to just see his own page. -
ConnectionRefusedError in dJango rest api while registration process
ConnectionRefusedError error showing when register user, basic information added on database but password field was blank and other database fields submitted please find the following error and our class code, Class class ProfessionalRegistrationSerializer(serializers.HyperlinkedModelSerializer): password = serializers.CharField(max_length=20, write_only=True) email = serializers.EmailField() first_name = serializers.CharField(max_length=30) last_name = serializers.CharField(max_length=30) class Meta: model = User fields = ('url', 'id', 'first_name', 'last_name', 'email', 'password') def validate_email(self, value): from validate_email_address import validate_email if User.all_objects.filter(email=value.lower()).exists(): raise serializers.ValidationError('User with this email already exists.') return value.lower() def create(self, validated_data): password = validated_data.pop('password') email = validated_data.pop('email') user = User.objects.create( username=email.lower(), email=email.lower(), role_id=1, **validated_data) user.set_password(password) user.save() return user Error ConnectionRefusedError at /api/v1/register/professional/ [Errno 111] Connection refused Request Method: POST Request URL: http://127.0.0.1:8000/api/v1/register/professional/ Django Version: 1.8.14 Exception Type: ConnectionRefusedError Exception Value: [Errno 111] Connection refused Exception Location: /usr/lib/python3.5/socket.py in create_connection, line 702 Python Executable: /home/project_backend/env/bin/python Python Version: 3.5.2 Python Path: ['/home/project_backend', '/home/project_backend/env/lib/python35.zip', '/home/project_backend/env/lib/python3.5', '/home/project_backend/env/lib/python3.5/plat-x86_64-linux-gnu', '/home/project_backend/env/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/home/project_backend/env/lib/python3.5/site-packages', '/home/project_backend/env/lib/python3.5/site-packages/setuptools-36.0.1-py3.5.egg'] -
Django send email to the user when a specific field on a model has bean changed
I want to send an email to a user on model change. Here is what I have : I have a model called package containing a field status and a field owner , I want to send an email to the owner of the package when the status is changed. Is there a way to do so ? Thank you -
Django internal server error only on live server
I have one strange problem with Django by downloading pdf docs. The site is in two languages (Dutch and French) and I'm trying to download pdf documents in both languages. I have three pdf documents to download. If the site is in the Dutch everything works fine and all three documents are downloaded fine, without any problem (on localhost and on the live server). The problem is with French. On localhost everything works fine, all three docs without any problems, but on live server, two docs are downloaded fine but by the third one I get : INTERNAL SERVER ERROR I do not get any errors, nothing what could give me a hint what the problem is. Here is the code: @login_required def damage_determination_to_pdf(request, calculation_id): calculation = get_calculation(calculation_id) current_language = get_language() f_name_blank = 'master/documents/nl/bestek_schadebepaling.pdf' f_name_filled = 'master/documents/nl/bestek_schadebepaling_filled.pdf' for lang in settings.LANGUAGES: if current_language in lang: f_name_blank = 'master/documents/{}/bestek_schadebepaling.pdf'.format(current_language) f_name_filled = 'master/documents/{}/bestek_schadebepaling_filled.pdf'.format(current_language) buffer = BytesIO() p = canvas.Canvas(buffer, pagesize=A4) p.setFont('Helvetica-Bold', 8) # Seller info p.drawString(100, 640, "{}".format(calculation.make)) p.drawString(100, 627, "{}".format(calculation.model)) if calculation.customer: p.drawString(100, 613, "{}".format(calculation.customer.registration)) p.drawString(100, 599, "{}".format(calculation.customer.chassis)) p.drawString(100, 585, "{:0,} km".format(calculation.mileage)) # Buyer info if calculation.customer: p.setFont('Helvetica-Bold', 8) p.drawString(100, 526, "{} {}".format(calculation.customer.firstname, calculation.customer.lastname)) p.drawString(100, 511, "{}".format(calculation.customer.address)) p.drawString(100, 497, "{} {}".format(calculation.customer.postcode, … -
Preprocess a model field before it is inserted using the admin panel
I using the Django admin interface to be able to easily modify the entries in an existing MySQL database I have. One of my tables contains a password column which contains the hashed password for a user. Now, when I come to create a new user using the admin panel, I have to calculate the password hash externally and then paste that in to the admin panel. Is there anyway I can provide some sort of "pre-insert hook" so that I can enter the password directly, and the hook calculate the hash and pass that on to the admin panel to be saved? -
Django , How can I remain the select value after submit and set the default value to today of input date?
I'm using django to make website. I succeded remaining the input date value after submit passing the value. But I don't know how I can remain the selected value after submit. (I'm not using form) Also, I want to know how I set the default value to today of input type="date"! Here's my page. I want to keep remain the selected value after submit( after submit, the page return this page again) sales.management.html <form id="sales_search" action="{% url 'management:sales_search' %}" method="GET"> <select title="team_choice" name="team_choice" class="select" id="team_choice"> <option name='FC' value="FC" {% if team =='FC' %} selected {% endif %}>FC</option> <option name='Fitness' value="Fitness" {% if team =='Fitness' %} selected {% endif %}>fitness</option> <option name='Pilates' value="Pilates" {% if team =='Pilates' %} selected {% endif %}>pilates</option> <option name='All' value="All" {% if team =='All' %} selected {% endif %}>all</option> </select> <span>Start Day: <input type="date" class="startdate" name="startdate" value="{{ startdate }}" ></span> ~<span>End Day: <input type="date" class="enddate" name="enddate" value="{{ enddate }}" ></span> <button type="submit" class="btn btn-info" value="search" >search</button> </form> I tried {% if team =='FC' %} selected {% endif %} in select boxes. But, it gets error Could not parse the remainder: '=='FC'' from '=='FC''. views.py def sales_search(request): team_choice = request.GET.get('team_choice','') startdate = request.GET.get('startdate','') enddate = request.GET.get('enddate','') #Todo … -
How to make dynamic number of steps in Django form wizard?
Cant't find the answer to my question. I need make number of next steps in my first step of django form wizard, how to do that? Thanks! -
Django Haystack: How to index field from another class
I have a django model Story which I am successfully able to index using templates. However there is another class Reviews which has a static method which takes Story object and returns ratings. How can I index Story on ratings also. {{ object.story_name }} {{Reviews.ratings(object)}} I tried to call this method in template story_text.txt, but that results in an error. django.template.exceptions.TemplateSyntaxError: Could not parse the remainder: '(object)'.... -
How to start uwsgi automatically in ubuntu?
Right now i have a uwsgi.ini in /var/www/mooimom_django/mooimom_uwsgi.ini the content is # Full path: /var/www/mooimom_django/mooimom_uwsgi.ini [uwsgi] chdir = /var/www/mooimom_django chmod-socket = 777 socket = /var/www/mooimom_django/mooimom_django.sock logto = /var/www/log_uwsgi/%n.log wsgi-file = mooimom_django/wsgi.py master = true processes = 10 harakiri = 0 # respawn processes taking more than 0 seconds limit-as = 256 # limit the project to 256 MB threads = 2 vacuum = true the nginx sites-enabled is: /etc/nginx/sites-available/enabled the content is: server { listen 80 default_server; listen [::]:80 default_server; root /var/www/mooimom_django; access_log /var/www/log_nginx/access.log; error_log /var/www/log_nginx/error.log; index index.html index.htm index.nginx-debian.html; server_name _; location /static { alias /var/www/mooimom_django/static/; } location /media { alias /var/www/mooimom_django/media_root/; } location / { try_files $uri @mooimom; } location @mooimom { include uwsgi_params; uwsgi_pass unix:/var/www/mooimom_django/mooimom_django.sock; } } My problem is that right now i have to start uwsgi by typing this on the console, otherwise the application server UWSGI won't start: sudo uwsgi /var/www/mooimom_django/mooimom_uwsgi.ini How do i start UWSGI automatically when i restart the server OR when i restart nginx? Thanks. -
KeyError reading a JSON file
I'm coding a webapp in Django and trying to read through a JSON response POSTed to a webhook. The code to read through the JSON, after it has been decoded, is: if response_data['result']['action'] != "": Request.objects.create( request = response_data['result']['resolvedQuery'] ) When I try to run this code, I get this error: KeyError: 'result' on the line if response_data['result']['action'] != "": I'm confused because it looks to me like 'result' should be a valid key to this JSON that is being read: { 'id':'65738806-eb8b-4c9a-929f-28dc09d6a333', 'timestamp':'2017-07-10T04:59:46.345Z', 'lang':'en', 'result':{ 'source':'agent', 'resolvedQuery':'Foobar', 'action':'Baz' }, 'alternateResult':{ 'source':'domains', 'resolvedQuery':'abcdef', 'actionIncomplete':False, }, 'status':{ 'code':200, 'errorType':'success' } } Is there another way I should be reading this JSON in my program? -
makemessages previous-untranslated-string behavior
When running python3 manage.py makemessages I had the following: msgid "You currently do not have a password" msgstr "" The translator did the following: msgid "You currently do not have a password" msgstr "Vous n'avez actuellement pas de mot de passe." Then, I added (not replaced the previous string) the string A password you created to my codebase an ran python3 manage.py makemessages again. I have trouble to understand the result #, fuzzy #| msgid "You currently do not have a password" msgid "A password you created" msgstr "Vous n'avez actuellement pas de mot de passe." The gettext documentation states: #| msgid previous-untranslated-string-singular The previous-untranslated-string is optionally inserted by the msgmerge program, at the same time when it marks a message fuzzy. It helps the translator to see which changes were done by the developers on the untranslated-string. From my understanding, gettext seems to think the string has been modified instead of added in this case. I expected the following to be added: msgid "A password you created" msgstr "" Am I just misunderstanding something and this the correct behavior? If yes, why? -
Index related table using Haystack/Whoosh
How can I index a related table: class Foo(models.Model): name = models.CharField(max_length=50) Class FooImg(models.Model): image = models.ImageField(upload_to='img/', default = 'img/no-img.jpg', verbose_name='Image', ) foo = models.ForeignKey(Foo, default=None, null=True, blank=True) I want to index FooImg, so that I can get the images associated with Foo. I have already indexed Foo, and it works perfectly fine, it returns expected result. So in my template I have: {% for r in foo_search %} {{ r.object.name | slice:":18" }} {% endfor %} The above works, but I can't figure out how I can get the associated FooImg objects? Looking for direction, -
Can not get tables values using Python and Django
I am facing one issue. I am trying to fetch my tables values using the id in python but its not coming at all. I am explaining my code below. pers = User.objects.get(pk=request.session['id']) root = [] print(pers) user_name = pers.uname count = 1 root.append( {'username': user_name, }) return render(request, 'bookingservice/home.html', {'user': root, 'count': 1}) Here I am printing the pers value but its showing User object. Here I need to fetch the row values as per id present inside session. Please help me. -
How to use toastr in Django for success or fail message
I have been using Django message framework to show the success or failure message in my application. But I want the UI to be good so I found out that toastr is a good way to display messages to the user. But I am not sure how to use it. Please guide me through this. The function below saves the user to the database and when the user info is save a message is displayed: def addSubscriber(request): template = 'addSubscriber.html' if request.method == 'POST': form = addSubsForm(request.POST) if form.is_valid(): f = form.save(commit=False) f.save() messages.success(request, "The Subscriber has been successfully added") return redirect('report') else: messages.error(request, "Sorry the data has not been entered to the database") else: form = addSubsForm() return render(request, template, {'form': form}) The following template shows the display of the message: {% if messages %} <ul class="messages"> {% for message in messages %} <li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li> {% endfor %} </ul> {% endif %} -
need to run test case with authorised user using django, oauth, django-tenant-schema and django-rest-framework
I am writing a testcase for my django project which has django rest framework, oauth tool kit , django-tenant-schema(Postgres database). I have no idea how to have my testcases with authorized user access. -
Django request.body.decode security
I have a view set up to work with datatables; it accepts the data posted by datatables in JSON format, so I use: json.loads(request.body.decode('utf-8')) to grab the data I need to search, sort, and paginate my tables via ajax. All of this works, but I'm worried that loading the body of the request in this way could leave me open to attacks, especially since I could be loading arbitrary data in that line. What can/should I do to make sure this doesn't leave the code open to exploitation? Note: I am using csrf tokens in each request. I'm worried more about direct attacks from a malicious user of the system.