Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how do i send my order to my database in django
i'm beginner in django, and i'm trying to build an ecoomerce sute following this tutorial. although i'm not using the same payment gateway so its difficult for me to fllow up. i want the order details to be saved in the database. help my orders view from django.shortcuts import render from django.http.response import JsonResponse from django.shortcuts import render from cart.cart import Cart from .models import Order, OrderItem # Create your views here. def add(request): cart = Cart(request) if request.POST.get('action') == 'post': user_id = request.user.id carttotal = cart.get_total_price() # Check if order exists if Order.objects.filter(order_key=order_key).exists(): pass else: order = Order.objects.create(user_id=user_id, full_name='name', address1='add1', address2='add2', total_paid=carttotal, order_key=order_key) order_id = order.pk for item in cart: OrderItem.objects.create(order_id=order_id, product=item['product'], price=item['price'], quantity=item['qty']) response = JsonResponse({'success': 'Return something'}) return response def payment_confirmation(data): Order.objects.filter(order_key=data).update(billing_status=True) def user_orders(request): user_id = request.user.id orders = Order.objects.filter(user_id=user_id).filter(billing_status=True) return orders -
python -- i'm try print an element from site with authorization but it doest'n work - why?
please help me, i'm try print an element from site with authorization but it doesn't work, because block with authorization doesn't perform its functions and instead of "Hello -username-" output "u don't registered" ma code: from bs4 import BeautifulSoup as BS import fake_useragent session = requests.Session() url = "http://www.musicforums.ru/buysell/login.php?bn=mfor_buysell" user = fake_useragent.UserAgent().random header = { 'user-agent':user } data = { 'loginuser':'moscow_sunset', 'loginpassword':'PfEQg4' } responce = session.post(url, data=data, headers=header).text link = "http://www.musicforums.ru/" page = requests.get(link) soup = BS(page.content, 'html.parser') name = soup.find_all('div', {'class': "block-reg"})[0] find_td = name.find('td', {'align':"center"}).text t = find_td.encode('ISO-8859-1').decode('Windows-1251') print(t)``` P.S. before that there was a problem with encoding(answer output like unreadable symbols) but i solved it -
first day using django and here's a problem
Just on my first day uding Django, server doesn't run - there's a problem. Have I done something wrong? https://drive.google.com/drive/folders/1fBLzxMRj1Py7qwq2HrF07IC8ksokcio5?usp=sharing -
How do you add a widget to a form field in init in django?
Basically, I want to change a form field's widget in the init function. First of all, here is the form: class ModelForm(forms.ModelForm): date = forms.ChoiceField() def __init__(self, *args, **kwargs): super(ModelForm, self).__init__(*args, **kwargs) self.fields['date'].choices = DATE_CHOICES class Meta: model = Model fields = ( 'date', ) widgets = {'date': SelectDateWidget()} However, the widget SelectDateWidget() didn't seem to work for some reason. So, I want to instead add this widget to the init function so that the widget would be reflected on the form. However, this is just my thought. If adding this widget to the init function will not work, could you please give me some way to use this widget for the date field? Thank you, and please leave me any questions you have. -
How to add parameters to ManyToManyField Django
Question: Models.py Suggest i have got djanog class A: class A(models.Model): slug = models.SlugField(max_length=200, blank=True) code = models.CharField("A", max_length=250) name = models.CharField(("A"), max_length=250) body = RichTextField(("A"), max_length=2500, blank=True, null=True) policy = models.CharField(("A"), max_length=25, blank=True, null=True) and i create class B: class B(models.Model): block = models.ManyToManyField(A) In Admin portal, when creating an instance of class B, django chooses the ManyToMany field automatically to search based on name. I would like to add the fields based on the code of class A. Help please, I can't get it to work. Thanks in advance for the tips! -
databse design one table for several tables - django models
I'm working on a project has two models one for Invoice and the other for payments, in the both tables should have a field named next pay for the loaners to determine when he/she should pay his/her loan class Payment(models.Model): admin = models.ForeignKey(User,on_delete=models.CASCADE) price = models.DecimalField(max_digits=20,decimal_places=3) #others class CustomerInvoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) #others should i add new fields named next pay for both two models or create a new model , something like this class NextPayment(models.Model): next_pay = models.DateTimeField() and add NextPayment as ForeignKey for two both models ? which one is the most effective way please ? thank you in advance .. -
Unable to register a app in Django: Getting Exception: ModuleNotFoundError: No module named
1.I created a Django project in the azure function. 2.then I created a app with the name of Scan_domain. 3.Now i'm trying to register in main django settings enter image description here I'm unable to register.it is showing the error like this Worker failed to load function: 'CSFHTTP' with function id: '8e6ff963-aaa3-44b7-9275-72394fca2dc8'. [2021-12-07T17:03:12.027Z] Result: Failure Exception: ModuleNotFoundError: No module named 'Scan_Domain'. Troubleshooting Guide: https://aka.ms/functions-modulenotfound Stack: File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\dispatcher.py", line 305, in handle__function_load_request func = loader.load_function( File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\utils\wrappers.py", line 42, in call raise extend_exception_message(e, message) File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\utils\wrappers.py", line 40, in call return func(*args, **kwargs) File "C:\Program Files\Microsoft\Azure Functions Core Tools\workers\python\3.8\WINDOWS\X64\azure_functions_worker\loader.py", line 85, in load_function mod = importlib.import_module(fullmodname) File "C:\Users\iaila\anaconda3\lib\importlib_init.py", line 127, in import_module return bootstrap.gcd_import(name[level:], package, level) File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\CSFHTTP_init.py", line 4, in from Cloud_Security.wsgi import application File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\Cloud_Security\wsgi.py", line 16, in application = get_wsgi_application() File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\CSFPenv\lib\site-packages\django\core\wsgi.py", line 12, in get_wsgi_application django.setup(set_prefix=False) File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\CSFPenv\lib\site-packages\django_init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\CSFPenv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "D:\A_Time_Prov\dev\Cloud_Security\Cloud_Security_fApp\CSFPenv\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\iaila\anaconda3\lib\importlib_init_.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) -
'NoneType' object is not iterable when using context processors
I wrote a simple function that passes some info inside base.html like bellow: def payment_check(request): if request.user.is_authenticated: context = { 'paymentCheck':PaymentInfo.objects.filter(user=request.user) } return context but gives me 'NoneType' object is not iterable error. -
I can't redirect to the post after editing a comment of that post
I can't redirect to the post after editing a comment of that post. class CommentEditView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment fields = ['comment'] template_name = 'social/comment_edit.html' def get_success_url(self): pk = self.kwargs['pk'] return reverse_lazy('post-detail',kwargs={'pk': pk,}) def test_func(self): post = self.get_object() return self.request.user == post.author Here Comment editing is working. But after submitting the edited comment I want it should redirect to the post related to the commentt. -
Django url not calling particular view function
Particular View function couldn't be called from urls.py views.py is: def commentView(request): print('Function exectuted') #Not printing anything on the terminal return redirect(request. META['HTTP_REFERER']) urls.py is: app_name = "backend" urlpatterns = [ path('login/', views.loginView, name='login') #Not relevant path('login/comment/', views.commentView, name = 'comment'), inbox.html is: <form class="comment-box" action="{% url 'backend:comment' %}" method="get"> ... </form> So I want to call commentView in views.py from inbox.html through urls.py No particular error was raised but print statement was not executed What should i call from action tag? Where have i been wrong? -
Docker error while running: no module named 'pytz'
Running docker-compose run server python manage.py makemigrations and getting this error: django.template.library.InvalidTemplateLibrary: Invalid template library specified. ImportError raised when trying to load 'rest_framework.templatetags.rest_framework': No mo dule named 'pytz' Why does this happen? -
Django: Send E-Mail from my personal host E-Mail to any E-Mails
I want send E-Mail from info@MyDomainName.com to farhad.dorod@hotmail.com. But when i click send button i have problem an error: In settings.py page: EMAIL_HOST = 'mail.MyDomainName.com' (For example) EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'info@MyDomainName.com' (For example) EMAIL_HOST_PASSWORD = '1234567890' (For example) And in views.py def ResetPassword(request): subject="Your new password is" message="Your new password is: 1234567890" from_email= settings.EMAIL_HOST_USER recipient_list= ['farhad.dorod@hotmail.com',] send_mail(subject, message, from_email, recipient_list) messages.success(request, 'An email has been sent to your given address please check your mail') return HttpResponseRedirect('/forgotpassword') Now my Error is: Exception has occurred: TimeoutError [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond Please help me Thank you, everyone. -
drf_yasg with patterns keyword argument problem
In my project i have api/v1 endpoints, which i want to show in separated schema view. The problem is that using additional schema_view with api/v1 url patterns destroys prefix from router. How can I keep it? Here is code for urls.py of main application and screenshots of resulted swaggers: code of action_fm/urls.py (main application) from django.contrib import admin from django.urls import include, path from drf_yasg import openapi from drf_yasg.views import get_schema_view from rest_framework import permissions from action.urls import notify_router from action_fm.views import HealthView, api_root api_v1_urlpatterns = [ path("", include([path("", include(notify_router.urls))])), ] schema_view = get_schema_view( openapi.Info(title="Action FM Swagger", default_version="v1", description="API description for Action FM"), public=True, permission_classes=(permissions.AllowAny,), patterns=api_v1_urlpatterns, ) schema_view_common = get_schema_view( openapi.Info(title="Action FM Swagger", default_version="v1", description="API description for Action FM"), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ path("api/v1/", include(api_v1_urlpatterns)), path("", include("django.contrib.auth.urls")), path("", api_root), path("api-auth", include("rest_framework.urls", namespace="rest_framework")), path("health", HealthView.as_view(), name="health"), path( "swagger/v1", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui-v1" ), # for correct logically separated api endpoints to try path("swagger/common", schema_view_common.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui-common"), path("grappelli/", include("grappelli.urls")), path("admin/", admin.site.urls), ] code of action/urls.py (other application, here i’m storing my router) from rest_framework import routers from action.views import NotificationHandlerViewSet notify_router = routers.DefaultRouter(trailing_slash=True) notify_router.register(r"notify", NotificationHandlerViewSet, basename="notify") here is screenshot of correct common swagger, which saves ’notify/' prefix to url and here … -
Angular to Django - 'Unknown string format:'
I am building a front end using Angular where the user selects a file and a date (using a date picker). This is then sent to django using the django_rest_framework to to a standalone class that uploads this file onto an oracle database using sqlalchemy. The uploading page use to work fine when it was created on a Django template, however I need to migrate this to angular and when i pass the file and date parameters i get an error: Error: ('Unknown string format:', 'Tue Dec 07 2021 00:00:00 GMT+0000 (Greenwich Mean Time)') Where Tue Dec 07 2021 00:00:00 GMT+0000 (Greenwich Mean Time) represents the date chosen from the datepicker. Anyone know why this is happening? views.py @api_view(('POST',)) @csrf_exempt def uploader(request): if request.method == 'POST': try: instance= uploader(request.FILES['data'], request.POST['selectedDate']) _ = upload_instance.run_upload_process('data') upload_message = "Success" return Response(upload_message, status=status.HTTP_201_CREATED) except Exception as e: upload_message = 'Error: ' + str(e) return Response(upload_message, status=status.HTTP_400_BAD_REQUEST upload.component.ts onFileChange (event:any) { this.filetoUpload = event.target.files[0]; } inputEvent(event:any) { this.monthEndDate = event.value; } newUpload() { const uploadData = new FormData(); uploadData.append('data', this.filetoUpload, this.filetoUpload.name); uploadData.append('selectedDate', this.monthEndDate) this.http.post('http://127.0.0.1:8000/upload/', uploadData).subscribe( data => console.log(data), error => console.log(error) ); } -
Json.dumps(data) in python appends "\ n" in my data
I am working on an API where I have to send data via a post request. The data is base64, therefore has unusual characters. for example I want to send the following data data = "HBj8//8B". Here is my code payload= "HBj8//8B" data = { ... "data":payload ... } data = json.dumps(data) print(data) When I try to print data after json.dumps(data), this is what it gives me: {... "data": "HBj8//8B\n"} How can I remove the added "\ n" character? -
Custom permissions in Django
In Django Rest framework, we can verify permissions such as (isAuthenticated, isAdminUser...) but how can we add our custom permissions and decide what django can do with those permissions? I really want to understand what happens behind (I didn't find a documentation that explaint this): @permission_classes([IsAdminUser]) Thank you -
How to count how many times is finished function in django?
I have created a function in Django with the purpose that users download files after they fill some form. I want to count how many times is downloaded a file, now how many times is called function. And I want to show that number on my site. How do I do this? This is my function... def Only(request): page_title = 'Title' if request.method == "POST": form = Form(request.POST, request.FILES) if form.is_valid(): newdoc = request.FILES['file'] #some tasks response = HttpResponse( output, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=%s' % filename return response else: form = Form() return render(request, 'only.html', { 'form': form, 'page_title':page_title }) -
switch and route does not work in full stack react-django
hello i'm learning full stack react and django and now work on routing in this my routing is not working i dont know why but my template did not show on my browser please help me My project consists of different parts, which is the React section in the front section, and in this section I have several folders The src folder in which the components are located[enter image description here][1] app.js import React, { Component } from "react"; import { render } from "react-dom"; import HomePage from "./HomePage"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import ReactDOM from "react-dom"; export default class App extends Component { constructor(props) { super(props); } render() { return <div> <p>sadiasidasipdhasip</p> </div>; } } const appDiv = document.getElementById("app"); render(<App />, appDiv); HomePage import React, { Component } from "react"; import ReactDOM from "react-dom"; import RoomJoinPage from "./RoomJoinPage"; import CreateRoomPage from "./CreateRoomPage"; import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom"; export default class HomePage extends Component { constructor(props) { super(props); } render() { return ( <Router> <Switch> <Route path=''> <HomePage /> </Route> <Route path='/join'> <RoomJoinPage /> </Route> <Route path='/create'> <CreateRoomPage /> </Route> </Switch> </Router> ); } } I created a component in … -
fork process under uwsgi, django
I need to execute some slow tasks upon receiving a POST request. My server runs under UWSGI which behaves in a weird manner Localhost (python manage.py runserver): when receiving request from browser, I do p = Process(target=workload); p.start(); return redirect(...). Browser immediately follows the redirect, and working process starts in the background. UWSGI (2 workers): Background process starts, but Browser doesn't get redirected. It waits until the child exit. Note, I have added close-on-exec=true (as advised in documentation and in Running a subprocess in uwsgi application) parameter in UWSGI configuration, but that has no visible effect, application waits for child's exit -
django models related manager filtering in views.py
I want to develop DJANGO application for booking rooms. The following two models are used. class suit(models.Model): iquarter = models.ForeignKey(iquarter, related_name= 'suit', on_delete=models.CASCADE) suit_no = models.IntegerField() remarks = models.CharField(max_length=100) def __str__(self): return self.remarks + ' - ' + self.iquarter.iq_name class suitbooking(models.Model): suit = models.ForeignKey(suit, related_name= 'suitbookingforsuit', on_delete=models.CASCADE) booked_for_date_from = models.DateField() booked_for_date_to = models.DateField(blank=True, null=True) booked_for_date = models.DateField(blank=True, null=True) booked_for_no_of_days = models.IntegerField(blank=True, null=True) booked_date = models.DateField(auto_now_add=True,) booked_by_officer = models.TextField(max_length=1000, default='') remarks = models.CharField(max_length=100,) class Meta: constraints = [ models.UniqueConstraint( fields=["suit", "booked_for_date"], name="unique_product_name_for_shop", ), ] def __str__(self): return self.suit.remarks To avoid assigning one room to 2 diffrent persons on any day, “ UniqueConstraint” is used. Now, how to query the list of rooms which are vacant from DATE1 to DATE2 -
Can't get css file in Django
I'm trying to get a css file in my new django application, but I keep getting errors like this: [07/Dec/2021 19:52:13] "GET /users/register HTTP/1.1" 200 4715 [07/Dec/2021 19:52:13] "GET /static/users/css/register.css HTTP/1.1" 304 0 Here is the structure of my project: register.html: {% extends '../main/layout.html' %} {% load static %} {% block styles %} <link rel="stylesheet" href="{% static 'users/css/register.css' %}"> {% endblock %} {% block content %} <div class="container"> <div class="row"> <div class="col-lg-12"> <h2>Регистрация</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Зарегистрироваться</button> </form> </div> </div> </div> {% endblock content %} settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static" ] How to fix it? -
i can't understand what is new in django 4.0?
what is new in django 4.0 ???? I am looking for release notes what is new in django-tastypie 4.0 but I can not find it. I would like to know what is new before update the package. Thanks -
Could not resolve URL for hyperlinked relationship using view name "<viewname>". ResourceRelatedField URL/pk problem (django+rest+json api)
Summary Background I am trying to implement a JSON:API-compliant general Django app to be used in various projects. I am able to generate decent JSON:API, but I only get "related"-links for one-to-one relationships (foreignkey in the model). I cannot get "related"-links to reverse relationships (other models with a foreign key pointing to my object). Thank you! //S Questions Is ResourceRelatedField the correct way to implement reverse relationship links (e.g. "related")? How do you properly use ResourceRelatedField with related_link_view_name and _url_kwarg? Specifics There are three models in the database: TopObject, Status and RelatedObject. TopObject-objects has a foreignkey status pointing to Status RelatedObject-objects has a foreignkey topobject pointing to its 'parent' TopObject-object. All of the following url's work properly when entering them manually (e.g. browser or httpie): localhost:8000/topobjects/1/relatedobjects/ (gives a list of related objects with topobject foreignkey = 1) *localhost:8000/topobjects/ (gives list, currently without reverse links. The related link for Status [direct relationship] works). *localhost:8000/topobjects/1/ (gives topobject 1, currently without reverse links. The related link for status [direct relationship] works). localhost:8000/relatedobjects/ localhost:8000/relatedobjects/1/ localhost:8000/statuses localhost:8000/statuses/1/ The view name topobject-relatedobject-list works from views when tested with print(reverse...) When related_link_view_name='topobject-relatedobject-list' is set under ResourceRelatedField, localhost:8000/relatedobjects/ and localhost:8000/relatedobjects/1/ raises a Django error. I have not figured … -
is there a way to display a particular inline in a new page based on a condition?
I need to display only one inline in a new page based on the condition like if the url has the parameter country_id then i need to display only one inline. Since I cannot make it in one ModelAdmin since the model admin has form validations in it, I used two modelAdmins for the same model. I have a readonly field called get_countries in CorporateConfig(admin which has form validations) and it will display a list of countries. If i click on a country based on that country id i need to display CorporateBrand which is an inline model to CorporateConfig on a new page(remember only that inline needs to be displayed). class CorporateConfigurationAdmin(admin.ModelAdmin): form = CorporateConfigurationAdminForm inlines = [CorporateIncludeBrandAdmin, CorporateExcludeBrandAdmin, CorporateBrandsAdmin] def get_urls(self): from django.urls import path urls = super(CorporateConfigurationAdmin,self).get_urls() filter_url = [ path('filter_brand/',self.admin_site.admin_view(self.brand_filter), name='brand-filter'), ] return filter_url + urls def brand_filter(self, request, obj=None): pass def get_countries(self, instance): country_list = '<ul style="font-weight: bold;list-style-type:circle;">' countries = Country.objects.all() print("countries", countries) for country in countries: url = reverse_lazy('admin:brand-filter') print("urls is",url) country_list += '<li class="changelist"><a href="{url}?country_id={id}" target="_blank">{country}</a></li>'.format(url=url, country=country.name,id=country.id) country_list+='</ul>' return mark_safe(country_list) get_countries.short_description = 'Country Url' Clicking on the link above should go to the custom url which is created by get_urls() class BrandOrderFilter(CorporateConfiguration): class … -
Django: Could not found exception in Traceback
I have facing some issue with python requests in a Django project. It only occur in 2nd requests.post(). Although It exited with exception TypeError: getresponse() got an unexpected keyword argument 'buffering'. But after updating urllib3. There is no exception in traceback. Traceback (most recent call last): File "/home/ubuntu/projects/project/api/views/a_view.py", line 765, in create_power_trace headers=power_trace_headers) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 117, in post return request('post', url, data=data, json=json, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/api.py", line 61, in request return session.request(method=method, url=url, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 542, in request resp = self.send(prep, **send_kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/sessions.py", line 655, in send r = adapter.send(request, **kwargs) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/requests/adapters.py", line 449, in send timeout=timeout File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 677, in urlopen chunked=chunked, File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 426, in _make_request six.raise_from(e, None) File "<string>", line 3, in raise_from File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/urllib3/connectionpool.py", line 421, in _make_request httplib_response = conn.getresponse() File "/usr/local/lib/python3.7/http/client.py", line 1373, in getresponse response.begin() File "/usr/local/lib/python3.7/http/client.py", line 319, in begin version, status, reason = self._read_status() File "/usr/local/lib/python3.7/http/client.py", line 280, in _read_status line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1") File "/usr/local/lib/python3.7/socket.py", line 589, in readinto return self._sock.recv_into(b) File "/home/ubuntu/projects/venv/lib/python3.7/site-packages/gunicorn/workers/base.py", line 201, in handle_abort sys.exit(1) SystemExit: 1 For your information, my code is something like this:- res1 = requests.post(url1, data=data1) result = res1.json() print(result['id']) # successfully prints data2 …