Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Improve the function of a template tag - Django
I am programming a star rating system, to calculate the stars graphically of a course, I used the following template tag: @register.simple_tag def get_course_rating(course): decimal, integer = math.modf(course.get_average_rating()) rating_stars = { 'stars': range(int(integer)) } if decimal > 0: rating_stars['star_half_empty'] = True rating_stars['stars_empty'] = range((5 - int(integer)) - 1) else: rating_stars['star_half_empty'] = False rating_stars['stars_empty'] = range(5 - int(integer)) return rating_stars In this way I put the star rating in the HTML: {% load course_tags %} {% get_course_rating course as rating %} {% for i in rating.stars %} <i class="icon-star"></i> {% endfor %} {% if rating.star_half_empty %} <i class="icon-star-half-alt"></i> {% endif %} {% for i in rating.stars_empty %} <i class="icon-star-empty"></i> {% endfor %} I find it very tedious to do that, so I wonder if there is a way to improve it? In the sense of the HTML. It occurs to me that the template tag returns html code but I am not sure if it is of good practice ... Any much more professional solution? It will help my learning a lot ... -
Why does Elasticsearch have a terrible performance indexing small amount of data inside docker?
I try to configure django app with elasticsearch inside docker using docker-compose. Building of a small index takes around 15 minutes inside docker. The same command executes in 30 seconds if I run it outside docker. Here is my docker-compose.yml which was based on the official docker installation guide: version: '3' services: web: build: context: ../.. dockerfile: compose/local/Dockerfile restart: on-failure volumes: - ../..:/var/www/chesno env_file: - ../../.env.local depends_on: - elasticsearch1 networks: - esnet - nginx_net nginx: image: "nginx:1.17.6-alpine" restart: always volumes: - ./nginx/conf.d:/etc/nginx/conf.d ports: - "5000:80" depends_on: - web networks: - nginx_net elasticsearch1: image: docker.elastic.co/elasticsearch/elasticsearch:5.5.3 container_name: elasticsearch environment: - node.name=chesno-node - cluster.name=chesno-cluster - bootstrap.memory_lock=true - "ES_JAVA_OPTS=-Xms1g -Xmx1g" ulimits: memlock: soft: -1 hard: -1 volumes: - esdata:/usr/share/elasticsearch/data ports: - 9201:9200 - 9301:9300 networks: - esnet volumes: esdata: driver: local networks: esnet: driver: bridge nginx_net: driver: bridge Command docker-compose docker-compose.yml exec elasticsearch1 curl -XGET http://localhost:9200/_cluster/health?pretty=true returns: { "cluster_name" : "chesno-cluster", "status" : "yellow", "timed_out" : false, "number_of_nodes" : 1, "number_of_data_nodes" : 1, "active_primary_shards" : 22, "active_shards" : 22, "relocating_shards" : 0, "initializing_shards" : 0, "unassigned_shards" : 22, "delayed_unassigned_shards" : 0, "number_of_pending_tasks" : 0, "number_of_in_flight_fetch" : 0, "task_max_waiting_in_queue_millis" : 0, "active_shards_percent_as_number" : 50.0 } The command utilizes only a fraction of machine's CPU and … -
How to serve <script src="somefile.js"> with django?
How to serve script src with django? Example:'''''' And this script should be colled from external website. Please, maybe some one tried or have solution for this. -
AssertionError: 301 != 200 : Couldn't retrieve redirection page
When trying to access a page that requires a User to be logged in, a user should be redirected to a login page to enter their user credentials. However, when the test is ran on that case, I'm getting the AssertionError: 301 != 200 : Couldn't retrieve redirection page '/accounts/sign_in'. I'm not clear on what is going on for this happen? Why am I getting a 301 and not a 302? class LoginRedirectRequest(TestCase): '''Verify that a user is redirected to a login page if they are not logged in.''' @classmethod def setUpTestData(cls): User.objects.create_user( username="testuser", password='*Dh&M3h36v*$J*' ) def test_redirect_to_login_from_edit_profile_view(self): response = self.client.get( reverse("accounts:edit_profile", kwargs={'user_id': 1}) ) self.assertRedirects(response, '/accounts/sign_in/?next=/accounts/profile_edit/1/') @login_required(login_url="/accounts/sign_in") def edit_profile(request, user_id): user = request.user user_data = model_to_dict( user, fields=['username', 'first_name', 'last_name', 'email', 'verify_email'] ) current_profile = Profile.objects.get(user=user) profile_data = model_to_dict( current_profile, fields=['birth', 'bio', 'avatar'] ) if request.method == "POST": user_form = EditUserForm( request.POST, initial=user_data, instance=user ) profile_form = ProfileForm( request.POST, request.FILES, initial=profile_data, instance=current_profile ) if profile_form.is_valid() and user_form.is_valid(): profile_form.save() user_form.save() if any(data.has_changed() for data in [profile_form, user_form]): messages.success(request, "Your profile is updated!") else: messages.success(request, "No profile changes applied...") return HttpResponseRedirect( reverse("accounts:profile", kwargs={'user_id': user_id}) ) else: profile_form = ProfileForm(initial=profile_data) user_form = EditUserForm(initial=user_data) return render( request, 'accounts/edit_profile.html', {'profile_form': profile_form, 'user_form': user_form, 'username': … -
NOT NULL constraint failed: accounts_sellerprofile.user_id
i'm' trying to create a profile form (2 types of user) but when i create the user using SellerProfileSerializer it gives me NOT NULL constraint failed: accounts_sellerprofile.user_id, I don't wanna to put null=True,blank= True in user=models.OneToOne field because this is key information, here is my code. Thanks in advance Models.py class User(AbstractUser): username = None email = models.EmailField(max_length=100,default=None,unique=True) password=models.CharField(max_length=10,default=None) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class SellerProfile(models.Model): user = models.OneToOneField(User,null=False,on_delete=models.CASCADE,default=None) company_name = models.CharField(max_length= 100,unique=True) company_phone = models.CharField(max_length= 100) company_zip = models.CharField(max_length= 50) company_phone = models.CharField(max_length= 50) seller_type = models.CharField(max_length = 50 ,choices =SELLER_CHOICES,default ='1') seller_product = models.CharField(max_length = 50 ,choices =SELLERPRODUCT_CHOICES,default ='1') def __str__(self): return self.company_name Serializers.py class UserCreateSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','email', 'password') def create(self, validated_data): user = User( email=validated_data['email'],) user.set_password(validated_data['password']) user.save() return user class SellerProfileCreateSerializer(serializers.ModelSerializer): user = UserCreateSerializer() def create(self, validated_data): user_data = validated_data.pop('user') user = User( email=user_data['email'], ) user.set_password(user_data['password']) user.save() caretaker = SellerProfile.objects.create(**validated_data) return caretaker class Meta: model = SellerProfile fields=('user','company_name','company_phone','company_zip','seller_type','seller_product') @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) View.py class SellerUsers(ModelViewSet): serializer_class = SellerProfileCreateSerializer queryset = SellerProfile.objects.all() -
Django DRF Field Exists but Serializer does not recognize it
I'm getting an AttributeError: 'QuerySet' object has no attribute 'description' for some odd reason. My model is really simple: class Question(models.Model): PROFILE = 0 EVENT_REPORT = 1 UNIVERSITY_REPORT = 2 USER_REPORT = 3 TYPE_LIST = [PROFILE, EVENT_REPORT, UNIVERSITY_REPORT, USER_REPORT] TYPE_CHOICES = ( (PROFILE, 'Profile'), (EVENT_REPORT, 'User Report'), (UNIVERSITY_REPORT, 'University Report'), (USER_REPORT, 'User Report'), ) description = models.CharField(max_length=100) type =models.IntegerField(choices=TYPE_CHOICES, default=PROFILE) def __str__(self): return self.description serializer: class QuestionSerializer(serializers.ModelSerializer): class Meta: model = Question fields = '__all__' View: class QuestionListView(ListAPIView): authentication_classes = (JWTTokenUserAuthentication, TokenAuthentication) serializer_class = QuestionSerializer permission_classes = (IsAuthenticated, ) def get(self, request, *args, **kwargs): """ takes type paramter. type must be an interger. Types are {}. Returns list of all questions of that type. """.format(Question.TYPE_CHOICES) types = Question.TYPE_LIST try: question_type = kwargs['question_type'] question_type = int(question_type) if question_type not in types: raise Exception("type must be in {}".format(Question.TYPE_CHOICES)) questions = Question.objects.filter(type=question_type) serializer = QuestionSerializer(questions) return Response(serializer.data) except ValueError: raise ValidationError('Must be an interger.') except Exception as e: raise e raise ValidationError(e) Any idea what I maybe missing? I have created objects and they appear fine in the admin view but when I request to list the questions by type I get the error. AttributeError: Got AttributeError when attempting to get a value … -
Return just the last object in Django REST Framework
I'm new to asking on StackOverflow and to Django so I'm sorry if I made any mistakes. So far, I have a basic API with Django and REST Framework. I want to return just the last object that was added to the database, which could be done with the highest ID. This is the models.py: class Humidity(models.Model): value = models.FloatField() def __str__(self): return self.id class Temperature(models.Model): value = models.FloatField() isFarenheit = models.BooleanField() I don't have any time fields, but I can add them if necessary. This is the serializers.py: class HumiditySerializer(serializers.ModelSerializer): class Meta: model = Humidity fields = ('id', 'value') class TemperatureSerializer(serializers.ModelSerializer): class Meta: model = Temperature fields = ('id', 'value', 'isFarenheit') And this is the views.py: class HumidityView(viewsets.ModelViewSet): queryset = Humidity.objects.filter() serializer_class = HumiditySerializer class TemperatureView(viewsets.ModelViewSet): queryset = Temperature.objects.all() serializer_class = TemperatureSerializer All I want to do is return the last object saved. I have searched online but didn't find anything. Thank you. -
How to get values instead of Key from Choices when you use objects.filter(id=pk).values() on Django
Is it possible to get the Choice VALUE instead of KEY, when you use Django model.objects.filter() In my case, I have models.py BIN_TYPE=( ('BLUE', 'Blue'), ('BROW', 'Brown'), ('GREY','Grey'), ('OTHER','Other') ) class BinCollection(models.Model): bin_type = models.CharField(max_length=25, choices=BIN_TYPE) views.py bin_collections':BinCollection.objects.filter(id=pk).values('bin_type') From HTML side, I can use obj.get_bin_type_display() . However, I need this data on views for further calculations. If I was using a table, bin_type__values would work but not for choice. Any ideas? -
Django: Cannot import 'Pages'. Check that 'apps.Pages.apps.PagesConfig.name' is correct
I'm trying to load a signal every time the app gets loaded. (I'm watching a tutorial and I have to do it like that don't ask me why) In the tutorial the guy edits the init.py file of the app like follows: default_app_config = 'payment.apps.PaymentConfig' Now my Problem: I put all my apps in a subfolder "apps" for more overview in my project. So thought I have to write that line like follows: default_app_config = 'apps.Pages.apps.PagesConfig' (My app is called Pages) If I try it I get the error in the title. I also tried to just write: Pages.apps.Pagesconfig but this didn't work either. I'm open for any ideas. Tanks -
Setting SECRET_KEY as enviorment variable
I'm trying to set the secret key as an environment variable. I followed exactly as instructed however get 500 Internal Server Error settings.py import os SECRET_KEY = os.environ['SECRET_KEY'] Then I run: export SECRET_KEY='<my secret key>' Followed by: sudo service apache2 restart -
How to use JavaScript to get the value of a form field which is rendered using crispy filter(from crispy-forms) in Django?
I am using javascript to get the value of a field of the rendered form , rendered using crispy filter from crispy-forms, but I am not getting any value. How do I do it? -
How to run gunicorn with django2.1
Sorry if this question is a duplicate but I am currently facing the problem below. Name of the project: nginx Name of the app: core from the same directory manage.py is, when I try to run gunicorn nginx.wsgi:core I receive the following message from the terminal. [2019-12-25 14:51:31 -0500] [28094] [INFO] Starting gunicorn 20.0.4 [2019-12-25 14:51:31 -0500] [28094] [INFO] Listening at: http://127.0.0.1:8000 (28094) [2019-12-25 14:51:31 -0500] [28094] [INFO] Using worker: sync [2019-12-25 14:51:31 -0500] [28161] [INFO] Booting worker with pid: 28161 Failed to find attribute 'core' in 'nginx.wsgi'. [2019-12-25 19:51:31 +0000] [28161] [INFO] Worker exiting (pid: 28161) [2019-12-25 14:51:31 -0500] [28094] [INFO] Shutting down: Master [2019-12-25 14:51:31 -0500] [28094] [INFO] Reason: App failed to load.``` P.S.: I have installed gunicorn and i am currently inside my virtual environment. pip freeze Django==2.1 django-crispy-forms==1.8.1 gunicorn==20.0.4 pytz==2019.3 I am not sure why this is happening. -
weasyprint not rendering bootstrap4 css correctly
I'm trying to generate an invoice by first designing it as html and then feeding that to weasyprint to generate the pdf. I'm using Django 2.2.5 with bootstrap 4.3.1 and weasyprint 50. The invoice_generator(request) function calls the generate_invoice function with the request, username and template_name. views.py: from invoice_generator import generate_invoice def invoice_generator(request, username): ret_val = generate_invoice(request, username, template_name="ui/invoice.html") return ret_val invoice_generator.py: from django.shortcuts import render from commons.models import SMSUser, SMSMessages, Invoice from commons.serializers import InvoiceSerialzer from django.template.loader import get_template from django.conf import settings from django.http import HttpResponse from weasyprint import HTML, CSS import tempfile from datetime import datetime, date def generate_invoice(request, username, template_name): user_to_invoice = SMSUser.objects.get(username=username) user_invoice = Invoice(invoice_to=user_to_invoice) company_to_invoice = user_to_invoice.company_name company_tin = user_to_invoice.company_tin account = user_to_invoice.pk user_email = user_to_invoice.email all_users_in_company = SMSUser.objects.filter(company_name=company_to_invoice) user_invoice.save() invoice_number = user_invoice.pk paid_status = user_invoice.payment_status all_sms_sent_by_users = {} for user in all_users_in_company: # TODO you can run the code at the begining of each month by doing: # TODO x = date.today() then x = x.replace(day=1) total_sent_by_single_user = SMSMessages.objects.filter( sending_user=user, delivery_status="True", sent_date__year=datetime.now().year, sent_date__month = 10 # sent_date__month = datetime.now().month - 2 ) all_sms_sent_by_users = { "all_sms_sent": [ { "user": user, "total_sent_single_user": total_sent_by_single_user.count() } ] } total_amount_sent = SMSMessages.objects.filter( sent_date__year = datetime.now().year, sent_date__month = 10, … -
django OSError: no library called "cairo" was found on windows
When I run the Django server, I see this problem !! OSError: no library called "cairo" was found no library called "libcairo-2" was found cannot load library 'libcairo.so': error 0x7e cannot load library 'libcairo.2.dylib': error 0x cannot load library 'libcairo-2.dll': error 0x7e -
Allow years before 1950 for Wagtail DateField widget?
I have defined a custom Wagtail Page model with a DateField. When Wagtail renders the date picker widget, it only allows years above 1950 to be selected: For our content, we need to add years before 1950 without expecting the user to manually edit the date string. How can we tell the Wagtail date widget to allow selection of years before 1950? -
Untracked files: (use "git add <file>..." to include in what will be committed) | Error while deploying app through Travis
authentication succeeded checking for app darshil found app darshil dpl.2 Preparing deploy dpl.3 Deploying application HEAD detached at 06887fd Changes not staged for commit: (use "git add <file>..." to update what will be committed) (use "git checkout -- <file>..." to discard changes in working directory) Untracked files: (use "git add <file>..." to include in what will be committed) flights/__pycache__/tests.cpython-36.pyc no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (f8fb8e36aad97af55d2aaccc94a3e830fc75eec5) deploy failed failed to deploy I'm getting this untracked file error while deploying the application through Travis. It seems like it is related to the files that are generated(pycache files) on running the app. I can't figure out how do I fix this problem. -
How do I configure Django URLS to work with all react-router paths
I am trying to use Django Python with React Javascript to create a web application. At first, my Django URLS would load my react-router-dom pages as 404, but after some researching I found that I could use url(r'^(?:.*)/?$', views.index) to load all of my "first level" pages. ex: index/settings. But this url map didn't work for my "second level" pages. ex: index/settings/about. I can't for the life of me figure out how load my second level pages, or re-engineer the previous solution to work for this. I would appreciate any insight on how to solve this issue, and perhaps these types of problems in general when it comes to URLS, because I am a relatively new programmer and I have LOTS to learn. Thanks! urls.py: from django.contrib import admin from django.urls import include, path, re_path from django.conf.urls import include, url from backend import views urlpatterns = [ path('admin/', admin.site.urls), url(r'^$', views.index), path('api/', include('backend.urls')), url(r'^(?:.*)/?$', views.index), ] index.js: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import LoginIndex from './login_index'; import Settings from './settings'; import About from './about'; import * as serviceWorker from './serviceWorker'; import { Route, Link, BrowserRouter as Router } from 'react-router-dom'; const routing = … -
Django create linked models using receiver or overwriting save?
Currently on my first advanced Django project and have what seems to be more of an architectural question. I have two models that represent an approval process and are related as follows: from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Transaction(models.Model): uid = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) requester = models.ForeignKey(User, on_delete=models.PROTECT) type = models.ForeignKey(TransactionType, on_delete=models.PROTECT) class TransactionApproval(models.Model): ACTIONS = ( (0, 'Declined'), (1, 'Approved'), ) transaction = models.ForeignKey(Transaction, on_delete=models.PROTECT) user = models.ForeignKey(User, on_delete=models.PROTECT, related_name='approval_user') action = models.PositiveSmallIntegerField(choices=ACTIONS, null=True, blank=True) @receiver(post_save, sender=Transaction) def create_transaction_approval(sender, instance, created, **kwargs): """ Automatically adds approvers to the transaction when it's created. """ if created: approvers = instance.requester.profile.get_manager() logger.info('[TRANSACTION] Adding managers {0} to approval list (UUID {1})'.format(str(approvers), instance.uid)) for approver in approvers: TransactionApproval.objects.create(transaction=instance, user=approver) Now I've been creating the TransactionApprovals automatically when a certain Transaction is created using @receiver as outlined above as approvals are a crucial and required part of Transactions. However I'm not sure if it actually doesn't make more sense move these actions to the already overwritten def save() method of Transactions, to avoid scattering logic and linking back and forth to models. Which of the two is architecturally cleverer and more standard-compliant? """ Alternative def save(): method of … -
How to Add a Folder to Path onn Ubuntu Virtualenv?
here is my manage.py, as you see I added my software folder inside the path so that I can import any module inside it from anywhere. This completely works in my local server but when I try to deploy my django project on my real server, it gives import error every time I try to import a module from software folder. I also try add2virtualenv but it didn't work either. How can I solve this issue ? -
Is there any request.forms in django rest framework same like flask restful?
I am facing an error in which when I use form data in angular to send a post request to django restframework I am receiving data like this "{'product_name': ['some'], 'product_price': ['100'], 'product_description': ['product_description'], 'incremented_by': ['1.0'], 'category_id': ['1'], 'sub_category_id': ['2']}" I successfully used formdata from angular to flask restful backend service but in django i am recieving as list : Angular code : formData.append('product_name',this.formGroup.get('name').value); formData.append('product_description',this.formGroup.get('description').value); formData.append('product_price',this.formGroup.get('price').value); formData.append('incremented_by',this.formGroup.get('name').value); formData.append('category_id',this.formGroup.get('name').value); formData.append('sub_category_name',this.formGroup.get('subCategoryName').value); -
django send json patch request during test
I am using django 3.0. Here is my view that I am trying to test: def myview(request): values = {} if request.method == 'PATCH': keys = QueryDict(request.body) print(keys) for key in keys: cache.set(key, keys[key], timeout=300) values[key] = keys[key] return JsonResponse(values, status=200) and my test case: class ValueViewTestCase(TestCase): def setUp(self): self.c = Client() def test_value_updated(self): data = {'key_1': 'updated_val'} response = self.c.patch('/values/', data) print(response.json()) # self.assertEqual(response.json(), data) # ->> test failing console logs: Creating test database for alias 'default'... System check identified no issues (0 silenced). <QueryDict: {'{"key_1": "updated_val"}': ['']}> {'{"key_1": "updated_val"}': ''} I want to send data as key value pair, but somehow it malformed , right now whole request acting as a key. -
Django view function not being called on click of submit
I have two view functions in my views.py. The first one renders the index.html Second is created for the form action on index.html (update_db). When I click on submit on the index.html file, it changes url to /update1, but the function call has print('HI') and I cannot see that on console. Neither are any new files created after it runs. Intially I had return render(request, 'index.html', {} ) but I am not sure if that should be returned. Is there some problem with my urls.py? views.py from django.shortcuts import render from django.conf import settings from .models import Image, Profile import random # Create your views here. def index(request): y= random.randint(0,10) for i in range(0,10): pass p = Image.objects.all()[y] print(p.p_img) count = p.p_img_count lst = [p.s_image1, p.s_image2, p.s_image3, p.s_image3, p.s_image4, p.s_image5] tmp =[] for i in range(0,3): px = Image.objects.all()[random.randint(0,14)] tmps=[px.s_image1, px.s_image2, px.s_image3, px.s_image3, px.s_image4, px.s_image5] tmp.append(tmps[random.randint(0,4)]) x = random.randint(0,4) s_img = [lst[x]] + tmp random.shuffle(s_img) print('hevfxy') print(p.p_img) return render(request,'index.html',{"p_img":p, "s_img": s_img, 'media_url':settings.MEDIA_URL}) def update_db(request): print('HI') # username = request.user.username user = request.POST.get("user") p_img = request.POST.get("p_img") ans = request.POST.get("ans") y = Image.objects.get(p_img=p_img).id y=y-8 Profile.objects.create(user=user, p_img_id=y, p_ans=ans) return something urls.py (main conf) from django.conf.urls import url, include from django.urls import path from … -
How to use django-filter with a ListView class view for search?
I have a filter: class BookFilter(django_filters.FilterSet): class Meta: model = Book fields = '__all__' and a ListView to see the results: class SearchResultsListView(ListView): model = Book context_object_name = 'book_list' template_name = 'book/search_results.html' I want to have a search form where you can filter based on all fields of a class (ex, all books written by X with more than 3 stars). How do I pass the form to the model, and how do I use the get request to filter with django-filter as needed? I'm using Django 3.0 and django-filter 2.2.0 -
Using a django model method as static function
I would like to use a django model method as a static function. More specifically, I would like to use a model method called age, indicated below, both on an instance of my table Patient but I would also like apply the age function to a rows in a pandas dataframe using the pandas apply function. Is this possible to do or will I have to write another function specifically to work on my dataframe? class Patient(models.Model): pat_id1 = models.AutoField(db_column='Pat_ID1', primary_key=True) birth_dttm = models.DateTimeField(db_column='Birth_DtTm', blank=True, null=True) objects = models.Manager() class Meta: managed = False db_table = 'Patient' @property def age(self): return relativedelta(date.today(), self.birth_dttm.date()).years -
Why urls.py is not creating automatically
Hello i'm new in django and sorry for my weird question! Almost every video which i saw about Django (for begginers), people who create applications with startapp command, they have to adds urls.py manually in app. Question is, if urls.py is so important for views and for our app why it's not creating automatically when we run startapp command! I'm using (2.2v)