Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get request.META['HTTP_HOST'] in settings.py
I am making a django application where it will have 2 apps. When you open www.webName.co.id it will use urls.py from app A, but when you open webName.co.uk it will use urls.py from app B This is the urls.py from the main project: urlpatterns = [ url(r'^tinymce/', include('tinymce.urls')), url(r'^filer/', include('filer.urls')), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^admin/', admin.site.urls), ] I was planning to add something like this to that file: if settings.CURRENT_HOST_IP == 'www.webname.co.id': urlpatterns += url(r'^', include('webname_id.urls')), else: urlpatterns += url(r'^', include('webname_uk.urls')), That way, it will simply use the urls from the app that is being used, depending on the current www you are entering the site with. So my project have 1 backend admin, but multiple front-end templates and urls. The problem is i can't figure out how to set CURRENT_HOST_IP in the settings.py, Usually i use this to get the current IP / host the user is using: request.META['HTTP_HOST'] But i can't access the request object in settings -
django - authentication: user turns into "admin" user when going through follow-up views
so essentially my problem is this, after I authenticate the user with the dajngo built in system, the user switches to the user "admin" instead of keeping the previous user in session. code: from django.contrib.auth import authenticate from django.contrib.auth.decorators import login_required def new_login_view(request): if request.method == 'POST': data = dict(request.POST) data.pop('csrfmiddlewaretoken') id_client = data['lg_username'][0] pass_client = data['lg_password'][0] user = authenticate(username=id_client, password=pass_client) if user is not None: # A backend authenticated the credentials ... return render(request, 'initial_page.html', dictionary_with_info) when I am in the initial_page.html and activate a view, that is: @login_required def home(request): if request.method == 'POST': ... when I call for request.user I get: User: admin instead of the user before. any idea why? -
Using Google App Engine's send_mail in Django
I'm trying to use GAE's send_mail in Django. from google.appengine.api import mail mail.send_mail(sender=x,to=y,subject='Test Mail',body='Test',) And I get this error: ImportError: No module named google.appengine.api -
Django, how to call python from JS?
i work on a framework called Chatterbot 0.6. It's coded in Python. The project is based on a website and a bot. The bot is implemented on the website and the user can speak with him through a chatbox. Until here, i did the chat bot in python and the web site. The mission is to implement the bot on the website thanks to Django. I always managed to implements the website but now, i have to make the bot works. The chatbox is coded in JS and the bot in Python. My mate who coded the site made a JS Function that prompt in the chatbox the bot's answer. My question is : How to implement the Python in my JS function ? var $msg_holder = undefined; $(document).ready(function(){ $msg_holder = $("#message_holder"); }); /**Function that appends a String (msg) to a DOM element ($dom) *@param msg being the String to append (String object or literal string) *@param $dom being a JQobject/JQselection of a DOM element to append the msg to */ function appendToDom(msg, $dom){ $(msg).appendTo($dom); } /**Function that append a String (msg) to the Message Holder *@param msg being the String to append (String object or string literal) */ function … -
Serving static and media files from S3 wagtail
We're going to start using S3 to host our static AND media files. Does anyone have a good link that describes how to do both with wagtail? We're on wagtail 1.9. I can't get both of them to work at the same time. https://wagtail.io/blog/amazon-s3-for-media-files/ Any help greatly appreciated. -
Django dynamic filters operator.or_ & operator.and_
Problem: I currently have a range of dates which display values in that date range and now i want to add a filter that allows expired values to display first as well as the ones in the date range, I need to do this with the operator.and_ & operator.or functions to join the two conditions that decide if the value is Expired, below is my logic along with the code so far exp = ("condition_one", False) exp_two = ("due_by__lte", start_date) if date_range(x,y) or (exp and due_by__lte(x,y)) code example so far: date_range = ["due_by__range", (day_start(start_date), day_end(end_date))] exp = ("condition_one", False) exp_two = ("due_by__lte", start_date) expired = [exp, exp_two] test = [Q(expired) for expired in date_range] qs_params.append( test) if qs_params: qs = qs.filter( ) -
Django:raise condition while calling the critical function
I am designing Django application in which client will send the multiple POST request with some data values.I have designed the function to process this data values. The structure of my view.py is something like below, def index(request): bla..... process_data(request) bla... And the structure of the process_data function is like below, def process_data(request): blah... update dict print dict blah... Sometimes when huge amount of POST request arrives then the value of the "dict" is appended with the some of the field of the old "dict".I think that is because of the raise condition.Please help me. -
No 'Access-Control-Allow-Origin' header is present on the requested resource even though it is present
I am building an application with Django + Phonegap. When I try to send an Ajax Request using this function: <script> $.ajax({ url: "http://192.168.0.101/commerce/product/" + localStorage.getItem("toView"), type: "GET", data: {}, success: function (json) { console.log(json); } }); </script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> I get an error saying in the Chrome console: XMLHttpRequest cannot load http://192.168.0.101/commerce/product/2. Redirect from 'http://192.168.0.101/commerce/product/2' to 'http://192.168.0.101/commerce/product/2/' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.101:3000' is therefore not allowed access. The problem is in the fact that I am including the requested header. When I open the given URL in chrome and see the server response, I get this. HTTP/1.0 200 OK Date: Tue, 16 May 2017 09:42:29 GMT Server: WSGIServer/0.2 CPython/3.4.3 Content-Type: application/json Access-Control-Allow-Origin: * X-Frame-Options: SAMEORIGIN Access-Control-Allow-Methods: OPTIONS,GET,PUT,POST,DELETE Access-Control-Allow-Headers: X-Requested-With, Content-Type Content-Length: 89 I am also including my server code. def product(request, prod_id): #### SOME CODE response = JsonResponse(response_data) response['Access-Control-Allow-Origin'] = '*' response['Access-Control-Allow-Methods'] = 'OPTIONS,GET,PUT,POST,DELETE' response['Access-Control-Allow-Headers'] = 'X-Requested-With, Content-Type' return response Why am I getting this error? Please help. Thanks. -
Why is this not working? [Django]
I am struggling with this {% extends "base_generic.html" %} {% block content %} <h1>{{ author.first_name }} {{ author.last_name }}</h1> {% for book in view.books_by_author %} {% if author.last_name in book.author %} <p>{{ book.title }}</p> {% endif %} {% endfor %} {% endblock %} "author" is a context variable. This is books_by_author function: def books_by_author(self): books = Book.objects.all() return books This portion is not working: {% if author.last_name in book.author %} <p>{{ book.title }}</p> But when I tried this, it's working. Is there a way to make "book.author" a string or is there a way around? {% if "Twain" in book.author %} <p>{{ book.title }}</p> -
Django Rest Framework - Append HostName to response
when i request an image http://127.0.0.1:8000/api/images/1/ or pass in params for cropping http://127.0.0.1:8000/api/images/1/?height=320&width=420 the response i get is: { "image": "/media/10438039923_2ef6f68348_c.jpg", "description": "Description 1", "title": "Item 1" } while as on http://127.0.0.1:8000/api/images/ the response is : { "title": "Item 1", "description": "Description 1", "image": "http://127.0.0.1:8000/media/10438039923_2ef6f68348_c.jpg" }, { "title": "Item 2", "description": "Description 2", "image": "http://127.0.0.1:8000/media/ALLEY-stock1502.jpg" }, why isn't easy thumbnails returning the hostname and how can i append the base url to the responses ? here is my views.py from __future__ import unicode_literals from django.shortcuts import render from rest_framework import viewsets from rest_framework.response import Response from .models import Image from .serializers import ImageSerializer from easy_thumbnails.files import get_thumbnailer class ImageViewSet(viewsets.ModelViewSet): queryset = Image.objects.all() serializer_class = ImageSerializer def retrieve(self, request, pk=None): height = request.query_params.get('height', None) width = request.query_params.get('width', None) img = self.get_object() if height and width: options = {'size': (height, width), 'crop': True} thumb_url = get_thumbnailer(img.image).get_thumbnail(options).url else: thumb_url = get_thumbnailer(img.image).url serializer = self.get_serializer(img) response_dict = {} response_dict.update(serializer.data) response_dict['image'] = thumb_url return Response(response_dict) -
(Django) Login from a custom model instead of admin : Users & How to create Login and Homepage having the same URL
I'm new to Django and I have 2 question here 1) I wanted to create a login authentication from a custom model named UserProfile but whenever I try to log in using the user I created in my UserProfile model, it says "This user doesn't exist" but whenever I login from a user in admin Users model, it works here is my code : model.py from django.db import models class Login_ID(models.Model): username = models.CharField(max_length=20) password = models.CharField(max_length=20) full_name = models.CharField(max_length=50) USERNAME_FIELD = 'username' def __str__(self): return self.username form.py from django import forms from .models import * from django.contrib.auth import authenticate, get_user_model, login, logout # Login_ID = get_user_model() class LoginForm(forms.ModelForm): class Meta: model = Login_ID fields = ['username', 'password', 'full_name'] widgets = {'password': forms.PasswordInput()} def clean(self, *args, **kwargs): username = self.cleaned_data.get('username') password = self.cleaned_data.get('password') if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user does not exist") return super(LoginForm, self).clean(*args, **kwargs) views.py from django.shortcuts import render, redirect from django.contrib.auth import authenticate, get_user_model, login, logout from .forms import * from django.contrib.auth.decorators import login_required from .models import * # Create your views here. @login_required(login_url='/login/') def index_view(request): return render(request, 'index.html') def login_view(request): print(request.user.is_authenticated()) title = "Login" form = LoginForm(request.POST or … -
django does not show images from MEDIA
this is my urls: urlpatterns = [ url(r'^', include('my_website.urls')), url(r'^tinymce/', include('tinymce.urls')), url(r'^filer/', include('filer.urls')), url(r'^ckeditor/', include('ckeditor_uploader.urls')), url(r'^admin/', admin.site.urls), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT + os.path.altsep ) this is my settings: # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['localhost', '127.0.0.1'] When debug is True, the images works fine, but when i turn it into False, only images from {% static %} shows up. The rest gets 404. -
Validate data by serializer and than get plain but valid json
I want to make validation of users input by serializers but after validation I want to get dict with json types (str, int, bool, float not python instances) without excess fields that could be passed by user. Example: serializer = SomeSerializer(data=request.data) # request.data = {'a':'abc', 'some_primary_key':33, 'c':'abc'} if serializer.is_valid(): # serializer has fields 'a' and 'some_primary_key' and doesn't have 'c' serializer.validated_data == {'a': 'abc', 'some_primary_key': <python instance with pk=33>} How can I get something like this serializer.plain_validated_data == {'a': 'abc', 'some_primary_key':33} after validation? -
How to serialize in Django
I have an serializer in Django as follow: class ListSerializer(serializers.HyperlinkedModelSerializer): vehicles = serializers.HyperlinkedRelatedField( view_name='asset-detail', many=True, read_only=True ) class Meta: model = List fields = ('url', 'name', 'start', 'stop', 'state', 'vehicles') Result that I get is as follows: [ { "url": "http://127.0.0.1:8000/sales/api/v1/lists/3741/", "name": "DEA 2017", "start": "2017-03-09T10:00:00", "stop": "2017-12-31T12:00:00", "state": "OPEN", "vehicles": [ "http://127.0.0.1:8000/sales/api/v1/assets/134299/", "http://127.0.0.1:8000/sales/api/v1/assets/154368/", "http://127.0.0.1:8000/sales/api/v1/assets/154367/", "http://127.0.0.1:8000/sales/api/v1/assets/154246/", "http://127.0.0.1:8000/sales/api/v1/assets/155906/", "http://127.0.0.1:8000/sales/api/v1/assets/155212/", "http://127.0.0.1:8000/sales/api/v1/assets/154574/", "http://127.0.0.1:8000/sales/api/v1/assets/155683/", "http://127.0.0.1:8000/sales/api/v1/assets/153347/", "http://127.0.0.1:8000/sales/api/v1/assets/153183/", "http://127.0.0.1:8000/sales/api/v1/assets/153182/", "http://127.0.0.1:8000/sales/api/v1/assets/153152/", "http://127.0.0.1:8000/sales/api/v1/assets/153116/", "http://127.0.0.1:8000/sales/api/v1/assets/154913/", "http://127.0.0.1:8000/sales/api/v1/assets/152389/", "http://127.0.0.1:8000/sales/api/v1/assets/153459/", "http://127.0.0.1:8000/sales/api/v1/assets/153568/", "http://127.0.0.1:8000/sales/api/v1/assets/153659/" ] } ] If I click on one of those url's in vehicles I get an object as follows : { "vin": "WVWZZZ6RZEY104640", "make": "VOLKSWAGEN", "model": "POLO", "fuel": "Diesel" } What I want is to get result with the objects instead of url's. Thus something as follows: [ { "url": "http://127.0.0.1:8000/sales/api/v1/lists/3741/", "name": "DEA 2017", "start": "2017-03-09T10:00:00", "stop": "2017-12-31T12:00:00", "state": "OPEN", "vehicles": [ { "vin": "WVWZZZ6RZEY104123", "make": "VOLKSWAGEN", "model": "POLO", "fuel": "Diesel" }, { "vin": "WVWZZZ6RZEY10452", "make": "VOLKSWAGEN", "model": "Golf", "fuel": "Diesel" }, {...}, {...}, {...}, .... ] } ] Any advice? P.S. I'm total beginner and please have mercy :) -
Django get_initial method with few fields
I have django app, and I want to have initial data for date fields promoted_from = models.DateTimeField(blank=True, null=True) promoted_to = models.DateTimeField(blank=True, null=True) In this app I have get_initial method: def get_initial(self): initial = super(BasePostEdit, self).get_initial() get = self.request.GET initial.update(get) if initial.get("pub_date", None): initial["pub_date"] = datetime.strptime(initial["pub_date"][0], "%d/%m/%Y") return initial But I want to have also two another fields promoted_from and promoted_to. I tried in this way, without success: def get_initial(self): initial = super(BasePostEdit, self).get_initial() get = self.request.GET initial.update(get) if initial.get("pub_date", None): initial["pub_date"] = datetime.strptime(initial["pub_date"][0], "%d/%m/%Y") if initial.get("promoted_from", None): initial["promoted_from"] = datetime.strptime(initial["promoted_from"][0], "%d/%m/%Y") return initial Please for help/some hint. -
Django TypeError when creating objects in a model using dictionary
I'm trying to pass the items of a dictionary into a model, each key, value pair to be an object. d1 = {'Alex': 3.0, 'Chriss': 7.42, 'Robert': 9.13} this is the model: class Team_one(models.Model): name = models.CharField(max_length=100) score = models.FloatField(default=0.0) When i'm trying to do an example in the shell, i'm getting a type error This was the example: x = {'Alex': 3.0} Team_one.objects.create(**x) or m = Team_one(**x) m.save() This is the error: `TypeError: 'Alex' is an invalid keyword argument for this function` -
How to sort Django ManyToManyField By middle table's id?
Django version: 1.7.9 python version: 2.7.6 Django Models: class VideoList(models.Model): playbill_list_set = OrderedManyToManyField( "self", related_name="video_list_playbill+", symmetrical=False, verbose_name=u"related videos", null=True, blank=True ) class Meta: db_table = "videolist" Then I syncdb, there is a new table named videolist_playbill_list_set. It's a middle table, and the table's construction is: <table border="1"> <tr> <td>id</td><td>from_video_list_id</td><td>to_video_list_id</td> </tr> <tr> <td>1</td><td>1</td><td>3</td> </tr> <tr> <td>2</td><td>1</td><td>2</td> </tr> </table> My sort code like these: result = make_order(self.playbill_milist_set).all().order_by('id') unfortunately,the result sorted by to_video_list_id in middle table, I wanna sort by id in middle table, what I should do? -
What to do when requirements.txt fails?
I've been asked to look at a Python / Django website and make some changes. I've downloaded the app, set up a virtual environment and run pip install -r requirements.txt. Unfortunately, or 10 separate instances, I get the response Could not find a version that satisfies the requirement ... This is because they seem to be apps specific to the previous supplier and I do not have access. Is there a way to install these apps from the Heroku virtual environment? I've tried simply copying them down using heroku run cp -R .heroku/python/lib/python2.7/site-packages/* ./ It doesn't work. Any thoughts and help greatly appreciated. -
Service worker and Django
I create a project in Django and I want add a service worker that will be redirect to another page (normal html without django tags ) in the absence of a connection. How can i do this? Sorry for my english. -
Return identical object names
Allow identical objects to return, passing user in. url = name_of_site/username/(canvas_name / slug) MultipleObjectsReturned at /username/canvas_name/ get() returned more than one Canvas -- it returned 2! Request Method: GET Request URL: http://127.0.0.1:8000/picxii/new/ Django Version: 1.10.5 Exception Type: MultipleObjectsReturned Exception Value: get() returned more than one Canvas -- it returned 2! Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python35-32\lib\site-packages\django\db\models\query.py in get, line 389 # model class Canvas(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) canvas_name = models.CharField( max_length=100, validators=[ # validate_canvas_title, RegexValidator( regex=CANVAS_REGEX, message='Canvas must only contain Alpahnumeric characters', code='invalid_canvas_title' )], ) slug = models.SlugField(max_length=100, blank=True) # view def canvasView(request, username=None, slug=None): if request.user.is_authenticated: user = get_object_or_404(User, username=username) canvas = get_object_or_404(Canvas, user=user, slug=slug) template = "pages/canvas.html" context = { 'user' : user, 'canvas': canvas, } return render(request, template, context) -
Django 1.9.13 cannot rename a many to many model AttributeError: 'unicode'
I am renaming a many to many model, removing it's last 's' class ModelA(models.Model): class ModelB(models.Model): manytomany = models.ManyToManyField(ModelA, through='ManyToManyModels') class ManyToManyModels(models.Model): to class ModelA(models.Model): class ModelB(models.Model): manytomany = models.ManyToManyField(ModelA, through='ManyToManyModel') class ManyToManyModel(models.Model): I can create the migration correctly with makemigrations, and it asks me if I renamed the model. But when I migrate I get this error: ./manage.py migrate File "./manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/lib/python2.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/lib/python2.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/lib/python2.7/site-packages/django/core/management/base.py", line 348, in run_from_argv self.execute(*args, **cmd_options) File "/lib/python2.7/site-packages/django/core/management/base.py", line 399, in execute output = self.handle(*args, **options) File "/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 200, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/lib/python2.7/site-packages/django/db/migrations/executor.py", line 92, in migrate self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial) File "/lib/python2.7/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/lib/python2.7/site-packages/django/db/migrations/executor.py", line 198, in apply_migration state = migration.apply(state, schema_editor) File "/lib/python2.7/site-packages/django/db/migrations/migration.py", line 123, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, from_field, to_field) File "/lib/python2.7/site-packages/django/db/backends/base/schema.py", line 465, in alter_field old_field.remote_field.through._meta.auto_created and AttributeError: 'unicode' object has no attribute '_meta' -
Cannot upload image in django using filefield
I am not able to upload image. here is my models.py class Post(models.Model): author = models.ForeignKey('auth.User') title = models.CharField(max_length=200) text = models.TextField() image = models.FileField(upload_to = 'post/static/images/' , null= True, blank= True) created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title the image is not getting uploaded to 'post/static/images/' here is the template for uploading the image {% if post.media %} <img src="{{ post.image.url }}" class="img-responsive" /> {% endif %} -
Django form missing method="post" action=""
Good day, Using Django 1.11, I have created signin and signup forms. My signin form is working correctly, but my signup form is using the GET method, not the POST method specified. Using the inspector on the signin form, it just shows . The method="POST" action="...." are missing and I cannot see why. urls.py: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.home, name='home'), url(r'signin/$', views.sign_in, name='signin'), url(r'signup/$', views.sign_up, name='signup'), url(r'signout/$', views.sign_out, name='signout'), ] views.py def sign_in(request): form = AuthenticationForm() if request.method == 'POST': form = AuthenticationForm(data=request.POST) if form.is_valid(): if form.user_cache is not None: user = form.user_cache if user.is_active: login(request, user) return HttpResponseRedirect( reverse('stb:home') ) else: messages.error( request, "That user account has been disabled." ) else: messages.error( request, "Username or password is incorrect." ) return render(request, 'stb/signin.html', {'form': form}) def sign_up(request): form = UserCreationForm() if request.method == 'POST': form = UserCreationForm(data=request.POST) if form.is_valid(): # Unpack form values username = form.cleaned_data['username'] password = form.cleaned_data['password1'] email = form.cleaned_data['email'] # Create the User record user = User(username=username, email=email) user.set_password(password) user.save() user = authenticate( username=username, password=password ) login(request, user) messages.success( request, "You're now a user! You've been signed in, too." ) return HttpResponseRedirect(reverse('stb:profile')) return render(request, 'stb/signup.html', {'form': form}) signup.html: {% … -
Sort by relation model
I have following models: class Order(models.Model): price = models.DecimalField(verbose_name=_("Price"), default=0.0, decimal_places=2, max_digits=7) ... class Bid(models.Model): order = models.ForeignKey(Order, verbose_name=_("Order"), related_name="orders") bid = models.DecimalField(verbose_name=_("Bid"), default=0.0, decimal_places=2, max_digits=7) status = models.IntegerField(verbose_name=_("Status"), choices=BID_STATUSES, default=BID_STATES_IN_BIDS) ... I need sort Orders by price of Orders and by bid of Bids where status == BID_STATES_IN_BIDS. How can I get this result? -
Form submission error on django as object has no attribute 'clean_data'
I am getting the error like 'ContactForm' object has no attribute 'clean_data'. What I did as follows: forms.py from django import forms TOPIC_CHOICES = ( ('general', 'General enquiry'), ('bug', 'Bug report'), ('suggestion', 'Suggestion'), ) class ContactForm(forms.Form): topic = forms.ChoiceField(choices=TOPIC_CHOICES) message = forms.CharField(widget=forms.Textarea(),initial="Replace with your feedback") sender = forms.EmailField(required=False) views.py from django.http import HttpResponseRedirect from django.shortcuts import render from .models import Book from django.core.mail import send_mail from .forms import ContactForm def contact(request): if request.method == 'POST': form = ContactForm(request.POST) if form.is_valid(): topic = form.clean_data['topic'] message = form.clean_data['message'] sender = form.clean_data.get('sender', 'test@example.com') send_mail( 'Feedback from your site, topic: %s' % topic, message, sender, ['test2@example.com'] ) return HttpResponseRedirect('/contact/thanks/') else: form = ContactForm() return render(request, 'contact.html', {'form': form}) contact.html <body> <h1>Contact us</h1> <form action="." method="POST"> {% csrf_token %} <table> {{ form.as_table }} </table> <p><input type="submit" value="Submit"></p> </form> </body> I have search over net and done as their instruction but could not remove this error.