Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to write tests for django form views?
Django v1.10 FormView code: class PasswordResetConfirmView(FormView): template_name = "dashboard/account/reset_password_form.html" success_url = '/dashboard/' form_class = SetPasswordForm def authenticate_password_token(self, request, uidb64=None, token=None, encodedtimestring=None): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) timestring = force_text(urlsafe_base64_decode(encodedtimestring)) timestamp = timeparse(timestring) timediff = timezone.now() - timestamp except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None timediff = None if timediff is None or timediff.days < 0 or timediff.days > PASSWORD_RESET_TIMEOUT_DAYS: messages.error(request, _( 'The reset password link is no longer valid.')) return None if user is None or not default_token_generator.check_token(user, token): messages.error(request, _('The reset password link is not valid.')) return None return user def get(self, request, uidb64=None, token=None, encodedtimestring=None, *arg, **kwargs): form = self.form_class() assert uidb64 is not None and token is not None and encodedtimestring is not None user = self.authenticate_password_token( request, uidb64, token, encodedtimestring) if user is None: return redirect(reverse('dashboard-login')) return self.render_to_response(self.get_context_data(form=form)) def post(self, request, uidb64=None, token=None, encodedtimestring=None, *arg, **kwargs): form = self.form_class(request.POST) assert uidb64 is not None and token is not None and encodedtimestring is not None user = self.authenticate_password_token( request, uidb64, token, encodedtimestring) if user is None: return redirect(reverse('dashboard-login')) if not form.is_valid(): return self.form_invalid(form) new_password = form.cleaned_data['new_password2'] try: with transaction.atomic(): user.auth_token.delete() Token.objects.create(user=user) user.set_password(new_password) user.save() except: messages.error(request, _('Password reset was unsuccessful.')) return redirect(reverse('dashboard-login')) messages.success(request, _('Password has … -
I can not add a slug url to my django app
I am trying to use slug url like /post/5post-title or /post/post-title. I am currently using plain URLs in the form of /post/123 , I tried a lot of methods, and all failed.. Now I am trying "Migrating from primary-key based lookups" from https://keyerror.com/blog/slug-fields-an-alternative-approach and I got a broswer error 'Too many redirections'... How to solve this problem? Or do you have a better method to change the plain url to slug url? My models: class Post(models.Model): title,article and someFields....... def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail',kwargs={'pk':self.pk}) def slug(self): return slugify(self.title) and my urls: urlpatterns=[ url(r'^$',views.IndexView.as_view(),name='index'), url(r'^post/(?P<pk>[0-9]+)(?:/(?P<slug>[\w-]+))?$',views.detail,name='detail'),] my views: def detail(request,pk,slug=None): post=get_object_or_404(Post,pk=pk) if slug!=post.slug(): return redirect(post, permanent=True) return render(request,'blog/detail.html',context=context) -
Developing an Informative page for a product
I need to create a web page for an android app which will be published in the app store. I want to know which will be the best approach to create it, because it's just an informative website (contains tutorials, videos, related info), but I need multi language support (several languages will be available) I tried to do a the multi language page by creating several pages with the same content but different strings (localised strings). For example, index.html index_es.html, etc, but this will not scale well if I have several languages. I used to develop with python django, but I don't know if a framework will be too much complexity for this simple website, in this case the internationalisation will be solved. Any ideas? or different approaches ? thanks! -
How to call multiple embedded mongo document objects in a single django view using mongoengine
I have created the django views and models using mongoengine. Below are the code snippets. I am unable to send the posts_1 object to the HTML. Can you please guide me analysing the error. Model.py class C_name(EmbeddedDocument): x_fname = StringField(max_length=200,required=True) x_lname = StringField(max_length=200,required=True) class dummy(Document): x_id = IntField(max_value=5,required=True) x_name= MapField(EmbeddedDocumentField(C_name)) Views.py from django.shortcuts import render_to_response from django.template import RequestContext from sms.models import dummy from django.shortcuts import render def post_index(request): if request.method == 'POST': # save new post x_id = request.POST['x_id'] x_fname = request.POST['x_fname'] x_lname = request.POST['x_lname'] post = dummy(x_id=x_id) post_1 = C_name(x_fname=x_fname,x_lname=x_lname) post.save() posts = dummy.objects posts_1 = c_name.objects context = { 'Sms': posts, 'dd': posts_1 } return render(request,'index.html',context) I am getting the error, c_name does not have the type Objects. Can any one please help me in how to pass embedded mongodb documents in django views Thanks -
How to build and deploy my django app on EC2 instance through Jenkins server?
I am running my application on EC2 instance with nginx+gunicorn setup. I cloned the application manually and did the setup. It is working fine. But, how do I make continuous Integeration& deployment with Jenkins. I couldn't find any EC2 plugins in Jenkins manage. Can anyone tell me what is the Jenkins plugin used to deploy django app on EC2? -
How to avoid getting user private data (user's email) on server (Django Social Auth)
In my Django application I am using Python Social Auth to use Google OAuth for my site's login. As a part of login mechanism the authentication middleware appends User object to reach request. Because of this I can easily access user emails through request.user.email on my server (which I don't want because of my site's privacy policy). So is there a way to use third party authentications systems without getting user emails on my server side. I am fine with writing a code that assigns username/alias for the first time user, which shall be used in future references. -
How to convert datetime that takes the tzinfo to json serializable data?
I get the bellow error: TypeError at /api/pro/list/ datetime.datetime(2017, 12, 24, 11, 12, 13, 932155, tzinfo=<UTC>) is not JSON serializable Through stackoverflow I get the famous error. But all the answer is for: datetime.datetime(2017, 12, 24, 11, 12, 13, 932155) this format, but mine there is timezone info there: tzinfo=<UTC>. How to convert this type datetime to json serializable data? -
django-requestlogging 1.0.1
I am trying to implement a logging in my Django Project (django 1.11, Py 3.6). I'm using default django logger. To get the username in log, I have used django-requestlogging 1.0.1. As of now, I don't have any user other than superuser admin. When I'm trying 'get' request on front-end side, error occurs like 'LogSetupMiddleware' is not callable. I) What is the reason for LogSetupMiddleware not callable? how to make it work? II) How to get 'anonymous' user in log? `Django settings.py` snippet INSTALLED_APPS= [..., 'django_requestlogging', ] MIDDLEWARE = [ .., 'django_requestlogging.middleware.LogSetupMiddleware', .. ] LOGGING = { 'version': 1, 'formatters': {'standard' : { 'format': '%(asctime)s %(username)s %(request_method)s' } } -
CORES django-react application
Getting issue on api call No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. My react app is running at 'http://127.0.0.1:8080' and django api app at 'http://127.0.0.1:8000' -
Can't logging into django admin panel
In production, after entering username and password in order to access django admin panel, the website arrises following error 'OperationalError at /admin/login/ unable to open database file' Here's my settings of db.sqlite3 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # BASE_DIR => /var/www/name_of_website/src where db.sqlite3 stored So far, I have changed the read/write mode of db.sqlite3 to -rw-rw-rw- And it is my apache log file /var/log/apache/error.log [Mon Nov 27 12:16:26.737719 2017] [wsgi:error] [pid 13974] Traceback (most recent call last): [Mon Nov 27 12:16:26.737724 2017] [wsgi:error] [pid 13974] File "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py", line 65, in execute [Mon Nov 27 12:16:26.737728 2017] [wsgi:error] [pid 13974] return self.cursor.execute(sql, params) [Mon Nov 27 12:16:26.737733 2017] [wsgi:error] [pid 13974] File "/usr/local/lib/python3.5/dist-packages/django/db/backends/sqlite3/base.py", line 328, in execute [Mon Nov 27 12:16:26.737737 2017] [wsgi:error] [pid 13974] return Database.Cursor.execute(self, query, params) [Mon Nov 27 12:16:26.737740 2017] [wsgi:error] [pid 13974] sqlite3.OperationalError: unable to open database file [Mon Nov 27 12:16:26.737744 2017] [wsgi:error] [pid 13974] [Mon Nov 27 12:16:26.737747 2017] [wsgi:error] [pid 13974] The above exception was the direct cause of the following exception: [Mon Nov 27 12:16:26.737751 2017] [wsgi:error] [pid 13974] [Mon Nov 27 12:16:26.737754 2017] [wsgi:error] [pid 13974] Traceback (most recent call last): [Mon Nov 27 … -
How to Sort dictionary in python
i already tried some snippet [{"number": "1"},{"number": "10"},{"number": "101"},{"number": "2"},{"number": "20"}] expected answer should be [{"number": "1"},{"number": "2"},{"number": "10"},{"number": "20"},{"number": "101"}] -
Django: Model clean method called before form clean
I don't understand, why is my model clean method called before full form validation. I have required fields in my form. If I don't fill them, I don't get form errors, instead of, the model clean method is called (so I suppose it's because save is called). It crashes in models clean() method: if self.date_from > self.date_to can't compare datetime.date to NoneType Because I didn't filled date_to field. I think that form should have handle it and raise ValidationError and models save() shouldn't be even called. Create view should inherit form_invalid method. class TripCreationForm(forms.ModelForm): date_from = forms.DateField(required=True) date_to = forms.DateField(required=True) place_id = forms.CharField(widget=forms.HiddenInput(),required=True) class Meta: model = Trip fields = ['date_from','date_to','detail','participants','place_id'] def __init__(self, *args,**kwargs): user = kwargs.pop('user') super(TripCreationForm, self).__init__(*args,**kwargs) fs_helpers.add_widget_attribute('class','datepicker',self.fields['date_from']) fs_helpers.add_widget_attribute('class','datepicker',self.fields['date_to']) self.instance.user = user def clean(self): cleaned_data = super(TripCreationForm,self).clean() city, created = City.objects.get_or_create(place_id=self.cleaned_data['place_id']) self.instance.city = city date_from = self.cleaned_data.get('date_from') date_to = self.cleaned_data.get('date_to') if date_from and date_to and date_from>=date_to: raise ValidationError(_('Date from can\'t be higher that date to')) return cleaned_data This is my view: class TripCreationView(SuccessMessageMixin,CreateView): form_class = TripCreationForm template_name = 'trips/add_new_trip.html' success_message = _('Congratulations! You\'ve added a new trip!') context_object_name = 'trip_creation_form' def post(self, request, *args, **kwargs): # TODO Switch to get_success_url return super(TripCreationView, self).post(self, request, *args, **kwargs) def get_form_kwargs(self): … -
How in CBV correctly redirect user if he dont have permission?
I want to redirect user to url (reverse_lazy('dashboard')) if Class Based View is not available to user (he dont have permission). I use next code but it dont redirect user. Whats wrong? views.py: from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.urlresolvers import reverse_lazy class UserEditView(PermissionRequiredMixin, UpdateView): template_name = 'users/edit_user.html' form_class = UserEditForm model = User permission_required = ('auth.change_user') login_url = None redirect_field_name = reverse_lazy('dashboard') LOG in terminal: LevelName: WARNING | Message: Not Found: /accounts/login/ LevelName: WARNING | Message: "GET /accounts/login/?/=/user/50/edit/ HTTP/1.1" 404 2838 Also I tried next. If in settings.py I set LOGIN_URL = reverse_lazy('administration_login')in terminal I see but it dont redirect user: LevelName: INFO | Message: "POST /user/50/edit/ HTTP/1.1" 302 0 LevelName: INFO | Message: "GET /login/?/=/user/50/edit/ HTTP/1.1" 302 0 LevelName: INFO | Message: "GET / HTTP/1.1" 200 2427 QUESTION: Can someone say how to make correct redirection to custom url if user don't have permission? -
Django - get_queryset() missing 1 required positional argument: 'request'
I was trying to make an API using REST Framework for uploading a file to the server and my codes are below. If you have any other easy method to do the same please post your code. models.py from django.db import models # Create your models here. class FileUploader(models.Model): file = models.FileField() name = models.CharField(max_length=100) #name is filename without extension version = models.IntegerField(default=0) upload_date = models.DateTimeField(auto_now=True, db_index=True) owner = models.ForeignKey('auth.User', related_name='uploaded_files') size = models.IntegerField(default=0) def __str__(self): return self.name serializers.py class FileUploaderSerializer(serializers.ModelSerializer): class Meta: model=FileUploader fields='__all__' read_only_fields = '__all__' def validate(self, validated_data): validated_data['owner'] = self.context['request'].user validated_data['name'] = os.path.splitext(validated_data['file'].name)[0] validated_data['size'] = validated_data['file'].size return validated_data def create(self,validated_data): return FileUploader.objects.create(**validated_data) views.py class FileUploaderViewSet(viewsets.ModelViewSet): serializer_class = FileUploaderSerializer parser_classes=(MultiPartParser,FormParser) def get_queryset(self,request, *args, **kwargs): qs = super(FileUploaderViewSet, self).get_queryset(self,request, *args, **kwargs) qs = qs.filter(owner=self.request.user) return qs urls.py from django.conf.urls import url from django.conf.urls import url,include from django.contrib import admin from rest_framework import routers from rest_framework.authtoken.views import obtain_auth_token from rest_framework.urlpatterns import format_suffix_patterns from webapp import views from webapp.views import( UserCreateAPIView, UserLoginAPIView, FileUploaderViewSet, ) router = routers.DefaultRouter() router.register(r'upload', views.FileUploaderViewSet,base_name='file-view') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(router.urls)), #url(r'^upload/$',FileUploaderViewSet.as_view()), ] My requirement is that i need to upload a file to the server and the details of the uploaded file is to … -
django - remember data between bound and unbound forms
I'm defining a new Form, using __init()__ to modify the queryset for a ModelMultipleChoiceField and also adding a variable that i will use for the query: class ProductPickerForChangeForm(forms.Form): products = forms.ModelMultipleChoiceField(queryset=None) def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) total_amount = kwargs.pop('total_amount', None) super(ProductPickerForChangeForm, self).__init__(*args, **kwargs) if user and total_amount: self.fields['products'].queryset = # stuff self.total_amount = total_amount now, in views.py I'm creating a new unbound form for the GET request (and the parameters are coming from the user): form = ProductPickerForChangeForm(user=request.user, total_amount=amount) but, how to recover the data previously used for creating the unbound form when I'm creating the bound form from the POST request (the queryset could have changed in the meantime) - and without the risk of users messing with the posted data, too? -
Mixin fields not existing on Django migrations
Let's say I have this mixing: class Test(object): ...some logic... class TestMixin(models.Model): db_field = django database field test = Test() # not a database field class Meta: abstract = True class Foo(TestMixin, models.Model): ... more db fields ... I am having a strange issue here. If I inspect Foo through django shell I can see both fields, db_field and test But if I create this migration: from __future__ import unicode_literals from django.db import migrations def custom_operation(apps, schema_editor): Foo = apps.get_model('django_app', 'Foo') stuffs = Foo.objects.all() for stuff in stuffs: print stuff.test # this doesnt exist class Migration(migrations.Migration): dependencies = [ ... ] operations = [ migrations.RunPython(custom_operation), ] And if I add a breakpoint at Test() __init__ it gets called through the shell or Django but not when running the migration. Which is the differente between with using the model through the migration? -
DJango REST Framework: add additional functionality to ModelViewSet create method
I am attempting to add to the django server additional functionality upon different host requests. To do do so, I overridden the ModelViewSet functions with thought to add functionality within those functions. What I saw is that when setting a breakpoint on retrieve and list (GET requests), the debugger stopped. But when trying to break on create or update (POST requests) the debugger didn't break. How to resolve this? class GraphViewSet(ModelViewSet): queryset = Graph.objects.all() serializer_class = GraphSerializer def create(self, request, *args, **kwargs): response = super(ModelViewSet, self).create(request, args, kwargs) return response def retrieve(self, request, *args, **kwargs): response = super(ModelViewSet, self).retrieve(request, args, kwargs) return response def update(self, request, *args, **kwargs): response = super(ModelViewSet, self).update(request, args, kwargs) return response def partial_update(self, request, *args, **kwargs): response = super(ModelViewSet, self).partial_update(request, args, kwargs) return response def destroy(self, request, *args, **kwargs): response = super(ModelViewSet, self).destroy(request, args, kwargs) return response def list(self, request, *args, **kwargs): response = super(ModelViewSet, self).list(request, args, kwargs) return response def post(self, request, *args, **kwargs): response = super(ModelViewSet, self).post(request, args, kwargs) return response Python 3.6.3 Django 1.11.7 djangorestframework 9.0.1 Appreciate also any additional possible solutions for adding functionality on the server side to the different client requests. -
Unable to debug with DRF and GCP in Pycharm
I'm using Pycharm to develop a REST API (with Django Rest Framework - DRF). I started the project without Google Cloud Plateform (GCP) and could debug locally without any problem. Now I'm using GCP with Google App Engine (GAE) and run/debug buttons on Pycharm don't launch the project locally. When pushing the "Run" button I got this message: /Users/XXX/Collector/bin/python /Users/XXX/PycharmProjects/XProject/manage.py runserver 127.0.0.1:8000 Traceback (most recent call last): File "/Users/XXX/PycharmProjects/XProject/manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/Users/XXX/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/core/management.py", line 1520, in execute_from_command_line parser = DjangoOptionParser(usage=get_usage(action_mapping), version=get_version()) File "/Users/XXX/google-cloud-sdk/platform/google_appengine/lib/django-0.96/django/core/management.py", line 1501, in get_usage available_actions = action_mapping.keys() AttributeError: 'list' object has no attribute 'keys' I found a workaround to launch the project locally with "python manage.py runserver" but I can't run the server locally in debug which is very painfull for development. Does anybody know how to resolve this problem? -
I'm new in python/django thing so I can't access my project while running an virtual
enter image description here I can't oppen the "settings.py" file from here. Wich steps do I have do take to work it out? -
Form with list of members of my group [Django Admin]
How could I customize Django Admin (GROUP)? When I log in to system as no real admin, I would like to display only form with list of members of group in which I am. Thanks so much. -
Is there a way to host a django server on a mobile device?
Have a couple of unused android phones. As android has linux behind the scenes, wanting to know that is there a way to host a server using the phones? -
How can I change header when user is logged in django?
I have two headers header.html and headersuccess.html . I user is logged in, I need to change the header.html as headersuccess.html. How can I able to implement that? My views.py is.. By this I am going to loginsuccess.html.. So, if login is success I need to change header from header.html to hadersuccess.html def logsuccess(request): if('loggedIn' in request.session): id = request.session['uid']; return render(request,"loginsuccess.html",{'uid':id}); else: return render(request,"failed.html",{}); I am getting uid using this. I am using html and vue js for displaying. -
Django : can't add foreign key constraint while migrate table in mysql
I have bunch of tables and tried to do migration which is change Charfield into manytomany field. However while I am doing this I encountered this error. What I trying to do was alter columns in the table that already has data, and create two new tables that related to new columns. I have no idea how I can solve this. The error log is this. Operations to perform: Apply all migrations: food Running pre-migrate handlers for application food Running pre-migrate handlers for application admin_tools Running pre-migrate handlers for application theming Running pre-migrate handlers for application menu Running pre-migrate handlers for application dashboard Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application rest_framework Running migrations: Applying fiid.0113_auto_20171127_1852...Traceback (most recent call last): File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/django/db/backends/utils.py", line 65, in execute return self.cursor.execute(sql, params) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/home/i-06/PycharmProjects/food-front-service/.venv/lib/python3.5/site-packages/MySQLdb/cursors.py", line 374, in _do_query … -
Why does range is 'reversed' when filtering objects?
I've got a car database and I show "similar cars" on each car's page. To sort the similar cars, I'm going through this filter: min_power = int(float(car.power_ps) * .8) max_power = int(float(car.power_ps) * 1.2) similar_cars = Car.objects.filter(power_ps__range=(min_power, max_power)) This mostly works. However, similar cars don't show up on some cars' pages. When I tweaked my code a bit, I figured that If I use power_kw (another power unit and model field) instead of power_ps in my queryset, similar cars successfully show up on those pages. But this time, they don't show up on some other cars' pages. So, I have model instances that: don't show similar cars when used power_ps but get them with power_kw don't show similar cars when used power_kw but get them with power_ps show similar cars either when I use power_ps or power_kw When I investigated further, I found out that If I swap the min_power and max_power in my range filter, similar cars that don't show up before work successfully. All in all, my range variables are somehow 'reversed' in some instances. Any suggestion or feedback will be welcomed and greatly appreciated. Thank you. -
static files doesn't load on cache clear?
I have a Django project when I set Debug=true and cache clear when running the static files will not load. If I set it to false the page will load with static files. Any solution to this problem