Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
JSONDecodeError Expecting value: line 1 column 1 (char 0). (New to Django)
I am new to Django and currently, I am developing an eCommerce site. Facing this error -- JSONDecodeError Expecting value: line 1 column 1 (char 0). Can someone please help me out. Request Method: GET Request URL: http://127.0.0.1:8000/process_order/ Django Version: 2.2.8 Exception Type: JSONDecodeError Exception Value: Expecting value: line 1 column 1 (char 0) Exception Location: C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py in raw_decode, line 355 Python Executable: C:\Users\User\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.2 Python Path: ['D:\pythonprac\ecommerce\Website', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32', 'C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in raw_decode 353. obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\pythonprac\ecommerce\Website\store\views.py" in processOrder 88. data = json.loads(request.body) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json_init_.py" in loads 348. return _default_decoder.decode(s) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in decode 337. obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py" in raw_decode 355. raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /process_order/ Exception Value: Expecting value: line 1 column 1 (char 0) -
How to solve KeyError in Django?
I have multiple Apps in my Django website, And i want to get the data from all Apps, I definds all the apps in settings.py file, and i created a function in admin.py file for display the data. But i am getting Keyerror, please check my code and let me know where i am Mistaking here is my settings.py file code.. ADMIN_ORDERING = [ ('manager', [ 'Products', 'ProductTemplates', ]), ] here is my admin.py file which is displaying the data in views.. def get_app_list(self, request): app_dict = self._build_app_dict(request) for app_name, object_list in settings.ADMIN_ORDERING: app=app_dict[app_name] app['models'].sort(key=lambda x: object_list.index(x['object_name'])) yield app i am getting error in this line app=app_dict[app_name] it's displaying KeyError at/ manager, and manager is my django project app name -
Duplicate results when querying using SearchVector
I have an abstract model class called PostType with a few submodels derived from it. The model looks like this: class PostType(models.Model): title = models.CharField( max_length=255, unique=True, verbose_name='Title' ) description = models.CharField( max_length=255, default='', verbose_name='Description' ) tags = models.ManyToManyField( to=Tag, blank=True, verbose_name='Tags' ) content = RichTextUploadingField( default='', verbose_name='Post Content' ) class Meta: abstract = True It has a related Tag model that looks like this: class Tag(models.Model): name = models.CharField( max_length=255, verbose_name='Name', unique=True ) description = models.TextField( verbose_name='Description', default='' ) In one of my views I am trying to query all of the subclasses, using a SearchVector and searching multiple fields: query = request.GET.get('s') from django.contrib.postgres.search import SearchVector get_qs_list = [model.objects.annotate( search=SearchVector('title', 'description', 'content', 'tags__name') ).filter(search=query) for model in models.PostType.__subclasses__()] Now, the search is returning all of the results that it should. However, for some reason it's returning duplicate results for some items. Sometimes I get two copies of the same item, sometimes three or four. The problem seems to go away if I remove 'tags__name' from the SearchVector, but I don't understand why. What am I doing wrong, and why does it work if I don't search the related field? -
Django | Render Plotly graph
I'm trying to pull a Plotly graph into a Django view. If I use the code of the Plotly graph inside views.py I have no problem on seeing the line chart, however, I'd like to move this code to a plots.py file and then import it into views.py so there's a better project structure. Current views.py from plotly.offline import plot import plotly.graph_objects as go def plotlyTest(request): x_data = [1,2,3] y_data = [4,3,6] stuff = go.Scatter( x=x_data, y=y_data, mode='lines', name='Stuff', opacity=0.8, marker_color='blue' ) data = [stuff] # Create figure fig = go.Figure(data=data) plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False, link_text="") context = { 'plot_div':plot_div, } return render(request, 'custom_app/plotly_test.html', context) Desired views.py (pseudo code) from apps.another_app import plots def plotlyTest(request): plot_div = testPlot context = { 'plot_div':plot_div, } return render(request, 'admin/plotly_test.html', context) plots.py from plotly.offline import plot import plotly.graph_objects as go def testPlot(request): x_data = [1,2,3] y_data = [4,3,6] stuff = go.Scatter( x=x_data, y=y_data, mode='lines', name='Stuff', opacity=0.8, marker_color='blue' ) data = [stuff] # Create figure fig = go.Figure(data=data) plot_div = plot(fig, output_type='div', include_plotlyjs=False, show_link=False, link_text="") return plot_div This seems to be more a Python logic than a Django logic. Maybe creating a class based view and use template tags should work? -
Django unable to load static files: Attribute error at /admin you need a private key to sign credentials
I have a docker image, which I deploy using Google Cloud Run. For static and media files I'm using Google Cloud Storage. Here is the relevant part of settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(os.environ.get('STORAGE_URL', default=BASE_DIR), "media") STATIC_ROOT = os.path.join(os.environ.get('STORAGE_URL', default=BASE_DIR), "static") DEFAULT_FILE_STORAGE = os.environ.get('STORAGE_BACKEND', default='django.core.files.storage.FileSystemStorage') STATICFILES_STORAGE = os.environ.get('STORAGE_BACKEND', default='django.core.files.storage.FileSystemStorage') GS_BUCKET_NAME = os.environ.get('GS_BUCKET_NAME') The environment values are: STORAGE_URL= https://storage.googleapis.com/<my-bucket-name>/ STORAGE_BACKEND=storages.backends.gcloud.GoogleCloudStorage GS_BUCKET_NAME=my-bucket-name After deployment, when I visit my google cloud run app url. I am not able to go to admin page. it gives the following error: AttributeError at /admin you need a private key to sign credentials.the credentials you are currently using <class 'google.auth.compute_engine.credentials.Credentials'> just contains a token. see https://googleapis.dev/python/google-api-core/latest/auth.html#setting-up-a-service-account for more details. Interestingly, the collectstatic command works flawlessly... When I deploy my image it copies static files to my storage bucket. But when accessing it through the url, it gives me this error. -
Django query objects by subset of possible foreign keys
I have a query: topics, that looks like topics = Topic.objects.filter(top_is_published=True, top_last_used_date__range=(issue.wir_issue_date - timedelta(days=7), issue.wir_issue_date)) And I want all the articles which have one of the objects in 'topics' as their foreign key. When I try to use a lookup like: articles = News.objects.filter(top_name=topics) or something similar, I get the error "ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing." I've searched for an example, but I can't find one. Thanks for any help. -
Scheduling Tasks in Django
I am new to Django. I built a program that lets teachers assign homework to students. The homework has a due date that is different for each student. I want to make it so that 1 hour before the homework is due for that particular student, they get sent an email. So, for example: Student 1 with HW due at 3 pm would get an email at 2 pm Student 2 with HW due at 1 am would get an email at 12 am How can I achieve this? Thanks!!! -
How to get request values from Django decorator
In my decorator: def check_user_identity(function): def wrap(request, *args, **kwargs): response_check_user = mock_response.check_user_identity(requested_data=request.data['msisdn']) if response_check_user['status'] == SUCCESS_CODE: return function(request, *args, **kwargs) return Response(data=INVALID_USER, status=status.HTTP_400_BAD_REQUEST) wrap.__doc__ = function.__doc__ wrap.__name__ = function.__name__ return wrap In my views: Here the request parameter has my values which i have requested to proceed. First of all decorator is called. I want to access my request data from the decorator. class VerifyWallet(APIView): @check_user_identity def post(self, request): logger.debug(msg=request.data) serializer = VerifyWalletSerializer(data=request.data) if not serializer.is_valid(): logger.error(msg=serializer.errors) return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(data='success', status=status.HTTP_200_OK) -
Django forms: Accessing cleaned_data in clean() - not working?
Ok so I'm trying to write the clean() in a forms class. Issue: when accessing the values: name, age, height from the clean_data dict it is not returning the field values. Am I accessing the dictionary correctly? because the if condition isn't working correctly class PersonForms(forms.ModelForm): name = forms.CharField(max_length=20, help_text="Your Name") height = forms.DecimalField(help_text="height..") age = forms.IntegerField(help_text="age:") class Meta: model = Person fields = ('name', 'height') # Fields are validated in their own field_clean() method.clean() method is to validate any combination or # multiple fields with values relating to one another. def clean(self): print("clean...$$") # run the standard clean method first - this ensures # The ModelForm.clean() method sets a flag that makes the model validation step validate the uniqueness of # model fields that are marked as unique, unique_together or unique_for_date | month | year. cleaned_data = super(PersonForms, self).clean() # once the parent's clean function valids data - access fields via cleaned_data dictionary name = cleaned_data.get("name") age = cleaned_data.get("age") height = cleaned_data.get("height") if "max" not in name or age > 13: print("*************** name", name) raise ValidationError(_("Err, type %(value) as name or age %(age) invalid"), params={'value': name, 'age': age}, code='invalid1') -
Django: How to add Image of User in UserPostList View
I am trying to add the profile image of each user(designer) in the below list view For each designer, there is a profile image that has already been uploaded before I am just trying to get it and show it in the UserPost List View. Currently, with the below code, the designer image is not showing. Here is the views.py class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' queryset = Post.objects.filter(admin_approved=True) paginate_by = 6 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user, admin_approved=True).order_by('-date_posted') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) has_items = Item.objects.filter(designer__username=self.kwargs['username']).exists() context['has_items'] = has_items return context Here is the template {% if has_items %} <h1> Hello, this is {{ view.kwargs.username }} </h1> -------------------------------------- <img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear {% else %} <h1>Hello, this is {{ view.kwargs.username }} </h1> -------------------------------------- <img class="profile_image" src={{ designer.profile.image.url }}> <----------- I want it to appear {% endif %} -
Migrate UUID PK to Django's Default PK
I made a mistake and made the PK of my model a UUID: id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) I want to revert it to Django's default, where every instance automatically has a PK, without having an ID model field. How can I do this? Thanks! -
Django Server Unable to Open Admin Page
I am following an online course on Django, and my browser fails to load the admin page. I created a job, added it to INSTALLED_APPS in settings.py, and added it in admin.py as follows: from .models import Job Register your models here. admin.site.register(Job) In urls.py I believe I have the standard admin url urlpatterns = [ path('admin/', admin.site.urls), path('home/', jobs.views.home, name='home'), ] I'm not sure if any other any information is needed but please ask if there is anything else. I start the server using python manage.py runserver and it can access /home okay, but if I change the url to admin or admin/ it says 'Firefox can’t establish a connection to the server at 127.0.0.1:8000.'.I've tried it on different browsers and the same outcome is reached. My question is similar to the one here: Django error browser is unable to connect at 127.0.0.1:8000/products/ and I tried all of the solutions there but none worked. I followed the tutorial very specifically, so I have no idea what is causing this. I am using Atom on a Windows 10 machine, the project is connected to a postgresql database. -
Django Polling App TypeError between Nonetype and datetime.datetime
I am practicing Django Polling App and get the following error when I try my admin site to open questions TypeError: '>=' not supported between instances of 'NoneType' and 'datetime.datetime' My models.py import datetime from django.db import models from django.utils import timezone # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): # now = timezone.now() return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text It seems to work if I replace DateTimeField by DateField and use timezone.now().date() but the tutorial does not mention it. Am I doing something wrong ? -
NameError: name 'admin' is not defined (Django/GeoDjango)
I am in the process of building a web app using Django and GeoDjango (I am also following this tutorial) I am trying to register a new model in admin.py but after I do so I get the following error: NameError: name 'admin' is not defined I have checked my code carefully, and also tried adding django.contrib.gis.admin to installed apps for Django but this just returned an error because I already have 'django.contrib.gis listed. Here is my code, any help greatly appreciated: from django.contrib.gis.admin import OSMGeoAdmin from .models import Cafe # Register your models here. @admin.register(Cafe) class CafeAdmin(OSMGeoAdmin): list_display = ('name', 'location') And here is the model from django.contrib.gis.db import models # Create your models here. class Cafe(models.Model): name = models.CharField(max_length=100) location = models.PointField() address = models.CharField(max_length=100) -
djfractions in Django model - error "'DecimalFractionField' object has no attribute 'context'"
I'm looking to have a fraction field in a Django model. I've been trying using djfractions and it seems to be working and successfully adding a fraction value as a decimal to my (sqlite3) database, but when I try to review my database from the (local) server, I get the error "'DecimalFractionField' object has no attribute 'context'". Below is the attribute in my model that I'm using the fraction in, and the value I added to my database is 1/2, which gets translated to 0.5. ''' ingredient1_amount_fraction = djfractions.models.DecimalFractionField(verbose_name=None, name=None, max_digits=10, decimal_places=5, limit_denominator=None, coerce_thirds=True, null = True) ''' -
Replacing data of database table when certain condition meet in django
I want to check if the role of user is admin or customer. For this, I have given the role of users as customer by default and when the condition i.e. when the username is admin I want to replace the role from customer to admin. How can I replace the role from customer to admin and save it in db table? from django.db import models from django.contrib.auth.models import User from django.contrib.auth.models import AbstractUser class User(AbstractUser): email = models.EmailField() phone=models.CharField(max_length=30,unique=True) confirm_password=models.CharField(max_length=128,null=True) role=models.CharField(max_length=10,default='customer') def save(self, *args, **kwargs): if self.username =='admin': self.role.replace('customer','admin') print(self.role) super(User,self).save(*args, **kwargs) -
Fetch and display image in reactjs from django backend using json
An image is used as default in imageField in model.py file. from django.db import models class Product(models.Model): item_title= models.CharField(max_length=50) item_desc=models.TextField() item_price=models.IntegerField() item_image=models.ImageField(upload_to='post_images',default='default.png') Here is my serializer class from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields= ('item_title', 'item_desc', 'item_price', 'item_image') And views.py is- class ProductView(viewsets.ModelViewSet): serializer_class = ProductSerializer queryset = Product.objects.all() The json data received at localhost:8000 is localhost:8000/api/products Getting data at frontend(react js) in App.js. Here is code class App extends Component { constructor(props) { super(props); this.state = { productList: [], }; } refreshList = () => { axios .get("/api/protducts/") .then((res) => this.setState({ productList: res.data })) .catch((err) => console.log(err)); }; componentWillMount() { this.refreshList(); } render() { return ( <div> {this.state.productList.map((item) => ( <Product key={item.id} item={item} /> ))} </div> ); } } export default App; And Product component at front end is class Product extends Component { constructor(props) { super(props); } render() { return ( <div class="jumbotron col-sm-2"> <img src={this.props.item.item_image}></img> <mark>{this.props.item.item_title}</mark> <div class="lead">{this.props.item.item_desc}</div> <div class="text-primary">{this.props.item.item_price}</div> </div> );}} export default Product; Displayed data at fronted doesn't show any image. localhost:3000 -
showing update and delete links only to post author in django
I want to display Update and delete link only to the author of the post in django blog.But {% if request.user == posts.author %} on template is throwing an error Could not parse the remainder: '==posts.author' from 'request.user==posts.author'.How do i slove this? Views.py def post_detail(request,slug): posts=Post.objects.get(slug=slug) posts.seen_by=posts.seen_by+1 posts.save() context={'posts':posts} return render(request,'blog/post_detail.html',context) post_detail.html {% extends 'blog/base.html'%} {% block content%} <a href="{%url 'post-cate' posts.category %}">{{posts.category}}</a> <p>{{posts.date_posted}}</p> <h1>{{posts.title}}</h1> {% if request.user==posts.author %} <p><a href="{% url 'post-update' posts.slug %}">Update</a> <a href="{% url 'post-delete' posts.slug %}">Delete</a> </p> {% endif%} <strong>{{posts.content}}</strong><p>- <a href="{% url 'post-by-user' posts.author %}">{{posts.author}}</a></p> Seen:{{posts.seen_by}} <hr> {% endblock content%} -
How to filter query result with some matching letters instead of complete match in python django?
This code works if I send search word exactly like in the database. But if I have a task "Learn django" I want it to be found with "lea" or "djan"search string for example. At Views.py: def filter_tasks(request:HttpRequest): context = {'task_list' : Task.objects.all().filter(content=request.POST['content']) } return render(request,'tasks/task_list.html', context) At HTML form <form action="{% url 'filter_tasks' %}" method="POST" autocomplete="off"> {% csrf_token %} <div class="input-group"> <input type="text" class="form-control" name="content" placeholder="search for tasks"> <div class="input-group-append text-info"> <span class="input-group-text bg-white py-0"> <button type="submit" class="btn btn-sm text-info"> <i class="fa fa-search fa-lg"></i> </button> At model: class Task(models.Model): content = models.TextField() -
Dynamic time in django template
Dynamic time in django template How to show dynamic time and specific period of time in django template!! I have researched in internet but i didn't get information of this -
Stripe does not pass stripeToken to Django backend
I am building a Django application with stripe integration. I would like to use the charges api in order to have individuals make donations through the website. Currently I have copy/pasted most of the charges api code from the documentation and stripe elements pages. However, the javascript included under the python tab does not send the stripeToken needed to create a customer and charge the card. I have printed the information at the specific url, but the stripeToken key does not even seem to be generated as it does not even return an empty form part. The rest of the default javascript seems to work fine, but the submit function, or the stripeTokenHandler does not seem to function at all. I have tried adding in a hidden input for the field and switching the handler to ajax and both these methods were unsuccessful. Is there something I am missing? Django HTML: <form action="{% url 'Charge' %}" method="post" id="payment-form"> {% csrf_token %} <div class="input-section"> <label>Name on Card:</label> <input type="text" name="name" placeholder="enter name..." /> </div> <div class="donation-input"> <div class="input-section"> <label>Donation Amount:</label> <div style="display: flex;"> $<input id="amount" type="text" name="amount" /> </div> </div> </div> <div class="form-row"> <label for="card-element" style="font-family: 'Oswald', sans-serif;"> Credit or debit … -
How to fetch a post method in localhost?
I have the index route, where I have a form with a textarea field and I want to send a post request when that form is submited without reloading the page, so I'm doing: document.querySelector('form').onsubmit = (event) => { fetch("https://jsonplaceholder.typicode.com/posts", { method: 'POST', body: JSON.stringify({ body: document.querySelector('#new_message').value }), headers: { "Content-type": "application/json; charset=UTF-8", "X-CSRFToken": getCookie('csrftoken') } }) .then(response => response.json()) .then(result => { // Print result console.log(result); }); event.preventDefault(); } This code works fine. But If if want to make the post request in my index localhost fetch("/") This doesn't work. The console.log doesn't print anything. Also, with the code that fetchs JSONPlaceholder, it does't return any POST request on my server. If i just change the url for a "/" it wont work at all. Any ideas? -
Is there a way I can run a Discord bot alongside Django?
I've used Django to make the site and now I'd like to be able to use the bot to grab info from Discord to use. For example how many members are in a particular server or only letting a person through to a certain page if they're in the server. Is there a way I can run the bot alongside everything else, or an alternative solution? Thanks in advance for any help! -
as_view() takes 1 positional argument but 2 were given
help me this problem url.py urlpatterns = [ url(r'login/$',auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), url(r'logout/$',auth_views.LogoutView.as_view(),name='logout'), url(r'signup/$',views.SignUp.as_view(),name='signup'),] views.py class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = 'accounts/signup.html' -
Javascript inside Django Template
I am using JS inside Django template, but the JS code isn't responding. What to do? This inside <script> tag: var pageStrucVal = {{ pagestruc }}; if (pageStrucVal >= 82){ var pageWarn = ["Brilliant, your site's structure and design is awesome and rocking. <gold>RockingStructure</gold>", 'pp'] } else if ( pageStrucVal >= 72){ var pageWarn = ["Nice, your site's structure and design is suitable", 'pp'] } else if ( pageStrucVal < 45){ pageWarn = ["Extremely bad condition, your site's structure and design is extremely bad and unmanaged. Strictly to use a different theme or change the interface (UI). <red>#ExtremelyBad</red>", 'dd']; } else if ( pageStrucVal < 50){ pageWarn = ["Worst conditon, the content quality of your site is too much poor. Use a well-managed theme or change the interface (UI).<orange>#ReallyPoor</orange>", 'dd']; } else if ( pageStrucVal < 55){ pageWarn = ["Too much bad, your site's structure and design is too much bad and unmanaged. Try to use a different theme or change the interface (UI).<orange>#VeryPoor", 'dd']; } else if ( pageStrucVal < 63){ pageWarn = ["Very bad, your site's structure and design is very unmanaged. You can try to use a different theme or change the interface (UI).<orange>#MuchBad</orange>", 'dd']; } else …