Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImportError: cannot import name 'url' from 'django.conf.urls' django-rest-auth
error : from django.conf.urls import url ImportError: cannot import name 'url' from 'django.conf.urls' -version Django==4.0.1 django-rest-auth==0.9.5 Pl help me.Thank you in advance url.py # Core Django imports from django.contrib import admin from django.urls import path, include from django.urls import re_path,include # from django.conf.urls import url,include from django.conf import settings # Rest framework imports from rest_framework import permissions # Simple JWT imports from drf_yasg.views import get_schema_view from drf_yasg import openapi schema_view = get_schema_view( openapi.Info( title="Heathy Living Guide API", default_version='v1', description="Heathy Living Guide", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = ( path('admin/', admin.site.urls), path('api/authentication/', include('apps.authentication.urls'),authentication'), path('api/users/', include('apps.users.urls'), name='users'), path('rest-auth/', include('rest_auth.urls')), # re_path(r'^rest-auth/', include('rest_auth.urls')) ) urlpatterns += [ path('api/swagger/', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('api/redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc') ] -
Optimize Django tests with preloaded database
I am trying to reduce my CI usage and make my code cleaner by pre-loading my test database using a custom class. I had multiple files/classes that looked like this: class TestSomething(TestCase): def setUp(self): User.objects.create(...) def test_something(self): pass I converted them into: class TestSomething(PreloadedTestCase): def test_something(self): pass with a common PreloadedTestCase class: class TestSomething(TestCase): def setUp(self): User.objects.create(...) This does make the code cleaner and removes a lot of duplicate lines, but it seems to increase the CI execution time. Is PreloadedTestCase.setUp() run multiple times? If so, how can I have a common class that is run only once against the database? I looked into fixtures but it is only populating the database, I would have to query it to access my objects in the tests. -
What's the default value for a DecimalField in Django?
I'm adding a new DecimalField to my model, what value will it have by default in the database (if I don't specify the default explicitly)? amount = models.DecimalField(max_digits=15, decimal_places=3) I'm expecting it will be either NULL or 0.0 (or None or Decimal(0.000) in python), but which? Couldn't find this mentioned in the docs: https://docs.djangoproject.com/en/2.2/ref/models/fields/#decimalfield I'm using Django 2.2, but expect this is consistent across versions. -
'builtin_function_or_method' object has no attribute 'split' in django [closed]
def index(request): product = () catProds = Product.objects.values(category) cats = {items['category'] for items in catProds} for cat in cats: prod = Product.objects.filter(category=cat) product.append(prod) params = {'product':product} return render(request, 'shop/index.html', params) -
Django 4 and Unittest loader
We use Django for an online webshop, and want to upgrade to Django 4. However, since upgrading on a test branch, we have a problem, that I will highlight here. We serve two different markets, lets call them Market A and B :) Since these two markets can have different functionalities, our INSTALLED_APPS gets populated like so: MARKET_SPECIFIC_APPS = { MARKET_A: [ 'market_a.apps.MarketAConfig', 'payment_system_a.apps.PaymentSystemAConfig' ], MARKET_B: [ 'market_b.apps.MarketBConfig', 'payment_system_b.apps.PaymentSystemBConfig', ], } if MARKET in MARKET_SPECIFIC_APPS: # If there is a market-specific app, add it to INSTALLED_APPS INSTALLED_APPS += MARKET_SPECIFIC_APPS[MARKET] However, when running MARKET specific tests for each market, only MARKET_A passes. MARKET_B now throws an error, since upgrading from Django 3.2 to Django 4 RuntimeError: Model class payment_system_b.models.payment.Payment doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. Meaning, this test is still run, and the test runner includes it in INSTALLED_APPS even tho it shouldnt. Is there any change from the Django 4 changelog im missing about this? Running these market-specific tests was working fine before upgrading to Django 4 -
What does set -e do in Nginx?
This is my code, I don't understand it completely. I would really appreciate your help #!/bin/sh set -e envsubst < /etc/nginx/default.conf.tpl > /etc/nginx/conf.d/default.conf nginx -g 'daemon off;' -
How can I resolve this issue with installing django2-semantic-ui=1.2.2 using pip?
I am trying to locally run an existing django application and install django2-semantic-ui==1.2.2 using the command: pip install django-semantic-ui=1.2.2. Here is the error I am getting: Using cached django2_semantic_ui-1.2.2.tar.gz (8.1 kB) ERROR: Command errored out with exit status 1: command: 'C:\Users\aakar\OneDrive\Documents\Data4Good\data4good-django\myenv\Scripts\python.exe' -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"'; __file__='"'"'C:\\Users\\aakar\\AppData\\Local\\Temp\\pip-install-fti4wdiz\\django2-semantic-ui_86580566b774418c94ae3e3de149c712\\setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\aakar\AppData\Local\Temp\pip-pip-egg-info-u198istg' cwd: C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\ Complete output (7 lines): Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\aakar\AppData\Local\Temp\pip-install-fti4wdiz\django2-semantic-ui_86580566b774418c94ae3e3de149c712\setup.py", line 5, in <module> long_description = fh.read() File "c:\python3\lib\encodings\cp1252.py", line 23, in decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 919: character maps to <undefined> ---------------------------------------- WARNING: Discarding https://files.pythonhosted.org/packages/a1/76/e57ee8bf33259f832ae9f5c8d4d24a701516389f633efa37627922b6706a/django2_semantic_ui-1.2.2.tar.gz#sha256=a5efe89908c11e231dcea7cad249fd7bf629f7189d5621cd0d3bc82d154a9676 (from https://pypi.org/simple/django2-semantic-ui/) (requires-python:>=3.*). Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ERROR: Could not find a version that satisfies the requirement django2-semantic-ui==1.2.2 (from versions: 1.0.0b0, 1.0.0b1, 1.0.0b3, 1.0.0b4, 1.0.0, 1.0.1b0, 1.0.1, 1.1.0b0, 1.1.0, 1.1.1, 1.1.2, 1.2.0b0, 1.2.0b1, 1.2.0b2, 1.2.0b3, 1.2.0, 1.2.1b0, 1.2.1b1, 1.2.1b2, 1.2.1b3, 1.2.1b4, 1.2.1b5, 1.2.1b6, 1.2.1, 1.2.2b0, 1.2.2b1, 1.2.2) ERROR: No matching distribution found for django2-semantic-ui==1.2.2 All the other packages from requirements.txt were successfully installed. … -
Get input from front-end of the website and generate file corresponding in python
i am creating an website in which the users are going to input some form data and from the form data that the user given i will generate a excel file based on it using python, my python script is already done, but i dont know how i can connect it to the front-end / javascript so the i can pass the data to my python file script download the excel file to the user, i was looking at some django / flask tutorials but haven't found nothing that solves my problem, thanks for any reply in advance -
After intregation of django and reactjs blank page is rendered instead of component
I am working on full stack website I tried to integrate django with reactjs and was successful, but the problem is that it has returned a blank page instead of the reactjs component. this is output this is index.html inside build folder this is index.js from src -
'collections.OrderedDict' object has no attribute 'id'
My serializers: class SpeakerSerializer(serializers.ModelSerializer): class Meta: model = Speaker fields = ['id',...] class CourseSerializer(serializers.ModelSerializer): .... author = SpeakerSerializer(many=False, required=True) .... class Meta: model = Course fields = ['id', 'author',...] def create(self, validated_data): ... author = validated_data.get('author') ... course, _ = Course.objects.create(author=author.id, **validated_data) course.save() I'm sending POST request to this serializer and getting this response: Help please! course, _ = Course.objects.create(author=author.id, **validated_data) AttributeError: 'collections.OrderedDict' object has no attribute 'id' -
Convert django request.body (bytes) into json
I have a class based view in which a put function and trying to get request.body into json. from django.views import View import json class StudentView(View): def put(self, request): body = request.body #b'name=Arpita+kumari+Verma&roll=109&city=USA' json_body = json.loads(body) # JSONError 'expecting dict values but given bytes object' # I want something like this # { # 'name':'Arpita kumari Verma', # 'roll':'109, # 'city':'USA', # } json_dumped_data = json.dumps(json_body) return HttpResponse(json_dumped_data, content_type="application/json") -
Django template won't respond to css file , worked briefly yesterday
It is exactly how it sounds. My main goal is to make the css file work with django template so I can design my templates. Yesterday I tried and initially my folder structure was wrong. I placed static folder in myapp folder. Didn't work. I tried putting it in templates folder. It only worked when I had 2 static folders both in myapp and templates folder. Realized it isn't a working solution. I placed a single static folder with a css file in it in mysite folder, at the same level with myapp folder and everything seemed to work. Satisfied I left at that. Today I came back to it and it stopped working. It seems to be frozen. Not responding to the new codes. Old colors are showing but new colors aren't, which is odd. Tried changing the old colors, it won't change. Literally my css file has a class name .intro where I changed the color from purple to red, my template still showing purple which I set yesterday. My template shows no error and all the texts and divs I am adding are updating with no issue.Kind of lost where I may have gone wrong. Certainly don't … -
How to open a modal when moving a page
The currently implemented code shows the modal when clicking the button. However, I would like the modal to be displayed when moving to the main page after logging in. (using Django) JavaScript's window.open is not what I want because it prints a new window. I want the modal window to be displayed automatically when the main page is reached upon successful login. Is there a way? [index.html] <div class="modal fade" id="quality" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-lg" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">Quality</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body row"> <div class="col-sm-12"> {% include 'pages/quality_POPUP.html' %} </div> </div> </div> </div> <button type="button" class="btn pull-right" data-toggle="modal" data-target="#quality">POP UP</button> -
Get sales totals per account using model property in django
Okay I thought I can google my way out of this but I am stuck. Desired results are Account_name Total local sales 1802.50 int sales 0.00 from my models class Account(models.Model): account_number = models.IntegerField(unique=True, null=True, blank=True, default=None) account_name = models.CharField(max_length=200, null=True, blank=True, unique=True) class Sales(models.Model): account_name = models.ForeignKey(Account, on_delete=models.CASCADE, related_name='incomes') amount = models.DecimalField(max_digits=8, decimal_places=2, blank=True, null=True) def sales_total(self): sales_total = Income.objects.values('account_name').order_by('account_name').annotate(sales_total=Sum('sales__total')) return sales_total so in my template when I do {% for account in accounts %} <tr> <td>{{ account.sales_total }}</td> </tr> {% endfor %} I get Account_name Total local sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> int sales <QuerySet [{'account_name': 3, 'sales_total': Decimal('1802.5')}]> -
cannot import name 'Channel' from 'channels'
I am using python version==3.8.10 and Django==2.2 and channels==3.0.4 . I am getting error from channels import Channel ImportError: cannot import name 'Channel' from 'channels' (/home/kritik/py38_djanngo2.2_new/lib/python3.8/site-packages/channels/init.py) Can anyone help me on this ? -
after login having error 'Anonymous User' object has no attribute '_meta'
I m new in Django m creating a signup form if submit the form the data is stored success fully but I m having a error in redirection or login view.py from Blog.forms import SignupForm from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect def signup_form(request): form=SignupForm() if request.method=='POST': form=SignupForm(request.POST) if form.is_valid(): user=form.save() user.refresh_from_db() # load the profile instance created by the signal user.save() raw_password = form.cleaned_data.get('password') user = authenticate(username=user.username, password=raw_password) login(request, user) return HttpResponseRedirect('home/') return render(request,'blog/signup.html',{'form':form}) redirecting in setting file setting.py LOGIN_REDIRECT='home/' LOGOUT_REDIRECT_URL='/logout' my form file look like that forms.py from django.contrib.auth.models import User class SignupForm(ModelForm): class Meta: model=User fields=['username','first_name','last_name','email','password'] labels={'username':' Enter User Name','password':' Enter Password','email':'Enter Email','first_name':'Enter First Name','last_name':'Enter Last Name'} widgets={'password':forms.PasswordInput,'username':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Your User Name'}), 'password':forms.PasswordInput(attrs={'class':'form-control','placeholder':'Enter Your Password'}), 'email':forms.EmailInput(attrs={'class':'form-control','placeholder':'Enter Your Email'}), 'first_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter First Name'}), 'last_name':forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Last Name'}) } urls.py path('signup/',views.signup_form,name='signup/'), 'Anonymous User' object has no attribute '_meta' -
Django post request field always null
My post request from React frontend to Django backend won't work and I'm not sure why. It always says that "question" is null. I know there to be a question already in the database with a primary key id of 19. Quiz.js: const createAnswerSubmission = () => { submit(questionIndex); const data = { "question": quiz.question[questionIndex].id, "answer_choice": answerSelected[questionIndex], "user": window.localStorage.getItem("user") } const url = "http://localhost:8000/api/submittedanswer/"; axios.post(url, data, {headers: { Authorization: `Token ${window.localStorage.getItem('auth_token')}`, Accept: "application/json", 'Content-Type': 'application/json', } }).then(function (response) { console.log(data) }) .catch(function (error) { console.log(data); alert(error); }); } The console log shows the following: {question: 19, answer_choice: 4, user: '1'} And the request payload shows: {question: 19, answer_choice: 4, user: "1"} Yet I am getting some error: IntegrityError at /api/submittedanswer/ null value in column "question_id" of relation "api_submittedanswer" violates not-null constraint DETAIL: Failing row contains (123, 4, null, 1). models.py: //... class Question(models.Model): pt = models.ForeignKey(PT, on_delete=models.CASCADE, null=True, blank=True, related_name = 'pt') section = models.ForeignKey(Section, on_delete=models.CASCADE, null=True, blank=True, related_name = 'section') question_type = models.CharField(max_length=20) number = models.IntegerField() stimulus = models.CharField(max_length = 1000) question = models.CharField(max_length = 400) answer = models.ManyToManyField(AnswerChoice) correct_answer = models.IntegerField(default = 0) def __str__(self): return "PT " + str(self.pt) + " Section " + str(self.section) + " … -
Use python par file with gunicorn
I want to use a django app packaged as a par file generated via https://github.com/google/subpar with gunicorn. Is this possible? -
Factory boy field not getting expected value
I am using factory boy to generate data for my django application. It is a tennis matches app which has player one and two as shown in below class. Either of it will be a winner which will be store in winner_one field. I am getting some third player name in this field instead of player one or two. That player is also present in table. Please advise what would be the best way to fix this? class MatchFactory(factory.django.DjangoModelFactory): class Meta: model = Match player_one = factory.SubFactory(UserFactory) player_two = factory.SubFactory(UserFactory) league = factory.Iterator(League.objects.all()) type = fuzzy.FuzzyChoice(Match.MATCH_CHOICES, getter=lambda c: c[0]) winner_one = random.choice([player_one, player_two]) start_date = fuzzy.FuzzyNaiveDateTime( datetime.today() + relativedelta(months=1), datetime.today() + relativedelta(months=3) ) end_date = start_date -
How to open URL when clicking push notification using firebase-admin in Python Django
I'm going to use python django's firebase-admin to send a notice to FCM push notification when the app is in the background state. When the user clicks the push notification, the iOS/Android app attempts to open the url of the notice. How should I pass this url value? noticeView.py: from firebase_admin import credentials, messaging import firebase_admin class noticeCreateView(View): def post(self, request, *args, **kwargs): title = request.POST.get('title') content = request.POST.get('content') push = request.POST.get('push') if push: key = '....FCM Server Key...' cred = credentials.Certificate('./serviceAccountKey.json') default_app = None if '[DEFAULT]' not in firebase_admin._apps: default_app = firebase_admin.initialize_app(cred) else: default_app = firebase_admin._apps['[DEFAULT]'] if default_app is not None: topic = 'notice' message = messaging.Message( notification=messaging.Notification( title=title, body=sentence, ), apns=messaging.APNSConfig( payload=messaging.APNSPayload( aps=messaging.Aps(alert=messaging.ApsAlert( title=title, body=content, )), ), ), topic=topic ) try: response = messaging.send(message) print(response) except Exception as e: print('Push Fail', e) return HttpResponseRedirect(reverse('notice_list')) -
Postgresql - "ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252""
So I was querying on my Heroku server with this query // Command to get into postgres heroku pg:psql // Query SELECT * FROM cheers_post; then I get this error ERROR: character with byte sequence 0xf0 0x9f 0x98 0x84 in encoding "UTF8" has no equivalent in encoding "WIN1252" I don't know what character 0xf0 0x9f 0x98 0x84 is in UTF8. This error isn't super explicit so I'm not really sure what the issue is or how to fix it. Anyone experience this? Something interesting is when I query the cheers_post table via a Django API endpoint it returns Post.DoesNotExist error. -
Django & Celery: no such table
I am attempting to create a couple tasks with Celery that post data to a Django model, I have everything functioning except for some reason the Celery tasks are not able to see the table even though it exists in the DB and Django can post data to it. This is happening with PostgreSQL, it works when using SQLite3. Has anyone encountered this type of issue and how were you able to solve it? tasks.py -------- # tasks from __future__ import absolute_import, unicode_literals from celery import Celery from celery import app, shared_task # scraping import requests from bs4 import BeautifulSoup import json from datetime import datetime import lxml from rss_feed_scraper.models import PressReleases # logging from celery.utils.log import get_task_logger logger = get_task_logger(__name__) @shared_task(serializer='json') def save_function(article_list): for article in article_list: try: PressReleases.objects.create( title=article['title'], description=article['description'], link=article['link'], image_url=article['image_url'], published=article['published'], source=article['source'] ) except Exception as e: print('failed at inserting article') print(e) break @shared_task def prnewswire_rss(): article_list = [] try: print('Starting the scraping tool') r = requests.get('https://www.prnewswire.com/rss/all-news-releases-from-PR-newswire-news.rss') soup = BeautifulSoup(r.content, features='lxml') articles = soup.findAll('item') for a in articles: title = a.find('title').text description = a.find('description').text # Get Link link = str(a) i = link.find("<link/>") j = link.find("<guid") media_content = a.find('media:content') image_url = None if media_content: image_url = … -
Iterable list in Django HTML?
I want to use bootstrap to make a carousel using D.R.Y. methods. my idea (and it may not even be feasible) is to have a list or dictionary and cycle through image locations. Here's what I've written so far. <div class="carousel-inner"> {% with images = ['gyro.jpeg', 'pizza.jpeg', 'soup.jpeg', 'brocpizza.jpeg' ,'dessert.jpeg'] %} {% for image in images %} <div class="carousel-item active" data-bs-interval="10000" style="background-image:url({%static {image}%})"> <div class='container'> <section class='time'> <h3><strong>HOURS</strong></h3> <h3><strong>Monday - Saturday</strong></h3> <h3><strong>11 a.m. - 9 p.m.</strong></h3> </section> <div class='headline'> <h1>Title</h1> <h2>Menu</h2> </div> <section class='address'> <h3> <strong>NAME</strong> </h3> <h4>Phone</h4> <h4>Address</h4> <h4>City</h4> </section> </div> </div> {% endfor %} {% endwith %}``` -
Getting a 400 Bad Request Error After GCP App Engine Deployment of Django App
So I have a Django App which has its views connect to a BigQuery where it would pull data from. I want to deploy the web app to a GCP App Engine and have followed the instructions that are stated on GCP App Engine Website. I have successfully created the SQL instances and can run the web app locally. I deploy the app using gcloud app deploy, it says that it is successfully deployed. When I try to open the web app on the browser gcloud app browse, it just returns me a 400 Bad Request Error. I'm kinda lost as I don't know what I'm missing during deployment plus I don't know which part of my code I should be putting on here so do comment below what I need to be posting in order to guide you to help me and I will update the post. Another thing is that, since I'm pulling data from the BigQuery, locally I have this JSON file which has all the credentials needed for the BigQuery API and I access it in the settings.py as such: os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/Users/user/Documents/website/bq-api.json' The thing is I'm wondering if I should be including this inside the … -
Django Filters 'str' object has no attribute '_meta'
I am creating an page that allows the user to filter a dataset, hit search, and see the results update below. I am getting the following attribute error: 'str' object has no attribute '_meta' and I cannot figure out why this is happening. Any help is appreciated views.py: def week(request): #orders = Pick.objects.get(id=pk_test) orders = Pick.objects.all() #orders = week.order_set.all() myFilter = PickFilter(request.GET, queryset=orders) orders = myFilter.qs context = {'week':week, 'orders':orders, 'myFilter':myFilter} return render(request, 'app/filter_list.html',context) pick_list.html: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ myFilter.form }} <button type="submit">Search</button> </form> <ul> <table class="table table-hover" id="table-ajax" style="background-color: white;"> <thead style="background-color: #de5246; color:white; border-bottom:white"> <tr> {% comment %} <th></th> {% endcomment %} <th style="width: 50px; text-align: center;"></th> <th>{{ object_list|verbose_name:'field:name' }}</th> <th>{{ object_list|verbose_name:'field:hometown' }}</th> <th>{{ object_list|verbose_name:'field:occupation' }}</th> <th>{{ object_list|verbose_name:'field:age' }}</th> <th>Progress</th> <th style="width: 160px; text-align: center;">Rank</th> </tr> </thead> <tbody class="order" data-url="{% url 'cms:reorder' …