Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django-hitcount - display the date and ip of each recorded "hit"
This is a noob question, so excuse the lack of understanding. I'm using python 3.6 & django 1.10.5. I've been given a test page that now uses django-hitcount to track the number of times a document is "hit" - viewed and downloaded. This seems to be working OK. I now want to extend the code so that I can display the date and ip of each time the document is "hit". I've looked at the db tables and the date and ip is stored in the django-hitcount tables as shown below: Here's the views.py code to display the recorded hitcount "hits": document_hits = HitCount.objects.filter( content_type=content_type, modified__gte=one_week_ago).order_by('object_pk') I've read the django-hitcount docs, however I am unable to understand how to write/extend the view to display the date and ip of each hit. I've tried many things, but I'm missing something fundamental here. Any assistance to steer me in the right direction would be greatly appreciated. -
Django-Postgres WHERE query using varchar_pattern_ops index instead of pkey index
I have a Django-Postgres setup with this table - class User(models.Model): id = models.CharField(max_length=255, primary_key=True) Running the migration creates two indexes on the field (which is what Django automatically does as I checked from running sqlmigrate) - one index for pkey and one for varchar_pattern_ops - \d+ "user"; Column| Type | Modifiers | Storage | Stats target | Description ------+--------------------------+-----------+----------+--------------+------------- id | character varying(255) | not null | extended | | Indexes: "user_pkey" PRIMARY KEY, btree (id) "user_id_90845346_like" btree (id varchar_pattern_ops) As I understand it, if I run this query select * from "user" where id='id1234'; it should use user_pkey. Instead it uses user_id_90845346_like. explain analyze select * from "user" where id='id1234'; Index Scan using "user_id_90845346_like" on "user" (cost=0.41..8.43 rows=1 width=770) (actual time=0.033..0.0 33 rows=0 loops=1) Index Cond: ((id)::text = 'id1234'::text) Planning time: 1.335 ms Execution time: 0.072 ms (4 rows) I also don't see any option to force Postgres to use an index, but what I actually want to know is why an = search doesn't use the primary key. Shouldn't like text% searches use the varchar_pattern_ops index? -
keeping a function always running in django
I am working on a django project where I'm suppose to check a date with today's date and if it's difference is of 1 month then there should happen something. Is there any method or any thing that can help me pls do help me. -
How to restrict the number and time of upload actions in Django Python?
How to restrict the number and time of upload actions in Django Python? Need to enable a user to upload once every 2 hours. During this time interval the uploaded data are processed and the link with a download data should be returned to the user. That is the other question: how to return a download link to the user? Is it possible without uploading to the cloud like MegaNZ? -
Django model limit choices based on another model but with a specific field value
I have got 2 models, simplified for this question. In the Article model, how can I limit the choices= of the field Article.status based on the entries in the Category model which have a specific Category.type value? class Article(models.Model): name = models.CharField(max_length=100) # Set choices= only to values of Category which have a type of 'foo' status = models.CharField(max_length=10, choices=) class Category(models.Model): name = models.CharField(max_length=10) type = models.CharField(max_length=10) For transparency, I know I've done this before but I can't seem to remember how or find the project where I did it. It's like the solution just disappeared on me...*poof*. Magic. -
How to use variable with model name in Django ORM?
from .models import model_a, model_b N = 'model_a' result = N.objects.all() -
how to dynamically pass headers while making post request in django?
Right now I'm harcoding the token in headers and it works fine but i don't want to harcode it . I want to pass it while making post request in postman. So how to do that . Thanks in advance. def addtocart(request): payload = request.data headers = {"content-type":"application/json", "token": "tk_ju9fdm8e", "source":"android"} response = requests.post('http://api/cart/update/v2', data=json.dumps(payload), headers=headers) return HttpResponse(response) -
Encountered unknown tag 'load'.?
I want to add some custom-template-tags.But, {% load userfilters %} => 'load' tag is not working. settings.py # project/settings.py TEMPLATES = [ { 'BACKEND': 'django.template.backends.jinja2.Jinja2', 'DIRS': [ os.path.join(BASE_DIR, 'html/jinja2'), ], 'APP_DIRS': True, 'OPTIONS': { 'environment': 'accountv1.jinja2.environment', }, }, ] jinja2.py # project/jinja2.py from django.templatetags.static import static from django.urls import reverse from jinja2 import Environment def environment(**options): env = Environment(**options) env.globals.update({ 'static': static, 'url': reverse, }) return env app/templatetags/userfilters.py from django import template register = template.Library() @register.filter(name='a') def a(value): return 1 views.py # use django-rest-framework class IndexView(generics.GenericAPIView): renderer_classes = [TemplateHTMLRenderer] template_name = 'index.html' def get(self, request, *args, **kwargs): return Response({'name': 'max'}) demo.html is not working {% load userfilters %} <!-- custom filter --> {{ name|a }} is work <!-- default filter --> {{ name|title }} I hope to solve this problem. -
Is Django a MVC or MVT framework?
I was wondering that whether Django is a MVC or MVT framework? I searched this question on net but didn't find any suitable or satisfactory answer. -
How to share models between two different Django web applications?
I am creating a micro service based architecture in my Django project. So I have one parent service that is exposed to the outer world. I am planning two create a second service for processing orders. The second service basically needs to be created to be able to process orders independently of the parent service using Kafka. Now my concern is how do I maintain django migrations in the second application, like if I have a change to the model class in the first application, so I replicate the same change in the second application(this is a very rare scenario), now since both these application share the same database, I need to run migrations only in one application? Will this work? Is this a good approach? What else you can suggest? -
How to create a custom class having a many to many relationship in factory-boy?
My models are as follows: class Question(models.Model): content = models.CharField( max_length=1000, blank=False, default='', ) def __str__(self): return self.content class OptionGroup(models.Model): question = models.ForeignKey( 'Question', on_delete=models.CASCADE, default='', ) options = models.ManyToManyField('Option') class Option(models.Model): content = models.CharField( max_length=1000, blank=False, default='', ) My factories are as follows: class QuestionFactory(factory.django.DjangoModelFactory): class Meta: model = Question content = factory.Sequence(lambda n: 'Question %d' % n) class OptionGroupFactory(factory.django.DjangoModelFactory): class Meta: model = OptionGroup question = factory.SubFactory(QuestionFactory) @factory.post_generation def options(self, create, extracted, **kwargs): if not create: return if extracted: for option in extracted: self.options.add(option) class OptionFactory(factory.django.DjangoModelFactory): class Meta: model = Option content = factory.Sequence(lambda n: 'Option %d' % n) Now, for ease of use, I wanted to create a Question factory class which creates two OptionGroup objects having two Option objects each. In order to do this, I'm using this factory but it isn't working: class QWith2OptGrps4Options(QuestionFactory): option_group1 = factory.RelatedFactory( OptionGroupFactory, 'question', options=(OptionFactory.create(), OptionFactory.create()) ) option_group2 = factory.RelatedFactory( OptionGroupFactory, 'question', options=(OptionFactory.create(), OptionFactory.create()) ) I figure it has to do something with how I'm declaring OptionFactory but I don't know how to do it correctly. Any help? -
How to get a record from database which is matching to list of values?
I have a list which contains the employee ids. now I want to compare values containing in the list with the database and need to retrieve the record from the database which is matching with list ids I have written this code which getting the employee's id from the database and stores these values in the list. employees_list = Employee.objects.values_list('employeeid', flat=True) Now I want to fetch records from another database which contains this id. Now I am writing following query but it is not retrieving this record. employees_list = ActualSheet.objects.filter(employeeid__contains= employees_list).values() it must fetch the record but it is not fetching any record -
How to let the limited access dashboard partners to also add variants in django oscar
I have gone to the django-oscar dashboard and went to Fulfillment - > Partners, there I created a partner and linked a user and gave a limited dashboard access. Now I see that most of the drop-downs are not visible to them(partner), that's fine.This is due to the permission given 'Can access dashboard'. But, when I go to add the products, I see only the Stock and Pricing tab is there on the left, but there is no tab for variants, how do I get it to show in the dashboard of the partner also? Should I give any other permission for the user linked ? According to the docs link https://django-oscar.readthedocs.io/en/releases-1.6/ref/apps/dashboard.html in the note it says The permission-based dashboard currently does not support parent or child products.Supporting this requires a modelling change. If you require this, please get in touch so we can first learn about your use case. , but how and whom do I contact? Or can I extend some of the partner views to achieve this? -
How to fix 'Too many levels of symbolic links' error in virtuanenv?
I am getting error(Too many symbolic link levels) while setting up virtual envirionment in Django web application framework. I tried to look the following question and answer on stack overflow: mkvirtualenv: Too many levels of symbolic links virtualenv: Too many levels of symbolic links Kuldeeps-MacBook-Pro:trydjango kuldeep$ pip freeze branca==0.3.0 certifi==2018.8.24 chardet==3.0.4 folium==0.6.0+11.g71ab988 idna==2.7 Jinja2==2.10 MarkupSafe==1.0 numpy==1.15.1 requests==2.19.1 six==1.11.0 urllib3==1.23 virtualenv==16.1.0 Kuldeeps-MacBook-Pro:trydjango kuldeep$ source bin/activate (trydjango) Kuldeeps-MacBook-Pro:trydjango kuldeep$ ls ``` bin db.sqlite3 include lib manage.py src trydjango ``` (trydjango) Kuldeeps-MacBook-Pro:trydjango kuldeep$ pip freeze -bash: /Users/kuldeep/Dev/trydjango/bin/pip: /Users/kuldeep/Dev/trydjango/bin/python3: bad interpreter: Too many levels of symbolic links -
Restricting logged in user to access the front page of login and registration without log out
Like in facebook. after logging in how to prevent user to the login register page unless user is logged out, other wise display user dashboard in django -
Is it possible to specify an instance for a form if request= request.GET? django
I will need to populate a form based on an id, which I take in as a parameter to my view. However, while the form does populate with that instance, it seems like the form is automatically taken to be doing request.POST, since I get errors around the required fields "This field is required" when I first load the page. I have tried specifying request.GETas an argument but to no avail... def inputClassInfo(request, mod_id=0, class_id=0): template_name = "formstoadmin/inputclass.html" a = Class.objects.filter(module__subject=subject)[0] form = InputClassInformation(request.GET, instance=a) context = {'form': form} return render(request, template_name, context) So my question is, is it possible specifying instance for a request.GET form instead of a request.POST one? Otherwise I get those errors saying field is required upon first load of the form... -
Do you know written solutions for auto-deploy a new Django DB for every new subdomain?
I have a product, which required a separate DB for every customer. Now I'm using one Django source code and separate settings and wsgi for every customer which is in a separate VirtualHost of Apache. Currently everything works fine, but when we add a new customer - we need to restart apache. I'm going to move to nginx, but maybe someone can recommend any tools that allow me to automate those steps when new customer sign up: - new mysql DB - settings - wsgi - requests to create subdomain at hosting panel (DO) etc Thanks p.s. I'm not asking for criticism to that solution, as every customer is a large business, a whole architecture require current solution -
Is there a way to configure an external SSO login system with my existing Django Web Application
I have a django application with a default login configured. I also have an external SSO login system. Need to configure the django application so that it can use the SSO and login to the application. -
Pagination of ListView - Django
Views class ThreadListView(ListView): model = Thread template_name = 'forums/thread.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of the Thread & Replies context['thread'] = Thread.objects.get(pk=self.kwargs['pk']) context['reply'] = Thread.objects.get(pk=self.kwargs['pk']).replies.all() return context HTML {% extends 'forums/base.html' %} {% block title %} Forum - {{ thread.title }} {% endblock title %} {% block content %} <!--Thread real--> <table class="table table-hover"> <thead> <tr class="table-primary"> <th class="col-2"><a href="{% url 'threadview' thread.id %}"> {{ thread.title }}</a></th> <th scope="col-10" id="content-col"></th> </tr> </thead> <tbody> <!--Thread Author and Content--> <tr class="table-info"> <td class="border-right text-center"> <span> <img class="rounded-circle" style="height: 100px;width: 100px;" src="{{ thread.author.profile.image.url }}"> <br /> Username:&emsp;<a href="#">{{ thread.author.username|capfirst }}</a> <br /> Ranks:&emsp; <!--Ranks Go Here--> <br /> <hr> Posts:&emsp; <!--Posts Go Here--> <br /> Badges:&emsp; <!--Badges Go Here--> <br /> <hr> Date Joined:&emsp;{{thread.author.date_joined| date:'Y-m-d'}} <br /> </span> </td> <td>{{ thread.content }}</td> </tr> <!--Reply Author and Content--> {% for rply in reply %} <tr class="table-secondary"> <td class="border-right text-center"> <span> <img class="rounded-circle" style="height: 100px;width: 100px;" src="{{ rply.author.profile.image.url }}"> <br /> Username:&emsp;<a href="#">{{ rply.author.username|capfirst }}</a> <br /> Ranks:&emsp; <!--Ranks Go Here--> <br /> <hr> Posts:&emsp; <!--Posts Go Here--> <br /> Badges:&emsp; <!--Badges Go Here--> <br /> <hr> Date Joined:&emsp;{{thread.author.date_joined| … -
Insert a contact form from an app into a Class view in Django
If you have this view class index(TemplateView): template_name = 'index.html' where index.html have this structure {% block content %} {% include "content.html" %} {% content %} How do you include this view from a contact app in content.html? def contactForm(request): #....some form processing here return render(request, "contact.html", {'form': form}) Thanks. -
How can I pass my sqlite data to django, and make chart?
I'm trying to make line chart using data in sqlite database. But I have no idea how to pass my data to views.py and html template file. I want to make line chart ( x-axle : date , y-axle : count by date ) I tried to make it using raw queryset and other things... requestCnt = ActivityLog.objects.raw("SELECT date(doDate), count(requestType) FROM mainApp_activitylog GROUP BY doDate") OR requestCnt = ActivityLog.objects.values('doDate').annotate(Count('requestType')) AND ETC... Models.py class ActivityLog(models.Model): doDate = model.DateTimeField() userIP = models.CharField(max_length=200) userName =models.CharField(max_length=200) requestType = models.CharField(max_length=200) Below is my raw sqlite query. sqlite> SELECT date(doDate), count(requestType) FROM mainApp_activitylog GROUP BY doDate; and the result is as below 2019-04-15|3 2019-04-16|16 2019-04-17|13 2019-04-18|10 2019-04-19|13 2019-04-22|24 How can I pass those results above to X-Axle and Y-axle ? I want to make line chart (X-Axle:date , Y-axle: request count by date) I have a little idea that I should use Json dumps or things like that. I've already encountered error such as " cannot be serialized as Json file (?) " I really hope someone can solve my problem. Thx for your help in advance. -
Object caching multiple queries with same where clause
Just wondering if Django 2.2 ORM caches the returned QuerySets in this code, or are the queries executed on the DB for each call? Is there a way to tell Django to "re-use" the QuerySets to lesson impact on DB. I'm building this application which retrieves several values and objects for different reasons, but the underlying query is the same in each case . hrs = Sale.objects.filter(createdate = dte).aggregate(sum=Sum('duration'))['sum'] / 60 stf = Sale.objects.filter(createdate = dte).values_list('idsalestaff', flat=True).distinct().count() csh = Sale.objects.filter(createdate = dte).aggregate(sum=Sum('cash'))['sum'] crd = Sale.objects.filter(createdate = dte).aggregate(sum=Sum('card'))['sum'] -
Cannot query "object": Must be "User" instance
I am creating sample-api which have post and follower. Post should visible to followers only My models.py from django.contrib.auth.models import User class Post(models.Model): creator = models.ForeignKey(User, related_name='creator_post_set', null=True, on_delete=models.CASCADE) title = models.CharField(max_length=25) created_date = models.DateTimeField(auto_now_add=True) content = models.TextField() likes = models.BigIntegerField(null=True) comments = models.BigIntegerField(null=True) class Follow(models.Model): follower = models.ForeignKey(User, related_name='following', null=True, on_delete=models.CASCADE) followed_on = models.DateTimeField(auto_now_add=True) following = models.ForeignKey(User, related_name='follower',null=True, on_delete=models.CASCADE) My views.py: class PostList(generics.ListCreateAPIView): serializer_class = PostListSerializer follow_model = FollowSerializer.Meta.model post_model = PostSerializer.Meta.model def get_queryset(self): try: followers = self.follow_model.objects.get(follower_id = self.request.user.id) queryset = self.post_model.objects.get(creator__in = followers) except self.follow_model.DoesNotExist: queryset = None return queryset When I call this view it returns the following error: Cannot query "Follow object (1)": Must be "User" instance. I need help Thanks in Advance. -
Django Content-Types Foreign Key Contraint Failure
For the sake of dynamic forms that can accept different data-types, I am attempting to use Django Content-types to create a relation between a field in the form and the data stored within (i.e. linking an instance of the formfield model to an model that consists solely of an integer). I have followed multiple tutorials and managed to troubleshoot a lot of problems along the way, but am now stuck at what appears to be the final step - after creating the integer model with the desired value, attempting to link to a newly created formfield instance results in the error Cannot add or update a child row: a foreign key constraint fails (`formfieldresponse`, CONSTRAINT `form_content_type_id_0bc41ecc_fk_django_co` FOREIGN KEY (`content_type_id`) REFERENCES `django_content_type` (`i) This was not a constraint created by me, and seems to be automatically generated. Of note to me is the fact it is referencing django_content_type (`i) and not the ID, however I cannot trace this foreign key constraint ti anyway in my database. Can anyone advise of the mistake I have made? Fragment of the model code for review class FormFieldResponse(models.Model): form_response = models.ForeignKey(FormResponse, on_delete=models.CASCADE, related_name='field_responses') field = models.ForeignKey(FormField, on_delete=models.CASCADE, related_name='field_responses') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, related_name="value") object_id = … -
Setting BASE_DIR and PROJECT_DIR appropriately for my Django project to capture my STATICFILES_DIRS
Below is my project structure in Django 1.11. repo-directory/ ├── addons | |__ project1 | |__ static | |__ template | |__ model.py | |__ project2 | |__ static | |__ template | |__ model.py ├── config │ ├── settings.py │ └── urls.py | └── wsgi.py └── manage.py What am trying to do is to set STATICFILES_DIRS to know where my static folder is. So I did the following below inside my settings.py file but did not resolve to be working properly. # Build paths inside the project like this: os.path.join(BASE_DIR, ...) PROJECT_DIR = os.path.abspath(os.path.dirname(__file__)) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'static'), os.path.join(PROJECT_DIR, "static/fonts/"), os.path.join(PROJECT_DIR, "static/extras/"), os.path.join(PROJECT_DIR, "static/img/"), os.path.join(PROJECT_DIR, "static/js/"), ) Any help will be appreciated.