Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django generic view Delete but not immediately
User sometimes do things they should not do and if you ask them they say I don't know... Is there a way to alter the default behavior of deleteview? Someway to create a bin table where all deleted records go, with a field of who and when the deletion has been made? from django.views.generic.edit import DeleteView class EntryDeleteView(DeleteView): model = MYMODEL success_url = reverse_lazy('mymodel_app:mymodel') Should I replace it with a request and create another model same as the one that should be deleted and use this model for logging? -
Django get field's name from Field object
I am trying to find out the recommended way of getting a model field's name from a Field object. It seems field.name works (which I found out from some SO posts) if field is the object name but surprisingly its not mentioned anywhere in the docs, so want to know if its still the best way or am I missing something obvious? -
Django 1.10 - why the app does not work with DEBUG=FALSE
I am completely beginner of Django / Python. I wrote my app in Django 1.10, everything works good and now I would like to move the app at production server. So, I have set the DEBUG on FALSE and suddenly whole app stopped working. It means, generally an app works, but static links doesn't work, the program does not see js, css files. Do you know - why? Thanks -
Web Application: User holding room
Goal is to implement a online system where users can login using a social authentication system and until total number of logged in users reach specific capacity we hold them. Once the capacity is reach goal is to guide them to different page. After doing some research I only found following link in the stackoverflow Implementing an Online Waiting Room Have experience in java and python any example in either django/flask/play2 would be great as a starting point. If the question doesn't belong here kindly advise the proper location. -
Model using inheritance: You are trying to add a non-nullable field 'id' to typemod without a default;
I am using model inheritance in my models.py. This is my code: class Email(models.Model): stuff = models.CharField(max_length=40, blank=True, null=True, default="") class TypeMod(Email): pass When I run makemigrations, I get the following message although I have set the default value for all of my fields in the Email model: You are trying to add a non-nullable field 'id' to typemod without a default; we can't do that (the database needs something to populate existing rows). Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py What am I doing wrong?! -
url captured regex (\w+) not matching certain urls
The two lines of the urls.py config file for my_app are shown below. They're almost the same, only the second has a uuid4 appended to it # preview views to allow us to preview stuff url(r'^(?P<hash>\w+)/preview/$', Start.as_view(), {'preview':True}, name='preview'), url(r'^(?P<hash>\w+)/preview/(?P<uuid>[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12})/$', PreviewController.as_view(), name='previewcontroller'), The following urls work without error: http://example.com/my_app/2307099758/preview/ http://example.com/my_app/2660962971/preview/ http://example.com/my_app/475966143/preview/ The following urls yield the below error (all hash values are valid, but that shouldn't affect the url resolution): http://example.com/my_app/841211121/preview/ http://example.com/my_app/2398929036/preview/ Internal Server Error: /my_app/841211121/preview/ NoReverseMatch at /my_app/841211121/preview/ Reverse for ‘previewcontroller’ with arguments ‘()’ and keyword arguments ‘{'uuid’: None, ‘hash’: ‘841211121'}’ not found. 1 pattern(s) tried: ['my_app/(?P\w+)/preview/(?P[a-f0-9]{8}-?[a-f0-9]{4}-?4[a-f0-9]{3}-?[89ab][a-f0-9]{3}-?[a-f0-9]{12})/$'] Request Method: GET Request URL: http://example.com/my_app/841211121/preview/ Django Version: 1.10... Regex101.com says that the url should match (with escaped slashes, of course). Why on earth are the second group of urls not matching the preview url, and what is provoking the url resolver to attempt to match them to previewcontroller when there is no uuid string appended to the url? -
In a Django serializer, take default field value from context
I'm using Django with the REST Framework. In a serializer, I would like to assign a field value based on a view parameter, so I need the view in the context. I succeeded, but only in a cumbersome way, and I am looking into ways to simplify the code. Here's the successful approach (omitting irrelevant fields): class TypeDefault(object): def set_context(self, serializer_field): view = serializer_field.context['view'] self.type = view.kwargs['type'] def __call__(self): return self.type class RRsetSerializer(serializers.ModelSerializer): type = serializers.CharField(default=serializers.CreateOnlyDefault(TypeDefault())) class Meta: model = RRset fields = ('type',) read_only_fields = ('type',) To simplify things, I tried removing the TypeDefault class, and replacing the type serializer field by type = serializers.SerializerMethodField() def get_type(self, obj): return self.context.get('view').kwargs['type'] # also tried self._context However, context.get('view') returns None. I am unsure why the view context is not available here. My impression is that it should be possible to get the desired functionality without resorting to an extra class. As a bonus, it would be nice to specify the default in the field declaration itself, like type = serializers.CharField(default=self.context.get('view').kwargs['type']) However, self is not defined here, and I'm not sure what the right approach would be. -
Unable to run django application on nginx as development server?
I am new to django , i am facing difficulties in deployment of django project on Nginx web server i have followed configuration steps from this articlehow-to-serve-django-applications-with-uwsgi-and-nginx-on-ubuntu-14-04 As nginx is successfully installed and working fine, but my application is not runnig? Do i need to configure in my django project ? please check this image enter image description here -
django-guardian: inconsistent reporting of permissions
So I'm using django-guardian with a custom User model, but it's acting up. I did implement all changes as advised in the docs. Assume the following shell session: >>> our_user = GeneralUser.objects.get(id=25) >>> our_biz = Business.objects.get(id=5) >>> assign_perm('delete_business', our_user, our_biz) <UserObjectPermission: UserObjectPermission object> >>> our_user.has_perm('delete_business', our_biz) False This has led me me to believe that maybe trying to edit one of django's built-in permissions (add|change|delete) isn't possible through guardian, so I tried to the permission label to del_business, but got the same result as above. But upon inspecting the table guardian_userobjectpermission I can see that the above session, and in fact all of my attempts were successful: So why does .has_perm always report False when I check? The only case where has_perm returns True is when both objects (User & Business) are created within the shell session. Otherwise it always returns False, even though its SQL-table clearly says it should be True. -
Django 'str' object has no attribute 'as_widget'
I've made a register form in django and i've created a template tag add_class to create users, the problem is i'm getting this error: 'str' object has no attribute 'as_widget' to {{ form.username|add_class:'form-control' }} register_user.html <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <div class="form-group"> <div class="col-md-12"> {{ form.username|add_class:'form-control' }} </div> </div> <div class="form-group"> <div class="col-md-12"> {{ form.email|add_class:'form-control' }} </div> </div> <div class="form-group"> <div class="col-md-12"> {{ form.password|add_class:'form-control' }} </div> </div> <div class="form-group"> <div class="col-md-12"> {{ form.confirm_password|add_class:'form-control' }} </div> </div> <div class="form-group"> <div class="col-md-12"> <button type="submit" class="btn btn-info btn-block">Register</button> <input type="hidden" name="next" value="{% url 'register_user_success' %}"/> </div> </div> </form> form.py class UserForm(ModelForm): username = forms.CharField(widget=forms.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Password'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'placeholder': 'E-mail'})) confirm_password = forms.CharField(widget=forms.PasswordInput(attrs={'placeholder': 'Confirm Password'})) class Meta: model = CustomUser fields = ('username', 'email', 'password', 'confirm_password') def clean(self): cleaned_data = super(UserForm, self).clean() password = cleaned_data.get('password') confirm_password = cleaned_data.get('confirm_password') if password != confirm_password: raise forms.ValidationError('Password did not match.') template tag: my_filters.py from django import template register = template.Library() @register.filter(name='add_class') def add_class(value, arg): return value.as_widget(attrs={'class': arg}) I've made the template tag so i can add classes from css. -
Restrict certain pages for only some user group in Django
Here when one type of user is logged in he can access any other user's page by simply changing the URL. How can I restrict certain pages to only certain users along with @login_required views.py def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: u = User.objects.get(username=username) if user.is_active: login(request, user) if user.groups.filter(name='hod').exists(): return redirect('/hod') elif user.groups.filter(name='principal').exists(): return redirect('/principal') elif user.groups.filter(name='Rep').exists(): return redirect('/rep') elif user.groups.filter(name='Ajithzen').exists(): return redirect('/ajithsen') elif user.groups.filter(name='graphics').exists(): return redirect('/ashok') elif user.groups.filter(name='Event_incharge').exists(): return redirect('/incharge') elif user.groups.filter(name='Event_coord').exists(): return redirect('/chair') elif user.groups.filter(name='IEEE').exists(): return redirect('/ieee') else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) else: return render(request, 'retest/login.html', {'error_message': 'Your account has been disabled'}) else: return render(request, 'retest/login.html', {'error_message': 'Invalid login'}) return render(request, 'retest/login.html') @login_required def rep(request): u = request.user all_requests= Retest.objects.all() return render(request, 'retest/home.html', {'u':u, 'all_requests' : all_requests }) urls.py url(r'^$', views.login_user, name='login_user'), url(r'^rep$', views.rep, name='rep'), If a user of group rep is logged in he can access the page of others by changing /rep to some other -
Django-Taggit GenericField
taggit and implemented a GenericTaggedItemBase like so: from taggit.models import GenericTaggedItemBase, TagBase class PeopleTag (TagBase): pass class BTaggit (GenericTaggedItemBase): tag = models.ForeignKey(PeopleTag) class UserProfile(models.Model): I_want = TaggableManager(verbose_name="I want",blank=False) content = TaggableManager(verbose_name='Content',through=BTaggit, blank=True) The problem was that if I write tags in the content models field, the tags are not saved in the Django-taggit admin (but saved in the profile of the User so they are viewable but not callable in the View). So when I try to call the values in the View: userArr = user.userprofile.content.values_list('name', flat=True) I get Cannot resolve keyword 'None' into field. (The field "I_want" works fine). This should be a QuerySet or list! Since the tags are not saved in the Taggit Admin I saved them in an extra table in the Admin, but this would be a messy solution. Does anybody have an Idea how to save the Tags normally though the GenericTaggedItemBase and make them callable in the View.py? -
clean() method causes files to lose data using POST form
I have set up a form and view to upload multiple *.gpx files to my website at once. These files are validated using a clean() method on the form and then once validated passed to a function for processing. When I upload some invalid files the clean() method catches them and informs the user as expected. When I upload some valid files the processing function crashes with an error saying the files are empty. If I comment out the clean() method then the valid files are uploaded fine. What can be happening to the form during the clean() method than means the files are being blanked? here is my form: class UploadGpxForm(forms.Form): gpx_file = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) here is my view: class UploadGpxView(FormView): form_class = UploadGpxForm template_name = 'dashboard/upload.html' # Replace with your template. success_url = reverse_lazy('dashboard:index') # Replace with your URL or reverse(). def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('gpx_file') if form.is_valid(): for f in files: SaveGPXtoPostGIS(f) return self.form_valid(form) else: return self.form_invalid(form) Here is my clean method for the UploadGpxForm: def clean(self): file_errors=[] files = list(self.files.getlist('gpx_file')) for f in list(files): #check file has only one full stop in it. if len(f.name.split('.')) != 2: … -
Displaying both sides of a ManyToMany relationship in Django admin
Say I have the following models that have a many-to-many relationship: models.py: class Foo(models.Model): name = models.TextField() class Bar(models.Model): name = models.TextField() foos = models.ManyToManyField(A, related_name='bars') And then having defined them in admin in the following way: admin.py @admin.register(Foo) class FooAdmin(admin.ModelAdmin): """Foo admin.""" list_display = ('name',) search_fields = ('name',) @admin.register(Bar) class BarAdmin(admin.ModelAdmin): """Bar admin.""" list_display = ('name',) search_fields = ('name',) In Django admin, when browsing Bar instances, I can see the Foo instances Bar is associated with and can modify them from there. However, no such luck with Foo, I can't see the Bar instances that every Foo object is associated with. Can Django define automatic handling for this or would I need to roll my own methond? I'm using Python 3.6.1 and Django 1.11. -
Pulling data from uploaded text file into django database
I am completely new to django (literally just started using it today!). I am running version 1.11.1 and so far I have written a script which uploads a text file to the root directory of django using the following code html <form action="{{ request.build_absolute_uri }}upload/" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="file"/> <br /> <input type="submit" value="Upload File" /> </form> views.py import os from django.http import HttpResponse def upload(request): if request.method == 'POST': handle_uploaded_file(request.FILES['file'], str(request.FILES['file'])) return HttpResponse("Successful") return HttpResponse("Failed") def handle_uploaded_file(file, filename): if not os.path.exists('upload/'): os.mkdir('upload/') with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): destination.write(chunk) urls.py from . import views urlpatterns = [ url(r'^$', views.home_view, name='home'), url(r'^upload/', views.upload, name="upload"), ] In my uploaded text file is the following formatted text some,random,data Is it possible to, on upload, send this information directly to a Django database using the "," as a delimiter on which to explode the data into seperate fields (like you would do if it was PHP). So the result would be 3 seperate files within the database each containing one piece of the above data without the "," -
Dynamically creating new URL in Django
i want to know how to create new pages in Django after a logged-in User clicks "create new group" links. class Blob(models.Model): #models.py Owner = models.OneToOneField(User) From = models.CharField() To = models.CharField() Leaving_Date = models.DateField() Leaving_Time = models.TimeField() Lower_Time = models.DateTimeField(default = datetime.now()) Upper_Time = models.DateTimeField(default = datetime.now()) URL = models.URLField() Each entry has a Owner. User queries in this table and if no matching entry is found, he is prompted to create a new entry in this table. How would you fill this URL field and corresponding changes in views.py and url.py. Asking users for it doesn't look good. Edit: I am thinking of creating a random string of fixed length, like 'xcedfr' and then appending it to the base URL, it would be good if every entry have unique URL -
Django FieldError Unsupported lookup
I've searched google and I tried to understand myself but I can't figure it out myself. Look at these two views, This one works great: def view_category(request, category_name): category = get_object_or_404(Category,name__iexact=category_name) subcategories = get_list_or_404(Subcategory, parent=category) context = {'category': str(category), 'subcategories': map(str, subcategories)} return render(request, 'basic_web/category.html', context) And this one: def view_subcategory(request, category_name, subcategory_name): category = get_object_or_404(Category,name__iexcat=category_name) subcategory = get_object_or_404(Subcategory, name__iexact=subcategory_name, parent=category) items = get_list_or_404(Information, parent=subcategory) context = {'category': str(category), 'subcategory': str(subcategory), 'items': map(str,items)} return render(request, 'basic_web/subcategory.html', context) Raises: FieldError Unsupported lookup 'iexcat' for CharField or join on the field not permitted. I can't seem to understand why since the code is the same. Here are the models: class Category(models.Model): name = models.CharField(max_length=32) description = models.TextField(max_length=256) def __str__(self): return self.name class Subcategory(models.Model): name = models.CharField(max_length=32) description = models.TextField(max_length=256) parent = models.ForeignKey(Category) def __str__(self): return self.name Please tell me if I need to provide any further information, thanks for your help! -
Update ordering of related model at runtime in django
I do not want to apply permanent ordering with the default ordering in Meta. I would rather update it at run time: def get_object(self, queryset=None): question = super().get_object(queryset) question.choice_set.ordering = '-votes' return question Is something like this possible? -
AttributeError at /account/login/oauth/complete/facebook/ 'NoneType' object has no attribute 'userprofile'
I have a problem, that instead of "User" Facebook account info is of "NoneType" type, so I can't save image as extended user model information (userprofile) after first facebook social authentication. If any additional information is needed please give me a notice. settings.py: SOCIAL_AUTH_FACEBOOK_SCOPE = ['email'] SOCIAL_AUTH_FACEBOOK_PROFILE_EXTRA_PARAMS = { 'fields': 'id,name,email', } SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'ridemaker.pipeline.save_profile', ) pipeline.py: from accounts.models import UserProfile from social_core.backends.facebook import FacebookOAuth2, FacebookAppOAuth2 from urllib.request import urlopen from django.template.defaultfilters import slugify from django.core.files.base import ContentFile def save_profile(backend, details, response, uid,\ user, *args, **kwargs): if backend.__class__ == FacebookOAuth2: url = "http://graph.facebook.com/%s/picture?type=large" % response['id'] avatar = urlopen(url) #Why is user argument "None"? profile = user.userprofile profile.image.save(slugify(user.username + " social") + '.jpg', ContentFile(avatar.read())) profile.save() -
Unable to get repr for <class 'django.db.models.query.QuerySet'> when accessing non default database
I am getting the following error when I try to access the non default (SQL Server) database from my Django application: Unable to get repr for class 'django.db.models.query.QuerySet' My Django application needs to access two databases. Here's the DATABASES snippet from my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db1', 'HOST': 'mycompany.com', 'PORT': '3306', 'USER': 'myuser', 'PASSWORD': 'mypw', }, 'otherdb': { 'ENGINE': 'sqlserver_ado', 'NAME': 'db2', 'HOST': 'server\SQLEXPRESS', 'USER': 'sqlserver_user', 'PASSWORD': 'sqlserver_pw', 'OPTIONS': { 'host_is_server': True, # must be True for remote db 'dsn': 'mssql-dsn', }, }} Here's the model class: class Person(models.Model): class Meta: db_table = "dbo.Person" Id = models.IntegerField('Id', primary_key=True, default='1') EmployeeId = models.CharField('EmployeeId', max_length=1024) Role = models.CharField('Role', max_length=1024) StoreTime = models.DateTimeField('StoreTime') def __str__(self): return self.id Here's a code snippet from my view: results = Person.objects.using('otherdb').values('Id', 'EmployeeId', 'Role', 'StoreTime') Thoughts on what is wrong? -
Django - more than one row returned by a subquery used as an expression
I'm getting this error for some reason on the server: more than one row returned by a subquery used as an expression on this line: asoc = Association.objects.get(id=asoc_pk) (commented down below in the code) but when I run it in localhost it works just fine. Been looking for similar solutions here with no help. Hopefully you can see other solutions that I can't figure out. Still new to this and appreciate your help, folks! models.py class Administrator(AbstractUser): ... association= models.ForeignKey(Association) class Meta: db_table = 'Administrator' class Association(models.Model): asoc_name = models.CharField(max_length=100) ... class Meta: db_table = 'Association' views.py def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if not form.is_valid(): return render(request, 'admin/signup.html', {'form': form}) else: ... asoc_pk = Association.objects.filter(asoc_name=request.user.association) asoc = Association.objects.get(id=asoc_pk) **#ERROR here but why?** ... Administrator.objects.create_user(... association=asoc, ...) user = authenticate(... association=asoc, ...) return redirect('/') else: return render(request, 'admin/signup.html', {'form': SignUpForm()}) -
Django tests with postgres - reset sequences
So far development and tests have been done on SQLite, while production was on Postgres. Now everything needs to run on Postgres, and a large number of tests broke. The reason is, IDs for each test don't start with 1, but continue between tests. One way how to fix this is to use TransactionTestCase, so changing class FooCase(APITestCase): with class FooCase(APITransactionTestCase): reset_sequences = True This works, but it becomes slow While I can try and fix tests, it is quite difficult because many tests have mocked methods. Is there another way, where I can reset sequences and keep it all fast and tidy? -
Django - Taking value from POST request
I have a list of zones, identified by id (integer). How can I get the zone that generated the post request? manual.html {% if zone_list %} <ul> {% for z in zone_list %} <b><p>{{z.name}}</p></b> <form action="" method="post"> {% csrf_token %} <input type="submit" name="{{z.id}}" value="ON"/> <input type="submit" name="{{z.id}}" value="OFF"/><br> <br> <label>Tiempo</label>: <input type="integerfield" name="Tiempo"> <input type="submit" name="{{z.id}}" value="Start"> </form> {% endfor %} </ul> {% endif %} In the views.py I have to change the 1 for something that dynamically represents the zone views.py def manual(request): if request.POST.has_key('1'): z = Zone.objects.get(id = 1) keyword = request.POST.get("1","") if keyword == "ON": #do something if keyword == "OFF": #do something if keyword == "Start": #do something zone_list = Zone.objects.all() context = {'zone_list':zone_list} return render(request, 'irrigation_controller/manual.html', context) -
Django can't get counted votes in template
I'm trying to count and show how many votes every user gave. When i'm doing it in python console it shows me, but i can't get it from template. In console: from football_app.models import Score from football_app.models import CustomUser for user in CustomUser.objects.all(): x = Score.objects.filter(granted_to=user).count() print(x) 0 1 1 1 1 1 0 because the request.user is not allowed to give himself a vote. In views: def test(request): data = dict() User = get_user_model() for user in User.objects.all(): count_grades = Score.objects.filter(granted_to=user).count() data['count_grades'] = str(count_grades) return render(request, 'test.html', data) test.html {% for number_of_votes in count_grades %} {{ number_of_votes }} {% endfor %} or even {{ count_grades }} It shows me just 1, that's all. Why isn't it showing for each user? -
Django Multiple Foreign Keys to none target or source model in intermediate model
I'm trying to use multiple foreign keys within an intermediate model. From the Django documentation: Your intermediate model must contain one - and only one - foreign key to the source model (this would be Group in our example), or you must explicitly specify the foreign keys Django should use for the relationship using ManyToManyField.through_fields. If you have more than one foreign key and through_fields is not specified, a validation error will be raised. A similar restriction applies to the foreign key to the target model (this would be Person in our example). To me this implies that I should be able to use multiple references to a none target or source model assuming I have specified foreign keys it isn't the source or target. However with the sample below I still get the following error: "IntermediaryModel' has more than one ForeignKey to 'app.Model3' I've stripped back the code below to only include the relationships between the four models I'm seeing this issue with. Where have I gone wrong with the model relationships? class Model1(models.Model): ... class Model2(models.Model): competitions = models.ManyToManyField(Model1, through='Model4', through_fields=('field1', 'field2')) class Model3(models.Model): field1= models.ForeignKey(Model1) field2 = models.ForeignKey(Model2) class Model4(models.Model): field1 = models.ForeignKey(Model1) field2= models.ForeignKey(Model2) field3= models.ForeignKey(Model3, …