Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Upload" file from disk in Django
I generate a file in python, and want to "upload" that file to the django database. This way it is automatically put inside the media folder, and organized neatly with all other files of my application. Now here is what I tried: # forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadedFile fields = ('document',) # models.py class UploadedFile(models.Model): # mimetype is generated by filename on save mimetype = models.CharField(max_length=255) document = models.FileField(upload_to=get_upload_path) # ... additional fields # views.py, file_out has been generated with open(file_out, 'rb') as local_file: from django.core.files import File form = UploadForm(dict(), {'document': File(local_file)}) print(form.errors) if form.is_valid(): file = form.save(commit=False) # ... set additional fields file.save() form.save_m2m() return file Now this is not the only thing I've tried. First I've gone with setting the FileField directly, but that resulted in the save() to fail, while the mimetype field is set. Because the original file sits outside the media folder, and thus a suspicious file action is triggered. Also, the form gives some feedback about the "upload", through the form.errors. Depending on my approach, either the save() fails as mentioned above -- meaning the "uploading" does not actually copy the file in the media folder -- or the form … -
What are some suggestions on fixing or improving the database shown in the attached image?
Database Hi. I'm looking for suggestions on fixing or improving the database shown in the attached image. There are 7 tables, User, Tag, Post, Comment, UserTag, UserPost, and TagPost. Relationships: User and Tag Tables Many-to-many (an user can follow many tags and a tag can be followed by many users) One-to-many (an user can create many tags and a tag can be created by only one user) User and Post Tables Many-to-many (an user can like many posts and a post can be liked by many users) One-to-many (an user can create many posts and a post can be created by only one user) User and Comment Tables One-to-many (an user can create many comments and a comment can be created by only one user) User and User Tables Many-to-many (an user can follow many users and an user can be followed by many users) Post and Comment Tables One-to-many (a post can have many comments and a comment can belong to only one post) Tag and Post Tables Many-to-many (a tag can have many posts and a post can belong to many tags) -
Real-time notifications in Django
I have a requirement to implement a real time notification on my project where all notification are based on some status and duration, which i will get from DB. Apart from django-notifications i am not able to see any other thing to implement , I have to trigger the notification at every 15 minutes and post the data. What is the best way/approach to implement. -
Not taking value in foreign key django shell
i have models.py as follows: class category(models.Model): cid=models.IntegerField(unique=True,default=0) cname=models.CharField(max_length=20) def __unicode__(self): return self.cid,self.cname class Meta: db_table="category" class cateledetails(models.Model): cdid=models.IntegerField(unique=True,default=0) cid=models.ForeignKey(category,to_field='cid',on_delete=models.CASCADE) elename=models.CharField(max_length=20) imgsrc=models.ImageField(upload_to='elements/',blank=True) def __unicode__(self): return self.cdid,self.elename class Meta: db_table="cateledetails" and i have made an entry in shell b=category(cid=1,cname='Animal') b.save() next i try to input an entry into cateledetails table and it gives the following error: python manage.py shell Python 2.7.8 (default, Jun 30 2014, 16:08:48) [MSC v.1500 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.models import category,cateledetails Traceback (most recent call last): File "<console>", line 1, in <module> ImportError: No module named models >>> from student.models import category,cateledetails >>> b=category.objects.get(pk=1) >>> b.cid 1 >>> q=cateledetails(cdid=1,cid=1,'dog') File "<console>", line 1 SyntaxError: non-keyword arg after keyword arg >>> q=cateledetails(cdid=1,cid=1,elename='dog') Traceback (most recent call last): File "<console>", line 1, in <module> File "C:\Python27\lib\site-packages\django\db\models\base.py", line 468, in __init__ setattr(self, field.name, rel_obj) File "C:\Python27\lib\site-packages\django\db\models\fields\related.py", line 627, in __set__ self.field.rel.to._meta.object_name, ValueError: Cannot assign "1": "cateledetails.cid" must be a "category" instance. why is this error generating? -
Django comments not showing in template
I have a system setup to show comments on a post detail page, however the comments are not showing. I have been focusing on the template tags, because I have used this view code elsewhere and it has worked, however I may be wrong. No errors returning, just not showing the comment in the detail view. userpost_detail.html: {% extends 'base.html' %} {% block content %} <div class="main"> <h1 class="posttitle">{{ userpost.title }}</h1> <p class="postcontent">{{ userpost.post_body }}</p> {% if request.user.is_authenticated and request.user == post.author %} <a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a> {% endif %} <a href="{% url 'feed:add_comment' userpost.id %}">Add Comment</a> {% for comment in userpost.usercomment.all %} {% if user.is_authenticated %} {{ comment.create_date }} <!-- <a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}"> <span class="glyphicon glyphicon-remove"></span> </a> --> <p>{{ comment.comment_body }}</p> <p>Posted By: {{ comment.author }}</p> {% endif %} {% empty %} <p>No Comments</p> {% endfor %} </div> {% include 'feed/sidebar.html' %} {% endblock %} app PostDetailView: class PostDetailView(DetailView): model = UserPost app add_comment_to_post view: @login_required def add_comment_to_post(request,pk): post = get_object_or_404(UserPost,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.author = request.user comment.save() return redirect('feed:post_detail', pk=post.pk) else: form = CommentForm() return render(request,'feed/comment_form.html',{'form':form}) -
Empty request.POST in a Django view
When sending a POST request to the following view, the request.POST dictionary is empty: @csrf_exempt def created_query(request): if request.method == 'POST': print(request.POST) server = get_object_or_404(Server, pk=request.POST['server']) if server.owner == request.user: if server.created: return HttpResponse("created") else: return HttpResponse("pending") else: return HttpResponseForbidden else: return HttpResponseForbidden I have tried with multiple ways of generating the POST request such as this cURL request: curl --request POST \ --url http://localhost:80/created/ \ --form server=60 \ --form action=created I have checked the dictionary using a debugger as well as just printing it and it is always empty. I doubt it is a problem with the urls.py however here is the line in the file that handles this view: url(r'^created/', views.created_query, name='created'), Things we've already tried: Checking request content type Checking for use of raw_post_data -
django annotate models with an aggregate value based on query
Let's say I have the following model structure: Parent(): Child(): parent = ForeignKey(Parent) GrandChild(): child = ForeignKey(Child) state = BooleanField() num = FloatField() I'm trying to, from the Parent ViewSet, recover the following: The number of children. The SUM of the 'num' fields when 'state' is True. I can do the following: queryset = Parent.objects\ .annotate(child_count=Count('child'))\ .annotate(sum_total=Sum('child__grandchild__num')) This gives me (1) but instead of (2) it gives me the SUM for ALL grandchildren. How can I filter the grandchildren appropriately? -
Django filtering on Window functions
I have two Models in Django, A and B. Each A has several Bs assigned to it, and the Bs are ordered, which is done with a field B.order_index that counts upwards from zero for any A. I want to write a query that checks if there is any A where some of the Bs have a gap or have duplicate order_index values. In SQL, this could be done like this: SELECT order_index, RANK() OVER(PARTITION BY a_id ORDER BY order_index ASC) - 1 AS rnk WHERE rnk = order_index' However, when I try this in Django with this code: B.objects.annotate(rank=RawSQL("RANK() OVER(PARTITION BY a_id ORDER BY order_index ASC) - 1", [])).filter(rank=F('order_index')) I get an error saying: django.db.utils.ProgrammingError: window functions are not allowed in WHERE LINE 1: ...- 1) AS "rank" FROM "main_b" WHERE (RANK() OVE... In SQL this would be easy enough to fix by wrapping the entire thing in a subquery and applying the Where clause to that subquery. How can I do the same in Django? -
CeleryBeat suddenly skips scheduling few tasks while using Custom DatabaseScheduler
We are using django-celery==3.1.10 celery==3.1.20 python 2.7.13 Broker - RabbitMQ We have written a CustomDataBaseScheduler to schedule task which reads entries from a MySQL Table(Django Model) and schedules the task perfectly on given time (mysql Table column specifies the time). We are running CeleryBeat Process as init script. Our Scheduler Model has approx 3000 entries, most of them are getting scheduled every 5 mins and some are every 15 mins and few is hourly. But out of them some tasks are getting skipped i.e doesn't get schedule on time. This behaviour is randomly and happens to any of the tasks. While digging on beat logs, we found an MySQL exception on the logs, Traceback (most recent call last): File "/opt/DataMonster/datamonster/db_monster/scheduler.py", line 202, in schedule_changed transaction.commit() File "/opt/python-2.7.11/lib/python2.7/site-packages/django/db/transaction.py", line 154, in commit get_connection(using).commit() File "/opt/python-2.7.11/lib/python2.7/site-packages/django/db/backends/__init__.py", line 175, in commit self.validate_no_atomic_block() File "/opt/python-2.7.11/lib/python2.7/site- packages/django/db/backends/__init__.py", line 381, in validate_no_atomic_block "This is forbidden when an 'atomic' block is active.") Have Checked the error across multiple sites and it shows it realted to isolation level. We didn't found any other exception in BEAT logs. The isolation method used in MySQL is READ-UNCOMMITED Need help in digging this issue. -
restframework-jwt asks for username/password when using JWT token
I am using Django rest framework-JWT for authentication to handle the protected urls, I am trying to have the UserDetail view protected by using the IsAutchinted class from rest framework, however every time I try to send the generated token I am getting the following response { "username": [ "This field is required." ], "password": [ "This field is required." ] } I have included Authorization header and as I have set in my header prefix to "JWT" curl -H "Authorization: JWT <token>" -X PUT http://localhost:8000/user/3/ -d '{"first_name":"curl_test"}' the obtain JWT token, refresh,verfiy urls are working fine and generating links, I just can't get JWT to verify username and password using a token instead of the username and password. here is my view for user details class UserDetail(APIView): permission_classes = (IsOwner,IsAuthenticated,) """ Retrieve, update or delete a user instance. """ def get_object(self, pk): try: return User.objects.get(pk=pk) except User.DoesNotExist: raise Http404 def get(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user) return Response(serializer.data) def put(self, request, pk, format=None): user = self.get_object(pk) serializer = UserSerializer(user, data=request.data) if serializer.is_valid(): serializer.save() user = Profile.objects.get(id=pk) user.profile.updated = timezone.now() user.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) def delete(self, request, pk, format=None): user = self.get_object(pk) user.delete() … -
Django model enum field creates new migrations every time makemigrations is run, even though unchanged
As part of a user preferences model: DAILY = "d" WEEKLY = "w" FORTNIGHTLY = "f" MONTHLY = "m" DISABLE = "x" EMAIL_FREQUENCY_CHOICES = { (DAILY, 'Daily'), (WEEKLY, 'Weekly'), (FORTNIGHTLY, 'Fortnightly'), (MONTHLY, 'Monthly'), (DISABLE, 'Disabled'), } email_frequency = models.CharField( max_length=1, choices=EMAIL_FREQUENCY_CHOICES, default=WEEKLY, ) Every time I run makemigrations a new migration file is created for this model, with console output of: - Alter field email_frequency on profile Looking at the migration files, it seems like each migration is a different permutation of the enum dictionary. Any ideas why this is happening? -
How to deploy Django app on Azure?
I have posted before but not received an answer. I have a Django web app developed in VS2017. I have published it but getting a server error. Can you please advise how I need to configure my web.config file so that it works? Currently it's: <?xml version="1.0" encoding="utf-8"?> <configuration> <appSettings> <add key="PYTHONPATH" value="D:\home\site\wwwroot"/> <add key="WSGI_HANDLER" value="app.wsgi_app"/> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.webServer> <handlers> <add name="PythonHandler" path="*" verb="*" modules="FastCgiModule" scriptProcessor="D:\home\Python361x64\python.exe|D:\home\Python361x64\wfastcgi.py" resourceType="Unspecified" requireAccess="Script"/> </handlers> </system.webServer> </configuration> but I am getting an server error and Python log file says: D:\home\Python361x64\python.exe: can't open file 'D:\home\site\wwwroot\runserver.py': [Errno 2] No such file or directory I would appreciate any help. -
proper naming convention in Django
I am using Django 1.11 I have created an app country and inside country/models.py class Country(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=50) pub_date = models.DateTimeField('date published') and included the model in admin.py from django.contrib import admin from country.models import Country # Register your models here. admin.site.register(Country) When I visited http://127.0.0.1:8000/admin, it shows The spelling of country has been pluralized to Countriys which is wrong. What is proper naming convention to prevent such mistakes? -
Validate serializer object without the field need for validation
I have a following viewset, class VoteViewSet(viewsets.ModelViewSet): serializer_class = VoteSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): serializer.save(created_by=self.request.user) def get_queryset(self): return Vote.objects.filter(created_by=self.request.user) serializer class VoteSerializer(serializers.ModelSerializer): class Meta: model = Vote fields = ('id', 'request') read_only_fields = ('id',) and model. class Vote(models.Model): created_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='votes') request = models.ForeignKey(Request, related_name='votes') class Meta: unique_together = [('request', 'created_by')] I am trying to save user's vote but I get IntegrityError: UNIQUE constraint failed when I post a vote for the same request twice. I can fix the error by adding created_by to VoteSerializer however I don't want to have it in my serialized data. What are my options? -
Adding a conditional to my code causes VueJS code to not render
I have the following code in Vue; /* Does early detection on if the user is logged in or not. If the user is not logged in, this code is passed over. This is done to make rendering and compilation of the code faster by filtering out unneeded elements. */ // Debug. Brackets will be placed around 'user-home component later' if djangoUser === "AnonymousUser" { Vue.component('user-home', { template: `<div class=""> <a href="#" style="margin:0px; padding:0px;"> <img class="avatar-img" src="https://i.vimeocdn.com/portrait/58832_300x300"> </a> </div>`, }); var userHomeDiv = new Vue({ el: "#user-home-div", }) } I want to have the conditional there so that if the user isn't logged in, then those elements won't be processed. However, when I add that conditional, whether or not it evaluates to true, it causes all of the custom elements and Vue code to disappear from my HTML. When I remove it, everything works as normal. What could be causing this to happen? -
adding instances from django admin
This is how my classes look. class School(models.Model): state = models.ForeignKey(State, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) cluster = models.ForeignKey(Cluster, on_delete=models.CASCADE) school_name = models.CharField(max_length=250) facilitator = models.CharField(max_length=250) f_number = models.IntegerField() f_email = models.EmailField() school_logo = models.FileField(default='') school_strength = models.IntegerField() In which state, region, cluster are also classes. I have tried to create a network of schools with classification in 3 levels i.e state, region, cluster. I have assumed that when I add schools from django admin I thought it might filter regions if I select state and filter clusters when I select region so that it would be easy. But It doesn't seem to work. Though after selecting a particular state and region while adding a school in the cluster dropdown all the clusters from all the states and regions are coming. Is there a solution for this or as of now we don't have such option in django? -
Where should Django project files be located in a production server to allow multiple authorized users to manage?
If the project will be pulled from git, where should it go? I also need to give multiple authorized users to access and manage the project. Also, how should virtualenv be handled on this scenario? My default virtualenv location would be ~/.env so other users wouldn't be able to access. -
how to automatically add a foreign key in django model form
models.py class OtherData(models.Model): title = models.CharField(max_length=120) user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='other_data') class ProductImage(models.Model): other_data = models.ForeignKey(OtherData, verbose_name='Select title') user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='product_image') image = models.FileField(blank=True, null=True, upload_to='images/') featured = models.BooleanField(default=False) What I wanted is add images to otherdata instance automatically. I tried writing the views.py as follows. def image_create(request, id=None): other_data = get_object_or_404(OtherData, id=id) form =ImageForm(request.POST or None) if form.is_valid(): instance=form.save(commit=False) instance.other_data = other_data instance.save() But getting the error "DoesNotExist at /image/add/ OtherData matching query does not exist" -
saving date and time of user response in django model field
i am making this app in django where on a particular html template if the user selects a particular response by clicking on it, the date and time at which the user clicked that particular response is stored in my database. part of models.py class userresp(models.Model): rid=models.Integerfield(unique=True,default=0) uid=models.Foreignkey(user,to_field='uid',on_delete=models.CASCADE) resp=models.ForeignKey(elementsound,to_field='csid',on_delete=models.CASCADE) date=models.DateTimeField() time=models.DateTimeField() so how do i store that? and what will be the extra parameters in the DateTimeField of both? -
django get the id value
I have asked this question plenty of times and no one seems to know the answer...i did get answers that had nothing to do with my question. How can i get the table_id value from the html template and then once i get the table_id use that to get the table name using that id. I have 4 tables.. 1 table contains the other 3 tables names and the date they were created. The Primary table structure contains: id (primary key) Name (the tables names in that DB) Date (the date the tables were created) In my table_base.html i use the fucntion table_base to show me all the tables that in there. When i click on a table i get the id like this http...../tables/(table_id)/details Now i need to use that value that i get in table_id to get the the table name and then get all the content of that table using the class Details from views.py views.py def table_base(request): table_name = Crawledtables._meta.db_table list_tables = Crawledtables.objects.order_by('id') return render(request, 'tables/table_base.html', {'table_name': table_name, 'list_tables': list_tables}) class AboutDetail(DetailView): model = Crawledtables pk_url_kwarg = 'table_id' template_name = 'tables/table_list.html' def __init__(self, **kwargs): super(AboutDetail, self).__init__(**kwargs) def get_object(self): if 'table_id' not in self.kwargs: return Crawledtables.objects.get(id=1) else: … -
pycharm The red wave line cannot be filled
Pycharm imports custom module to run normally but has red line hint, and cannot use code completion function, what should be set? from datetime import datetime from django.db import models from courses.models import Course from users.models import UserProfile The imported packages have red underlining, and cannot be complemented, but the code is running normally, such as and solving -
ValueError at /feed/post/5/comment/ The view feed.views.add_comment_to_post didn't return an HttpResponse object. It returned None instead
I am using this exact code in another project, the only difference is that I have changed the model names, urls patterns, and template names since it is a different project. However, I am getting this error and I have no idea why. I am trying to bring the user to a detail page that has both the post and any comments on the post, as well as a link that takes to a page that allows the user to add a comment to the post. app Views.py: @login_required def add_comment_to_post(request,pk): post = get_object_or_404(UserPost,pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('feed:post_detail', pk=userpost.pk) else: form = CommentForm() return render(request,'feed/comment_form.html',{'form':form}) userpost_detail.html (post_detail in urls) {% extends 'base.html' %} {% block content %} <h1 class="posttitle">{{ userpost.title }}</h1> <p class="postcontent">{{ userpost.post_body }}</p> {% if request.user.is_authenticated and request.user == post.author %} <a class="link" href="{% url 'feed:edit_post' post.id %}">Edit Post</a> {% endif %} <hr> <a href="{% url 'feed:add_comment' userpost.id %}">Add Comment</a> <div class="container"> {% for comment in post.comments.all %} <br> {% if user.is_authenticated or comment.approved_comment %} {{ comment.create_date }} <a class="btn btn-warning" href="{% url 'comment_remove' pk=comment.pk %}"> <span class="glyphicon glyphicon-remove"></span> </a> <p>{{ comment.comment_body }}</p> <p>Posted … -
Create a form that uses attributes from 2 different models
I'm trying to create a form that blends elements from a couple different places. I think the best way to do this may be 2 different forms and showing them on the same page, unless someone else can help me pop it all into one form? I see no problem using 2 forms but I'm kind of unsure how to proceed (and maybe I don't need to!). I have 2 classes that are somewhat related: Person(User) and Friend and they share PersonBenefits. models would look like this: class PersonBenefit(models.Model): benefit = models.ForeignKey(Benefit, null=True) user = models.ForeignKey(User) class Friend(models.Model): first_name = models.CharField(max_length=40) last_name = models.CharField(max_length=40) has_benefit = models.BooleanField(default=False) ben_id_num = models.CharField(max_length=10, blank=True, null=True) person = models.ForeignKey(User) #good, better, best class BenefitType(models.Model): name = models.CharField(max_length=25) def __str__(self): return self.name class Benefit(models.Model): type = models.ForeignKey(BenefitType) name = models.CharField(max_length=25) The forms.py looks something like this: class GoodBenefitForm(forms.Form): benefit = forms.ModelChoiceField( queryset=Benefit.objects.filter(type__name='Good'), widget = forms.Select(attrs={'class':'g-1-3'}) ) # THIS SHOWS A LIST OF ALL THE FRIENDS FOR THIS USER - DISPLAYS THEIR NAMES NICELY WITH CHECKBOXES friend = forms.ModelMultipleChoiceField( queryset = Friend.objects.none(), widget = forms.CheckboxSelectMultiple(), ) # I WANT THIS TO BE A BUNCH OF TEXTBOXES INSTEAD OF CHECKBOXES - ONE FOR EACH FRIEND FOR THE … -
What is the easiest way to allow users of my Django site to search for posts that I've written on the site?
I don't want to write a search algorithm and I suspect that there must be a library or script to do this. Are there any suggestions? Thank you very much. -
saving audio files in django table(model)
I want to store audio files under an attribute 'soundsrc' in the model elementsound. A part of models.py is given below: models.py(code snippet) class elementsound(models.Model): cdid=models.IntegerField() soundsrc=models.FileField() sounddesc=models.CharField(max_length=20) how do i do that? what changes have to be made in settings.py? please explain in detail.