Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Mark as Read "Notifications"
I'm working on a school project. Right now any user can ask a question. In order to notify all the users when any users asks a question I've created a new app & notifying them through the simple 'view' whenever a question is asked. But it's just plain notifications yet. How can I mark them read once a user opens the Notification tab? Just like on social networks! -
Turning a Page Object Into Its Page Derived Object
I am new to wagtail but I keep running into something that I am sure there is a better solution for than what I am currently doing. Lets say I have a Wagtail Page called ProductPage. Lets say this page has a field that is another ProductPage called related_product. When I try to access this page in my templates or context by the following code, self.related_product it returns a Page object instead of a ProductPage object. Because of this, I cannot get to the fields that I actually want to without transforming it into a ProductPage object by way of, ProductPage.objects.get(page_ptr_id=self.related_product.id) There has to be a way to transform this without this above query. -
Can someone link me to an example site that uses django-filter?
I have found the docs, which are very helpful, but I want to see how it looks in practice. Does anyone know of a tutorial where it is used, or an active site? Thanks! -
Returning Related (1:M) Django Objects with many as a List
I'm new to Django and I'm building a Document Visibility/Status application. Each document, called an "Indent", has some "Attributes", and these attributes have multiple "Status". On the dashboard of the application, I need to dynamically render the attributes as columns, and the statuses as choices in a dropdown list. I'm thinking that I'll need to return a dictionary as follows - but if you have a better suggestion, please let me know. { 1 : ['status1','status2', 'status3'], 2 : ['status1','status2', 'status3'], ... } Where the number is the attribute ID. Here are my models: class Indent(models.Model): dateCreated = models.DateTimeField(auto_now=True) indentNumber = models.CharField(max_length=75) creator = models.ForeignKey(settings.AUTH_USER_MODEL) def __str__(self): return '%s' % (self.indentNumber) class Meta: verbose_name = 'Indents' verbose_name_plural = "Indents" class Files(models.Model): fileLink = models.FileField(upload_to='indents/', null=True) #Add 'indents/userID' indent = models.ForeignKey(Indent, on_delete=models.CASCADE) def __str__(self): return '%s' % (self.indent) class Meta: verbose_name = 'Files' verbose_name_plural = "Files" """ TO-DO REMOVE NULL CONSTRAINT """ class Attribute(models.Model): name = models.CharField(max_length=75) user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True) def __str__(self): return '%s' % (self.name) class Meta: verbose_name = 'Attributes' verbose_name_plural = "Attributes" """ TO-DO For the names of Status objects, it needs to be more descriptive and accurate """ class Status(models.Model): name = models.CharField(max_length=255) attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) … -
Exception Value: no such table: example_post
I have a little issue of trying the exemple file from https://github.com/zhebrak/django-statsy OperationalError at / no such table: example_post Request Method: GET Request URL: http://localhost:8000/ Django Version: 1.11.5 Exception Type: OperationalError Exception Value: no such table: example_post Exception Location: /home/jeremie/.virtualenvs/statsy/local/lib/python2.7/site-packages/django/db/models/sql/compiler.py in execute_sql, line 894 Python Executable: /home/jeremie/.virtualenvs/statsy/bin/python Python Version: 2.7.12 Python Path: ['/home/jeremie/django-statsy', '/home/jeremie/.virtualenvs/statsy/lib/python2.7', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/plat-x86_64-linux-gnu', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-tk', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-old', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/lib-dynload', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/home/jeremie/.virtualenvs/statsy/local/lib/python2.7/site-packages', '/home/jeremie/.virtualenvs/statsy/lib/python2.7/site-packages', '/home/jeremie/django-statsy'] Server time: Fri, 15 Sep 2017 15:13:34 -0500 Here is what I have done so far : git clone https://github.com/zhebrak/django-statsy.git mkvirtualenv statsy cd django-statsy workon statsy pip install -r requirements.txt python manage.py makemigrations python manage.py migrate python manage.py runserver I just want to enter inside the example to see what type of result and test out the app itself. Why do I have the problem? Do you recommend this app if I am working in a project using Django 1.10 and python 2.7? -
Django get latest "multiple" elements
I have these two models: class SeoKeys(models.Model): keyword = models.TextField(blank=True, null=True) key_nbr = models.IntegerField(blank=True, null=True) status = models.TextField(default='example_keyword', blank=True, null=True) class SeoMetrics(models.Model): parent_key = models.ForeignKey('SeoKeys', on_delete=models.CASCADE) seo_url = models.TextField(blank=True, null=True) url_found = models.TextField(blank=True, null=True) position = models.IntegerField(blank=True, null=True) date = models.DateField(auto_now=True, blank=False, null=False) Now I'm trying to get the latest metrics for each SeoKey, however a SeoKey could have multiple seo_url for each day. In other words I need to get for each SeoKey, the latest SeoUrl(s). The closer I get is with this code: key_status = ['example_keyword', 'deactivated', 'demo'] all_keywords = SeoKeys.objects.all().exclude(status__in = key_status) for key in all_keywords: #print(key.status, key.email) all_metrics = key.seometrics_set.filter(parent_key=key).order_by('parent_key', '-date').distinct('parent_key') for metrics in all_metrics: print('Sending {} for date {} with parent: {}'.format(metrics.seo_url, metrics.date, metrics.parent_key.id)) But it does not include the case that a user has multiple seo_urls. How can I manage to get the latest for a group? -
How customize inline in django admin to show unique entry in the OneToOne field drop down.
class Question(models.Model): question_name = models.TextField(max_length=200) positive_answer = models.PositiveIntegerField(default=2) negative_answer = models.PositiveIntegerField(default=1) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) def __unicode__(self): return u'%s' % self.question_name class Task(models.Model): task_name = models.CharField(max_length=100) description = models.TextField(max_length=2000) added_date = models.DateTimeField(auto_now_add=True) status = models.BooleanField(default=True) def __unicode__(self): return self.task_name class TaskAssignment(models.Model): answer_choice = models.CharField(max_length=5, choices=ANSWER_CHOICES, null=True) question = models.ForeignKey(Question, related_name='%(class)s_requests_created') task = models.OneToOneField(Task, related_name='%(class)s_requests_created') I have these three models. First clients added some task on task admin. After that he is creating questions at the time of question creation he wants to assign some tasks for that question. For this am adding "TaskAssignmnet" model as inline in questions admin. But problem is that with this "task" field shows all tasks in drop downs but my I wants to show only those tasks which are not assigned to question. -
Iterate through JSON data in Django template
I am having trouble iterating through some JSON data that I managed to import into my Django Wagtail project. I want to list travel advisories on a website that are pulled in from here: http://data.international.gc.ca/travel-voyage/index-updated.json I was able to do this in my model like so: import requests def get_context(self, request): response = requests.get('http://data.international.gc.ca/travel-voyage/index-updated.json') json_response = response.json() data = json_response['data'] context = super(TravelAdvisoriesPage, self).get_context(request) context['data'] = data return context I am now unsure of how to get the data into my template. I am able to pull in all of the data using {{ data }}. But how do I pull out specific items from that JSON data? I want to grab both the English and French name, url-slug, advisory-text, etc. And all of those are nested within data > country code > language > item within the JSON structure. I have tried something like: {% for country in data %} {{ data[country].eng.name }}<br /> {% endfor %} This is giving me errors like Could not parse the remainder: '[country].eng.name' from 'data[country].eng.name'. How do you grab these in the template? -
Django page update no ajax or comet
I'm making a small app for internal use between 3 people. the idea is to have a page where user can upload files and data ( more specifically images.) to the database and a second page where the information the user uploaded in the first page will be visible without having to manually refresh the page. I have read about comet and ajax and I think having a function check the Db every certain time is not what I'm looking for. Since there will be almost no updates in the DB. maybe every 3 to 4 months the user might update a new image. -
Include values of different table in django models
I'm trying to check if files reported in one system exist in a different system. The models belong to different tables in different databases. They have no relationship other than the name in common. I'm using django rest framework to serialize the values of one table and I'd like to include the values of the other table in one efficient way. The way I'm currently doing, makes too many queries! My question is: Is there a way to improve this performance issue? Here is an example of what I have //model1 class Product(models.Model): name = models.CharField(max_length=50) //model2 (different database) class Files(models.Model): name = models.CharField(max_length=50) filename = models.CharField(max_length=50) And my view set is class ProductViewSet(viewsets.ModelViewSet): queryset = Inventory.objects.all() serializer_class = ProductSerializer I managed to get the result as I said (not efficiently, though) in two different ways: 1) Including the fields in the serializer class ProductSerializer(serializers.ModelSerializer): has_png = serializers.SerializerMethodField('has_png') has_jpg = serializers.SerializerMethodField('has_jpg') def has_png(self, product): // I wish I could avoid this code duplication too... // I'm basically using the same code in two functions files = Files.objects.filter(name=product.name) filtered_files = files.filter(file_format__startswith='png') return filtered_files.exists() def has_bam(self, product): files = Files.objects.filter(name=product.name) filtered_files = files.filter(file_format__istartswith='jpg') return filtered_files.exists() Meta: model = Product 2) Including properties … -
django-bootstrap3-datetimepicker and Dango 1.11
Nkunihiko django-bootstrap3-datetimepicker looks abandoned and doesn't support for Django 1.11 I see a lot of pull requests to Nkunihiko repo, but they doesn't help. Is where an actual fork or some another django package for bootstrap-datetimepicker? -
Is there any way to build an interactive terminal using Django Channels with it's current limitations?
It seems with Django Channels each time anything happens on the websocket there is no persistent state. Even within the same websocket connection, you can not preserve anything between each call to receive() on a class based consumer. If it can't be serialized into the channel_session, it can't be stored. I assumed that the class based consumer would be persisted for the duration of the web socket connection. What I'm trying to build is a simple terminal emulator, where a shell session would be created when the websocket connects. Read data would be passed as input to the shell and the shell's output would be passed out the websocket. I can not find a way to persist anything between calls to receive(). It seems like they took all the bad things about HTTP and brought them over to websockets. With each call to conenct(), recieve(), and disconnect() the whole Consumer class is reinstantiated. So am I missing something obvious. Can I make another thread and have it read from a Group? -
"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?