Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django forms: “This field is required” when file POSTed to file field WITH enctype
I fail to upload a file and get "This field is required." Up until now it's the same as the issue reported here. However, I am using enctype="multipart/form-data" like suggested in that issue. The form: class ContentSheetForm(forms.ModelForm): content_sheet_name = forms.CharField(max_length=50) content_sheet_name.widget.attrs.update({'autofocus': 'autofocus', 'placeholder': 'Content Sheet Name'}) content_sheet_file = forms.FileField() class Meta: model = ContentSheet exclude = tuple() The HTML: <form id="user_sentence_form" method="post" enctype="multipart/form-data" action="/lf_classifier/send_text/"> {% csrf_token %} {% for field in user_sentence_form.visible_fields %} {{ field.errors }} {{ field.help_text }} {{ field }} {% endfor %} <input type="submit" data-icon="action" data-iconpos="right" name="submit" data-inline="true" value="upload" /> </form> -
Cannot retrieve data from endpoint
I have installed Chatterbot for Django integration. I followed the easy tutorial with every step and made it so that the endpoint was: http://127.0.0.1:8000/chatterbot/ What I did next was try to communicate with that endpoint to see if I would get back any results. So I made an Ajax request as follows: var query = {"text": "My input statement"}; $.ajax({ type: 'POST', url: "http://127.0.0.1:8000/chatterbot/", data: JSON.stringify(query), contentType: 'application/json', success: function (data) { console.log(data); } }); However, what returns in console is: POST http://127.0.0.1:8000/chatterbot/ 403 (Forbidden) and what returns in the cmd prompt when I run my server is: csrf: WARNING - Forbidden (CSRF token missing or incorrect.): /chatterbot/ [29/Mar/2018 02:16:43] "POST /chatterbot/ HTTP/1.1" 403 2502 Why am I getting this error? How can I fix it so I receive the call back from the endpoint? -
Docker Postgres DB initialization
I am having containerized the postgreSQL database along with the python Django project. Django framework requires a database created in the postgres DB before running the framework itself. I have included the necessary scripts in the project and the statements in the docker-compose file, but unfortunately it is not picking up the files and executing the statements. As a result database is not created.I need a solution on how to create the postgres database using docker-compose -
Remove Permission attached to Groups using permission object Django 1.8
I have permission object and need to remove this permission from all groups having this permission. How to achieve this things. -
Django Remove all Empty Lines from Template Output
I'm rendering a Django template with lots of nested loops and if statements. This causes a template output of approximately 30 000 lines. Obviously I need to remove those empty lines! I have tried: {% spaceless %} {% endspaceless %} However I get thrown an error when using it with 'if' statements in between: Invalid block tag on line 447: 'endspaceless', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? I have also tried: outputStr = str(result._container[0],'utf-8') outputStr2 = re.sub(r'^$\n', '', outputStr, flags=re.MULTILINE) with result being the HttpResponse object. However the blank lines are not removed and I'm unsure of how to convert the string back to bytes. Then the option exists to use middleware such as this post suggests: How to remove spaces and empty lines from HTML in Django? That seems a bit dangerous to me. SO would like to avoid that. Any help will be appreciated! -
Judging the form being rendered
I have a modal here through which user can login/signup.Now that through Jquery and Ajax I am able to change forms on clicking the respective links but in landing view only 1 function is working(either login or signup). I want to judge whether UserLoginForm is being rendered or UserRegisterForm so that in landing view I can render the respective functionality. I am new to Django so I don't know what I am saying is possible or not but if anyone can guide me in the right direction that would be great. Thanks!! <!-- Login Modal--> <div class="modal fade" id="LoginModal" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" >DearDiary</h5> </div> <div class="modal-body"> <div class="container"> <div class="omb_login"> <h3 class="omb_authTitle"><span class='log-in'>Login</span> or <span class='sign-up'><a href="#" class='signup'>Sign up</a></span></h3> <div class="row omb_socialButtons"> <div class="col-xs-4 col-sm-12"> <a href="{% url 'social:begin' 'facebook' %}" class="btn btn-lg btn-block omb_btn-facebook"> <i class="fa fa-facebook visible-xs"></i> <span class="hidden-xs">Facebook</span> </a> </div> <!-- <div class="col-xs-4 col-sm-2"> <a href="#" class="btn btn-lg btn-block omb_btn-twitter"> <i class="fa fa-twitter visible-xs"></i> <span class="hidden-xs">Twitter</span> </a> </div> <div class="col-xs-4 col-sm-2"> <a href="#" class="btn btn-lg btn-block omb_btn-google"> <i class="fa fa-google-plus visible-xs"></i> <span class="hidden-xs">Google+</span> </a> </div> --> </div> <div class="row omb_loginOr"> <div class="col-xs-12 col-sm-12"> <hr class="omb_hrOr"> <span class="omb_spanOr">or</span> </div> … -
Deploying Django App on PythonAnywhere without using GitHub
I need to deploy django app on pythonanywhere.com, but I wish to upload codes without using GitHub because I don't have private repo and I don't want my codes to be exposed to the public. How can I deploy my django app on pythonanywhere without using GitHub? -
Django database entry created by concatenation of two fields
I have the following Django model class Labels(models.Model): user = models.CharField(max_length=200) label = models.CharField(max_length=200) live = models.CharField(max_length=1) unique_key = models.CharField(max_length=200) def __str__(self): return '%s / %s' % (self.user, self.label) I would like unique_key to be automatically populated with a concatenation of md5(user + label) e.g. user = 'James' label = 'KDJ' concat = user + label unique_key = print(hashlib.md5(concat.encode()).hexdigest()) Output 1935636b374a17f87636460e4307f736 -
Does ALLOWED_HOSTS use get_host()?
I'm slightly confused when it comes to how django is using the tuple in ALLOWED_HOSTS to validate host. Does it use a get_host() call or does it use REQUEST.META? The django documentation indicates the following with regards to ALLOWED_HOSTS: This validation only applies via get_host(); if your code accesses the Host header directly from request.META you are bypassing this security protection. https://docs.djangoproject.com/en/2.0/ref/settings/ If I create middleware that uses get_host() to get the host and compare it to a list of approved host names and pass the user 404 if the domain isn't in the list, I assume this would essentially be replicating the ALLOWED_HOSTS functionality? I ask this question because I do, in fact need to write middleware to replace ALLOWED_HOSTS. The list of approved hosts grows over time as more users sign up. As a result, I the tuple that I'm validating against is dynamic and thus, I can't use the default ALLOWED_HOSTS config in django. Thanks! -
Static files being referenced via different path in same Django view
I recently updated one of my views and URLs to take an additional parameter and now that I have done this the page which is rendered displays with no css or javascript because the static path is wrong. I am obviously not understanding correctly how static is served however I didn't think that changing the URL confs would change the path that Django would look for static. All my static for the whole site is in the one place. urls.py url(r'^fill/(.*)/(.*)/$', views.fill_survey, name='unique_getfile'), url(r'^fill/(.*)', views.fill_survey, name='unique_getfile'), and here is my view ... first block executes for the first url match and the second block executes for the bottom url def fill_survey(request, unique_url, new_name="blank"): """ get file or redirect to error page """ if len(unique_url) < 50: if unique_url == "new": firstlast = new_name.split(" ") c = Client.objects.get(firstname=firstlast[0], lastname=firstlast[1]) survey_url_number = generate_survey(request, c.email) response = Survey.objects.get(number=survey_url_number['number']) return render(request, 'survey/survey.html', {'survey': response}) else: response = Survey.objects.get(number=unique_url) return render(request, 'survey/survey.html', {'survey': response}) The rendered page then has the following static paths for the first and second url match respectively: wwww.mysite.com/static/etc... www.mysite.com/module_name/static/etc... Why are these different URLs leading to different static paths? Thanks in advance! -
Django and Gunicorn - Gateway time-out for loop
I'm trying to setup a Django project inside a 1GB Digital Ocean droplet. One critical function of the project is to import data from .ods files. When testing the project with the Django development server manage.py runserver (already inside the droplet) I can import a quite big number of rows - up to 20000 with no problems and without eating the server's memory as the loop that iterates the ods file sleeps 2 seconds every 100 rows. But when using Gunicorn (alongside with nginx), only 20 to 30 rows are processed, on average. After that I'm getting Gateway time-out 504 code errors. I already tried with no result: Increasing the --timeout of the gunicorn workers Installing eventlet and using --worker-class eventlet in the workers Upgrading my droplet to a 4GB Ram / 2 Cpus plan and increasing to --workers 6 This is how a simplified version of the code looks like: table = read(path_to_ods_file) stop_every_rows = 100 rows_done = 0 stop_seconds = 1 for i in range(len(table)): User.objects.create( first_name=table[i][0], last_name=table[i][0], ) rows_done += 1 if rows_done >= stop_every_rows: rows_done = 0 time.sleep(stop_seconds) Something really weird is that most of the times not even a single user is created. This is … -
How do I run django project in python 2.7 without using pycharm IDE
How do I run django project in python 2.7 on windows 7 32 bits without using pycharm IDE? -
Django test runs 0 test if I download the repo as zip but not when I clone
I find something very strange and I would like to have your input as why this is happening. So I have my repo: https://github.com/wonjoonSeol/ScienceScape If I clone this and run the follwing django test command: python3 manage.py test tests/ --with-coverage --settings=mysite.settings.local It runs all tests fine, proof : However, when I download code as zip from the github page and run it, it no longer runs the test file: Why is this happening? My understanding is downloading a repository just downloads the files from the most recent commit of the default branch. It doesn't download any of the files in the .git folder. So this shouldn't happen? If you want to try out yourself, you can install dependencies by using pipenv Many thanks in advance, -
django runserver giving error for libmysqlclient_18 not defined in file libmysqlclient.so.18
on running django-server with django==1.9 and pgsql 9.5, virtualenv=15.0.9 with python2.7 installation no-wheel no-site-packages on ubuntu 14.04 no previous mysql installation prior mariadb==10.2 after which this error occured. tried purging mariadb then, installing mysql=5.6 from dpkg but it didn't solved it either, then reinstalled mariadb==10.2 for sudo apt-get install libmariadbclient but it didn't solved it either. Any help would be appreciated, .... getting the below error -
what's the best practice drf serializer in foreign key relation
I have two model class class Parent(models.Model): sha256 = models.CharField(max_length=64) class Child(models.Model): parent = models.ForeignKey(Parent, related_name="childs") a = models.CharField() b= models.CharField() I'll request following I want to save the child class after finding the parent class corresponding to sha256 {"sha256" :"ABC....", "a":"test", "b":"test"} how to override the validate and create function and how to write view? I think class ChildSerializer(serializer.ModelSerializer): class Meta: model = Child fields = ('sha256', 'a', 'b) def create(self, validate_data): sha256 = vadliated_data.pop('sha256') parent = Parent.object.filter(sha256=sha256).first() if parent is None: raise serizlier.ValidationError('....') child = Child.objects.create(**validated_data, parent=parent) return child but it is not working correctly...what is the best way to do -
Wagtail frontend streamfield implementation
Is there a way in wagtail to use a streamfield on the frontend? Example usage: Let's say I'm building a news gallery and I present a frontend form fo rusers to create content / article pages. Since the streamfield is ineherently tied into the admin I don't see any easy way to do this besides using say a BleachField and rich text editor. But, then this isn't using some of wagtails nice features and even then I'd still have to override the admin to include the custom editor. -
Django - Access django context array with variable from JavaScript
Let's say I have a dynamic JavaScript variable var i = 1; Also I have a context users which is an array. The problem is, How to access users[i] in JavaScript? I've tried like this alert("{{ users." + i + ".name }}"); But it didn't works. Thanks -
Django ModelForm not saving data even though form.save is executed
I have a website where user have 2 model for their profile, user_detail and user_location. I tried to serve 2 model form on one page with one submit. The problem is when the data from those model form does not save in to the database. I confirmed that self.request.POST in the post method returns the correct data. I tried : Django ModelForm not saving data to database - Does not work Django ModelForm not saving data - Does not work The following code if for admins. Here is my view : class UpdateProfile(LoginRequiredMixin, UpdateView): template_name = 'account/user_profile.html' fields = '__all__' model = models.UserProfile user_detail_form_class = forms.UserDetailForm user_location_form_class = forms.UserLocationForm def get_context_data(self, **kwargs): user_profile = get_object_or_404(models.UserProfile, pk=self.kwargs.get(self.pk_url_kwarg)) context = super(UpdateProfile, self).get_context_data(**kwargs) if 'user_detail_form' not in context: context['user_detail_form'] = self.user_detail_form_class(instance=user_profile.user_detail) if 'user_location_form' not in context: context['user_location_form'] = self.user_location_form_class(instance=user_profile.user_location) return context def get(self, request, *args, **kwargs): super(UpdateProfile, self).get(request, *args, **kwargs) return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): user_detail_form = self.user_detail_form_class(request.POST) user_location_form = self.user_location_form_class(request.POST) if user_detail_form.is_valid() and user_location_form.is_valid(): user_detail_form.save() user_location_form.save() return redirect(self.get_success_url()) else: return self.render_to_response(self.get_context_data()) def get_success_url(self): return reverse('account:admin_client_list') def dispatch(self, request, *args, **kwargs): if not request.user.groups.filter(name__in=['Admin']).exists(): return errors.render_403(request) return super(UpdateProfile, self).dispatch(request, *args, **kwargs) Here is my template : {% extends 'base.html' %} {% … -
Store incoming sms number in server(django)
Newbie to python. I have a ideal to develop a sms marketing campaign. I'm using Twilio Api, Django framework, django_twilio. I will be sending out mass text messages introducing my business and will allow subscriptions to different types of offers based on keyword responses. I've been able to send out the messages and pull the number from the respondents. I'm puzzled about how would I code taking those numbers and store them in the database in a way that would have to those who want to subscribe to one offer in a viewable listing and those who want to subscribe to other offers in their own viewable list. I have little experience in django, but so far this is what Ive manage to get on my own. views.py from django.http import request from django_twilio.decorators import twilio_view from django_twilio.request import decompose from twilio.twiml.messaging_response import MessagingResponse @twilio_view def sms_choice(request): twilio_request = decompose(request) contact_num = twilio_request.from_ resp = MessagingResponse() resp.message('Thanks For Subscribing') print(contact_num) return str(resp) By "viewable list" I intend to keep count of how subscribers I have for each offer so that i can present to my clients as to say "I Have this {} many subscribers to your offer" -
python display datetime in differnet timezone
I have a timezone aware date time field in django called started on: class Meeting(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) started_on = models.DateTimeField() ended_on = models.DateTimeField() def started_on_tz(self): return self.started_on.astimezone(timezone(self.event.time_zone)) I want to show the startedon date in the events timezone. It is currently displaying on the screen with my timezone. I want to use the started_on_tz function to display the time in the timezone of the event. For example: I created a started on at 11am CST. It prints on my web page as 9am PST. How do I print 11am CST when I am currently in the PST time zone? -
Show objects on APIView
I have a model, and I just want to show the data of the model in my /api/ from django.db import models from rest_framework.authtoken.models import Token from django.contrib.auth.models import User class Book(models.Model): order_id = models.IntegerField() isbn = models.IntegerField() publisher = models.CharField(max_length=256) school = models.CharField(max_length=256) price = models.IntegerField() duration = models.CharField(max_length=10) order_datetime = models.DateTimeField(auto_now=False, auto_now_add=False) def __str__(self): return str(self.order_id) This is my urls.py: from django.contrib import admin from django.urls import path from filter import views urlpatterns = [ path('', views.index, name='index'), path('api/', views.BookApiView.as_view(), name='book_api'), path('admin/', admin.site.urls), ] This is my views.py: from django.shortcuts import render from rest_framework.views import APIView from .models import Book from django.http import JsonResponse class BookApiView(APIView): def get(self, request, format=None): books = Book.objects.all() return JsonResponse({'model': list(books)}) I get the following error: 'Object of type 'Book' is not JSON serializable' Regards, Anthony -
update only selected model fields
i have a list of tasks each task has a button edit for updating it , in my update view class TaskUpdate(UpdateView): model = Task fields = ['titre', 'objectif', 'date', 'theme'] urls.py url(r'^edit_task/(?P<pk>\d+)/$', views.TaskUpdate.as_view(), name='TaskUpdate'), the html code of edit button <td><a href="{%url "TaskUpdate" task.id %}"><button type="button"/><span class="glyphicon glyphicon-pencil" aria-hidden="true" />edit</td> when i click on the button edit i get this error : TemplateDoesNotExist at /edit_task/9/ app/task_form.html i don't have task_form.html i don't know where it comes from please help me , thank you -
CSRF token missing or incorrect. Django + Angular 2
I'm getting "CSRF Failed: CSRF token missing or incorrect." error while doing a POST request to a django api from my localhost machine. My service on Angular2: public login(user: any){ const body = JSON.stringify(user); const headers = new Headers(); headers.append('Content-Type', 'application/json'); return this.http.post("http://127.0.0.1:8000/auth_api/login/", body, { headers: headers }) .map((data: Response) => data.json()) } My settings on Django: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', 'scrumboard', 'auth_api' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True my LoginView API: class LoginView(views.APIView): def post(self, request): user = authenticate( username=request.data.get("username"), password=request.data.get("password")) if user is None or not user.is_active: return Response({ 'status': 'Unauthorized', 'message': 'Email or password incorrect' }, status=status.HTTP_401_UNAUTHORIZED) login(request, user) return Response(UserSerializer(user).data) What am i missing here ? -
Setting up conditional views in Django based on user permissions
I'm attempting to set up an index page in django that serves different content based on the user permissions (2+ types of users). I've looked into using the @permission_required decorator but it seems a bit wasteful and repetitive to use that with a view that's been mostly repeated. There's also no good fallback method that I can see (I can't do a @permission_required(!'jobs.can_edit')). views.py: @permission_required('jobs.can_add') def index(request): jobs = Job.objects.all context = { "jobs": jobs, } return render(request, 'jobs/index.html', context) @permission_required('jobs.can_edit') def index(request): jobs = some.different.data context = { "jobs": jobs, } return render(request, 'jobs/index.html', context) Is there an easier way to hook this into the index function and change the context based on user permissions? My ideal scenario would be more like this imaginary views.py: def index(request): if user.can_add: context = x return render(request, 'jobs/index/can-add.html', context) context = y return render(request, 'jobs/index/can-edit.html', context) I've also set the three user groups up by name, but I don't see much documentation on accessing group names. -
Count Number of Entries in a Column Django
I have a counter object defined as class Counter(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) counter_text = models.IntegerField(default=100) I want to count exactly how many instances exist in django. I am using this as an average, so if there is a better way to average a column, please tell me. Thanks in advance!