Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: running a python shell in a sandbox environment, similar to rails console --sandbox
Inside my Django project, I want to fire up a python shell wherein I can make simple changes to my database (saving new records, updating old ones, etc.) which are then automatically reverted back when I exit the shell. Essentially the same functionality as running "rails console --sandbox" in a Ruby on Rails project. I'm not looking for all the features of a traditional sandbox such as blocking web-service calls, just the basic database rollback. Is this--or something similar--possible in Django? I want to use this for testing purposes. I know I can use Django's testing infrastructure to do this, but there are some basic instances where this would be very useful (e.g. quickly confirming that a specific model functions the way I expect it to). -
How do I use a CSS attribute's value of an html element as input when submiting a form with Django?
Please first click the link to the image below to understand my question/situation. If the text below a particular species icon (circle with animal image inside it) is bold, I would like that to be used as input criteria for getting information from a database. In other words, I want to use the font-weight CSS property of a element as an input. Only one "species text" can be bold at a time. For example, if I have "D. rerio" selected (its font is bold) and I click the "search" button, I would like for the back-end to know that it needs to pull information from the "D. rerio" database specifically. Click here to see the picture of the situation I described above -
How could I extend my user model with field profile_image = models.FileField()?
I have created a form and have all criterias of name, email, password but not the image. In order to create "upload image" option, I am in need to extend my user model with field profile_image = models.FileField() Do help. -
Pre-populating dropdown menus with ViewFlow Material Forms
I am using Django and am trying to get a dropdown menu to prepopulate. This is how I am currently trying to do it in the form: {% if asset.id|stringformat:"s" == pageID|stringformat:"s" %} {% attr form.assetID "option" selected %}"selected"{% endattr %} {% endif %} As you can see, I am trying to select the asset from the dropdown menu if it's ID matches the ID that was passed into the page and change it's selected attribute to "selected" if it matches. I know this isn't the right way to do it but I haven't been able to figure it out otherwise. I have tried overriding {% part form.assetID control %} and putting this code in there but that just removes the dropdown field entirely. Is there a way to do this without just writing the whole field myself? -
Django REST: Automatically update connected model (After POST)
I would like to create an ability for users to exchange 1-to-1 messages. To do this, I would like to update fields in my Django models, depending on actions taken by the Message model. For example, I would like to update the last_message in Conversation model, each time a new message is posted. I have 2 main models: Conversation and Message, where each conversation can have many messages. Models.py class Conversation(models.Model): last_message = models.CharField(max_length=50, blank=True) class Message(models.Model): body = models.TextField(max_length=500, blank=False) conversation = models.ForeignKey(Conversation, on_delete=models.CASCADE) I figured that I need to use the override the save() method in the Message class. def save(self, *args, **kwargs): super(Message, self).save(*args, **kwargs) # something that I need self.conversation.last_message = self.body In the end, I would like to send a POST request to my API endpoint e.g. /api/conversation/<id>/messages/ and it will update the Conversation object with every new latest message. -
How Could I Add Image Upload Option To The Registration Form?
My forms.py is this. from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm,UserChangeForm class RegistrationForm(UserCreationForm): email= forms.EmailField(required = True) class Meta: model = User fields = { 'username', 'first_name', 'last_name', 'email', 'password1', 'password2' } def save(self, commit=True): user = super(RegistrationForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() And, i have to add "upload image" option for the user so that user could upload their image from any file and load it on the profile. -
Linking two django fields in two different models
I am going slightly crazy as I am sure this is a super simple question. I have two models in django: class Play(models.Model): gid = models.IntegerField() pid = models.IntegerField(primary_key=True) off = models.CharField(max_length=5) deff = models.CharField(max_length=5) type = models.CharField(max_length=10) class FGXP(models.Model): pid = models.IntegerField() fgxp = models.CharField(max_length=5) fkicker = models.CharField(max_length=10) This is a football database and when there is a Play that scores there is another table where additional data about the extra point is held: FGXP. So in Play pid is the primary_key. In FGXP there is a link between pid and the pid in play. In my Django model should I link them? I will end up needing to join the data when I do a query. Thanks - an apologies if a duplicate. -
CreateView doesn't save related objects
I have two models: Student and Group. A group consists of multiple students and a student can be in only one group. Here are the models: class Group(models.Model): created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) section = models.PositiveSmallIntegerField(default=1) group = models.ForeignKey( Group, on_delete=models.SET_NULL, null=True, blank=True ) I am trying to build a form where I can select multiple students to create a group. class CreateGroupForm(forms.ModelForm): students = forms.ModelMultipleChoiceField( required=True, queryset=Student.objects.all() ) class Meta: model = Group fields = ('students', ) I am using the following view for the form: class SelectGroup(CreateView): model = Group form_class = CreateGroupForm template_name = 'selection.html' success_url = reverse_lazy('test') When I submit the form, it creates a group but the group's student_set is empty. I am guessing this is because I cannot add students to a group without saving the group first. Is there a way for me to modify this view to save the students or should I use something else? -
AWS S3 and Django - An error occurred (AccessDenied) when calling the PutObject operation
I am trying to set up media and static files storage in an AWS S3 bucket, in a Django app, and am getting the following error when I try to run python manage.py collectstatic to put the static files into the bucket: botocore.exceptions.ClientError: An error occurred (AccessDenied) when calling the PutObject operation: Access Denied I am running boto3 and django storages. Have trawled through the other answers on here and tried the ideas in there first. My access key etc is correct as I can connect to SES OK. I have CORS configured in the bucket. My bucket policy is { "Id": "Policyxxx", "Version": "2012-10-17", "Statement": [ { "Sid": "Stmtxxx", "Action": "s3:*", "Effect": "Allow", "Resource": [ "arn:aws:s3:::bucketname/*", "arn:aws:s3:::bucketname" ], "Principal": { "AWS": [ "arn:aws:iam::xxxx:user/xxxx" ] } } ] } My IAM user has AmazonS3FullAccess as below: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": "*" } ] } I have also tried creating my own policy and attaching that to the IAM user as follows: { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": "s3:*", "Resource": [ "arn:aws:s3:::bucketname", "arn:aws:s3:::bucketname/*" ] } ] } None of these work so I am clearly missing something. Can anyone help please? -
SyntaxError: invalid syntax - Python/Django
I am trying to simply display data from my database in Django. I am getting the following error; Syntax Error My code in views.py is as follows; def InputDisplay(request): input_info = Input.objects.all() args = {"input_detail" : input_info} print args return render_to_response('Project/display.html', args, context_instance=RequestContext(request)) My if statement in display.html; {% block head %} <title> Display Measurements</title> {% endblock %} {% block body %} <div class="container"> <h1> Input Details </h1> {% for detail in input_detail %} {{ detail.id }} {{ detail.waist }} {{ detail.height }} {% endfor %} </div> {% endblock %} Any help is greatly appreciated. -
Save filled form data in Django if user is not logged in?
I search Django-way to do some non tipical feature (I think). My env is Django 2.0.2, PostgreSQL 9.6 and Python 3.6.4. So, I have model and form like: # ./app/models.py class SubscribeModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) phone = models.CharField(max_length=80) # ./app/forms.py class SubscribeForm(forms.Form): phone = forms.EmailField(label='Phone Number', max_length=100) Also, my view for this model like: # ./app/views.py from django.contrib.auth.mixins import LoginRequiredMixin from users.models import User class SubscribeView(LoginRequiredMixin, View): login_url = '/login/' redirect_field_name = 'redirect_to' template_name = 'app/subscribe.html' form_class = SubscribeForm def post(self, request): user = get_object_or_404(User, id=request.user.id) form = self.form_class(request.POST, instance=user) if form.is_valid(): form.save() return redirect('/') return render(request, self.template_name, {'client': user, 'form': form}) Would be great to understand what to do that logic after save form: Anonymous user fill the form and click Save; He is redirecting to login page (because LoginRequiredMixin); After enter to the site, all data which he filled — saved to his account (automatically). This feature we can see when online shopping: we choose goods, add to our cart and only later, site ask us for login to site, if we are not (for save our order). I think, my question solve saving data to request.session and re-save to DB after logged in, but I have … -
How to test without hitting database
I want to test this code without hitting the database and using pytest and pytest-mock: from django.db.model import Q from orders.models import Order def get_orders_without_comment(): return Order.objects.filter(Q(comment__exact='') | Q(comment__isnull=True})) Here is my test: import pytest from django.db.models import Q from pytest_mock import mocker from .utils import get_orders_without_comment def test_get_orders_without_comment(mocker): orders_mock = mocker.patch('orders.models.Order.objects') orders = get_orders_without_comment() orders_mock.filter.assert_called_with(Q(comment__exact='') | Q(comment__isnull=True)) Here is the pytest exception: E AssertionError: Expected call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E Actual call: filter(<Q: (OR: ('comment__exact', ''), ('comment__isnull', True))>) E E pytest introspection follows: E E Args: E assert (<Q: (OR: ('p...ll', True))>,) == (<Q: (OR: ('pi...ll', True))>,) E At index 0 diff: <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> != <Q: (OR: ('comment__exact', ''), ('comment__isnull', True))> E Use -v to get the full diff What am I doing wrong? -
Why django is not accepting spaces in template?
{% %} means that this is a django template delimiter. So inside {% %} the space should not matter I guess. Now in the example: <a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a> This is showing expected output whereas <a href="{% url 'post_detail' pk = post.pk %}">{{ post.title }}</a> is showing error. Why this is sensitive to whitespace? -
Django Attribute Error: object has no attribute '__state' and removing __init__ from Class
I'm trying to create a model for a sample Django application "webshop", and I'm having trouble at understanding what my problems stem from. The models.py I have is: from django.db import models class Product(models.Model): def __init__(self, title, quantity, description, image_url=""): title = models.CharField(max_length=255) self.quantity = quantity self.title = title self.description = description self.image_url = image_url def sell(self): self.quantity = self.quantity - 1 and what I want to be able to do with it is to initialize it with something like: toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) I can call it with print(toy1.quantity) print(toy1.title) toy1.sell() and so on fine, but doing toy1.save() returns the error AttributeError: 'Product' object has no attribute '_state' Upon googling about the problem, I came across the fact that it's not advised to use init here, but the offered alternatives in https://docs.djangoproject.com/en/1.11/ref/models/instances/#creating-objects both utilize a logic where the first call of the class function is different from the initial call. If the problem I'm facing is due to relying in __init__, how can I get rid of it while still being able to initialize the objects with toy1 = Product(title="Bear plush", description="Fluffy bear plush toy", quantity=10) or is my problem something completely different? -
Join related models in django rest framework
Trying to create an API method for getting user profile. The problem is that there are two tables related to user: built in django User and SocialAccount from allauth framework. I guess the joining part should be in serializers so after a research I came up with this: from rest_framework import serializers from django.contrib.auth.models import User from allauth.socialaccount.models import SocialAccount class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('pk', 'first_name', 'last_name') class SocialSerializer(serializers.ModelSerializer): user = UserSerializer(many=False, read_only=True) class Meta: model = SocialAccount fields = ('uid', 'provider', 'user') It works but it outputs it as nested objects: { "uid": "", "provider": "", "user": { "pk": 5, "first_name": "", "last_name": "" } } I would like it to be as one object: { "uid": "", "provider": "", "pk": 5, "first_name": "", "last_name": "" } -
Django_hosts Not Working With Django's Default Authentication
I'm using this package called django_hosts to re-route urls for some apps. Everything is working fine except for the fact that django_hosts is not working with Django Authentication. I hosted this url api.example.com, so on this page with the url api.example.com:8000/add_post, I want users to add post but before doing that you must be authenticated. So after I logged in, I still can't submit post via the form talkless of posting. But when I go back to example.com, it shows that I'm logged in but api.example.com is telling me otherwise. How do I make django authentication work with this package? -
Docker alpine python 3.6 build for django and postgres
I want to build and setup and docker image. My dependencies on requirements.txt bcrypt passlib psycopg2 Django My Docker File FROM python:3.6-alpine ENV PYTHONUNBUFFERED=1 RUN apk update \ && apk add --virtual build-deps gcc \ && apk add postgresql-dev \ && apk del build-deps RUN apk add libffi-dev ENV APP_DIR=/service RUN mkdir $APP_DIR WORKDIR $APP_DIR ADD requirements.txt $APP_DIR/ RUN pip install -r requirements.txt ADD . $APP_DIR/ CMD ["python", "manage.py", "runserver", "0.0.0.0:5000"] I am getting errors like Collecting cffi>=1.1 (from bcrypt->-r requirements.txt (line 1)) Downloading cffi-1.11.4.tar.gz (436kB) Complete output from command python setup.py egg_info: unable to execute 'gcc': No such file or directory unable to execute 'gcc': No such file or directory No working compiler found, or bogus compiler options passed to the compiler from Python's standard "distutils" module. See the error messages above. Likely, the problem is not related How can I setup docker python3.6 for my django project successfully. ? -
django choice field returning index but not actual name
models.py class WebFieldType(models.Model): WEBFIELD_CHOICES = ( ('FACEBOOK', 'fb'), ('INSTAGRAM', 'Insta') ) webfield_type = models.CharField(null=True, blank=True, max_length=30, choices=WEBFIELD_CHOICES) def __unicode__(self): return '{}".format(self.webfield_type) class WebTokens(models.Model): token_name = models.TextField() web_field_type = models.ManyToManyField(WebFieldType) def __unicode__(self): return '{}-{}".format(self.token_name,self.template_type) Now in shell if I do like: WebFieldType.objects.all().values('webfield_type'), it is returning [{'webfield_type' : 'FACEBOOK'}, {'webfield_type' : 'INSTAGARAM'} But if I do like WebTokens.objects.all().values('token_name','web_field_type') it is returning [{'token_name' : 'some_token_name','web_field_type' : 1}] As you can see in web_field_type it is returning id, but I need name. Even tried using return '{}".format(self.get_webfield_type_display()) in WebFieldType model but in vain. So basically I need everything that is stored in WebTokens model when I make a call to it. -
Django Triagam: create gin index and search suggested words in Django
I have model with title and description fields. I want to create a GIN index for all the words in the title and description field So I do it the following way using SQL: STEP1: Create a table with all the words in title and description using simple config CREATE TABLE words AS SELECT word FROM ts_stat('SELECT to_tsvector(''simple'',COALESCE("articles_article"."title", '''')) || to_tsvector(''simple'',COALESCE("articles_article"."description", '''')) FROM "articles_article"'); STEP2: Create GIN index CREATE INDEX words_idx ON words USING GIN (word gin_trgm_ops); STEP3: SEARCH SELECT word, similarity(word, 'sri') AS sml FROM words WHERE word % 'sri' ORDER BY sml DESC, word; Result: word sml sri 1 srila 0.5 srimad 0.428571 How to do this in DJANGO and also i have to keep updating the GIN index -
docx file downloaded from Django is corrupt
Im trying to take user input from a form and then using that data to create a document using python docx module. But the downloaded file is not opening in MS word. It says the file is corrupt. Can someone help me with this? def resume_form(request): form = forms.resume() if request.method == 'POST': form = forms.resume(request.POST) if form.is_valid(): document = Document() document.add_heading(str(form.cleaned_data['full_name']),0) document.add_heading('Summary', 1) document.add_paragraph(str(form.cleaned_data['summary'])) f = io.BytesIO() document.save(f) length = f.tell() f.seek(0) response = HttpResponse(document, content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document') response['Content-Disposition'] = 'attachment; filename=download.docx' response['Content-Length'] = length #document.save(response) return response return render(request, 'sample_app/index.html', {'form' : form}) -
git server and django program inside nginx
I want to run a git server inside my django program. my nginx config is like this: server{ listen 192.168.1.250:80; root /var/www/html/git; location /server\.git { client_max_body_size 0; # Git pushes can be massive, just to make sure nginx doesn't suddenly cut the connection add this. auth_basic "Git Login"; # Whatever text will do. auth_basic_user_file "/var/www/html/git/htpasswd"; include /etc/nginx/fastcgi_params; # Include the default fastcgi configs fastcgi_param SCRIPT_FILENAME /usr/lib/git-core/git-http-backend; # Tells fastcgi to pass the request to the git http backend executable fastcgi_param GIT_HTTP_EXPORT_ALL ""; fastcgi_param GIT_PROJECT_ROOT /var/www/html/git; # /var/www/git is the location of all of your git repositories. fastcgi_param REMOTE_USER $remote_user; fastcgi_param PATH_INFO $1; # Takes the capture group from our location directive and gives git that. fastcgi_pass unix:/var/run/fcgiwrap.socket; # Pass the request to fastcgi } location / { include proxy_params; proxy_pass http://192.168.1.250:8000; } } my django program run correctly, but for git server, I cannot open that. but when I change the location of django program, both of them work correctly. location /user { include proxy_params; proxy_pass http://192.168.1.250:8000; } I want to use just "/" and not to "/" + string. what should I do?? -
use pygobject in apache
I want to use NetworkManager in a module in a django project. for use this module I use this codes: import gi gi.require_version('NM', '1.0') from gi.repository import NM . .#the code that use NM . when I run this django project with "runserver" there is not any error and anything work correctly. but when I run with apache, it does not work. it stop at line "from gi.repository import NM". I check for apache accesability but it is not affect. beacuse NM (or any other modules form gi,for example GLib) is dynamic and in C language I can not debug it. my system is ubuntu server 16. anybody can help me what is wrong in apache? -
Django: namespace isn't unique
In Django 1, I used to have the following URL mappings: ... url(r'^main/', include('main.urls', namespace='main')), url(r'.*', include('main.urls')) The r'.*' mapping is always at the last line to take care of all kinds of URLs not mapped. In Django 2, the following mappings are used instead: path('main/', include('main.urls', namespace='main')), re_path('.*', include('main.urls')), Although it also works, yet Django complains: ?: (urls.W005) URL namespace 'main' isn't unique. You may not be able to reverse all URLs in this namespace Giving the second mapping another namespace is not working. Any solutions? -
Get onclick url with request in django
I have a template like bellow: <a href={{j}}> <img src="{{k}}" class="img-responsive img-rounded" data-toggle="modal" data-target="#myModal" style="width:350px;height:200px;"> </a> Now i have a function like bellow: def finction_url(requerst): a=get_the_value_of_{{j}} ### how to get the value of {{j}} Now i want to send the {{j}} value to the function (function_url) when user clicks on the photo url . Kindly suggest , either with ajax or django -
AttributeError: module 'django.db.models' has no attribute 'DateTime'
I am new to Django and i'm struck in this error: AttributeError: module 'django.db.models' has no attribute 'DateTime' I don't know the module related to DateTime model