Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'foo'
I´m trying to make a cron inside my django app with django-crontab==0.7.1,. Within my project settings installed apps, crontab app first, and then my app, both registered. In my cron.py: from .models import Url urls=Url.objects.values_list('url') def foo(url): if url not in urls: link= Url( url=url, ) link.save() foo('https://example.org') Also tried to put inside cron.py, but it doesn´t make sense since both are inside same app from foo.models import Url Also init.py inside app My models.py inside foo app, after migrations ran from django.db import models class Url(models.Model): url=models.URLField('url',blank=False,null=False) but still getting ModuleNotFoundError: No module named 'foo' Sorry if this has been asked before, but nothing watched yet gives me the answer Thank you -
date time model table for two models-OneToOne - django
I'm working on a project which has several models but two of them are Invoice and the other for Payment, in the both tables should have a field named next_payment 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 Invoice(models.Model): seller = models.ForeignKey(User,on_delete=models.PROTECT) customer = models.CharField(max_length=50) #others should i add new fields named next_payment for both two models or create a new model , something like this class NextPayment(models.Model): next_payment = models.DateTimeField() and add NextPayment has OneToOne connection for two both models ? which one is the most effective way please ? thank you in advance .. -
request.data empty when request is sent by Insomnia
I just want to update the "name" attribute via API, but when I make the request through Insomnia, data appears as an empty dictionary. Why "name" is not in request.data? Below is the Insomnia JSON request: (method = PATCH) { "name": "name_test" } Everything is working well, but when I access the data dictionary from request it's empty. See below in the image: Below is the code of backend API def partial_update(self, request, pk=None): try: flow = Flow.objects.get(pk=pk) if "name" in request.data and request.data["name"]: flow.name = request.data["name"] flow.save() return Response({"Response": "Object changed successfully"}) except Exception as e: return Response({"Response": str(e)}) Any suggestions about why data is empty? The JSON format is wrong? -
Add digicert certificate for django/python web app on Azure
A wild card cert has been purchased through Digicert for a domain and I'm currently trying to add this cert to a django/django-rest API hosted on Azure which will resided on a subdomain under that purchased custom domain. I have configured the web app to recognize the custom subdomain and at this point need to add the pfx file. I have received the pfx file from another who created it through Digicerts windows utility. NGINX was used as the server type, not sure if this is part of the issue or not. When creating a python/django web app on Azure it seems to make a Linux container which runs gunicorn.... When uploading the pfx file and supplying the password given, Azure Portal returns with an error either saying the file or password is incorrect. Tried multiple times with multiple recreations of the pfx file. Even tried taking a given crt file and using openssl locally to generate a pfx file with password and no luck. Thoughts & guidance? Do I need to use a Key Vault instead and link to Digicert? -
Django Admin Dropdown
I am trying to get the selected value from the dropdown in django admin model but unable to achieve it. Just want to select any of the value from the dropdown and when I click that Need that value should print in my console -
while loop not seeing dynamic created form fields
So everything looks good on the html and css where the dynamically created objects have the correct attributes. let $this = $("#id_variant_0") let $clone = $this.clone() let name = $clone.attr('name') let n = count name = 'variant_' + n count++ $clone.val('') $clone.attr('name', name) let new_id = "id_" + name $clone.attr('id', new_id) $clone.appendTo($this.parent()) $this.addClass('form-control') }) but I can't seem to get the while loop to work, it only sees the first one. variants = set() i = 0 field_name = 'variant_%s' % (i,) while self.cleaned_data.get(field_name): variant = self.cleaned_data[field_name] print("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^") print(variant) if variant in variants: self.add_error(field_name, 'Duplicate') else: variants.add(variant) i += 1 field_name = 'variant_%s' % (i,) self.cleaned_data["variants"] = variants def get_variant_fields(self): for field_name in self.fields: if field_name.startswith('variant_'): yield self[field_name] What am I doing wrong here? -
Selenium tests in docker fails after 1st time
I am trying to run a selenium test in docker. The test runs for the first time when I deploy the application for the first time, but after that I get error in fetching page using self.driver.get(url). Fetch error Message: Reached error page: about:neterror?e=connectionFailure&u=https%3A//web.url.com/&c=UTF-8&d=Firefox%20can%E2%80%99t%20establish%20a%20connection%20to%20the%20server%20at%20web.url.com. Stacktrace: WebDriverError@chrome://remote/content/shared/webdriver/Errors.jsm:181:5 UnknownError@chrome://remote/content/shared/webdriver/Errors.jsm:488:5 checkReadyState@chrome://remote/content/marionette/navigate.js:64:24 onNavigation@chrome://remote/content/marionette/navigate.js:312:39 emit@resource://gre/modules/EventEmitter.jsm:160:20 receiveMessage@chrome://remote/content/marionette/actors/MarionetteEventsParent.jsm:42:25 I have tried code : options = Options() options.headless = True profile = webdriver.FirefoxProfile() profile.accept_untrusted_certs = True self.driver = webdriver.Firefox(firefox_profile=profile, options=options) Later used, self.driver.get(url) -
Display foreign key info within Django Detail View Template
As the title says I have a detailed view that I'm presenting via Django templates. I have a foreign key that I'd also like to present within that detailed view and I just can't get it to work. I've tried everything, but all I get is the basic detailed view template with no foreign key info. Any help would be greatly appreciated. Here's what I've got so far: Models: class Cust(models.Model): #this is the main model id = models.UUIDField( primary_key=True, default=uuid.uuid4, editable=False) email = models.CharField(max_length=200) firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) watchmanSlug = models.CharField(max_length=200, unique=True) class Watchman(models.Model): group = models.ForeignKey(Cust, on_delete=models.CASCADE,to_field='watchmanSlug', related_name='watchman_group_slug') uid = models.CharField(max_length=500) computer_name = models.CharField(max_length=500) computer_url = models.CharField(max_length=500) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Views class CustomerDetailView(DetailView): model = Cust template_name = 'cust/cust_detail.html' def get_context_data(self, ** kwargs): context = super(CustomerDetailView, self).get_context_data( ** kwargs) context['computer_name'] = Watchman.objects.all() return context Detail Template <tbody> <ul> {% for p in watchman_group_slug.all %} <li>{{ watchman.computer_name }}</li> {% endfor %} </ul> </tbody> -
Django, Gunicorn, Nginx redirect to local host
I am trying to configure a production server using gunicorn and nginx for my Django app. Currently I have gunicorn running but when I do a curl to my local host, I receive no output, so I think the issue is in my Django urls/views but I am not sure what to change as I am not referencing localhost anywhere. I also have nginx running. I am not using the nginx.conf file directly as I created a symlink and am using site-enabled. Here is my sites-available config: # /etc/nginx/sites-availible/msc_project.conf # HTTP to HTTPS redirect: server { listen 0.0.0.0:80; server_name mscentral.mysite.com; # Certbot Letsencrypt verification location /.well-known/acme-challenge { alias /home/mscentral/mscentral_project/static/.well-known/acme-challenge/; # } return 301 https://mscentral.mysite.com$request_uri; } # Virtual host for mscentral server { listen 0.0.0.0:443 ssl; server_name mscentral.mysite.com; ssl_certificate /etc/letsencrypt/live/mscentral.mysite.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mscentral.mysite.com/privkey.pem; #static file handling location /static/ { alias /home/mscentral/mscentral_project/static/; } location /media/ { alias /home/mscentral/mscentral_project/media/; } #WSGI server location / { proxy_set_header X-Real-IP $remote_addr; proxy_pass http://localhost:8000/; } access_log /var/log/nginx/mscentral_project-access.log; error_log /var/log/nginx/mscentral_project-error.log; } here is my gunicorn service file: [Unit] Description=My Central Service for Gunicron After=network.target [Service] Type=simple # Another Type: forking User=mscentral_internal WorkingDirectory=/home/mscentral/mscentral_project ExecStart=/home/mscentral/venv/bin/gunicorn -b localhost:8000 mscentral_project.wsgi Restart=on-failure # Other restart options: always, on-abort, etc # The install section is … -
How do I inherit columns from a parent django-tables2 Table when model has different accessors?
I have the following models. class Foo(models.Models): X_CHOICES = ( ('abc','Display String for ABC'),) x = models.CharField(max_length=10, choices=X_CHOICES) class Bar(models.Models): foo = models.ForeignKey(Foo, on_delete=models.CASCADE) y = models.CharField(max_length=10) class BarRelative(models.Models): bar = models.ForeignKey(Bar, on_delete=models.CASCADE) z = models.CharField(max_length=10) I need to have two django-tables2 Tables as follows; one for Bar and one for BarRelative. class BarTable(tables.Table): foo = tables.Columns(accessor='foo') y = tables.Columns(accessor='y') class Meta: model = Bar def render_foo(self, record): return f'{record.foo.get_x_display()}' class BarRelativeTable(BarTable): # I don't want to have to redefine the foo column just to change the accessor # foo = tables.Column(accessor='bar__foo') # I just want to add the new column z z = tables.Column(accessor='z') class Meta(BarTable.Meta): model = BarRelative # I don't want to redefine render_foo() just to change the accessor like this... # def render_foo(self, record): # return f'{record.bar.foo.get_x_display()}' def render_z(self, record): return f'{record.z}' I tried using "multi-table" inheritance with my models, however this did not work because Bar to BarRelative is a one-to-many relationship. Multi-table inheritance only works for one-to-one, so I am forced to use a ForeignKey in my model. Next I tried annotating each Field in Bar in my QuerySet for BarRelative in a manager like this... class BarRelativeManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate(foo = F(bar__foo)) … -
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?