Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Django tests with pipenv in intellij
I started writing a django app with the help of pipenv. From the CLI I run my tests via pipenv run ./manage.py test. That loads my .env-file puts me inside the virtualenv and executes the test command. Now I want to do the same with a Run configuration in intellij. What I did: Created a new run configuration with "Django tests" base "use specified interpreter" is set to my virtualenv all other options are set to default When I run the tests with that new configuration, I get errors that indicate, that DJANGO_SETTINGS_MODULE wasn't really set. Looking further the command intellij uses for running my tests is /home/user/.virtualenvs/django-proj-wQnnAIXN/bin/python /home/user/.IntelliJIdea2017.3/config/plugins/python/helpers/pycharm/django_test_manage.py test /home/user/dev/django-proj_site How can I tell intellij to run the tests with pipenv run .. so that my .env file is loaded? -
How to do subcomments
from django.db import models class Post(models.Model): post_title = models.CharField(max_length=120, default=None) post_text = models.TextField() pub_date = models.DateTimeField('date published') def __str__(self): return self.post_title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) sub_comment = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True) author = models.CharField(max_length=50) comment_text = models.CharField(max_length=250) pub_date = models.DateTimeField('date published') def __str__(self): return self.author Hello, i've got a question. How to preform displaying comment as a thread if i have models like this? -
Should I prefer a timezone-aware datetime object over a naive date object in Python?
I am working in the context of Django and am storing the subscription_end field of a subscription plan database model in a date format, as in 2018-03-27, but according to the official Python documentation: Objects of the date type are always naive. Since I'm translating some timezone-naive datetime code to aware, should I apply these modifications to my subscription_end field, which as already stated is of type date, or DateField in Django? I would have preferred some bare DateField storage type since it is easier to work with, but am I going to experience timezone-related issues when dealing with different timezones and date/DateField object types only? -
Django: KeyError while fetching multiple tables
Iam new to Django and i need to fetch columns from multiple tables, so i tried this: queryset = Offre.objects.filter(idRecruteur=1).values('dateAjout','idRecruteur__entrepriseName') models.py @python_2_unicode_compatible class Recruteur(models.Model): recruteur_id = models.AutoField(primary_key=True,verbose_name="Recruteur id") entrepriseName = models.CharField(max_length=50) def __str__(self): return "Recruteur: {}".format(self.recruteur_id) @python_2_unicode_compatible class Offre(models.Model): dateAjout = models.DateField(auto_now=False, auto_now_add=False) idRecruteur = models.ForeignKey(Recruteur,verbose_name = "recruteur", on_delete=models.CASCADE) def __str__(self): return "Offre: {}".format(self.title) I need to output both dateAjout from table 'Offre' and entrepriseName from table 'Recruteur' but django raises a KeyError: 'idRecruteur'. What am i doing wrong ? -
Django ValueError - add user to userteam
I am creating a Django form where you can add a user to a UserTeam (UserTeams model below). The 'invite' page (below) queries the Team model to get the id of the current team, which it then assigns to 'teamID', so you can only add a user to the current team. (I have disabled this field so the user cannot change the team) The user then selects the user they want to add, and submits the form. I am trying this using the Team "Kate FC", and adding the player 'steven'. When I submit the form, however, i get this error: ValueError at /teams/1/invite/ Cannot assign "'Kate FC'": "UserTeams.teamID" must be a "Team" instance. What does this error mean?? class UserTeams(models.Model): userID = models.ForeignKey(User,on_delete=models.CASCADE) teamID = models.ForeignKey(Team,on_delete=models.CASCADE) class Team(models.Model): name = models.CharField(max_length=100) venue = models.CharField(max_length=100) countryID = models.ForeignKey(Countries, on_delete=models.CASCADE) owner = models.ForeignKey(User) def invite(request, teamID): try: query = Team.objects.get(id=teamID) except: raise Http404() if request.method == 'POST': form = InvitePlayerForm(request.POST or None, initial={'teamID': query}) if form.is_valid(): userteam = form.save(commit=False) userteam.save() return redirect('teammanager/teams.html') else: form = InvitePlayerForm(initial={'teamID': query}) query = Team.objects.get(id=teamID) return render(request, 'teammanager/invite.html', { "team": query, "form": form }) the form: class InvitePlayerForm(forms.ModelForm): teamID = forms.CharField(disabled=True) class Meta: model = UserTeams … -
URLs Python Issues
i put in views.py this function: def index(request): return HttpRequest('Hello Ahmed') and i call it in urls.py like this: from django.contrib import admin from django.urls import path from first_app import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), ] but when i run server it give me this issue: System check identified some issues: WARNINGS: ?: (2_0.W001) Your URL pattern '^$/' [name='index'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). i use django v2.0.1 -
Django - Select nested collection Avg with group by in one-many relationship
I have the following models, and what I would like is to select a collection of businesses, each of them with a collection of AVG(rate) based on group by review_question_id. Here are the necessary models: class ReviewQuestion(models.Model): """Represents a question to be given in a business type """ business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) question_text = models.CharField(max_length=100) class Business(models.Model): """Holds values for a specific business, based on a type will inherit questions and answers """ business_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE) name = models.CharField(max_length=100) class CustomerReview(models.Model): """ Holds the review value by a/all customers on a specific quesiton for a specific business """ business = models.ForeignKey(Business, on_delete=models.CASCADE) review_question = models.ForeignKey( ReviewQuestion, on_delete=models.CASCADE) review_value = models.PositiveSmallIntegerField() The nearest query I tried to get close on this: items = Business.objects.filter(business_type_id=type_id).values( 'id', 'name', 'business_type_id', 'address', 'customerreview__review_question_id').annotate(rate=Avg('customerreview__review_value')) and the problem with it is duplication. It duplicates the entire list and the result is flat, sort of what you get when you write it in flat tsql. The ideal result would look something like: [ { "business_id": 1, "business_name": "something", "rating":[ { "Question_1":{ "title":"ReviewQuestion__question_text", "Avg":5.0 }, "Question_2":{ "title":"ReviewQuestion__question_text", "Avg":5.0 },{ ... } } ] } ] Any help would be appreciated as I'm new to python/django. -
Django: Show which form fields are required
Is there an easy enough way for .as_table() (et al.) of a form to show required fields differently (for example adding asterisk after the field label)? Django 2.0. -
How to pass arguemnts with slash in Django2 urls
I would like to call a Django URL with an argument containing a forward slash. For example, I would like to call mysite.com/test/ with 'test1/test2'. (e.g. naively, the url would be mysite.com/test/test1/test2) urls.py: urlpatterns = [ path('test/<test_arg>/', views.test, name='test'), ] Accessing either of the following fails: mysite.com/test/test1/test2 mysite.com/test/test1%2Ftest2 (%2F is the standard URL encoding for forward slash) with the below error: Error: Using the URLconf defined in test.urls, Django tried these URL patterns, in this order: reader/ test/<test_arg>/ admin/ The current path, test/test1/test2/, didn't match any of these. I would expect using the path in 1 to fail, but I am surprised the path in 2 fails. What is the correct way of going about this? Using Django 2.0.2 -
How to test celery periodic_task in Django?
I have a simple periodic task: from celery.decorators import periodic_task from celery.task.schedules import crontab from .models import Subscription @periodic_task(run_every=crontab(minute=0, hour=0)) def deactivate_subscriptions(): for subscription in Subscription.objects.filter(is_expired=True): print(subscription) subscription.is_active = False subscription.can_activate = False subscription.save() And I want to cover it with tests. I found information about how to test simple tasks, like @shared_task, but nowhere can I find an example of testing @periodic_task -
Use Django Filters in ModelViewSet which return serializer data
I want to combine 2 models: City and Country in order to have a filter like this: http://localhost:8000/api/v1/geo/location-search/?name=Santa+Fe I have a ModelViewSet which return serializer data like this: class LocationSearchAPI(ModelViewSet): queryset = City.objects.all().order_by('name') permission_classes = [AllowAny] serializer_class = CityListSerializer filter_backends = (DjangoFilterBackend, SearchFilter) filter_class = LocationFilter def get_location_list(self, request): city_qs = City.objects.all().order_by('name') country_qs = Country.objects.all().order_by('name') result_qs = list(chain(country_qs, city_qs)) sorted_list = sorted(result_qs, key=lambda instance: -instance.id) results = list() for item in sorted_list: item_type = item.__class__.__name__.lower() if isinstance(item, City): serializer = CityLocaliaztionSrl(item) if isinstance(item, Country): serializer = CountryLocaliaztionSrl(item) results.append({'type': item_type, 'data': serializer.data}) return Response(results, status=200) and this Filter's not work: class LocationFilter(FilterSet): class Meta: model = City fields = ('type', 'data__name') How can I use Django Filters in ModelViewSet which return serializer data, hope your guys help me. -
How do you execute a flow.Function()?
I am currently trying to figure out how I can activate my_trigger so that my process can advance to Take The Order. My repo is here: https://github.com/vincentwhales/Pizza I have the following flows.py: @flow.flow_func def trigger_triggered(activation, *args, **kwargs): print("Calling trigger_triggered") activation.prepare() activation.done() @frontend.register class MyPizzaFlow(Flow): process_class = MyPizzaProcess start = ( flow.Start(CreateProcessView, fields=['content']) .Available(available_in_group('customers')) .Next(this.order_pizza) ) order_pizza = ( flow.Handler(this.save_content_to_order) .Next(this.external_join) ) # To run this, we need to know which task we are specifically referring to # This can be done by querying the database my_trigger = ( flow.Function(trigger_triggered, task_loader=lambda flow_task, task: task) .Next(this.external_join) ) external_join = ( flow.Join() .Next(this.take_the_order) ) take_the_order = ( flow.View(TakeTheOrderView, fields=['table_location']) .Permission('users.can_take_the_order') .Next(this.prepare_pizza) ) .... So I logged onto my customer workflow dashboard, created a new process. Order Pizza is executed. Then I log onto the waiter's workflow dashboard, nothing in "unassigned" is showing, good. Now I am trying to run my_trigger but I don't know how I can do it in python manage.py shell. In [15]: MyPizzaFlow.my_trigger.run() ... ~/.virtualenvs/pizza/lib/python3.6/site-packages/viewflow/nodes/func.py in run(self, *args, **kwargs) TypeError: <lambda>() missing 1 required positional argument: 'task' How should I run my_trigger? Edit: According to the test case, tests/test_flow_gate_join.py, I am supposed to keep the activation object around from the … -
Twitter Social login in Django
Respected all seniors i am very new to Django learning and wanted to add login with Twitter option in my Django application. Can you please provide me some basic intro or detailed description or recommend some book so that where i can read all and get information and apply Thanks -
Django count unique dates in queryset
I have a queryset that return objects like this: [ {created_at: "2018-03-01"}, {created_at: "2018-03-01"}, {created_at: "2018-03-02"} ] I want to select the count of unique days from my queryset. In the above example the expected answer would be 2. My current query look like this, where created_at is a DateTimeField: from django.db.models import Count from django.db.models.functions import TruncDate days = queryset.annotate(date=TruncDate('created_at')) \ .values('date') \ .annotate(dates=Count('date')) Unfortunately that returns 3, not the expected 2. -
TemplateDoesNotExist error in Django version 2.0.2
My Django project structure The codes are: settings.py is: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], # 'DIRS': ['templates', ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'python_django_blog', 'USER': 'root', 'PASSWORD': 'Coder123', 'HOST': '127.0.0.1', 'PORT': '3306', } } urls.py is: from django.contrib import admin from django.urls import path, re_path, include from first import views urlpatterns = [ path('admin/', admin.site.urls), path('post-list/', views.postlist, name='post-list'), ] views.py is: from django.shortcuts import render from django.template.loader import render_to_string from .models import Post def postlist(request): all_post=Post.objects.all() # return render(request,'post_list.html', all_post) return render_to_string(request,'post_list.html', {'all_post_list': all_post}) post_list.html is: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Oh No</title> </head> <body> <h1>Problem and problem</h1> </body> </html> Problem is I think, all the settings are alright. http://127.0.0.1:8000/admin/ also works fine. But I'm getting errors entering http://127.0.0.1:8000/post-list/. I've searched many question similar to this. After fixing, I've made the above codes. But those codes shows errors. I cannot figure out what the problem is. Help me to solve this problem. Thanks in advance. -
How to solve circular import in django if I need to count each other before creating objects
Let's take an example: I have a subscription and device models. I'm adding a check in a clean method of both. I want to disallow creating more instances of devices that limit in the subscription.devices_numer field. From the other side, I want to disallow making subscription.devices_numer field less than the number of instances of devices I already have. -
python / django using a variable as a dict key
I'm using python 3.6 and Django 2.0. I have a dict/json like this: dict = [ {'object A': '100'}, {'object B': '101'}, {'object C': '102'}, ] and: data = [ {'title': 'object A', 'description': 'Some Text'}, {'title': 'object B', 'description': 'Some Text'}, {'title': 'object C', 'description': 'Some Text'}, ] then try and access that number in another function output = [] for x in range(0, len(dict)): j = { 'id': x, 'title': data[x]['title'], 'description': data[x]['description'], 'value': dict[x][data[x]['title']], } output.append(j) The issue I'm running into is that data[x]['title'] within dict[x][] is coming out as a string and not a slice. I've tried splitting the title before putting it in, i've tried manually adding ' before and after. My first question is, is that possible to do? if so, how would I achieve that? My second question is, is there a better way to achieve that, perhaps with .keys() or something along those lines? Thanks in advance -
Generate django multiple sitemaps
I have a blog site and i want to generate 2 sitemaps, one for posts and one for categories the code that i have : sitemaps.py from django.contrib.sitemaps import Sitemap from .models import Post, Category class PostSitemap(Sitemap): priority = 0.5 def items(self): posts = Post.objects.filter(is_published=True).order_by('-updated_at') return posts def lastmod(self, obj): return obj.updated_at class CategorySitemap(Sitemap): priority = 0.5 def items(self): categories = Category.objects.filter( is_published=True).order_by('-updated_at') return categories def lastmod(self, obj): return obj.updated_at urls.py from .sitemap import PostSitemap, CategorySitemap from django.contrib.sitemaps.views import sitemap sitemaps = { 'posts': PostSitemap, 'categories': CategorySitemap, } urlpatterns = [ url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}), ] Is the above code a proper way to create dynamic sitemaps with django ; -
Issues with Django Multiupload
I am trying to create a django form which lets me input certain details like name,email etc. I want to be able to upload multiple files at once too with this form and save the files in database and make these files display in admin panel. For this I tried with the simple form with widget(setting mutiple=True) but that didn't do any magic. Then after exploring a bit I got idea of django-multiupload library. I got the basic idea of setup from these two links Using django-multiupload within a ModelForm Multiple images in django form with multiupload After setting up I got the error as following Exception Value: Cannot assign "": "Students" instance isn't saved in the database. I tried looking out for answer in this link but I didnt understood what's going on Django | Cannot assign object: instance isn't saved in the (wrong?) database and the solution in Creating and saving non-empty Django model instance as part of subclass instance is quite similar I think what I am doing in my form.py except the force_insert part Below is my code Models.py class Students(models.Model): name=models.CharField(max_length=255) email=models.EmailField() Student_ID=models.CharField(max_length=20,null=True, blank=True) Course_Name=models.CharField(max_length=255,choices=certificates) Unit=models.CharField(max_length=512,choices=units,null=True) class Submissionss(models.Model): image = models.FileField(upload_to="files/%Y/%m/%d") students = models.ForeignKey(Students, on_delete=models.CASCADE, … -
Django cannot serialize model.Decimal
When I write a Python/Django class like: class MyClass(models.Model): price = models.DecimalField(..., max_digits=5, decimal_places=2) I get the following error when running python manage.py makemigrations: ValueError: Cannot serialize: Ellipsis There are some values Django cannot serialize into migration files. For more, see https://docs.djangoproject.com/en/2.0/topics/migrations/#migration-serializing If I exclude all decimal variables from all of my classes, then the above command runs successfully. So, how does one include decimals in a way that is acceptable to Django? -
Install google oauth2
How to install google oauth2 in django. I have tried installing sudo pip install --upgrade google-api-python-client But still gets error at importing. Imports are: from google.oauth2 import id_token from google.auth.transport import requests I still get red marks at import. Is it correctly installed or anything else to do. Thanks in advance. -
How do I send data from Unity to Django server?
As it is, I want to transfer images from Unity to Django using 'UnityWebRequest.Post'. However, Request's dictionary(request.POST) in views.py was null. Can I get examples(source code), so that I can get the ultimate inspiration? i tried the C# source code as follows. IEnumerator ServerThrows() { byte[] bytes = File.ReadAllBytes(imagePath + "Sohyeluv.jpg"); WWWForm form = new WWWForm(); form.AddField("Things", 10); UnityWebRequest www = UnityWebRequest.Post("http://127.0.0.1:8000/testforunity/", form); yield return www.SendWebRequest(); if(www.isNetworkError||www.isHttpError){ Debug.Log(www.error); } else { Debug.Log("Form upload complete!"); } } Here is the contents of views.py on my Django server. def fromunity(request): print(request.POST) return HttpResponse("h") -
Django With Aerospike as Data Store
Has Anyone implemented or tried Django Framework with Aerospike. Currently, I am in a learning phase, so just tried with SQLite. I want to perform all model-based DB operations using Aerospike. -
Django create a custom form permission
I'm developing a management software. And I need create a module for manage the permissions and groups using the auth of django. I dont want use the admin django because this just allow log in for super users. I want override the admin route and create a form with the same features from the admin site. If is possible, i want use the widget for the assignament of permission and group. All this i need built into a app because i need this works for this and other project. I already write a custom form to add, edit and view users extending the class UserCreationForm, I need something similar to that. I hope you can help me... -
Database for Django
First of all, I am learning myself Django through online tutorial. I am stuck with settings.py not knowing what should be the databases should I set.I dont think my pc has any database or its driver inbuilt. So how can I proceed? Secondly, when I run Manage.py runserver, I dont get it run anything on my CMD. Is it because I didnt set up my db on settings file? Thirdly, I am completely new to IT and programming language as I have a Biological science background.I somewhat learnt Python, BeautifulSoup, Pandas etc., Will I able to learn Django? Do I need any prerequistes or do I also need to learn javascript, CSS etc., Kindly help. Thanks