Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ViewDoesNotExist when it does
I have a django app running off a Twisted service that can't resolve the views of some of the applets. I get the error Could not import apps.ai_stats.views. Error was: No module named aidb when I navigate to those applets in the browser, the only issue is that the aidb.py file is absolutely located in these applet directories. My structure is as follows. apps/ ai_stats/ aidb.py models.py urls.py views.py manage.py settings.py urls.py views.py I can't figure out why it won't load this particular module. I have a bunch of different applets in the one app and some work with this and others don't. If there is any other information needed please let me know. -
How to add "ON DELETE" rules to existing column in a PostgreSQL database table?
I'm using PostgreSQL in a Django project. Django does not support "on delete" rules at the database level. At the application level it allows this parameter when setting a ForeignKey for a model, but it's only used to emulate the behavior when deleting instances. I'm trying to run a data migration that deletes a set of rows from a table which is reference by another one. The models look something like this: class Album(models.Model): name = models.CharField(max_length=128) # ... class Track(models.Model): name = models.CharField(max_length=128) album = models.ForeignKey(Album, related_name='tracks', null=True, on_delete=models.SET_NULL) # ... I don't know if this behavior is supposed to be emulated in delete calls performed on querysets, or only model instances. For me neither is working. The cleanest solution in my mind would be to add a RunSQL that adds a "ON DELETE SET NULL" rule on the album foreign key at the database level. The problem is Django creates a foreign key constraint with a dynamic name, so if I drop that constraint by name and create another one, the migration may fail when I deploy. Isn't there a simple way to add the rule (or drop/create the constraint) by column name? -
Django forms.ChoiceField is always changed
Django==1.10 I want to use a models.BooleanField as a forms.ChoiceField in the admin app. # models.py from __future__ import unicode_literals from django.db import models class MyModel(models.Model): name = models.CharField(max_length=255) bool_field = models.BooleanField() # admin.py from django.contrib import admin from .models import MyModel from .forms import MyModelForm @admin.register(MyModel) class TemplateAdmin(admin.ModelAdmin): form = MyModelForm list_display = ['name','bool_field'] # forms.py from django import forms class MyModelForm(forms.ModelForm): bool_choices = ((True, "Yes"),(False, "No")) bool_field = forms.ChoiceField(choices=bool_choices) Everything displays just like I want, but in fact every time I save the instance the History link shows that the bool_field was changed even if it wasn't. I tried to change the bool_field to TypedChoiceField with coerce=bool, but it doesn't work well. After I change and save the instance the value remains the same. Please, advise, what should I probably change in order to get History working right. -
Annotated django queryset is getting ignored during serialization
I have a modelviewset where I want to annotate the list() response. I've extended the queryset with an annotation and added the field to the serializer, but the serializer just ignores the new data and doesn't add the field at all in the final data. I am using customized get_queryset() too (show abbreviated here) which is definitely getting called and producing the right annotations. It just doesn't show up in the REST API response. If I set 'default=None' on the serializer field definition, it appears in the response. class SequenceSerializer(serializers.ModelSerializer): unread=serializers.IntegerField(read_only=True) ..... class SequenceViewSet(viewsets.ModelViewSet,ScopedProtectedResourceView): authentication_classes = [OAuth2Authentication] queryset = Sequence.objects.all() serializer_class = SequenceSerializer ..... def get_queryset(self): mytopics=getMyTopics(self.request,False) queryset = Sequence.objects.all().filter(<..... some filter>) queryset=queryset.annotate(unread=FilteredRelation('unreadseq', condition=Q(unreadseq__userid=self.request.user))) print("Seq with unread",queryset.values('id','unread')) ## <<<<this shows the correct data return queryset def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) ##<<< this is missing the annotation I have been banging my head agains this all day and I can't for the life of me see what's going wrong. Any ideas please? -
Error:Django app deployment on digitalocean
I am deploying my Django app on digitalocean but i get an error after the giving the command in my Terminal for migrate.Help me to figure out the error so that i can remove it. terminal output urban@ubuntu-s-1vcpu-1gb-blr1-01:~$ source bin/activate (urban) urban@ubuntu-s-1vcpu-1gb-blr1-01:~$ cd lok (urban) urban@ubuntu-s-1vcpu-1gb-blr1-01:~/lok$ python manage.py migrate File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax (urban) urban@ubuntu-s-1vcpu-1gb-blr1-01:~/lok$ ls business List manage.py news sports templates db.sqlite3 lokswar movie README.md static_my_project -
Why is Django on_delete rule not working?
I have two models connected via a ForeignKey sort of like this: class Album(models.Model): name = models.CharField(max_length=128) # ... class Track(models.Model): name = models.CharField(max_length=128) album = models.ForeignKey(Album, on_delete=models.SET_NULL) # ... I'm writing a data migration where I try to delete some Albums: # -*- coding: utf-8 -*- # Generated by Django 1.9.13 on 2018-12-12 14:05 from __future__ import unicode_literals from django.db import migrations def forwards_func(apps, schema_editor): Album = apps.get_model("myapp", "Album") db_alias = schema_editor.connection.alias for album in Album.objects.using(db_alias).filter(foo='bar'): album.delete() def reverse_func(apps, schema_editor): pass class Migration(migrations.Migration): dependencies = [ ('myapp', '0049_blabla'), ] operations = [ migrations.RunPython(forwards_func, reverse_func), ] However, I am getting this error: File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 211, in _commit return self.connection.commit() IntegrityError: update or delete on table "Album" violates foreign key constraint "f2274d6f2be82bbff458f3e5487b1864" on table "Track" DETAIL: Key (id)=(1) is still referenced from table "Track". But the on_delete rule is there. Isn't the whole point of the delete rule to avoid errors like this? Or am I missing something? Initially I was trying a delete on the queryset, and I thought the on_delete rule wasn't supported and I had to loop through the queryset and call a delete on each instance. But apparently not even this is enough. What is the … -
Method Not Allowed (POST)
I'm trying to allow for the user to press the submit and for that to create another comment post but I receive "Method Not Allowed (POST): " when clicking post def get_context_data(self, **kwargs): # post = Post.objects.filter(id = self.kwargs['pk']) post = get_object_or_404(Post, id=self.kwargs['pk']) comments = Comment.objects.filter(post=post).order_by('-id') is_liked = False if post.likes.filter(id=self.request.user.id).exists(): is_liked = True context = super().get_context_data(**kwargs) if self.request.method == 'POST': comment_form = CommentForm(self.request.POST or None) if comment_form.is_valid(): content = self.request.POST.get('content') comment = Comment.objects.create(post=post, user=self.request.user, content=content) comment.save() return HttpResponseRedirect(post.get_absolute_url()) else: comment_form = CommentForm() context['is_liked'] = is_liked context['total_likes'] = post.total_likes() context['comments'] = comments context['comment_form'] = comment_form return context and for the template: <form method="post"> {% csrf_token %} {{ comment_form.as_p}} <input type="submit" value="Submit" class="btn btn-outline-success"> -
How I can save encodings in a model using my function?
I get a photo from form and after that i want to process photo and save photo encodings to db. How I can save encodings (the array with 128 float value) in a model using my function? My model: class FaceRec(models.Model): photo = models.FileField(upload_to=user_directory_path) encodings = ArrayField(models.FloatField()) My function to get encodings: def get_encodings(self): image_encodings = face_recognition.face_encodings(self.photo)[0] return image_encodings -
Python Django using wsgi.py with apache2 loads filter fields out of order every restart
I have a django app that works just fine when running the python manage.py runsever command locally. When I tried to migrate it and modified my apache config file to use wsgi.py, everything works except for one page where the django filter fields are shuffled above a django table. Every time I restart the apache server, the filter fields are shuffled again in a new order. The local server always displays the filter fields in the correct order. Does anyone know why this is happening? local server using python runserver command apache server using wsgi apache2.conf WSGIDaemonProcess /SeedInv python-home=/path/to/Software/anaconda3/envs/Django python-path=/path/to/WebServer/SeedInv WSGIProcessGroup /SeedInv WSGIScriptAlias /SeedInv /path/to/WebServer/SeedInv/SeedInv/wsgi.py process-group=/SeedInv <Directory /path/to/WebServer/SeedInv/SeedInv> <Files /path/to/WebServer/SeedInv/Seedinv/wsgi.py> Require all granted </Files> </Directory> Alias /static "/path/to/WebServer/SeedInv/static" <Directory "/path/to/WebServer/SeedInv/static"> Require all granted </Directory> Alias /media "/path/to/WebServer/SeedInv/media" <Directory "/path/to/WebServer/SeedInv/media"> Require all granted </Directory> wsgi.py import os import sys sys.path.append('/path/to/anaconda3/envs/Django/lib/python3.6/site-packages') from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "SeedInv.settings") application = get_wsgi_application() filters.py class GenoFilter(django_filters.FilterSet): class Meta: model = Genotypes fields = {'parent_f_row': ['icontains'], 'parent_m_row': ['icontains'], 'parent_f_geno': ['icontains'], 'parent_m_geno': ['icontains'], 'genotype': ['icontains'], 'seed_count': ['lt', 'gt'], } tables.py class GenotypesTable(tables.Table): export_formats = ['tsv'] class Meta: model = Genotypes template_name = 'django_tables2/bootstrap.html' views.py def InventoryTable(request): queryset = Genotypes.objects.all() f = GenoFilter(request.GET, queryset=queryset) table = GenotypesTable(f.qs) RequestConfig(request, … -
There is no effect of required=False to Serializer in Serializer
Serializers: class AvatarBaseSerializer(Serializer): uuid = ReadOnlyField() user = UserBaseSerializer(read_only=True) name = CharField(allow_blank=True) GENDER = (("M", "Man"), ("W", "Woman")) gender = ChoiceField(choices=GENDER) body = BodySerializer(partial=True, required=False) head = HeadBaseSerializer(read_only=True) head_pk = IntegerField(write_only=True) head_adjust = HeadAdjustBaseSerializer(partial=True, required=False) hair = HairBaseSerializer(read_only=True) hair_pk = UUIDField(write_only=True) hair_adjust = HairAdjustBaseSerializer(partial=True, required=False) thumbnail = ImageField(required=False, allow_null=True) Viewsets: class AvatarViewSet(viewsets.ModelViewSet): queryset = Avatar.objects.all() serializer_class = AvatarBaseSerializer permission_classes = (permissions.UserIsRequestUserPermission,) ... def partial_update(self, request, *args, **kwargs): self.check_thumbnail_file_size(request) return super().partial_update(request, *args, **kwargs) I send below parameters by PATCH method. However Django rest framework returns 400 Bad Request("Invalid Input"). { "head_pk": 1, "hair_pk": "89d4c318-c9bf-42cd-b4c4-b7e70a2c8f40", "name": "gewgew", "gender": "W" } I want to send parameters without body, head_adjust, hair_adjust. -
Django Image in Admin Form
I want to attach and display an image in my django admin form. I have a model that gets used to create a matrix of fields that the user needs to understand how the mapping will work, and that is best described by using an image in the form. I could do it in the frontend manually, but I want to keep it strictly in the admin. I can also overwride the admin form with a form that has custom widgets, but I'm not sure how to include an image from the sites static folder to get it into the admin form. from django import forms from django.contrib import admin from .models import Buttons class BTNForm(forms.ModelForm): custom_widget = forms.TypedChoiceField( choices = ((1, "Yes"), (0, "No")), coerce = lambda x: bool(int(x)), widget = forms.RadioSelect, initial = '1', required = True,) class Meta: model = Buttons class ButtonAdmin(admin.ModelAdmin): form = BTNForm How to go about it? -
how i do to download file from my website?
When I define FileField in django this field to upload the files I need when uploading on my site, I also want to put the possibility of downloading these files again from my site how can I write a code to download the files again. I want to work as a site to upload and download files -
passing information to django views using redirect
I am trying to pass following information through redirect(note:Username is not the username using django authentication). views.py def SUserLoginFormView(request): if request.method=='POST': form1=SUserLoginForm(request.POST) if form1.is_valid(): UserInfo=form1.save(commit=False) return redirect('Display',{'slug':UserInfo.Username}) else: form1=SUserLoginForm() return render(request,'FormLoginTemplate.html',{'form1':form1}) def Display(request,slug): pass here is urls.py urlpatterns=[ path('',views.CreateDiaryUserView,name='CreateDiaryUserView'), path('Login',views.SUserLoginFormView,name='SUserLoginFormView'), path('<slug:slug>',views.Display,name='Display'), ] But it is not working & showing Reverse for 'Display' with arguments '({'slug': 'zjzcjzbhz'},)' not found. 1 pattern(s) tried: ['(?P<slug>[-a-zA-Z0-9_]+)$'] -
Firefox won't update view more than one time. (Django)
I have simple web app with 3 boolean fields (checkboxes). I create database to keep their values and set that only one can be checked. If I run this on Chrome it works like charm. For example at start I have first checkbox checked : Then I click second one This is proper bahavior which I get using Chrome. But when I'm using Firefox it works only on first change state then I can check all checkboxes. I checked database and inside of it I have all the time good values but firefox display wrong one. html {% for object in objects %} {% if object.is_active %} <input id="active" type="checkbox" checked="checked" onclick="changee({{ object.id }})"> {% else %} <input id="active" type="checkbox" onclick="changee({{ object.id }})"> {% endif %} {% endfor %} views.py schedule_id is object.id I pass in html by changee function if schedule_id is not None: schedule_value_change = TimeTable.objects.get(pk=schedule_id) schedule_rest = TimeTable.objects.exclude(pk=schedule_id) if schedule_value_change.is_active: schedule_value_change.is_active = False else: schedule_value_change.is_active = True for schedulerest in schedule_rest: schedulerest.is_active = False schedulerest.save() schedule_value_change.save() return redirect('schedule') Could someone tell me what I'm doing wrong ? P.S On Edge it works too, only firefox is retarded -
Flask/Django maintain state data outside view functions
I'm working on a simple boardgame and I want to provide a web interface (currently trying flask, but django would also be an option). Users will send HTTP requests (or ajax) for the game actions, which will be processed using view functions. These actions (view functions) will alter the game state data that is maintained on the server. Now my question is, how should I implement the game state data? I could store this in a database and access (get/set) the database in any view function call (game action). But this may be heavy on the database? I searched online and learned that I can't use global variables because they aren't shared between multiple server threads/instances. Using session storage also won't work because the game state is shared between multiple users (sessions). -
Django web displaying stream from webcam using jetson tx2 as a server
I am writing web app, where I would like to: Display LOCAL stream from webcam - it means, that I want to stream video from server (I do not want to open webcam of client) Read QR Codes and list them in text box These two were already achieved but! I came across some unexpected behaviour. Functionality that I have described is working perfectly, but only on localhost. I want to deploy it, so it could be accessible via different computer (it is meant to be used on a robot). So to describe my architecture: I am using Jetson TX2 as a server (webcam is connected here). I am using Django web framework, django-channels, daphne as a web server and ngingx as a proxy. I am running daphne and background process in supervisor. I am using worker (background process) to capture frames from webcam and send it via redis to the web backend. So when I run it on localhost everything work as expected. When I set Debug to FALSE and I add Jetson's IP to ALLOWED_HOSTS and try to access the web from different computer this happens: I can see, that webcam is accessed because the webcam light turns … -
Get variable from template in custom filter, without passing it as argument
This might be a weird question, I apologize in advance. I have a template in which I call a custom filter highlight a lot. The role of this filter is simply to add special tags around the text to highlight them, but only if the boolean highlight is True in the template context. So when rendering the template, I set highlight to True or False in the context, and then do {{ a_variable|highlight:highlight }} in the template. My custom tag is defined as follows: @register.filter def highlight(value, should_highlight): [...] I was wondering if there was any way to remove the should_highlight parameter and get the variable in another way, so that I can just do {{ a_variable|highlight }} in the template without having the :highlight part every time (I'm talking close to a hundred occurrences in the template). Thanks a lot in advance and have a nice day :) -
Django models saving
How I can process salary with function from model and save it to year_salary Example model: class Staff(models.Model): salary = models.FloatField() year_salary = ArrayField(models.FloatField() And function: def function(salary): year_salary = salary * 12 return year_salary -
DJANGO Generic View Cannot Find Attribute 'as_view' [duplicate]
This question already has an answer here: How to require login for Django Generic Views? 9 answers I have a Django app where I have the following code: [app]/urls.py urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ... ] [app]/views.py from django.http import HttpResponseRedirect from .models import Chat from .models import Message from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.urls import reverse from django.views import generic from django.utils import timezone from django.contrib.auth.decorators import login_required @login_required() class IndexView(generic.ListView): template_name = "trout_line/index.html" context_object_name = 'latest_chat_list' def get_queryset(self): """Return the last five published questions.""" return Chat.objects.filter(start_date__lte=timezone.now()).order_by('-start_date')[:5] and a template at [app]/templates/[app]/index.html. When I run the server I receive the following message. ... path('', views.IndexView.as_view(), name='index'), AttributeError: 'function' object has no attribute 'as_view' I thought I followed the tutorial closely, but obviously I am missing something. Any help would be appreciated. I am running Python 3.6 and Django 2.1.2 on Ubuntu 16 -
I would like to only allow one entry for a row in a model in Django, is this possible?
Im building an inventory management web app (stock room manager). I have a model class: class location(models.Model): loc_room = models.CharField(max_length=20, blank=True, null=True) loc_section = models.IntegerField(blank=True, null=True) loc_shelf = models.CharField(max_length=4, blank=True, null=True) And a model class: class box(models.Model): box_contents = models.CharField(max_length=300, blank=True, null=True) location_id = models.ForeignKey('location', null=True) Is there a way that I could limit the number of boxes per location to only one entry? Its for a store room that only has one box per 'location'. E.g What I would like: At location Room: A, Section 1, Shelf 2 there should only ever be 1 x box with contents: 'Screwdriver, drill, shampoo'. E.g What is currently the case: At location Room: A, Section 1, Shelf 2 = 1 x box with contents: 'Screwdriver, drill, shampoo' ALSO 1 x box wiith contents: 'Towel rack, cups' At the moment, employees can add as many boxes per location as they like but I would like to limit this to one box as each location can physically only contain one box. -
How to use csrf (csrftoken) cookie session with django-rest-framework-social-oauth2
I have setup django-rest-framework-social-oauth2 to retrieve a token from django using facebook provider : curl -X POST -d "grant_type=convert_token&client_id=<client_id>&client_secret=<client_secret>&backend=facebook&token=<facebook_token> https://dev.myapp.com/api/auth/convert-token Everytime i do a request to my app, i add the token to the header : curl -i https://dev.myapp.com/api/users -H "Authorization: Bearer mytoken123" Everything works so far I am using ReactJs as frontend and do the above request from reactjs: axios.post("https://dev.myapp.com/api/auth/convert-token", postData).then(res => {console.log(res);} If the user closes the windows, he gets logged out as he does not have access to the token anymore, and if he goes back to my application, he has to login again. I would like to be able to use browser cookie to save the token i get from django-rest-framework-social-oauth2 and secure it with csrf protection to let the user access to my app without to click on "login" again and again I dont know how to do it and i dont know if it is possible? How should I setup django-rest-framework-social-oauth2, to get the csrftoken and use it for each API call ? The only solution I have got is to create another view that will create the csrftoken from django.shortcuts import render_to_response from django.template.context_processors import csrf def my_view(request): c = {} c.update(csrf(request)) data='my … -
How can I integrate existing MongoDB Database to generate Django Models and view in the admin site?
How can I integrate existing MongoDB Database to generate Django Models and view in the admin site? Can I use inspectdb for this? Are there any packages for this? How to connect Django to existing MongoDB Database? Thank you! -
displaying url in admin using model admin
class DirectAdmin(admin.ModelAdmin): def order_pdf(obj): # return "<a href='{}'>pdf</a>".format( url=reverse('orders:admin_order_pdf', args=[obj.id]) return "http://localhost:8000" + url order_pdf.allow_tags = True order_pdf.short_description = 'PDF bill' list_display=['id','name','price','phone_number',order_pdf] admin.site.register(Product) admin.site.register(Category) admin.site.register(Direct,DirectAdmin) this is my admin.py here in the admin section of my objects i want to display link where the link should act as anchor where it should redirect to that particular link in next tab but when i run this code i could see the uri but i want to make that section in my pdf as an anchor which redirects and opens in another tab is that possible,if yes please can you ttell me how ?? -
Django mode help_text before input widget
I'm looking how to create something like with Django. On models.py, I have something like class Fund(models.Model): success_targeted = models.TextField( help_text="Please specify what the successful outputs (what maybe be produced) and outcomes (what change it could lead to) would be for your participation in this event. These can include learning goals being met, collaborations, reports etc." ) On forms.py, I have something like class FundForm(ModelForm): class Meta: model = Fund The form is being render using django-crispy-forms {% crispy formset formset.helper %} The current render is with the help_text after the widget. How can I move the help_text to before the widget? -
How can solve this issue "cannot be considered a valid collection"
I'm running this code below but I'm getting an error that may probably come from this line of code "X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size)". I found similar problems from this platform but the solutions provided don't mutch with my issue. Please assist me. @permission_required('admin.can_add_log_entry') def upload_file(request): template='upload_file.html' if request.method == 'GET': return render(request, template) CSV_file=request.FILES['csv_file'] if not CSV_file.name.endswith('.csv'): messages.error(request, 'This is not a CSV file') # return HttpResponseRedirect(reverse('add_pull_requests')) data_set=CSV_file.read().decode('UTF-8') io_string=StringIO(data_set) next(io_string) dataset=csv.reader(io_string, skipinitialspace=True, delimiter=',') csv_list=list(dataset) # prediction_dataset=[] for row in csv_list: if row[11]=='Non-Reopened': row[11]=0 else: row[11] = 1 if row[9]=='Rejected': row[9]=0 else: row[9]=1 prediction_dataset = [row[3], row[4], row[5], row[6], row[7], row[8], row[9], row[10]] X = [prediction_dataset] y = row[11] print(X) print(y) test_size = 0.2 random_state = 5 clf = tree.DecisionTreeClassifier() X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=random_state, test_size=test_size) # clf = tree.DecisionTreeClassifier() clf = clf.fit(X_train, y_train) # y_pred = clf.predict(X_test) print(accuracy= accuracy_score(y_test,y_pred)*100) return render(request, template,{"csv_list": csv_list})