Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - csfr_token did not registered or not loaded
<form action = "" method="post"> {% csfr_token %} {{ form.as_p }} <button type="submit">submit</button> </form> This is where I am trying to use a csrf token to protect my form. However, when I try to run the website, it throws me an exception Exception Type: TemplateSyntaxError Exception Value: Invalid block tag on line 25: 'csfr_token'. Did you forget to register or load this tag? So I search some website, and changed my settings to TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.csrf', ], }, }, ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] After all these are done, I still get the same exception. Can anybody help me with it? -
Error POST 405 Phyton Django
I'm trying to create a webpage in html in which a user have to input a url into a textfield. <form name="submitURL" method ="post"> <input type="text" name="url_target"> <button type="submit">submit</button> When the user press the submit button a python script should intercept the data inserted by the user and pass it to another function inside this script. Python script: from flask import Flask, render_template, request app = Flask(__name__) @app.route('/') def indhtml() : return render_template('index.html') @app.route('/index.html', methods = ['POST']) def result(): result = request.form('url_target') link = result.link print (link) return if __name__ == '__main__' : app.run(debug = True) the first render is fine and i can see the index.html page, but when i insert something in the textfield appears the error HTTP 405. Do you have any suggestion for that? :( Thanks! -
Django - Should I use Django REST framework for a basic HTML site?
Per the suggestion in the answer to the question Django url paths what is optimal number to cover all combinations. I have been looking into Django REST Framework, it definitely looks a useful API, but I am just trying to make HTML website at the moment. The only rendering for HTML is 'TemplateHTMLRenderer' (and 'StaticHTMLRenderer'). I think I should be using REST Framework but there is not much on how to use on a basic website. As I am new to Django and Django REST Framework. Should I be using the REST Framework for a solo HTML render site? I am getting myself in a knot and I really need a pointer from someone who knows their way around this area. Thank you for your time. -
Django: Filtering the DataBase
Here's my code, In view, objects = Model.objects.all() In template, {% for obj in objects %} {{ obj }}<br /> {% for new in obj.game_set.all|slice:"2" %} ... {% endfor %} {% endfor %} As we can see "Game" is related with "Model" through a foreignkey. Also, Game is related with another model "Extras" through a foreign key. Here, I wants to filter out latest 2 "Games" having "Extras". Slice is not working properly because it's giving 2 "Games" no matter they have "Extras" or not. Or if I use if statement something like, {% for new in obj.game_set.all|slice:"2" %} {% if new.extra_set.all %} .... {% endif %} {% endfor %} Nothing will work this way in case if latest 2 Games don't have extras. So how can I filter out latest 2 "Games" having "Extras" in this case? -
Django how to access a uploaded file in views?
In my views.py file, there are some functions like follows: def upload_file(request): """ upload a file and store it into the database, and the file will be predicted in another view immediately. """ def predict(request): """ make prediction of the file uploaded in the 'upload_file' function. """ How to access the file which uploaded in upload_file function in the predict function? Here is my thought: 1. read the last row in the database, but this sounds a little silly. 2. use a cache system and retrieve the file from cache? Is there any useful solution for this problem? please give me any hints or other resources. Thanks for anyone's help. -
Django email validator not working
when I try myname@mail.com it is stored in DB using validate_email. but when I enter myname+1@mail.com it stored in DB instead of showing errors. views.py def register(request): if request.method == 'POST': next = reverse('login') user_form = UserRegistrationForm(request.POST) if user_form.is_valid(): new_user = user_form.save(commit = False) check_mail = new_user.email try: validate_email(check_mail) except ValidationError: raise ValidationError new_user.set_password(user_form.cleaned_data['password']) new_user.save() return HttpResponseRedirect(next) else: user_form = UserRegistrationForm() return render(request, "registration/register.html", {'user_form' : user_form} ) forms.py class UserRegistrationForm(forms.ModelForm): password= forms.CharField(label = 'Password', widget = forms.PasswordInput) password2= forms.CharField(label = 'Repeat Password', widget = forms.PasswordInput) class Meta: model =User fields = ('username', 'first_name', 'email') def clean_password2(self): cd = self.cleaned_data if cd['password'] != cd['password2']: raise forms.ValidationError('password don\'t match please try again') return cd['password'] def clean_email(self): email = self.cleaned_data['email'] if User.objects.filter(email=email).exists(): raise ValidationError("Your Email is already registered") return email -
Save data from a Django FileUploadHandler into a model
I create a subclass of Django's FileUploadHandler which counts lines in uploaded files. I want to save this count in a model field. What are my options? I know I have access to the request in the FileUploadHandler - should I just stick the line count into the session? -
django login() takes 1 positional argument but 2 were given
I am using the latest version of django and python 3, When I log in I get the below error message. django login() takes 1 positional argument but 2 were given Please find the code for my login view below. from django.shortcuts import render, get_object_or_404,redirect from django.contrib.auth.models import User from django.contrib.auth import authenticate, login from authentication.forms import LoginForm, ForgottenPasswordForm, ResetPasswordForm from authentication.functions import send_user_reset_password_link, resend_password_reset_link from authentication.models import ResetPassword # Create your views here. def login(request): error_message = None heading = 'Login Form' if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] remember_me = form.cleaned_data['remember_me'] user = authenticate(request,username=username, password=password) if not request.POST.get('remember_me', None): #request.session.set_expiry(0) if user is not None: login(request, user) return redirect('property_index',user.id) # A backend authenticated the credentials else: error_message = 'No login credentials found' # No backend authenticated the credentials form = LoginForm() return render(request,'authentication/forms/login.html',{ 'form':form, 'error_message':error_message, 'heading':heading }) -
Django unable to change timezone from UTC format
settings.py LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True models.py class mymodel(models.Model): auto_increment_id = models.AutoField(primary_key=True) datetime = models.DateTimeField(auto_now_add=True, blank=True) ip_add = models.CharField(max_length=30) data = models.TextField() I am making a post request to my URL, which stores the data to db (using sqlite) through my view. The datetime field always stores the time in UTC format (which was the default setting for TIME_ZONE variable in settings.py) I've changed TIME_ZONE to 'Asia/Calcutta; after referring this link : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones But still datetime is being stored in UTC format. I tried changing USE_TZ to False after googling for this problem but that didn't work for me. I'm simply querying the data from db in python shell. i.e. x = ListURL.objects.all() for i in range(len(x)): print x[i].__dict__ Please advise how to change the timezone to 'Asia/Calcutta'. -
Downloading input from textarea to server as a file (Django)
I am working on a django project and i have a textarea where user can type in. I want that when he hits the submit button, i can get the content of textarea to my server as a file. This file has to be linked to a model through the FileField in django. (I can create a Fileupload button through django forms but here user types on textarea field so what is the procedure to convert write it to file and save) What is the simplest possible way to do this (i.e. to save input of textarea at server in form of a file)? -
How to set initial values only to extra fields in a Django inline formset
I am fairly new to Django and python so please bear with me. I am trying to create a tabular timesheet form like below. Timesheet Form What I am trying to achieve is, when I call a particular timesheet I should get all related timesheet details data and populate above form in a way that all hours related to a combination of workdate/project will be in the same row and related hours are placed under the corresponding workcode(i.e. in pic row1 would have 8 hours under 'Norm', row2 would have 12 hours under RnR) Now how can I set initial value to populate correct hour cells (not related to model field) in each row with hours depending on the workcode for that combination of workday/project? Secondly how do I handle if the hours are split hours(e.g. norm 4 hours and Annu 4 hours) for same workday/project? How do I put the in same Row? If I could use a dictionary to populate this would be easy? Since I do not have any initial data in the form for 10/80/20... fields I can not check if any hours were deleted so that I could delete that record too. I have started … -
Iterating json using yield statement in Python / Django
There is a char field named json_field in Django Model. I am trying to iterate it from the view but it returns only one result as the return statement does. I am trying to figure it out how I can iterate json_field using yield. the result that Model Object returns like: id : 1 title : "Some Title" json_field : [{"key":"value","key2":"value2"},{"key":"value","key2":"value2"}] created : "Sat Oct 21 2017 14:00:53 GMT+0300 (+03)" view.py import json model_query = MyModel.objects.all() or MyModel.objects.filter or exclude... for item in model_query: data_item = json.loads(item.json_field) Any help will be appreciated. -
How to fix, limit_choices_to cannot be a ForeignKey in Django?
I've a snip of code like following: models.py class Notebook(models.Model): owner = models.ForeignKey(User, on_delete = models.CASCADE) name= models.CharField(max_length=50) class Note(models.Model): create_user = models.ForeignKey(User, on_delete = models.CASCADE) text=models.CharField(max_length=500) notebook=models.ForeignKey(User, on_delete = models.CASCADE, limit_choices_to = {'owner' : create_user}) But I'm getting an error that limit_users_to cannot be a Foreign Key. I want to users to select only notebooks they have created while writing a note, but now users can select other's notebook while limit_choices_to is not set. What can i do? -
Indentation error in Django UserCreationForm
When I try to runserver. It shows an indentation error on Line 10 at the end ')' in the UserCreateForm Class. Any remedies. I have already checked for tabs and spaces there. -
Django DRF - What's the use of serializers?
I've been using Django for over 3 years now, but have never felt the need to use DRF. However, seeing the growing popularity of DRF, I thought of giving it a try. Serializing is the concept I find it most difficult. Consider for eg:- I want to save user details. Following is the user related models. class Users(models.Model): GENDER_CHOICES = ( ('M', 'MALE'), ('F', 'FEMALE'), ('O', 'OTHERS'), ) first_name = models.CharField(max_length=255, blank=True, null=True) middle_name = models.CharField(max_length=255, blank=True, null=True) last_name = models.CharField(max_length=255, blank=True, null=True) gender = models.CharField(choices=GENDER_CHOICES, max_length=1, blank=True, null=True) class UserAddress(models.Model): ADDRESS_TYPE_CHOICES = ( ('P', 'Permanent'), ('Cu', 'Current'), ('Co', 'Correspondence') ) line1 = models.CharField(max_length=255) line2 = models.CharField(max_length=255, blank=True, null=True) pincode = models.IntegerField() address_type = models.CharField(choices=ADDRESS_TYPE_CHOICES, max_length=255) user_id = models.ForeignKey(Users, related_name='uaddress') class UserPhone(models.Model): phone = models.CharField(max_length=10) user_id = models.ForeignKey(Users, related_name='uphone') class UserPastProfession(models.Model): profession = models.CharField(max_length=10) # BusinessMan, software Engineer, Artist etc. user_id = models.ForeignKey(Users, related_name='uprofession') I'm getting all the user details bundled in one POST endpoint. { 'first_name': 'first_name', 'middle_name': 'middle_name', 'last_name': 'last_name', 'gender': 'gender', 'address': [{ 'line1': 'line1', 'line2': 'line2', 'address_type': 'address_type', }], 'phone': ['phone1', 'phone2'], 'profession': ['BusinessMan', 'Software Engineer', 'Artist'] } Without using DRF, I would have made a Users object first, linking it with UserAddress, UserPhone and UserPastProfession … -
Django models - create items which have to pass various tasks
I am trying to create a model for the following scenario: An item is delivered and has to pass through various tasks in a certain order. As soon as the item has passed through a task, the task is marked as completed. The names of the tasks are known in advance. For example: Create item task 1 'register the item' task 2 'install the item' task 3 'check logs of item' I started with a simple model like this, but it looks very static to me and not really i what i am looking for. models.py class Item(models.Model): item_id = models.PositiveIntegerField() item_priority = models.PositiveSmallIntegerField(default=2) item_date_created = models.DateField(auto_now_add=True) task1_name = models.CharField(max_length=128) task1_done_by = models.CharField(max_length=64, blank=True) task1_done_date = models.DateField(null=True, blank=True) task2_name = models.CharField(max_length=128) task2_done_by = models.CharField(max_length=64, blank=True) task2_done_date = models.DateField(null=True, blank=True) # ... next 20 tasks def __str__(self): return str(self.item_id) Trying Relational fields, for example a ManyToMany Field to pre define the tasks, i ended up with this, but i can't figure out how to assign a task only to a specific item. In this case the values of a task are assigned to all items i created. class Task(models.Model): name = models.CharField(max_length=128) done_by = models.CharField(max_length=64, blank=True) done_date = models.DateField(null=True, blank=True) class … -
django file create on server
I have a Django model with a fileField (it would basically be c++ or python programs). I want to give user facility to either to either submit it from his system or write the code on website (using Ace editor) which i want extract and save to server. I implemented the first feature (normal file upload) through a django form but i don't know how to save the text from the editor to a file at the server. Here is what i have created. The file upload submit is working but how to link submit option from editor. What are possible ways I can perform this?? -
How do I collect many pieces stored in html files into one template in Django?
Supposing I have a page to display that consists of several pieces like this: <!-- result page --> <div> <b>1st piece</b> </div> <div> <b>2nd piece</b> </div> <div> <b>3rd piece</b> </div> I want to keep each piece in a separate html-file: <!-- piece1.html --> <b>1st piece</b> <!-- piece2.html --> <b>2nd piece</b> <!-- piece3.html --> <b>3rd piece</b> And add them into a base template using Django templates: <!-- base.html --> <div> {% block piece1 %}... import piece1.html ...{% endblock %} </div> <div> {% block piece2 %}... import piece2.html ...{% endblock %} </div> <div> {% block piece3 %}... import piece3.html ...{% endblock %} </div> How do I manage base.html to make it import all pieces by their names in Django? Or maybe there's a different approach to do it easily? In my project I'm going to use a complicated structure of pieces and big size for each one. This is why I want to keep each piece in a separate html-file. -
Is there any way to execute custom makemessages command by running "django-admin makemessages -l ja"?
I'm using Django1.11.5 and I created makemessages.py file in "my-app/management/commands/" directory to customise makemessages command. And I made it to execute this command by running "python ../manage.py makemessages" from my-app directory. But I want to execute by "django-admin makemessages -l ja". (Running "django-admin makemessages -l ja" just executes default makemessages command) Is there any way to execute this customised command by running "django-admin makemessages -l ja"? -
Django Linking a html page to a view
So I know that there are other people who have asked the same question, and I have read through them. However, the solutions provided there are giving me a strange error, and I would appreciate any help in understanding it. So here's my home.html file: <head> <title>Home</title> </head> <body> <h1>Home Page</h1> <!-- <a href="/home/signup">Sign Up</a> --> <a href="{% url 'signup' %}">Sign Up</a> </body> And here's my views.py: from django.shortcuts import render # Create your views here. def home(request): return render(request, "home.html") def signup(request): return render(request, "signup.html") And here's my urls.py: from django.conf.urls import url from .views import home, signup urlpatterns = [ url(r'^signup/', signup, name="signup"), url(r'^', home, name="home"), ] Thank you for all the help :) -
Getting only two friends tags instead of five using graph API Django
I am trying to tag the friends with the post using the feed endpoint of the Facebook Graph API in my Django application. Here is the code that I used to do that: def share(request): access_token = SocialToken.objects.get(account__user=request.user, account__provider='facebook') message = 'well begun is half done' params = { "access_token": access_token.token, "fields": "taggable_friends.limit(5){id}" } friends = json.loads(requests.get('https://graph.facebook.com/v2.10/me', params=params).text) friend_id = ','.join([id1['id'] for id1 in friends['taggable_friends']['data']]) params = { "access_token": access_token.token, "message": message, "place": "post", "tags": friend_id } requests.post('https://graph.facebook.com/v2.10/me/feed', params=params) return I have all the required permissions. After running my code, I get the feeds on Facebook with only two friends tagged. I have applied the settings for 5 friends, but getting only 2 on the facebook wall. Kindly, suggest the necessary improvement to get the friends tagged properly using the feed end point of the Facebook Graph. -
Django duplicate ON_DELETE rule
I'm having a problem in my model design. I have 2 models implemented for my forum + User model. User Topic - User (on_delete CASCADE) Post - Topic (on_delete CASCADE) - User (on_delete CASCADE) The Post model is referenced in a CASCADE on_delete rule 2 times, and Django seems to be having problems with this when deleting User (just for tests). The problem here is, that I also want to store the author of the Topic on the Topic model, but that seems to be necessary in my implementation. I also tried different values for the User relation on Post, but it didn't seem to work. The only think I could probably try is DO_NOTHING, but with that, I'm getting the same issue as with CASCADE. Exception: Cannot resolve keyword 'max' into field. Join on 'added' not permitted. -
Installing jinja2 on a server returns an error says (system file is read only) on hostgator
I am trying to install jinja2 on a hosted server on Hostgator through SSH. When I type pip install jinja2 in a linux terminal, I get an error informs me that the file is set on read only. As far as I know, django and python2 are installed. I'm just trying to install jinja2 to fix the error in the picture below. (https://i.stack.imgur.com/RqTmm.png) -
Is it advisable to use PIL with Django to create a website which will generate images based on user upload?
I am Creating a website to cut and merge images uploaded by the user. The website was fast enough in virtualenv on the local machine, but as soon as I started using S3 for Media and static files, I noticed the following There was a huge time gap between the pages being loaded, I had to change the code to open and save images from S3. The website wasn't as responsive as before So it forced me to wonder if there is a better way to make such a website? Tech Used AWS S3 (for Static and Media storage) Heroku (for hosting) requirements boto==2.48.0 boto3==1.4.7 botocore==1.5.29 Django==1.11.5 django-storages==1.5.2 Pillow==4.2.1 requests==2.18.4 s3transfer==0.1.11 urllib3==1.22 -
how to use request_finished in Django signals
As the title says I'm confused on the implementation of request_finished. What I'm trying to setup is that when my function finishes (say an ajax call that returns some json and creates a model or the default (non-ajax) view finishes...) I want create a model instance (say a log) How would I set this up? Can anyone provide an example. I thought request_finished would be the best to use to try to avoid duplicate creations as the documentation talks about