Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
count the number of posts by a user - django
I am trying to clone a social media website. Can someone please suggest me how to count the total number of posts by a particular user ? Thanks models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.conf import settings from django.utils.text import slugify from blog.utils import unique_slug_generator from django.contrib.auth import get_user_model import uuid User = get_user_model() class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1) text = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) likes = models.ManyToManyField(User, related_name='post_likes', blank = True) def get_like_url(self): return reverse("posts:like-toggle", kwargs={"slug": self.slug}) def get_api_like_url(self): return reverse("posts:like-api-toggle", kwargs={"slug": self.slug}) def publish(self): self.published_date = timezone.now() self.save() def approve_comments(self): return self.comments.filter(approved_comment=True) def get_absolute_url(self): return reverse("post_detail",kwargs={'pk':self.pk}) def __str__(self): return self.title -
TypeError 'Profile' object not iterable
I don't know where to look any more. I have checked all the places related to the error, but i can't seem to find the cause. I keep getting the following: TypeError: 'Profile' object is not iterable I don't know if it occurs for all pre-created accounts or in general. I tried to create a new profile, but a new error occurs. Just help a noob, please. Files are located on git hub https://github.com/VictorLeRed1275/my-first-blog -
Django loading page that uses signals?
I have a long process wherein my application communicates with a server, saves a model based on the server's response, and restarts its communication. I'd like to present the user with a loading page which updates whenever a model is saved. For example: Working on request 1... Saving model 1... Working on request 2... Saving model 2... Finished task. [Back to Homepage] I've read through this(jango - show loading message during long processing) and its links; the first suggestion would not work, and the second requires threading, caching, etc. I've also read through the documentation for Signals. Let's say the model which is saved is ModelAfterResponse. My view might look like this: @receiver(post_save, sender=ModelAfterResponse) def loading_page(sender, **kwargs): model_name = kwargs['instance'].name return render(request, 'name/javascript_template.html', {"name": name}, content_type="application/x-javascript") And the javascript_template.html might look like this: <script> $('#some_loading_page_specific_div').innerHTML = "Working on " + {{ name }} </script> This is just quick mock-code—but do I have the gist of it? When I decorate a function as above, and do something simple like return HttpResponse(":D"), nothing happens—everything continues running and :D is nowhere to be found. I believe I'm on the right track. Is there a simple way to accomplish what I'm looking for? -
Getting values from a Django JSONField
I'm trying to retrieve values from a JSONField in my model, but i'm getting an error: 'Api' object has no attribute 'openapi_spec__info__title' class Api(models.Model): ''' Model to hold infomation on the API ''' # JSONB field to hold the OpenAPI spec openapi_spec = JSONField() # Derive product name from the OpenAPI spec, since it's a mandatory field def _get_product_name(self): return self.openapi_spec__info__title product_name = property(_get_product_name) According to the Django docs '__' is the correct way to filter on the JSON data, but maybe it's not the correct way to access it? {"info": {"title": "Test API", "version": "1.0.0"}} -
How to change class attributes using a method?
I know this is maybe a dumb question but I haven't found a solution yet. I have a Django model class who has some default attributes, and I want to change the value of the complete variable by calling a function: class Goal(models.Model): text = models.CharField(max_length=500) date = models.DateTimeField(auto_now=True) complete = False def set_complete_true(): complete = True But after calling set_complete_true() the complete variable still False, doesn't change. Thanks in advance! -
Django: pull pk from form submitted data into subsequent URL
So I have one page which contains a form so that the user can submit data to the database and a second page which contains specific fields from that record by using the assigned pk value. My question is whether I can use the submit button to post the data to the database and then immediately load up a URL with the pk value from that submitted record to use some of the fields? Or would this need to be done in 2 steps? i.e. 1. insert data into DB, then 2. load the URL with the relevant pk.. urls.py: from django.urls import path from django.conf.urls import url, include from django.views.generic import TemplateView from .views import * from . import views urlpatterns = [ url(r'^$', UserView.as_view(), name='user_new.html'), # form temporarily directs here after saving the data to the DB url(r'^thanks/$', TemplateView.as_view(template_name='thanks.html'), name='thanks'), # I would like it to go here instead path('adherence_agreement/<int:id>', views.adherence_agreement, name='adherence_agreement'), ] views.py: from django.views.generic.edit import FormView,CreateView class UserView(CreateView): template_name = 'user_new.html' form_class = UserForm success_url = 'thanks/' def post(self, request, *args, **kwargs): self.object = None if request.method == 'POST': form = UserForm(data=request.POST) if form.is_valid(): form.save() return self.form_valid(form) else: return self.form_invalid(form) else: form = UserForm() def adherence_agreement(request, … -
Word access denied with win32 python
I use Python 3.6 and Django 1.11. I created a Word document with MailMerge and it was ok. Right now I need to save this document as a pdf document. import win32com.client as win32 from os import path word = win32.DispatchEx("Word.Application") filedoc='c:\\growthtech\\Capturar6.docx' filepdf='c:\\growthtech\\Capturar6.pdf' in_file = path.abspath(filedoc) out_file = path.abspath(filepdf) doc = word.Documents.Open(in_file, 'rb') doc.SaveAs(new_file, FileFormat=17) doc.Close() word.Quit() It occurred the error bellow in line "doc = word.Documents.Open(in_file, 'rb')". >>> doc = word.Documents.Open(in_file, 'rb') Traceback (most recent call last): File "<console>", line 1, in <module> File "<COMObject <unknown>>", line 8, in Open pywintypes.com_error: (-2147352571, 'Tipo não correspondente.', None, 2) I appreciate any help. -
Safely importing models in django's middleware
I have been trying to import a model in a middleware process function but I am getting the error: Value: Model class x doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS I am guessing the problem is that the application setup is not complete, however, all my attempts to solve this have hit a wall. middleware.py function from notifications.models import Notification ... class CheckNotificationMiddleware(object): """ Checks clicked notification to mark it as read """ def process_request(self, request): if request.user.is_authenticated(): notification_id = request.GET.get('notification_id') if notification_id: AppConfig.get_model('Notification') try: notification = Notification.objects.get( pk=notification_id, status=0, recipient=request.user) notification.status = 1 notification.save() except ObjectDoesNotExist: pass settings.py INSTALLED_APPS = ( ... 'notifications', ... ) I have tried a couple of things including... from django.apps import AppConfig AppConfig.get_model('Notification') I am using Django version 1.11 and python 2.7 -
Django app hosting on Azure
I have created a Django sample app and want to host it as Azure app service. I have followed some articles but not got success with anyone. Is there step by step documentation to do so or can anyone help me out in this? I have created an app service on Azure Connected it with ftp There was a single file named hostingstart.html inside wwwroot I have copied the sample app in the wwwroot folder but unable to browse the app, the azure app link showing the default page -
EOFError: marshal data too short
Why do I get the following error when I run the django server and how do I fix it ? : EOFError: marshal data too short -
Calendar widget for django using crispy forms
I would like to use a calendar widget in my crispy-forms. I've found this which looks like a great package but i cannot get it working, it shows up like a normal text field and i don't know why, my template looks something like: {% load static %} <!DOCTYPE html> <html> <head> <title>App</title> <link href = "{% static 'css/bootstrap.min.css' %}" rel ="stylesheet"> </head> <body> <div class="mx-auto center-block w-50 p-3"> {% block content %} {% load crispy_forms_tags %} {% crispy form %} {% endblock %} </div> <script src = "{% static 'js/bootstrap.min.js' %}"></script> <script src = "{% static 'js/jquery-3.3.1.min.js' %}"></script> </body> </html> Are there any options there? Not posting the rest of the code because it looks very much like the one in the docs in the like above or here. -
view function isn't returning anything
the problem here is that when the form is posted the create_usecase function runs and then it redirects to another url this url runs quest function in the view and executes every line in the function but it doesn't make any return at all the create-usecase template stays as it is so the template is like this: <form> <div class="row"> <div class="input-field col s6 offset-s3"> <div class="row"> <div class="col m2 s4"> <p>Case name</p> </div> <div class="col m10 s8"> <input id="usecase_name" type="text" name="usecase_name" placeholder="Case name"> </div> </div> </div> <div class="input-field col s6 offset-s3"> <select id="category-list"> <option value="" disabled selected>Choose your Category</option> <option value="1">University/College</option> <option value="2">Hospital</option> <option value="3">Business Organizations</option> </select> <label>Categories</label> </div> </div> <div id="subcategory-list" class="row"> <div class="col s6 offset-s3"> {% if data %} <h6>Sub Category</h6> {% for item in data %} <div class="form-check"> <input class="form-check-input" onchange="subCategoryValue('{{ item.username }}')" type="radio" name="sub-category" id="{{ item.username }}" value="{{ item.username }}"> <label class="form-check-label" for="{{ item.username }}"> {{ item.username }} </label> </div> {% endfor %} {% endif %} </div> </div> <div class="row center"> <button type="submit" id="nextBtn" class="btn waves-effect waves-light orange">Next</button> </div> </form> <script type="text/javascript"> var flag = '' function subCategoryValue(v) { flag = v; $('#nextBtn').show(); } $(document).ready(function(){ $('#nextBtn').hide(); $('#category-list').change(function(e){ e.preventDefault(); if($('#usecase_name').val() !== '') { $.ajax({ type: 'POST', … -
Dynamically creating class variables in python
I new to python and Django. And I am trying to take the values from HTML sliders to my python. For instance, I have two sliders in page1.html and three sliders in page2.html I do have form classes in my forms.py for handling or taking these values which looks like this: class p_q(forms.form): p = forms.IntegerForm() q = forms.IntegerForm() class p_d_q(forms.form): p = forms.IntegerForm() d = forms.IntegerForm() q = forms.IntegerForm() Assuming p,d,q from page2.html and p,q from page1.html. Instead of having two classes, I have tried with class p_d_q() HTML page which is giving gives two values (page1.html) but it didn't work. My question is there any way could handle those requests dynamically with just one class. Rather than hardcoding it. -
How can I allow my users to post stuff on a social network I made using Django?
I'm making a social network site using Django, and I've got nearly everything ready. But I still can't get my users to post stuff like text and images. Any help? How can I do this? -
Django queryset: Build a dictionary from a queryset, with common elements
I'm trying to construct a dictionary from my database, that will separate my data into values with common time stamps. data_point: time: <timestamp> value: integer I have 66k data points, out of which around 7k share timestamps (meaning the measurement was taken at the same time. I need to make a dict that would look like: { "data_array": [ { "time": "2018-05-11T10:34:43.826Z", "values": [ 13560465, 87856595, 78629348 ] }, { "time": "2018-05-11T10:34:43.882Z", "values": [ 13560689, 78237945, 92378456 ] } ] } There are other keys in the dictionary, but I'm just having a bit of a struggle with this particular key. The idea is, look at my data queryset, and group up objects that share a timestamp, then add a key "time" to my dict, with the value being the timestamp, and an array "values" with the value being a list of those data.value objects I'm not experienced enough to build this without looping a lot and probably being very innefficient. Some kind of "while timestamp doesn't change: append value to list", though I'm not sure how to go about that either. Ideally, if I can do this with queries (should be faster, right?) I would prefer that. -
apps get_models only custom models
In my django rest project I have created total 5 apps with corresponding models (Authentication (-> Profile), crc (-> Card, Responsibility, Collaborator), project (-> Project), scenarios (-> Scenario) and tasks (-> Task)) each app has I want to list all the models and their corresponding methods that I have written. I tried import django.apps print(django.apps.apps.get_models()) but this lists all the classes it knows about: [<class 'django.contrib.admin.models.LogEntry'>, <class 'django.contrib.auth.models.Permission'>, <class 'django.contrib.auth.models.Group'>, <class 'django.contrib.auth.models.User'>, <class 'django.contrib.contenttypes.models.ContentType'>, <class 'django.contrib.sessions.models.Session'>, <class 'rest_framework.authtoken.models.Token'>, <class 'django.contrib.sites.models.Site'>, <class 'allauth.account.models.EmailAddress'>, <class 'allauth.account.models.EmailConfirmation'>, <class 'authentication.models.Profile'>, <class 'project.models.Project'>, <class 'tasks.models.Task'>, <class 'scenarios.models.Scenario'>, <class 'crc.models.Card'>, <class 'crc.models.Responsibility'>, <class 'crc.models.Collaborator'>] How can I retrieve only those models and their corresponding methods? -
Django, using "|": Expression tree is too large (maximum depth 1000)
I'm trying to concatenate many querysets together. I tried out the marked answer from this question a while back, but that didn't work in my case. I needed to return a queryset not a list. So I used the |, from the second answer. This worked fine at the time, but now that I'm trying to use it again for something else I get the following error: Expression tree is too large (maximum depth 1000) I originally thought that | would concat the querysets, but after reading the docs it appears that it concats the actual query. And that this specific problem occurs if the query becomes too long/complex. This is what I'm trying to do: def properties(self, request, pk=None): project = self.get_object() if project is None: return Response({'detail': 'Missing project id'}, status=404) functions = Function.objects.filter(project=project) properties = Property.objects.none() for function in functions: properties = properties | function.property_set.all() return Response([PropertySerializer(x).data for x in properties]) Since the functions query returns roughly 1200 results, and each function has about 5 properties, I can understand the query becoming too long/complex. How can I prevent the query from becoming too complex? Or how can I execute multiple queries and concat them afterwards, while keeping … -
How to Create my Own GeoDjango PointField Field-level validation
I'm currently using GeoDjango's PointField in my Project and would like to create my own field-level validation for the field as i want Users to be able to input a string such as '30,10' the change that string into the "Point(30,10)" that the field requires. My current model : class Location(models.Model): name = models.CharField(max_length=255) geopoint = PointField( null=True, blank=True, max_length=255, default=None, My serializer: class LocationSerializer(serializers.ModelSerializer): """ Location serializer class """ def validate_geopoint(self,value): #Doesnt run / validate # pylint: disable=too-few-public-methods class Meta(object): """ Meta options for LocationSerializer """ model = Location fields = [ 'id', 'name', 'country', 'geopoint', 'radius', 'shapefile', 'parent', 'created', 'modified' ] -
Visual Studio Code: Intellisense not working
My Visual Studio Code's Intellisense is not working properly. Every time I try to use it with Ctrl + Shift, it only displays a loading message. I'm using Python (with Django) and have installed ms-python.python. I also have Djaneiro. It is still not working. What seems to be the problem here? -
How to display a list in django template?
A list is created. I want to display the list in the template. search_query=[] #... #code here #... return render(request, 'query/list.html', {'search_query'}) But it is giving this error - "context must be a dict rather than set." In the list.html {% for c in suggest_search_query%} <p>{{c}}</p> {% endfor %} -
Django Viewset returning different data between shell/tests and actual requests
Simplified model structure (I'm leaving out important bits, obviously, there are good reasons these are in different models): class Contact(models.Model): receive_marketing = models.DateTimeField(null=True, blank=True) class User(models.Model): email_hash = models.CharField(max_length=255) contact = models.ForeignKey(Contact) This stores whether interested people want to receive email offers, etc. We have a page where people can change these settings, which uses the hash to identify the person so people can't change other's settings, see who's signed up, etc. The values are fully alpha-numeric. The view looks like this: class ContactViewSet(viewsets.ModelViewSet): queryset = Contact.objects.all() permission_classes = (AllowAny, ) def get_queryset(self): if self.request.user.is_staff: return ContactViewSet.queryset token = self.request.query_params.get('ref') return Contact.objects.filter(user__email_hash__isnull=False, user__email_hash=token).distinct() So staff members can see and access all Contact entries, but otherwise we'll return a queryset with one entry, the Contact linked to a User with an email_hash that matches the ref query param. This passes all the unittests checking various combinations of staff and not, with and without the ref query param, etc. If I log into our remote environment and start a django shell, I can do the following: >>> from user.views import ContactViewSet >>> from rest_framework.test import APIRequestFactory >>> factory = APIRequestFactory() >>> view = ContactViewSet.as_view({'get': 'list'}) >>> request = factory.get('/contact/?ref=a-valid-hash') >>> view(request).rendered_content b'{"count":1,"next":null,"previous":null,"results":[{"id":222,"receive_marketing":"2018-05-15T14:11:13.449719Z"}]}' … -
Django - Render a varible which stored in database field
In my application, I will ask user to input some text with variable and store it into database. like this... Url id | url | ---+-----------------------------------+ 1 | http://example.com/?aaa={{para1}} | 2 | http://example.com/?aaa={{para2}} | 3 | http://example.com/?aaa={{para2}} | 4 | http://example.com/?aaa={{para1}} | And there is a table with the actual value of those parameter. Parameter id | para | ---+-----------+ 1 | 932580234 | 2 | 865234932 | I want to render a html and replace the {{para1}} or {{para2}} on it. views.py def userpage(request): url_obj = Url.objects.filter(id=..not_important...)[0] url = url_obj.url para1_obj = Parameter.objects.filter(..not_important..)[0] para1 = para1_obj.para para2_obj = Parameter.objects.filter(..not_important..)[0] para2 = para2_obj.para return render(request, 'userpage.html', {'url':url, 'para1':para1, 'para2':para2}) templates/userpage.html You URL is {{ url }} My expected is You URL is http://example.com/?aaa=932580234 However, the actual html is You URL is http://example.com/?aaa={{para1}} How can I "pre render" the field in database before "return render...."? Or is there any other solution for this? I'm using python 3.4 and django 2.0 Thanks!! -
Django money USD format is different
I'm using django money field in storing prices, and there's this little problem in displaying the values. The USD displayed format is different from the rest of the currency. See the displayed format below. USD: $1,000 ----> This should be 1,000 USD SGD: 1,000 SGD CNY: 1,000 CNY How come that USD is using currency sign ($) while the rest uses currency code? How do i set the USD to display currency code? Thanks in advance -
Django : Send file as a response
I am receiving mimetype object for mail with attachments using python imaplib. Attachment format is like below with base64 as a encoding. Content-Disposition: attachment; filename="pdf-sample.pdf" Content-Transfer-Encoding: base64 Content-Type: application/pdf; name="pdf-sample.pdf" JVBERi0xLjMNJeLjz9MNCjcgMCBvYmoNPDwvTGluZWFyaXplZCAxL0wgNzk0NS9PID... In list, [ ('Content-Disposition', 'attachment;\r\n\tfilename="pdf-sample.pdf"'), ('Content-Transfer-Encoding', 'base64'), ('Content-Type', 'application/pdf;\r\n\tname="pdf-sample.pdf"') ] Considering the format as a part object, part.get_filename() outputs base64 as 'pdf-sample.pdf' part.get_payload() outputs base64 as JVBERi0xLjMNJeLjz9MNCjcgMCBvYmoNPDwvTGluZWFyaXp How to send this payload as a file response from django so that it could be downloaded from client? -
Load fixtures + add Page: IntegrityError (duplicate key value)
I have a migration that loads a fixture for populating the database with a basic site structure (from Loading initial data with Django 1.7 and data migrations ). After that migration ran, my test adds a (custom) NewsPage. THis yields an "IntegrityError at /admin/pages/add/website/newspage/5/ duplicate key value violates unique constraint "wagtailcore_page_pkey" DETAIL: Key (id)=(3) already exists." The same happens when i add the page through the admin interface. It's a bit suspicious that the Page with pk=3 is the first one that is created in my fixture. The other two pk's were already created by Wagtail's migrations. I've read up about fixtures an migrations, and it seems Postgres won't reset the primary key sequences. I'm assuming this is also my problem here. I found a possible solution in Django: loaddata in migrations errors, but that failed (with "psycopg2.ProgrammingError: syntax error at or near "LINE 1: BEGIN;"). Trying to execute the gist of it, I ran the sqlsequencereset management command (./manage.py sqlsequencereset wagtailcore myapp), but i still get the error, although now for id=4. Is my assumption correct that Postgres not resetting the primary key sequences is my problem here? Does anyone know how to reliably fix that from/after a migration …