Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django graphene returns Bad Request in unit test
I have defined the following graphql schema to create an inactive user from .models import User, UserManager import graphene from graphene_django import DjangoObjectType class UserType(DjangoObjectType): class Meta: model = User class PreSignupInput(graphene.InputObjectType): email = graphene.String(required=True) terms_of_use = graphene.Boolean(required=True) class PreSignup(graphene.Mutation): class Arguments: pre_signup_data = PreSignupInput(required=False) user = graphene.Field(UserType) def mutate(self, info, user_data=None): user = UserManager().create_inactive_user_with_email(user_data.email, user_data.terms_of_use) return PreSignup(user=user) class Mutation(graphene.ObjectType): pre_signup = PreSignup.Field() The User class is also defined as AUTH_USER_MODEL in the config and create_inactive_user_with_email creates an instance of User, saves it to the db and returns it. Whenever I run the following test: from graphene_django.utils.testing import GraphQLTestCase class UserSchemaTest(GraphQLTestCase): def test_create_inactive_user(self): response = self.query( ''' mutation preSignup($input: PreSignupInput!) { preSignup(input: $input) { user { id email } } } ''', op_name='preSignup', input_data={'email': 'test@example.com', 'terms_of_use': True} ) print(response.json()) self.assertResponseNoErrors(response) It fails with a Bad Request error and the following error message: { 'errors': [ {'message': 'Unknown argument "input" on field "preSignup" of type "Mutation".', 'locations': [{'line': 3, 'column': 27}]}] } Is there anything I'm missing? I used this tutorial for the test. Thank you! -
How to send two parameter id and name in onclick function?
Here I have many users(with id,name,role defined) in html. When I click in one of the user It displays the modal and inside this modal I want to display the id,name and role of that user. I am only being able to dispaly id. How can I display name and role also ? html {% for user in users %} <li> <i class="fas fa-user-circle"></i>{{ user.name }}, {{user.role}} <a href="" class="text-primary" onclick = "send_message({{user.id}} )">Message</a> </li> {% endfor %} script function send_message(id){ event.preventDefault(); $('#sendmessage').modal('show'); $('#send_message_modal_title').text("Send Message to User"); $('#sendmessage').on('shown.bs.modal', function (e) { $("#user_id").val(id); $("#user_name").val(name, role); }) modal <input name="cleaner" id="user_id"> <input type="text" value="name and role" class="form-control"> #how to display name and role ? -
SQL, order by .(Django, Queryset)
There is a table "Ad" with fields id, is_pro (boolean). There are entries (1, False), (2, True), (1, True), (1, False), (1, True), and so on. It should be sorted in the following way, True, False, True, False, True, False, True, False, True, False ... Any ideas? -
Subset query in ManytoMany relationship Django
I have two tables:Article and Publication. An Article can have multiple Publications. Given a list of Publication objects, I want to write a query that gives me only those articles which have Publications objects present in my list.(subset only) For e.g. ABC article has Publications P1, P2. BCD has P2, P3 DEF has P3, P4 Given publications are [P1, P2, P3]. So query output should be - ABC, BCD. DEF will be excluded as it has P4 which is not present in list. Using filter and exclude doesn't work properly in M2M relationship. So I am solving it using for loops which doesn't seem efficient and I want more Pythonic and ORM efficient solution. models.py from django.db import models class Publication(models.Model): title = models.CharField(max_length=30) class Meta: ordering = ['title'] def __str__(self): return self.title class Article(models.Model): headline = models.CharField(max_length=100) publications = models.ManyToManyField(Publication) class Meta: ordering = ['headline'] def __str__(self): return self.headline Views.py article = Article.objects.get(pk=pk) publications_in_article = article.publications.all() for publication in publications_in_article : if publication not in cleaned_data.get('publications'): exclude_publications.append({'id': publication.id, 'name': publication.title}) break return exclude_publications -
how can I show comments in django class view?
in my models.py file I hav 2 classes Question and Answer.And in views.py file I am using ready class forms from django.views.generic. So how can I show question answers in detailview HTML? models.py file from django.db import models from django.conf import settings from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Question(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField('Title', max_length=70) content = models.TextField('Body', null=True, blank=True) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('current', kwargs={'pk': self.pk}) class Meta: verbose_name_plural = 'Questions' verbose_name = 'Question' class Answer(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) content = models.TextField('Body', null=True, blank=True) date = models.DateTimeField(default=timezone.now) def __str__(self): return self.content class Meta: verbose_name_plural = 'Answers' verbose_name = 'Answer' views.py from django.shortcuts import render from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import Question, Answer from django.shortcuts import redirect from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) def index(request): context = { 'questions': Question.objects.all() } return render(request, 'f/index.html', context) class QuestionListView(ListView): model = Question template_name = 'f/index.html' context_object_name = 'questions' ordering = ['-date'] class QuestionDetailView(DetailView): model = Question answers = Answer class QuestionCreateView(LoginRequiredMixin, CreateView): model = Question fields = ['title', 'content'] def form_valid(self, form): form.instance.author = self.request.user return … -
how should Django auth User login with one type password [closed]
I am using django(2.2.10) web app and using django User model for authentication . I need add a feature login with registered number and otp . I need both authentication.User can either Login with password or he can choose otp . How should i impliment these feature in django web app . -
How can I access browser cookies of any site in Django?
I am creating an SSO system to connect 2 Django project, one project I locally hosted on localhost:8000 and other on localhost:8080. I did login on 8000 in chrome browser, I want to get stored 8000 cookies_data(session_key) by using an API of 8080 port. Is there any way in Django to access browser cookies of any site(in my case localhost:8000).? -
Add a field in Serializer depending on other field : django
I have a seriliazer: class aaaser(serializers.ModelSerializer): client_code = serializers.SerializerMethodField() status = serializers.SerializerMethodField() def get_status(self, obj): status_code = obj.status if obj.status else -1 return status_code class Meta: model = models.Order fields = ('client_code', 'status', 'order_id', 'details') In this seriliazer i want to add a field with name cancel_reason which should ONLY be added if value of status == 5. class aaaser(serializers.ModelSerializer): client_code = serializers.SerializerMethodField() status = serializers.SerializerMethodField() def get_status(self, obj): status_code = obj.status if obj.status else -1 if status_code == 5: # this felt dumb but had to try! cancel_reason = serializers.SerializerMethodField() return status_code def get_cancel_reason(self, obj): return "Dummy-reason" class Meta: model = models.Order fields = ('client_code', 'status', 'order_id', 'details') ^This Doesn't work Please suggest a solution or a alternative to SerializerMethodField for this usecase.. Thanks a lot!! -
Web site and mobile app: how to combine this 2 IT support?
I've been working with Django for one year now, to develop web site applications. And I've just started to learn about Flutter, the cross-plateform solution by Google to develop mobile app. Having this 2 IT supports TOGETHER for the same project would be ideal. That means web site application and mobile app should "share" the same database, at least for authentication (user should have the same account for web app and mobile app) but not only. Basically, principle of my web site applications is to give a random number from a list. A number can only be assigned once. So, mobile app should share the same database to get access to the list of number to be assigned. is it feasible? -
Filtering products by size in django by passing parameter in url
I am working on a django site. I have a product page on which I display products . I am wanting to filter the products based on the sizes available in the product. This is my url followed by the views.py and models.py: path("products/<str:type>/<str:sort>/<str:size>",views.products,name="products"), path("products/<str:type>/<str:sort>/",views.products,{'size':''}), def products(request,type,sort,size): sorting = ['category_id'] if sort == 'all': sorting.append('timeadded') elif sort == 'new': sorting.append('-timeadded') elif sort == 'priceltoh': sorting.append('price') elif sort == 'pricehtol': sorting.append('-price') prods=Product.objects.filter(category__type=type).order_by(*sorting) context = { 'categories':Category.objects.filter(type=type), 'prods':prods, } return render(request,"products.html",context) models.py: class Product(models.Model): S=models.IntegerField(blank=True,null=True,default=0) #example value 2 M=models.IntegerField(blank=True,null=True,default=0) #example value 0 L=models.IntegerField(blank=True,null=True,default=0) #example value 1 I have removed the parts which I dont think is required here: What I am wanting to do is that for example if I pass L as size in url then the products should filter such that all products with L>0 are displayed . Also if a size is chosen such that for that size not a single product has size>0 for that size then I send a message in template accordingly. I tried several ways to implement it but they were inefficient.Any help would be appriciated.Thanks -
How to update the web page on a new "question" in Django
I'am Working On A Q&A; Web Application. It was completed, but i have noticed a small bug, that is- we have to manually refresh the page in order to get the latest questions posted. But i thought it would be much much better if the page refreshed automatically when a new question was posted. I did hours of research on this, but it didn't solve my problem. Here Are The Reference Links- Django refresh page https://www.codingforentrepreneurs.com/blog/ajaxify-django-forms/ https://docs.djangoproject.com/en/3.1/ref/contrib/messages/ Using Django How Can I Automatically Update Information on a Template auto refresh url in django I didn't manage to find any useful info for me to fix the bug, that is why i posted this question becuase i thought some help by the community Specifications- OS: Windows 10 Python: 3.7.7 Django: 3.0.8 Here Are The Files For The Project- views.py from django.shortcuts import render from django.views import generic as genr from .models import Question, Answer from django.contrib.auth import mixins as mxn from django.urls import reverse_lazy # Create your views here. class HomePage(genr.TemplateView): template_name = 'core/home_page.html' class QuestionListView(genr.ListView): model = Question class QuestionDetailView(genr.DetailView): model = Question def get_context_data(self, **kwargs): context = super(QuestionDetailView, self).get_context_data(**kwargs) context['answer_list'] = Answer.objects.all() return context class QuestionCreateView(mxn.LoginRequiredMixin, genr.CreateView): model = … -
login form is not working in django. it only shows 'invalid credentials, please try again'
when email and password fill up in login form it shows invalid credentials, please try again' instead of successfully logged in. after fill up the login form it only read else part of the code and shows message invalid credentials, please try again. signup form is working and data of signup form save in database but after signup when i come to login its not working correctly. urls.py from django.urls import path, include from account import views from django.contrib import admin urlpatterns = [ path('', views.account, name='account'), path('signup', views.signup, name='signup'), path('login', views.login, name='login'), path('logout', views.logout, name='logout'), ] views.py from django.shortcuts import render, redirect, HttpResponse from django.contrib.auth.models import User, auth from django.contrib import messages from django.contrib.auth import authenticate, login, logout def login(request): if request.method == 'POST': # get the post parameters email = request.POST['email'] password = request.POST['pass'] user = authenticate(email=email,password=password) if user is not None: login(request, user) messages.success(request,'successfully logged in') return render(request, 'dashboard/dashboard.hmtl') else: messages.error(request, 'invalid credentials, please try again') return redirect('account') else: return HttpResponse('404 - Not Found') base.html <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <title>{% block … -
raised unexpected: EncodeError(TypeError('Object of type Products is not JSON serializable'))
I am working on a django project. In the project I am scraping some data from a webpage and storing the result in a django model. I achieve all this with celery. I want to display the records in the django model in my django template. But I am getting the following error when I do that raised unexpected: EncodeError(TypeError('Object of type Products is not JSON serializable')) This is my code so far mainapp/tasks.py from celery import Celery from celery.schedules import crontab from celery import shared_task from .models import Products from .scrape import ScrapeFunction app = Celery('tasks') app.conf.beat_schedule = { # executes every 1 minute 'scraping-task-one-min': { 'task': 'tasks.display_record', 'schedule': crontab() } } @shared_task def get_website(website): ... return 'done' @shared_task(serializer='json') def display_record(): return Products.objects.all().last() All of the scraping happens through the get_website() task. This task calls scrape.py where all the scraping happens. scrape.py also save the record into the model. All of this is working fine. The error occurs when I want to display the record in the template. Please check the display_record() task. And here is the views.py file. mainapp/views.py def index(request): if request.method == 'POST': website = request.POST.get('website-name') get_website.delay(website) return redirect('output') return render(request, 'index.html') def output(request): record = … -
Postgres/python django import json dump database
I got json database dump file to import into postgres but this file is not sql file (which I know how to import) it is json file. Its structure looks like this: [ { "model": "model.name", "pk": 1, "fields": { "version": 1584369114566125, "field_a": "something", "field_b": "something" } }, { "model": "model.name", "pk": 1, "fields": { "version": 1584369114566125, "field_a": "something", "field_b": "something" } }, ... ] I want to import it but I don't know if is there option for importing database in such format and structure without writing sql function? I was trying to find if there is in documentation of pg_dump any option for exporting in json but I didn't find. My guess is also that server is written in django and maybe django has script for exporting/importing database in such file? -
Anyone knows django inline formset alternative for nodejs
I need something similar to Django inline form set to use in my nodejs application. I tried searching it out on npm and some forms but couldn't get any success. Any Help will be appreciated -
Django rest api: user authentication with multyple databses
I need to developed Django rest API with access to multiple databases and also need to authenticate from multiple databases ex - user1 - authenticate from database1 user table user2 - authenticate from database2 user table router URL ex - http://examle.com/API/auth/{site1}/login - this route should use database1 user table username and password http://example.com/API/auth/{site2)/login - this route should use database2 user table username and password how can I achieve this task? -
Django class-based view processing form and adjusting context accordingly
I'm pretty new to Django and Python in general. I am building a Django app at the moment and am trying to stick to class-based views. I have a form (FormView) that I would like process, meaning take the data, clean it up and store it in the database. When processed I'd simply like to show the form again (so no redirect to another success page) and show the result of the processing above the form. How would I do that? I have played around with get_context_data to add the additional context for the result message but can't figure out how and where to process the data and how to tie it together with updating the context data then. Any help would be appreciated. forms.py: from django import forms class URLsForm(forms.Form): list_of_urls = forms.CharField(label='One URL per line', widget=forms.Textarea) views.py from django.views.generic import FormView from .models import URL from .forms import URLsForm class URLBatchCreateView(FormView): form_class = URLsForm template_name = 'bot/url_batch_create.html' success_url = reverse_lazy('url_batch_create') def form_valid(self, form): return super(URLBatchCreateView, self).form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['created_urls'] = 'The result' return context url_batch_create.html: {% extends 'bot/base.html' %} {% block content %} {% if created_urls %} <div>The following URLs where created:<br>{{ created_urls }}</div> … -
django url pass in context and post.id
views.py class CheongsamViewSet(viewsets.ModelViewSet): def list(self, request): # set context context = { 'url_update': 'item_update', } return Response(context) def update(self, request, pk): profile = get_object_or_404(itemModels, pk=pk) serializer = itemSerializers(profile, data=request.data) if serializer.is_valid(): serializer.save() print('status: status.Item Update') return redirect('item') else: print('status: status.Item Bad Update') urls.py urlpatterns = [ path('item/', cheongsam_router_list, name='item'), path(r'item/product_edit/<str:pk>', cheongsam_router_detail, name='item_update') ] create.html <a href="{% url url_update post.id %}" class="btn btn-success" title="btn btn-success">Edit</a> how do i pass in context variable and pk id at the same time in {% url %} ? both the context variable and object post has positive return so dont worry about it, but how do i put them into gether ? if i just do {% url url_update %} or {% url 'item_update' post.id %} things work just fine. error: Reverse for '' not found. '' is not a valid view function or pattern name. -
How to replace string in django model query
I want to replace a string in a django model query result. my model: class director(models.Model): direction = models.CharField(max_length=100) name = models.CharField(max_length=100) The content of the direction field is either "U", "D", "L" or "R". How do I make a query so that when I select the field direction, I get "Up", "Down", "Left", "Right" respectively. I can achieve this in SQL with: SELECT replace(replace(replace(replace(direction, "U", "Up"),"D", "Down"),"L", "Left"),"R", "Right) as direction from director or using CASE WHEN in in SQL. I know I can achieve this using for loop in python after director.objects.all() but I was hoping that I can do this in the query itself -
How to get the text file which is uploaded from android device and store it in a folder using django?
I want to save the text file or zip file in folder which can be uploaded in mobile devices(Android,IOS) using django framework.How to get the file in request ? Thanks in advance -
Reverse for 'customerdel' with arguments '('',)' not found.1 pattern(s) tried: ['dashboard/records/customerdel/(?P<pk>[0-9]+)$']
I am trying to delete an object from database using simple html button. Also, trying to implement "are you sure" message? BUt I am getting this error everytime and I am not able to crack. This is my view function. def customerdel(request,pk): objs = Customer.objects.filter(id=pk) if request.method == 'POST': objs.delete() # messages.success(request, 'Successfully deleted') return render(request,'records.html') else: content ={ 'items':Customer.objects.all } return render(request,'delete.html', content) This is record.html page <h1>Record's page</h1> {% for abc in Customerdata %} {{abc.name}} {{abc.pk}} <form > <button class="btn btn-danger btn-sm"> <a href="{% url 'customerdel' abc.pk %}">Delete</a></button> </form> {% endfor %} This is delete.html page <h1>Welcome to Delete page</h1> <p>Are you sure want to del {{items.name}} ??</p> <form action="{% url 'customerdel' items.pk %}" method="post"> {% csrf_token %} <a href="{% url 'records' %}">Cancel</a> <input name="confirm" type="submit" > </form> This is my URL. path('dashboard/records/customerdel/<int:pk>', views.customerdel, name='customerdel'), -
Django admin Template Error at admin Template incorrect padding
Default Django Admin not showing Error at /admin/ Incorrect padding Request Method: GET Request URL: http://127.0.0.1:8000/admin/ Django Version: 3.1 Exception Type: Error Exception Value: Incorrect padding Exception Location: C:\Users\ADMIN\AppData\Local\Programs\Python\Python38-32\lib\base64.py, line 87, in b64decode Python Executable: C:\Users\ADMIN\AppData\Local\Programs\Python\Python38-32\python.exe -
How to stream the contents of a log file in Django as a web-page
Since Django mainly uses static content served as web pages, how can I write a view that would scroll with the contents of a semi-fast moving log file? I know that redis can cache information as a high speed dictionary, but not sure if I need it for just tailing a log file & rendering the information. Any help here appreciated. -
How to get product id and display its details in django
i followed a youtube tutorial to make e-commerce site and now i'm trying to learn by adding new features to it .i am able to populate different products from the model. i want to display the details of the clicked product on a different page. this is what i have done so far.Thanks models.py class Product(models.Model): name=models.CharField(max_length=200,null=True) price=models.DecimalField(max_digits=7,decimal_places=2) digital=models.BooleanField(default=False,null=False,blank=False) image = models.ImageField(null=True,blank=True) description=models.CharField(max_length=500,null=True) def __str__(self): return self.name views.py def store(request): data=cartData(request) cartItems=data['cartItems'] order=data['order'] items=data['items'] products=Product.objects.all() context={'products':products,'cartItems':cartItems} return render(request,"foodapp/home.html",context) def detail(request): products=Product.objects.get(id=product.id) context={'products':products} return render(request,"foodapp/detail.html",context) urls.py urlpatterns=[ path('',views.store,name='store'), path('cart/',views.cart,name='cart'), path('checkout/',views.checkout,name='checkout'), path('update_item/',views.updateItem,name='update_item'), path('signup/',views.SignUp.as_view(),name='signup'), path('logout/',auth_views.LogoutView.as_view(next_page='login'),name='logout'), path('login/',auth_views.LoginView.as_view(template_name='foodapp/login.html'), name='login'), path('process_order/',views.processOrder,name='process_order'), path('detail/',views.detail,name='detail'), home.html {% for product in products %} <div style="margin-top: 30px;" class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{{product.imageURL}}" alt=""> <hr> <h6><strong>{{product.name}}</strong></h6> <hr> <h6>Type:</h6> <button data-product="{{ product.id }}" data-action="add" class="btn btn-outline-secondary add- btn update-cart"> <a href="#"> Add to Cart</a></button>&nbsp; <button data-product="{{ product.id }}" class="btn btn-outline-secondary"> <a href="{% url 'detail' %}">View</a> </button> <h4 style="display: inline-block; float: right;">{{product.price}} </h4> </div> </div> details.html {% for product in products %} <div style="margin-top: 30px;" class="col-md-4"> <div class="box-element product"> <img class="thumbnail" src="{{product.imageURL}}" alt=""> <hr> <h6><strong>{{product.name}}</strong></h6> <hr> <h6>Type:</h6> <button data-product="{{ product.id }}" data-action="add" class="btn btn-outline-secondary add- btn update-cart"> <a href="#"> Add to Cart</a></button>&nbsp; <button data-product="{{ product.id }}" class="btn btn-outline-secondary"> <a href="{% url 'detail' … -
Best way to define reusable blocks for streamfields
I'm planning on building large portions of my page templates with streamfields, using blocks that will be reused across page models. What's the best way to implement this so I can reuse my code across models, and leave only 1 place to update if I want to change the block or the way it renders? I'm envisioning basically building a library of streamfield block definitions, then selecting the applicable ones for a given field in a given model. Should I just go with a generic python library and include it and reference it in my page models, or use abstract Django models or something else? I think trying to make the actual instances of the blocks reusable within the page admin will be overkill (and over my head), but would be open to that as well.