Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django: user is no more Logged in after redirect
I have some issues with request.user object after a successful login, and redirect. The user.is_authenticated hopefully returns True after login, so I redirect him to Whatever page. However, in my WhateverView.GET, the request.user is Anonymous again! And it is so even if the session details are still there (the logout function has NOT been called, so I can still access request.session["_auth_user_id"] for example, "_auth_user_backend" and "_auth_user_hash"). Of course, since I still have all user's details (ID) I can call my database and set user=User.objects.get(pk=ID), but do I have to do this everytime I redirect my user somewhere? it's would be strange to do so some code here: class LoginView(generic.TemplateView): template_name = './Login.html' @staticmethod def post(request): print("__ IndexView:get __\n") pswd = request.POST['password'] email = request.POST['username'] user = EmailAuth.authenticate(email=email, password=pswd) if not user is None: login(request, user) # user.is_authenticated=True if user.is_agency: return redirect("/companydashboard/") else: return redirect("/landlorddashboard/") return redirect("/login/") class CompanyDashBoardView(generic.TemplateView): template_name = './CompanyDashBoard.html' def get(self, request, *args, **kwargs): pdb.set_trace() user = request.user # user is anonymous again! return render(template_name=self.template_name, context={"LoggedAs": user}, request=request) -
form.cleaned_data is while form handling
The error occurs when I input old == new. It's a really simple form but I don't know where's got wrong. When I check the debug mode of django site, I found that the clean_data of new field is missing, as the picture of following: class PasswordEditForm(forms.Form): old = forms.CharField(widget=forms.PasswordInput, min_length=6, max_length=30, label='舊密碼', label_suffix=' ') new = forms.CharField(widget=forms.PasswordInput, min_length=6, max_length=30, label='新密碼', label_suffix=' ') new_confirm = forms.CharField(widget=forms.PasswordInput, min_length=6, max_length=30, label='再輸入一次', label_suffix=' ') def clean_new(self): cd = self.cleaned_data if cd['old'] == cd['new']: raise forms.ValidationError('新密碼與舊密碼相同') return cd['new'] def clean_new_confirm(self): cd = self.cleaned_data if cd['new'] != cd['new_confirm']: raise forms.ValidationError('兩次輸入密碼不相符') return cd['new_confirm'] I'm stuck for hours, please help. -
How to change the time format in django in a generic class based view
Is there a way to change the format for datetime fields when using CreateView or UpdateView? I am trying to get the form to accept dates in the form of something like "2016-12-29 03:49 PM". I know the format should be '%Y-%m-%d %I:%M %p', and this tests just fine in the shell. I just don't know how to get it working using CreateView or UpdateView, but it seems that it should be able to be done. -
How to get jquery ajax error data, and is it the correct way to respond?
I'm using ajax to submit forms. This is a piece of code I wrote: $.post(this.action, $(this).serialize()) .done(function(data) { form.find(".success-msg").text(data); }); .fail(function() { // insert error msg to the form }); .always(function() { modal.modal("hide"); }); How can I get the server response in the fail handler? the .fail() callback does not get the returned data like .done() do.. Second, is it correct to return non 200 (say 40X) status for a form validation errors that occur on the server? Or I should return 200 OK status and somehow distinguish myself between error/success in my own response? i.e on validation errors I can do this return HttpResponse(error_msg) or, return HttpResponseBadRequest(error_msg) -
How to post geo locations from a file periodically to Django server?
I am currently working on a django server, which should periodically post geo locations from a file to a URI, as soon as an event is triggered in the server. A file is supplied to me with geo locations and I need to take one location at a time from the file and post it to the URI. My work is to simulate a real time movement along the path mentioned in the file. I thought of a cron job, but I don't know how to load only a certain record at a time and also cron job for this would be an over kill. Any help is certainly appreciated. -
cassandra-python(django) unable to create or update user defined type
I am unable to perform an update on a user defined type after an object is created. class address(UserType): street = columns.Text() zipcode = columns.Integer() class users(DjangoCassandraModel): name = columns.Text(primary_key=True) addr = columns.UserDefinedType(address) users.objects.create(name="Peter") u = users.objects.get(name="Peter") u.addr = address(street="Easy St.", zipcode=99999) u.save() cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 1:49 no viable alternative at input ',' (...SET "addr" = {'zipcode': [None],...)"> u = users.objects.create(name='Peter', addr=address(street='my street', zipcode=5678)) I get the same error for a direct creation as well. -
Install django1.8 for python3.4
I had python 2.7 in my system by default and I installed it and also installed django 1.11 with it. Now I want to upgrade to a newer version of both and in order to do so, I accidentally deleted django from usr/local/lib/python2.7. I'm not sure if the problem is because of this. Here are the errors that keep showing up: 1.) When I tried to remove the old version of django:- $ python -c "import django; print(django.__path__)" Traceback (most recent call last): File "<string>", line 1, in <module> ImportError: No module named 'django' 2.) When I check the django version installed $ python3 -m django --version /usr/local/bin/python3: No module named django 3.) By doing pip freeze pip freeze Brlapi==0.6.1 Django==1.8 I really want to learn django, can you please help me with this installation ? -
Django form not passing is_valid() test
In my Django app in a Createview class it never enters the is_valid(): statement and I can not seem to find any errors: models.py from django.db import models from django.core.urlresolvers import reverse from django.contrib.auth.models import User from django.conf import settings from .validators import validate_file_extension import zipfile class Post(models.Model): title = models.CharField(max_length=140) body = models.TextField(max_length=250) date = models.DateTimeField(auto_now=True, auto_now_add=False) album_image = models.FileField(validators=[validate_file_extension]) user = models.ForeignKey(User, default=1) face = models.IntegerField(default=1) def get_absolute_url(self): return reverse('photos:detail',kwargs={'pk':self.pk}) def __str__(self): return self.title views.py This is my view folder that contains a list view a detailed view and create view. Although the form doesnt pass the valid test, it still gets uploaded and is viewable by the user from django.http import Http404 from django.http import HttpResponse from django.shortcuts import render, get_object_or_404 from django.core.urlresolvers import reverse from .forms import PostForm from .models import Post from django.contrib.auth.models import User from django.template import loader from django.views import generic from django.views.generic.edit import CreateView import cognitive_face as CF import json class IndexView(generic.ListView): template_name='photos/post.html' def get_queryset(self): return Post.objects.filter(user=self.request.user) class DetailView(generic.DetailView): model = Post template_name = 'photos/detail.html' class PostCreate(generic.CreateView): form = PostForm() model = Post if form.is_valid(): print('valid') instance = form.save(commit=False) username = form.cleaned_data['username'] album_image = form.cleaned_data['album_image'] instance.save() if not form.is_valid(): print('not') post_form.html <html> … -
Overwrite maxlength/minlength of username by Django User model in the ModelForm
Try to overwrite User models by the following code, but somehow I cannot overwrite the max_length and min_length of username. More specifically, when I check by python manage.py shell, I do overwrite them. But it seems has no effect on the html which was rendered(username maxlength is still 150). Don't know which parts get wrong, please help. from django import forms from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(RegistrationForm, self).__init__(*args, **kwargs) email = self.fields['email'] username = self.fields['username'] email.required = True email.label_suffix = ' ' username.label_suffix = ' ' ######### this is not work!!!############### username.min_length = 6 username.max_length = 30 ############################################ class Meta: model = User fields = ('username', 'email') labels = { 'username': '帳號', } help_texts = { 'username': '', } -
Build HTML files using Django Template System or Static Site Generator?
I am trying to set up a proper workflow for a personal website. I am using the Cactus static site generator which makes use of the Django template system. I know what I want to do, but I am not sure how to do it as the tutorials for Cactus are limited. This is what my directory structure looks like: /mysite/pages/ /mysite/templates/ /mysite/mycontent/ /mysite/plugins/ My template, /mysite/pages/menu.html, looks like this: <p>Welcome to the page!</p> {% block body %} {% endblock %} And one of my page articles, /mysite/pages/testpage.html, looks like this {% extends "menu.html" %} {%block body %} <p> Test Content </p> {% endblock %} But what I am trying to do is set this up so that whatever I want to write for Test Content can be written somewhere else and the copied in to the folder. Something like this: {% extends "menu.html" %} {%block body %} {%include "../mysite/mycontent/TestContent.html} {% endblock %} Is this something that Django templates needs to manage? Like I said, I am using Cactus which uses Django templates but I have looked around and am not sure what the standard way of doing this is, even though it seems to work with MVC/MVT philosophy. There … -
zoom function not working properly on google maps on a django powered website
I am using google maps in my django powered web app, it works fine except when i try to zoom in or out, after a little bit it does not refresh and everything on the map goes blank. I guess it should be the javascript code, but I am not sure. Do you have any idea where the problem is? html file: {% extends "heaven/base.html" %} {% load staticfiles %} {% block content %} <h2>Location of Cemetery</h2> <div id="map" style="width:1000px;height:500px;background:yellow"> <script> function myMap() { var mapCanvas = document.getElementById("map"); var myLatLng=new google.maps.LatLng({{ cemetery.latitude }}, {{ cemetery.longitude }}) var mapOptions = {center: myLatLng, zoom: 20}; var map = new google.maps.Map(mapCanvas, mapOptions); var marker = new google.maps.Marker({position: myLatLng}); marker.setMap(map); } </script> <script src="https://maps.googleapis.com/maps/api/js?callback=myMap"></script> {% endblock %} -
set static lan ip on my virtualbox
I need to run celery on my computer on which the os is windows server 2012 which according to my little research is possible only with old versions . since celery stopped support for windows .. so i decided to host my application and celery in a Virtual machine based on ubuntu linux. my django uses the development server runs on a lan address(10.0.0.7:8000)to communicate with the arduinos and other nodes(we are a small factory with a less traffic and no internet connection in any of those nodes). Now i want the virtual machine on that LAN . I know bridge will make it part of the LAN but . i want to set the address myself since each time the machine boots dhcp may select a different ip address . like 10.0.0.15:8000 . how can i do it -
Django Reverse with Request Context?
I'm converting an e-commerce site to be region (e.g., US, EU) specific, so it will basically feel like a different site to visitors based on the content they'll see, even though it's actually one site (for many reasons). Most of the paths on my site will become region-specific, by prefixing with the region at the beginning of the path e.g., '/us/' (I could convert all however if it made it dramatically easier). My plan: Middleware identifies the region based on 1) request path, 2) session, or 3) guessing based on the IP address in that order, and it's set on the request object. Also, once they use a regional path, it gets stored as a session value. In this way the region context is carried across the URLs which are not region-specific. The URL patterns which are region-specific have to be updated to match region, even though I've already detected the region in the middleware, since the logic was more complicated than just path. Nevertheless I must make it a parameter and pass into all of my views, for the next reason (reversing). Also, any path which is becoming regional, will have their previous patterns 301 redirecting to their regional … -
Which Cron technology to use while using Django..? [on hold]
I am building a regular app with django and it demanded the need for writing a Cron job... It has djangoCron, Trivx and the Linux crons, Celery... My question is which one to use and reason behind using it..?? -
UNIQUE constraint failed: auth_user.username
I'm trying to store the First name and last name straight from the Facebook API to a User Auth model (which is extended with FacebookProfile model, containing webpull, id and year_formed) Models.py class FacebookProfile(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE) id = models.PositiveIntegerField(primary_key = True) #name = models.CharField(max_length = 200, null = True) year_formed = models.PositiveIntegerField(default = 0) webpull= models.CharField(max_length =1000, null = True) Views.py if request.method == 'GET': print 'im here' return render(request, "logV2.html") if request.method == "POST": first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') print first_name, last_name facebook_user = FacebookUserForm(data=request.POST) facebook_profile = FacebookProfileForm() has_account = authenticate(first_name = first_name, last_name = last_name) if has_account: print 'this has account' login(request, has_account) return HttpResponseRedirect('/music/home/') else: id_ = request.POST.get('id') birthday = request.POST.get('year_formed') webpull = request.POST.get('webpull') if birthday == "undefined": print 'im emplty' year_formed = random.randint(1993,1998) else: year_formed = re.findall(r"[0-9][0-9][0-9][0-9]$", birthday)[0] print id_, year_formed, webpull print facebook_user user = facebook_user.save() profile = facebook_profile.save(commit = False) profile.user = user profile.webpull = webpull profile.id = id_ ## steal birtday fucntion from log # move to new database facebook (neeed to change all artists to facebookprofile) profile.year_formed = year_formed profile.save() #authenticate user. then log him in. #user = authenticate(username = profile.user.username) now_has_account = authenticate(first_name = first_name, last_name … -
Django; squashmigrations and circular dependencies
I have a Django project with multiple apps, many of which contain lots of migration files. I am attempting to squash these one app at a time using the squashmigrations command, however doing so causes a CircularDepencdyError. The Django docs here advise breaking out one of the keys in the circular dependency to resolve the error, but the error does not specify this level of detail. With thousands of lines of migration code to sift through, I am feeling stuck. Does anyone have experience of solving this sort of issue or know of some best practices or tips on what to look for? -
I have a Django web app that is connected to S3 for storage of images, dont know how to combine python code
I have a Django application that gets deployed to AWS using Elastic Beanstalk. The main concept of the app is that the user uploads images to the website, the image gets stored in a S3 bucket. From here my plan is to take the image from the S3 bucket make a call to Microsoft API for Facial Recognition and then return the result to the user. But I have no idea how to combine the code for the API call with the Django app? I have the code, I just dont know where to put it so it is run when a user uploads an image. -
Django formset not rendering with django-widget-tweaks
I am getting the error 'LoginForm' object has no attribute 'as_widget' whenever I use formset. I really do not know what is the problem as the forms renders properly with normal Django forms. I am trying to see what characteristics in the formset is giving this problem with django-widget-tweaks, but up until now it is hard to figure out. I am getting the error at {% render_field field class="form-control" placeholder=field.label %} in the HTML code. forms.py: class LoginForm(ModelForm): user_login = forms.HiddenInput() prefix = 'prefix_login' class Meta: model = Usermie fields = ['email', 'password'] widgets = {'password': forms.PasswordInput(), 'email': forms.EmailInput()} views.py def manage_articles(request): article_formset = formset_factory(LoginForm) book_formset = formset_factory(SignUpForm) if request.method == 'POST': if 'login' in request.POST: login = article_formset(request.POST, request.FILES, prefix='login') if login.is_valid(): email = request.POST.get('prefix_login-email', '') password = request.POST.get('prefix_login-password', '') # Return a user_obj object if the username and password are valid # otherwise it will return null, the null variable is called None in python user_obj = auth.authenticate(email=email, password=password) # return HttpResponse("inside form if condition") if user_obj is not None: if user_obj.is_active: login_usermie(request, user_obj) return HttpResponseRedirect('/home/') else: # pass return HttpResponse("Your account is inactive.") elif 'signup' in request.POST: signup = book_formset(request.POST, request.FILES) if signup.is_valid(): pass else: login = … -
Better ArrayField form solution for Django
I use ArrayField to store Entry tags and the form appear as charfield. I don't know how to make this better with generics view. Should I use manual form ? -
Server side validation for CKEditor user input (django)
I want to use CKEditor for my app where where users(anyone) can post articles but I am not sure if it is safe. I have to mark the text from CKEditor as 'Safe' while rendering in django templates to get expected results. As per Django documentation it is not recommended to turn off escaping input text from unknown sources. Even CKEditor mentions that the input should be a clean HTML. Can CKEditor be used for my use case? if so I need some suggestions to avoid any security issues. Thank you! -
How to distinguish between two methods of same name in two modules but when used in one file
I have a function with name 'add_member_address' at two places but with different functionalities. First method is given below which is defined in a view. @login_required(login_url='/accounts/login/') def add_member_address(request, member_id): if request.method == "GET": pass else: data = request.POST add_member_address(data, member_id) #<-this method is defined in another file. Now when flow reaches inner add_member_address, it tries to call this outer method only. So I tried giving the full path of this inner method to distinguish. tenant.services.address_services.add_member_address(data, member_id) where tenant is name of my app which is already registered in settings file. But now this error is thrown. name 'tenant' is not defined Folder structure: project ->tenant ->services -> __init__.py -> address_services.py -> here is this add_member_address(data, member_id) method -> other_services.py ->views ->members.py ->here is this add_member_address(request, member_id) method inside service/__init__.py file, all services are imported as below from .address_services import * from .tag_services import * Please suggest me 1. how can I distinguish between two methods of same name but in two different modules when used in same file. 2. How to use method with full path instead of importing on top of file. -
Getting an error when I log in with incorrect credentials
So logging in works fine when I type in the correct username/password. However when I enter an incorrect username or password, it returns this error: AttributeError: AnonymousUser' object has no attribute '_meta' Here's my code: views.py def boxes_view(request): ... form = UserRegistrationForm(request.POST or None) form_login = UserLoginForm(request.POST or None) if request.user.is_authenticated(): print('LOGGED IN') context = { 'form': form, 'form_login': form_login } return render(request, 'polls.html', context) def register(request): form = UserRegistrationForm(request.POST or None) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] email = form.cleaned_data['email'] user = User.objects.create_user(username=username, password=password, email=email) user.save() user = authenticate(username=username, password=password, email=email) login(request, user) return redirect('/') else: print(form.errors) print(form.non_field_errors) form = UserRegistrationForm() return redirect('/') def user_login(request): form_login = UserLoginForm(request.POST or None) if form_login.is_valid(): username = form_login.cleaned_data['username'] password = form_login.cleaned_data['password'] user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: print(form_login.errors) print(form_login.non_field_errors) form_login = UserLoginForm() return redirect('/') def user_logout(request): logout(request) return redirect('/') forms.py class UserLoginForm(forms.Form): username = forms.CharField(max_length=25) password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'password', ] class UserRegistrationForm(forms.Form): email = forms.EmailField() username = forms.CharField(max_length=25) password = forms.CharField(widget=forms.PasswordInput) confirm_password = forms.CharField(widget=forms.PasswordInput) class Meta: model = User fields = [ 'username', 'email', 'password', 'confirm_password', ] def clean(self): email = self.cleaned_data.get('email') current_emails = User.objects.filter(email=email) if current_emails.exists(): raise … -
Django Rest Framework POST nested objects
I'm facing a little problem right now with Django Rest Framework. I'm trying to post an object with nested objects in it. Here are my serializers.py class ClassSerializer(serializers.ModelSerializer): class Meta: model = Class fields = ('number', 'letter') class SubjectSerializer(serializers.ModelSerializer): class Meta: model = Subject fields = ('title',) class ExamSerializer(serializers.ModelSerializer): subject = SubjectSerializer() clazz = ClassSerializer() class Meta: model = Exam fields = ('id', 'subject', 'clazz', 'topic', 'date', 'details') depth = 1 def create(self, validated_data): return Exam.objects.create(**validated_data) def update(self, instance, validated_data): instance.__dict__.update(**validated_data) instance.save() return instance And create() from views.py def create(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) return Response( serializer.validated_data, status=status.HTTP_201_CREATED ) And here it is the response from Postman: I've read some posts here about this problem but I'm still stuck with it. I've tried to fix it in several ways but it is still returning "This field is required.". I am trying to post an exam by specifying the subject and class, but I also want them to be selectable only from the entries that are already in my database (a dropdown). This is the problem that I'm facing. Thanks in advance! -
How I can return id in ModelSerializer?
I use django rest framework ModelSerializer class. I need to return id of serializer model LookupRequest class HistorySerializer(serializers.ModelSerializer): vehicle = serializers.SerializerMethodField() def get_vehicle(self, obj): instance = models.Vehicle.objects.get(id=obj['vehicle']) return VehicleSerializer().to_representation(instance=instance) ... class Meta: model = models.LookupRequest fields = ['id', 'vehicle', ...] But id value doesn't return in get request. Maybe someone know how i can return id. Thanks for any help. -
Django design patterns with an engine
I do not have code to discuss this. But more of a conceptual issue. Say the user would upload some file through a web file page or input some parameters via a page. Models.py would be storing all the data which I would need to have stored in my database. My question would be say after the user submits the webpage data via a form. Where should I put my processing logic? In forms.py? If it's a complex process what should be a proper design pattern to put this code?