Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
SMTPNotSupportedError at /contact/email STARTTLS extension not supported by server. Django 2
SMTPNotSupportedError at /contact/email STARTTLS extension not supported by server. Request Method: POST Request URL: http://127.0.0.1:8000/contact/email Django Version: 2.2.12 Exception Type: SMTPNotSupportedError Exception Value: STARTTLS extension not supported by server. Exception Location: /usr/lib/python3.8/smtplib.py in starttls, line 755 Python Executable: /usr/bin/python3 Python Version: 3.8.2 -
Is django-filter FilterSet behavior consistent with native Django behavior for queries spanning multi-valued relationships?
I’m trying to query all unread messages for a user via the recipient model (i.e. each message has many recipients with a read property). The query works as expected when run with the model manager. For example: Message.objects.filter(**{"recipients__user_id": 1, "recipients__read": False }) However, the query includes all messages the user received regardless of read status when run with FilterSet (using django-filter version 2.3.0). For example: MessageFilter(data={"recipients__user_id": "1", "recipients___read": False }).qs Here’s the MessageFilter: class MessageFilter(FilterSet): class Meta: model = Message exclude = ('deleted_at', ) fields = ('chat_id', 'recipients__user_id', 'recipients__read', ) filter_overrides = { # NOTE: enables support for querying pk rather than relay uuid models.ForeignKey: { 'filter_class': LocalIDFilter }, } # NOTE: enables mapping from camelcase to snakecase order_by = OrderingFilter(fields=(('created_at', 'createdAt'),),) Anyone know if my implementation is incorrect or if this is just desired library behavior (I couldn’t tell from the docs)? Also, any suggested workarounds would be appreciated. Aside from manually overriding the qs property on FilterSet, I'm not seeing any better solutions. -
Django: Fixing an error in the payment view
I am trying to know the reason for getting an error which arises as a result of an exception in the views after making a payment. Noting the payment goes through with a successful message that the order has been placed but along with it comes another message saying that A serious Error Occured. We have been notified. which is related to the very last exception in the payment view Here is the views.py: class PaymentView(View): def get(self, *args, **kwargs): # order order = Order.objects.get(user=self.request.user, ordered=False) if order.billing_address: context = { 'order': order, 'DISPLAY_COUPON_FORM': False } return render(self.request, "payment.html", context) else: messages.warning( self.request, "You have not added a billing address") return redirect("core:checkout") # `source` is obtained with Stripe.js; see https://stripe.com/docs/payments/accept-a-payment-charges#web-create # -token def post(self, *args, **kwargs): order = Order.objects.get(user=self.request.user, ordered=False) token = self.request.POST.get('stripeToken') amount = int(order.grand_total() * 100) try: charge = stripe.Charge.create( amount=amount, # cents currency="usd", source=token, ) # create payment payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = self.request.user payment.amount = order.grand_total() payment.save() # assign the payment to the order order_items = order.items.all() order_items.update(ordered=True) for item in order_items: item.save() order.ordered = True order.payment = payment order.ref_code = create_ref_code() order.save() messages.success(self.request, "Your Order was Successful ! ") # Email when … -
template shows markup and not the page when combining context and forms
I am fairly new to Django. I am trying to display a dictionary and form on the same page. However, it only vies the Html markup and not the actual page. Here is my code: home/views.py: from django.shortcuts import render from recruit.forms import RecruitForm articles = [ { 'author': 'Glenn', 'title':'title 1', 'content': 'first content', 'date_posted': 'January 12' }, { 'author': 'batman', 'title':'title 2', 'content': 'second content', 'date_posted': 'January 12' }, { 'author': 'batgirl', 'title':'title 3', 'content': ' Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptas ratione eaque nam totam! Labore consectetur nostrum dicta magnam ex expedita facilis illum odit quibusdam vitae?', 'date_posted': 'January 12' } ] # Create your views here. def index(request): form = RecruitForm() context = { 'articles': articles } return render(request, 'home/index.html', context, {'form':form}) recruit/forms.py: from django import forms from phonenumber_field.modelfields import PhoneNumberField from .models import Recruit class RecruitForm(forms.ModelForm): email = forms.EmailField() phone = PhoneNumberField() class Meta: model = Recruit fields = ['firstname', 'lastname', 'email', 'phone', 'city', 'contact_preference'] widgets = {'contact_preference': forms.RadioSelect } When I don't pass context the entire page renders. The same with form. I know how to validate forms, I just wanted to make this question as generic as possible. So either … -
df.to_sql results in server 502 bad gateway (not because of file size)
within a django form, I am importing the data from one postgresql table. I am modifying this data through pandas and I want to replace the existing data in the db by the modified data. Important to mention that the size of the df is about 100k rows and 4 columns. histo2db = histo2.to_sql('uploadfiles_historical_data', engine, if_exists='replace', method='multi',chunksize='10000') running that results in a 502 bad gateway error after 5 minutes (my nginx time out limit) I am pretty confused about why this is happening, I have verified that the datatype of the dataframe matches the postgresql table datatype. the logs are very not helpful, beside this one from postgresql where I can read this: 2020-08-22 23:09:14.339 GMT [24053] LOG: skipping missing configuration file "/rdsdbdata/config/recovery.conf" 2020-08-22 23:09:14 UTC::@:[24053]:LOG: database system is shut down Postgres Shared Memory Value: 515883008 bytes could it be something related with postgresql settings? -
Django Pythonanywhere, model field default=timezone.now() repeats the same time multiple times
I am hosting a web app on pythonanywhere. In one of my models I have this field, capturing the datetime when the user performs a certain action (submits a form in this case), which subsequently gets recorded in the database. from django.utils import timezone upload_datetime = models.DateTimeField('date uploaded', default=timezone.now()) However, seen in the image below, most of the rows in the database display the exact same time. This should under normal circumstances be a very rare case, so I am assuming a bug here. Can I get any help on where to start looking? Database entries of upload_datetime -
Django admin, how select several fields and edit at once
Good time. How to do following in Django admin: For example, I have model called Events. I have some events created. I have fields like event name, .... and also field "planning Date" I need set the same date in "planning Date" field for 5 events. I am selecting 5 events in checkbox and need in one action do it. I mean something like delete action for selected objects. -
ERROR: Exception in ASGI application Django to 3rd party python app
Trying to send payload data from the frontend via axios to django then via restapi to 3rd party python app I get a status code of 200 to django but then I get an internal server error to 3rd party after django with the following The 3rd party service error INFO: ::1:51365 - "POST / HTTP/1.1" 500 Internal Server Error ERROR: Exception in ASGI application Traceback (most recent call last): File "E:\projects\SethDash\django-vue\venv\lib\site-packages\uvicorn\protocols\http\h11_impl.py", line 388, in run_asgi result = await app(self.scope, self.receive, self.send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\uvicorn\middleware\proxy_headers.py", line 45, in __call__ return await self.app(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\applications.py", line 111, in __call__ await self.middleware_stack(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\middleware\errors.py", line 181, in __call__ raise exc from None File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\middleware\errors.py", line 159, in __call__ await self.app(scope, receive, _send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\exceptions.py", line 82, in __call__ raise exc from None File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\exceptions.py", line 71, in __call__ await self.app(scope, receive, sender) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 566, in __call__ await route.handle(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 227, in handle await self.app(scope, receive, send) File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\routing.py", line 41, in app response = await func(request) File "app.py", line 30, in homepage params = await request.json() File "E:\projects\SethDash\django-vue\venv\lib\site-packages\starlette\requests.py", line 227, in json self._json = json.loads(body) File "c:\users\admins\appdata\local\programs\python\python36\lib\json\__init__.py", line 354, in loads return _default_decoder.decode(s) … -
Everything crashed after install lib in django
Sorry for bothering, I am running Django 3.0.1 $ python -m django --version 3.0.1 After installed: pip install git+https://github.com/jhuapl-boss/boss-oidc.git Django was uninstalled automatically without asking (django 3.0.1 is not supported with that lib, I noted that late) First question: If I do a mistake installing no compatible libs the whole framework is uninstalled? So, I reinstalled django 3.0.1, uninstalled the boss-oidc lib, actually python too from scratch, virtualenv, and who knows what else. So, from that moment, after I apply makemigrations, nothing works. I tried cloning a github repo, going to a old commit, it does not work (at the end the log). If I create a new empty project and add some models, it does the migrations without problems. I am new in Django, I would like to know if this is so unstable or It is just me learning from scratch. I can not recover my whole work from the last 20 days. The log: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/core/management/base.py", line 341, in run_from_argv connections.close_all() File "/Users/mariano/Code/Python/Django3.1/lib/python3.8/site-packages/django/db/utils.py", line … -
How to use rest_framework token authentication with frontend pages django?
I'm working with a vue-django project, so I create a rest api for user authentication using django_rest_framework token authentication, now I want to use tokens to authenticate frontend pages. those are urls & views code lines def login_page(request): if not request.user.is_authenticated: return render(request, "login.html") else: return render(request, "home.html") def home_page(request): if request.user.is_authenticated: return render(request, "home.html") else: return redirect("login/") urlpatterns = [ re_path('^$', home_page), path('admin/', admin.site.urls), path('login/', login_page), path('api/', include("server.rest_api.urls")) ] so I create a backend to get a cookie from requests like this: class RestTokenBackend(ModelBackend): supports_object_permissions = True supports_anonymous_user = False supports_inactive_user = False def authenticate(self, request, username=None, password=None, **kwargs): print("inside", file=sys.stderr) token: str = request.COOKIES.get('token') if token and not token.isspace(): try: u = Token.objects.get(key=token) return u except: return None return super().authenticate(request, username, password, **kwargs) then I set the settings variables to: AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'server.rest_token_backend.RestTokenBackend' ] but it doesn't work ,as you can see , I put a print command to check in the console but nothing was printed, so what went wrong ? I followed the documentation and some others questions nothing worked out for me -
How to disable get by id or retrieve api in django rest framework using model viewset?
I am using Django Rest Framework 3.11.0 and Django 3.0.8 I have a very simple Hello World API and I am using it via model viewset. Therefore I need only GET method which is achieved by list function. I need to disable GET BY ID or retrieve API but not able to do this. Views.py from django.shortcuts import render from rest_framework.permissions import IsAuthenticated from rest_framework import viewsets from .serializer import DemoSerializer from rest_framework.response import Response from rest_framework import status # Create your views here. class DemoViewSet(viewsets.ModelViewSet): serializer_class=DemoSerializer http_method_names = ['get'] def get_queryset(): pass def list(self,request): """ WELCOME TO SUNFLOWER BACKEND HELLO WORLD API """ return Response(data={"message":"WELCOME TO SUNFLOWER BACKEND"},status=status.HTTP_200_OK) serializer.py from rest_framework import serializers class DemoSerializer(serializers.Serializer): pass urls.py from django.urls import path,include from .views import DemoViewSet #Router from rest_framework.routers import DefaultRouter router=DefaultRouter() router.register('',DemoViewSet,basename='demo') urlpatterns = [ path('',include(router.urls)), ] Still I am able to see in my swagger GET BY ID or retrieve api Please help me to disable GET BY ID or Retrieve API in model view set and I just want only one get API. -
GeoDjango admin map draws point at wrong location
I have a model like from django.contrib.gis.db import models class Letter(models.Model): """Letter Model""" class Meta: db_table = 'Letter' center = models.PointField(geography=True) and the model has a data as follows: a = models.Letter.objects.get(id='699c49db-1db7-41cf-90a9-a173f9352805') print(a.center) >>SRID=4326;POINT (40.7128 74.0) It should show data around NewYork, but django admin map points to uncorrect location: it points to Barents sea which is located on North of the finland. When I change the Point value, it locates to the different places. Please also note that I'm using django rest framework package for serializer and django_extensions package for inputting Point field. Could somebody help me find the cause and solution for this? -
How to implement multithreading or is it already implemented in Django?
I'm new to Django and I'm not even sure if the thing I want is called multithreading so sorry if I'm mistaken. I'm currently making an app in Django that users can upload files to etc. I'm still at the start and wanted to know if the file upload process will be different for all users i.e. if 2 users are uploading a file at the same time, will this be resolved automatically or do I need to implement something? -
Adding inline fields depending on another model's field value
I have a Survey model that defines the length of a survey. I want to make it so that in the admin page, when adding questions to a survey, there are automatically enough fields listed equal to the length of the survey, rather than adding the questions one at a time. I am unsure how to do this. Any help would be appreciated! models.py class Survey(models.Model): title = models.CharField(max_length=100, default='Nursing Survey') length = models.IntegerField(null=False) # e.g: If length = 10, I want 10 question fields when adding questions is_taken = models.BooleanField(default=False) def __str__(self): return self.title admin.py from django.contrib import admin from .models import Survey, Question, UserScore admin.site.site_url = "/survey" admin.site.register(Survey) admin.site.register(Question) admin.site.register(UserScore) -
Changed the relationship of a Foreign Key | Django model
my buyer field from the Sell model had relationship with the Buyer model like this: class Buyer(models.Model): name = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=200, blank=True) class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) buyer = models.ForeignKey(**Buyer**, related_name='sell', on_delete=models.CASCADE) But now, it's set to 'User' model as you can see below: class Sell(models.Model): item = models.OneToOneField(Buy, related_name='sell', on_delete=models.CASCADE) buyer = models.ForeignKey(**User**, related_name='sell', on_delete=models.CASCADE) When I go to Django admin, it shows me all the available users from the User model but if I try to save, I got an error like this: insert or update on table "dma_sell" violates foreign key constraint "dma_sell_buyer_id_4d165f92_fk_dma_buyer_id" DETAIL: Key (buyer_id)=(13) is not present in table "dma_buyer". I'm wondering I should NOT have changed this but what is the best way to correct that? I really need to relate the buyer field with User model! Thank you!