Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
It is the correct way to import UserCreationForm?
I am importing UserCreationForm but the server stops and shows me the following error: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. When I eliminate the import everything works again # -*- coding: utf-8 -*- from django.contrib.auth.forms import UserCreationForm from django.views.generic import CreateView from django.urls import reverse_lazy class SignUpView(CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' -
What is necessary to make the deploy of a Django Application in an internal network?
I'm a student, making a django project in school for a few months, since last year, using Django Rest Framework and React. A project for a hospital, to manage patients, appointments, medicines, etc. I have asked some questions here a few times on how to do a few things in Django and it was really helpful. I've presented the system for the people in the hospital, they liked it, there are some adjustments to do yet, going to fix it this weekend. I'm using python anywhere free account to host it. So now I have a few doubts, this month I need to make the deploy of this project in the hospital, they want to host it there for production. They have scheduled a meeting with me, my teacher who is the one guiding me and responsible for this project, and the director of IT of the hospital, the director want me to explain for him what he will need to host the project in the hospital. In my inexperienced head I thought the only thing he will need there is to install python 3.6 and MySQL on their servers. My teacher asked me to make a research of what … -
How to implement ObtainAuthToken view with ModelViewSet and rest_framework routers in DFR API
I have the default basic root view for DefaultRouter in DRF. I want to implement a view ObtainAuthToken in this DRF and list it in my root view. I have written a custom User Model. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from .managers import CustomUserManager class Account(AbstractBaseUser, PermissionsMixin): '''Custom user model, supports using email instead of username''' ... The model serializer and the authtoken serializer. serializers.py class AccountSerializer(serializers.ModelSerializer): '''Serializer for custom user model''' ... class AuthTokenSerializer(serializers.Serializer): '''Serializer for the user authentication object''' email = serializers.CharField() password = serializers.CharField( style={'input_type': 'password'}, trim_whitespace=False ) def validate(self, attrs): '''Validate and authenticate the account''' email = attrs.get('email') password = attrs.get('password') account = authenticate( request = self.context.get('request'), username = email, password = password ) if not account: msg = _('Unable to authenticate with provided credentials') raise serializers.ValidationError(msg, code='authentication') attrs['user'] = account return attrs views.py from rest_framework import viewsets from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from . import serializers as s from .models import * class CreateTokenView(ObtainAuthToken): serializer_class = s.AuthTokenSerializer renderer_classes = api_settings.DEFAULT_RENDERER_CLASSES class CreateAccountView(viewsets.ModelViewSet): queryset = Account.objects.all() serializer_class = s.AccountSerializer Finally I have a api_router.py from rest_framework import routers … -
How to send a notification by email for an user when press a button action
I am new programer in Django, but i need create a notification for an user when press a button in a form in django. Most information: We are developing an application than receive request from a portal and show this request in a list form, I have this list of request with two buttons, one is accept request and the other is refuse request. We need send an email for user when the request is refused or acepted. Do you have any code related? Any help will very appreciated send a email message for the userExample of the form -
Trying to configure gunicorn
I have been following this tutorial to deploy my django project on Digital Ocean. I am trying to configure gunicorn. My project structure looks similar to this: On my settings.py I use DEBUG=False I create the gunicorn.socket and gunicorn.service. /etc/systemd/system/gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=someuser Group=www-data WorkingDirectory=/home/someuser/myproject ExecStart=/home/someuser/myproject/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ Myproject.wsgi:application [Install] WantedBy=multi-user.target I start and enable the Gunicorn socket: sudo systemctl start gunicorn.socket sudo systemctl enable gunicorn.socket Check the status of the process to find out whether it was able to start: sudo systemctl status gunicorn.socket This is what I get and then it returns to the command line. Failed to dump process list, ignoring: No such file or directory β—� gunicorn.socket - gunicorn socket Loaded: loaded (/etc/systemd/system/gunicorn.socket; enabled; vendor preset: enabled) Active: active (listening) since Sat 2019-05-04 23:12:03 UTC; 13s ago Listen: /run/gunicorn.sock (Stream) CGroup: /system.slice/gunicorn.socket May 04 23:12:03 myproject systemd[1]: Listening on gunicorn socket. Next, I check for the existence of the gunicorn.sock file within the /run directory: file /run/gunicorn.sock /run/gunicorn.sock: socket It seems that a file or directory doesn't exist, but it doesn't provide any more details. The … -
Generating a data table to iterate through in a Django Template
I have this function that uses PrettyTables to gather information about the Virtual Machines owned by a user. Right now, it only shows information and it works well. I have a new idea where I want to add a button to a new column which allows the user to reboot the virutal machine. I already know how to restart the virtual machines but what I'm struggling to figure out is the best way to create a dataset which i can iterate through and then create a HTML table. I've done similar stuff with PHP/SQL in the past and it was straight forward. I don't think I can iterate through PrettyTables so I'm wondering what is my best option? Pretty tables does a very good job of making it simple to create the table (as you can see below). I'm hoping to use another method, but also keep it very simple. Basically, making it relational and easy to iterate through. Any other suggestions are welcome. Thanks! Here is my current code: x = PrettyTable() x.field_names = ["VM Name", "OS", "IP", "Power State"] for uuid in virtual_machines: vm = search_index.FindByUuid(None, uuid, True, False) if vm.summary.guest.ipAddress == None: ip = "Unavailable" else: ip … -
How to increment the value of and attribute in my Model in Django?
I want to do a likes button when one click the button, the likes property of the model increments by one. The model looks like this: class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length = 200) text = models.TextField() created_date = models.DateTimeField(default = timezone.now) likes = models.IntegerField(default=0) tags = models.CharField(max_length = 50, default = '' ) def process_likes(self): print(self.likes) self.likes += 1 def split_tags(self): return self.tags.split() def get_absolute_url(self): return reverse('blog:post_list') def __str__(self): return self.title The process_likes method is the one in charge of increment the counter of likes, but when I call the function pressing a button, it doesn´t increment the count? How can I solve this? -
how to make " request.user.is_authenticated" work without throwing an error
i have tried to use the authentication of a user but every time i use it i get a type error telling me that the 'bool' object is not callable. I can't get over it. if request.user.is_authenticated(): print(user) else: return redirect("/login") return render(request, 'home.html', context) -
Django class based view pagination not working
I have tried to add some pagination to my search page, I sourced some online and implemented it into my code and yet it does not work. I am unsure if there are parts of this I am missing such as a django import, but I could not figure any other way how to do it in class based views. HTML: <div id="page_navigation" > <a href="?{{ request.GET.urlencode }}&page=1{% if q_words %}&q={% for w in q_words %}{{ w }}{% if not forloop.last %}+{% endif %}{% endfor %}{% endif %}"> <button class="nav_button" >FIRST</button> </a> {% if page_obj.number|add:'-1' > 0 %} <a href="?{{ request.GET.urlencode }}&page={{ page_obj.number|add:'-1' }}{% if q_words %}&q={% for w in q_words %}{{ w }}{% if not forloop.last %}+{% endif %}{% endfor %}{% endif %}"> <button class="nav_button extra" ><img id="left_arrow" class="arrow" src="{% static 'publicnfx\images\arrow_left.png' %}" alt=""> PREV</button> </a> {% if page_obj.number|add:'-2' > 0 %} <a href="?{{ request.GET.urlencode }}&page={{ page_obj.number|add:'-2' }}{% if q_words %}&q={% for w in q_words %}{{ w }}{% if not forloop.last %}+{% endif %}{% endfor %}{% endif %}"> <button class="nav_button extra" >{{ page_obj.number|add:'-2' }}</button> </a> {% endif %} {# page number without adding the pages_plus, this is #} {% if pages_plus > 0 %} <a href="?{{ request.GET.urlencode }}&page={{ page_obj.number … -
Is it possible to export only table schema using django Import-Export?
I've created an inventory ordering system using Django and a PostgreSQL db. What I'd like to do is make printer friendly CSV file from my models that can be used as a paper list when they count inventory. I've set up Django-Import-Export and obviously, it exports all the instances as well. What I'd like to do is export the fields only. Is this possible to do using Import-Export or is there a better way to attack this. admin.py from django.contrib import admin from .models import * from import_export import resources from import_export.admin import ImportExportModelAdmin # Register your models here. class GordonResource(resources.ModelResource): class Meta: model = Gordon exclude = ('Order_date','store','id',) class GordonAdmin(ImportExportModelAdmin): resource_class = GordonResource admin.site.register(Gordon, GordonAdmin) -
How to apply (on conflict do nothing) using django get_or_create()
Lets say the first_name and last_name are as below in Models.py: unique_together = ('first_name', 'last_name',) and in view.py obj, created = Person.objects.get_or_create( first_name='John', last_name='Lennon', defaults={'birthday': date(1940, 10, 9)}, ) But sometimes I get an error caused by duplication: Normally in Postgres I use ON CONFLICT DO NOTHING. What is the best way in Django. Thanks -
How to display Elasticsearch default relevancy _score in the frontend
I'm setting up search functionalities in my Django Project using Django-Haystack and Elasticsearch and I want to display the matching score of every search results in percentage but I can't find a way to achieve this. I was thinking that maybe I could use an If / Else statement and use the default _score value of Elasticsearch and change it into percentages, to finally display the percentage for every objects in the frontend, but I don't know how to do it. Any solutions? My Elasticsearch index structure looks like this: {"took":3424,"timed_out":false,"_shards":{"total":5,"successful":5,"failed":0},"hits":{"total":19,"max_score":1.0,"hits":[{"_index":"searchindex","_type":"modelresult","_id":"search.product.4","_score":1.0,"_source":{"id": "search.product.4", "django_ct": "search.product", "django_id": "4", "text": "Lancaster\nlorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv\n", "title": "My Title 16", "description": "lorem sivbnogc hbiuygv bnjiuygv bmkjygv nmjhgv", "destination": "Lancaster", "link": "uvergo.com", "image": "gravitational_lens.png", "brandlogo": "destination.png", "ptags": ["Couple"], "ptags_exact": ["Couple"], "content_auto": "Lancaster"}} Here's my Models.py: class Product(models.Model): destination = models.CharField(max_length=255, default='') title = models.CharField(max_length=255, default='') slug = models.SlugField(null=True, blank=True, unique=True, max_length=255, default='') description = models.TextField(default='') ptags = TaggableManager() image = models.ImageField(default='') timestamp = models.DateTimeField(auto_now=True) def _ptags(self): return [t.name for t in self.ptags.all()] def get_absolute_url(self): return reverse('product', kwargs={'slug': self.slug}) def __str__(self): return self.destination I'm using a custom forms in forms.py: from haystack.forms import FacetedSearchForm class FacetedProductSearchForm(FacetedSearchForm): def __init__(self, *args, **kwargs): data = dict(kwargs.get("data", [])) self.ptag … -
How to self relation using GenericRelation in a Django model?
I want use the Comment to two things: 1 - comment on post 2 - reply on comment I can use the Comment model for comment on posts: me = User.objects.get(pk=1) post = Post.objects.get(pk=1) comment = Comment.objects.create(user=me, body='the comment', content_object=post) post.comments.all() <QuerySet [<Comment: the comment>, <Comment: post level comment>]> but I am not able to access the comments from the Comment instance itself: reply = Comment.objects.create(user=me, body='reply level comment', content_object=comment) reply.content_object <Comment: the comment> comment.replies.all() <QuerySet []> As you can see, accessing Comment.replies.all () does not return an instance of Comment related to itself. Here is my models.py: from django.db import models from django.contrib.auth import get_user_model from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation from django.contrib.contenttypes.models import ContentType from taggit.managers import TaggableManager User = get_user_model() # Create your models here. class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="comments") date = models.DateTimeField(auto_now_add=True) body = models.CharField(max_length=1000) replies = GenericRelation("self", related_query_name='replies') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey("content_type", "object_id") def __str__(self): return self.body class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="posts") title = models.CharField(max_length=260) body = models.TextField() is_published = models.BooleanField(default=True) comments = GenericRelation(Comment, related_query_name='comments') views = models.IntegerField(default=0) tags = TaggableManager() def __str__(self): return self.title -
Django: ValueError: too many values to unpack when calling Score.Objects.filter()
I have seen many answers on google related to the same error but none of them was useful for my case. models.py from django.db import models from django.db import models class Score(models.Model): id = models.IntegerField(primary_key=True) date = models.DateField() team = models.CharField(max_length=100) opposition = models.CharField(max_length=100) venue = models.CharField(max_length=100) inning = models.IntegerField() batsman = models.CharField(max_length=100) bowler = models.CharField(max_length=100) overs = models.FloatField() runs = models.IntegerField() wicket = models.IntegerField() class Meta: managed = False db_table = 'ipl' Query result = Score.objects.filter(query) query = Q(team__in=['Kings XI Punjab']) | Q(opposition__in=['Kings XI Punjab']),venue__in=['Punjab Cricket Association Stadium, Mohali'],inning__in=[1, 2],wicket__in=['0'] I have ran the same query in django shell and it gives me results. But when I run this query from views.py, I get this error. Error Internal Server Error: / Traceback (most recent call last): File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/shmitra/code/personal/cricketscreener/app/views.py", line 30, in home result = Score.objects.filter(query) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/db/models/query.py", line 892, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/db/models/query.py", line 910, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Users/shmitra/code/personal/cricketscreener/venv/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1292, in add_q … -
Does a library equivalent of PHP's omnipay exists for python?
This is the PHP lib : https://omnipay.thephpleague.com Basically it s a library that simplifies payments integrations for websites. I build a website using python and Django and I could not find an equivalent on the Python Package Index (https://pypi.org/). -
ajax calls don't have access to session variables on http
Through trial and error, I've provide that within my site, my ajax calls don't have access to session variables when the site is not running on https. My site servers my main site (which is https) and subdomains that are only http. Do you know if there is a setting that may be preventing my ajax calls from accessing session variables when the site is only setup as http and not https? Thanks! -
pass specific json data summations through django api or manipulate flat json data in browser with d3.nest?
I am curious to know what would be the best approach for a dashboard like application offering multiple views & data sets. From my view there are two possible approaches generate all data summations & groupings in the django back end and send json data via rest api when specific dataset/graph is loaded pass flat data json file to front-end when the app is loaded and create summations & groups with the data using d3.nest() when each specific view is requested. the second approach seems to me to be the better option, offering additional flexibility for user interactivity, but I do not have a lot of experience in this area and I am not sure of performance considerations. -
Reverse for 'tutorial_detail' with arguments '('', <TutorialSeries: HTML>, 'heading-and-form-tags')' not found
I have the following URL. path('<cat_slug>/<series_slug>/<tutorial_slug>/done/', views.tutorial_details, name='tutorial_detail') and this is the view of above stated URL def tutorial_details(request, cat_slug, series_slug, tutorial_slug): object = get_object_or_404(Tutorial, tutorial_slug=tutorial_slug) return render(request, 'tutorial/tutorial-detail.html', context={ 'obj': object }) and an achor tag in my template which refers to this URL {% for sub_cat in matching_series %} <a href="{% url 'tutorial:tutorial_detail' sub_cat.tutorial_series__series_maincategory sub_cat.tutorial_series sub_cat.tutorial_slug %}">read more</a> {% endfor %} I am not sure about sub_cat.tutorial_series__series_maincategory of above code. Question is how do I reference series_maincategory from within template. These are respective models: class TutorialCategory(models.Model): category_title = models.CharField(max_length=150) category_summary = models.CharField(max_length=150) category_slug = models.SlugField(default=1, blank=True) class TutorialSeries(models.Model): series_title = models.CharField(max_length=200) series_maincategory = models.ForeignKey( TutorialCategory, default=1, on_delete=models.SET_DEFAULT) series_summary = models.CharField(max_length=200) series_slug = models.SlugField(default=1, blank=True) class Tutorial(models.Model): tutorial_title = models.CharField(max_length=150) tutorial_content = models.TextField() tutorial_published = models.DateTimeField( "date Published", default=datetime.now()) tutorial_series = models.ForeignKey( TutorialSeries, default=1, on_delete=models.SET_DEFAULT) tutorial_slug = models.SlugField(default=1, blank=True) -
Is there any solution for adding social profiles to an existing user with my own backend?
I want to get photos from the users' social profiles when they connect their social account to my Django website and I don't want to allow them to login in with their social profiles. I need something. that allows my users to only connect their existing accounts to their social profiles. I tried social-auth-app-django but it only allows to log in with their social profiles. -
How do I resolve a Django query "'ExtractHour' object has no attribute 'split'" error?
I'm using Django and Python 3.7. I want to include a subquery in the criteria of a larger query. from django.db.models.functions import ExtractHour ... hour_filter = ExtractHour(ExpressionWrapper( F("article__created_on") + timedelta(0, avg_fp_time_in_seconds), output_field=models.DateTimeField() ), ) query = StatByHour.objects.filter(hour_of_day=OuterRef(hour_filter)) ... The larger query that contains it is qset = ArticleStat.objects.filter( votes__gte=F("article__website__stats__total_score") / F( "article__website__stats__num_articles") * Subquery(query.values('index'), outout_field=FloatField()) * day_of_week_index) However, when I run this, I get the error 'ExtractHour' object has no attribute 'split' What does this mean and how I can adjust my filter so that this error goes away? -
Django forms.IntegerField submit after each change
Is it possible to update the page after each change of value in forms.IntegerField? I have this form class CartProductForm(forms.Form): quantity = forms.IntegerField(min_value=1, max_value=50) update = forms.BooleanField(required=False, initial=False, widget=forms.HiddenInput) and this in template <form action="{% url 'cart:cart_update' product.id %}" method="POST"> {% csrf_token %} {{ item.update_quantity_form.quantity }} {{ item.update_quantity_form.update }} <button>Update</button> </form> Is it possible to send the form without a button? How to make an update thanks to this forms.IntegerField? -
please i need some help in using javascript es6 (async and await)
l have used react and l learn new concept (async & await) and i use django as backend in my Projcet and react as frontend (using webpack & babel). this my method in my components async loadProducts(){ const response = await fetch(this.endpoint, { method: "GET", headers: { "Content-Type": "application/json" } }); return await response.json(); } and raise some Error (Uncaught ReferenceError: regeneratorRuntime is not defined) -
Should front marketing pages use a separate platform?
We have a Django website with a lot of backend code for the main functionality after a user logs in. But now we are trying to develop the first landing pages, improve the SEO, add FAQ pages etc. Really there is no programming needed here, just a CMS functionality. There are CMS modules for Django, but since the team members who will work on this content are different from the main programming team, it seems to me there might be value in using a different platform for these front 'marketing' pages. I've noticed such dyamics with some websites, like my bank's website seems to run the intro pages on a different server which can't tell if I am logged in to the banking website or not. Any thoughts? Anyone have experience with this kind of scenario? Is it a good practice to use two platforms (kind of micro-services approach), or should I install a CMS module for our django website and keep it all in one monolithic code-base? -
Django Handle Anonymous user in status check
i want to make this function working with the AnonymousUser but dont know who to properly filter for AnonymousUser at the status line: def post_sell_multiple_detail(request, pk): post = get_object_or_404(Post_Sell_Multiple, pk=pk) list_comments = Post_Sell_Multiple_Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk') status = Post_Paid_Sell_Multiple.objects.filter(user=request.user, post_id=pk, status=1).count() paginator = Paginator(list_comments, 10) page = request.GET.get('commentpage') comments = paginator.get_page(page) return render(request, 'app/Post_Sell_Multiple/post_sell_multiple_detail.html', {'post': post, 'comments': comments, 'status': status }) With a user i created its working fine but not with the AnonymousUser. Currently i get the following error here: TypeError at /post/1/sell_multiple 'AnonymousUser' object is not iterable Kind regards -
Reverse for not found
I have some question about redirect. When i am using mapviews.index there are no errors but when i am using mpviews.inder Reverse for mythicPlus_list not found. mythicPlus_list is not a valid view function or pattern name. What should i do to fix this problem? shopping_cart/urls.py from mythicPlus import views as mpviews from mainPage import views as mapviews return redirect(reverse(mpviews.index)) mythicPlus/views.py def index(request): boost_keys_list = mythicPlusOrders.objects.all() context = {'object_list': boost_keys_list} return render(request, "mythicPlus/posts.html", context) mainPage/views.py def index(request): return render(request, 'mainPage/homePage.html')