Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
prefetch_related data can not be acquired
There are models as follows. class Account(AbstractBaseUser): username = models.CharField(_('username'), max_length=30, unique=True) first_name = models.CharField(_('first name'), max_length=30, blank=True) last_name = models.CharField(_('last name'), max_length=30, blank=True) email = models.EmailField(verbose_name='email address', max_length=255, unique=True) ... class Follow(models.Model): followed_user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='followed_user', verbose_name='followed_user', on_delete=models.CASCADE ) follow_user = models.ForeignKey( settings.AUTH_USER_MODEL, related_name='follow_user', verbose_name='follow_user', on_delete=models.CASCADE ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.followed_user) Then, in the view, as we get information on the Account as follows, we are also going to give follow / follow information associated with that account. class AuthInfoGetView(generics.RetrieveAPIView): permission_classes = (permissions.IsAuthenticated,) queryset = Account.objects.all() serializer_class = AccountSerializer def get(self, request, format=None): instance = self.queryset\ .prefetch_related('followed_user', 'follow_user')\ .get(email=self.request.user) However, debugging with print (instance.follow_user) in this view will return api.Follow.None even though there are other accounts that follow. Please tell me how to do it is best. -
How to read cookie from PHP set by Django on subdomain?
I am using Django v1.11 on sub.domain.com and PHP 7 on domain.com Is it possible to set cookie on sub.domain.com and read it on domain.com? I guess yes, but it does not work. Moreover, I don't understand how use and should I use SECRET_KEY and SESSION_COOKIE_NAME on Django. So, on Django (sub.domain.com) I set like this in view: response = redirect('home:index') response.set_cookie('my_cookie', 'test123') return response Django settings: SECRET_KEY = 'vnw8*o1cuc7bia1b8#c...' SESSION_COOKIE_DOMAIN = ".domain.com" SESSION_COOKIE_NAME = "mycookiename" PHP on domain.com: <?= $_COOKIE['my_cookie'] ?> // empty <?php print_r($_COOKIE); ?> // empty too BUT. If I check cookies on my Chrome browser, the domain is sub.domain.com instead of .domain.com (perhaps, SESSION_COOKIE_DOMAIN not working?) What am I doing wrong? -
Problems getting Django/Apache2/mod_wsgi configured without having extra component in URL
What I'm trying to accomplish is to have Apache serve all content at mysite.com/ and have Django handle everything under mydomain.com/signup and mydomain.com/login. The problem is that right now the user has to browse to mydomain.com/mysite/signup or mydomain.com/mysite/login for things to work. I want to get rid of the mysite part of the URLs. I created a project with django-admin startproject signup mysite cd mysite django-admin startapp login I ended up with this directory structure. mysite ├── login │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py ├── manage.py └── signup ├── __init__.py ├── settings.py ├── urls.py ├── views.py └── wsgi.py I have the following urlpatterns in signup/urls.py urlpatterns = [ url(r'^signup/', views.index, name='index'), url(r'^login/', include('login.urls')), url(r'^admin/', admin.site.urls), ] I have Apache mod_wsgi installed and working and have this WSGIScriptAlias in my virtual host file. WSGIScriptAlias /mysite /usr/local/www/wsgi-scripts/mysite/signup/wsgi.py process-group=mysite.com When the user goes to either mydomain.com/mysite/signup or mydomain.com/mysite/login everything works. What I want to do is get rid of the 'mysite' part of the above URLs so the user just has to browse to mydomain.com/signup or mydomain.com/login. I've tried WSGIScriptAlias /signup … -
how to get a CSV from an API and map it into a model
I am using Django and I want to get data via an API in CSV format and import it to my models but I don't know how to do this properly. Please help me. -
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.