Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why my own template_name doesn't show instead of default template_name in django?
I need to show my own template_name for (passwordResetConfirm) when I use template_name here I get the default Django template also when I get the successful message from (PasswordResetComplete) I get from the same place I mean (the default Django template too). however, I get no errors of code.so, How can I get my own template_name in this case? urls.py from . import views from django.conf.urls import url from django.contrib.auth.views import ( LoginView, logout, PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.core.urlresolvers import reverse_lazy from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required # django\contrib\admin\templates\registration\password_reset_done.html app_name = 'account' class PasswordReset(PasswordResetView): template_name = 'account/password_reset_form.html' success_url = reverse_lazy('account:password_reset_done') email_template_name = 'account/reset_password_email.html' class PasswordResetDone(PasswordResetDoneView): template_name = 'account/password_reset_done.html' success_url = reverse_lazy('account:password_reset_complete') class PasswordResetConfirm(PasswordResetConfirmView): success_url = reverse_lazy('account:password_reset_complete') template_name = 'account/password_reset_confirm.html' def func(self, request): return render(request, self.template_name) class PasswordResetComplete(PasswordResetCompleteView): template_name = 'account/password_reset_complete.html' urlpatterns = [ # /account/ url(r'^$', views.index, name="home"), # /account/login/ url(r'^login/$', LoginView.as_view(template_name='account/login.html'), name='login_page'), # /account/logout/ url(r'^logout/$', logout, {'template_name': 'account/logout.html'}, name='logout'), # /account/register/ url(r'^register/$', views.register, name='register'), # /account/profile/ url(r'^profile/$', views.view_profile, name='view_profile'), # /account/profile/edit/ url(r'^profile/edit/$', views.edit_profile, name='edit_profile'), # /account/change-password/ url(r'^change-password/$', views.change_password, name='change_password'), # /account/password-reset/ url(r'^password-reset/$', PasswordReset.as_view(), name='password_reset'), # /account/password-reset/done/ url(r'^password-reset/done/$', PasswordResetDone.as_view(), name='password_reset_done'), # /account/password-reset/confirm/ url(r'^password-reset/confirm/(?P<uidb64>[0-9A-Za-z]+)/(?P<token>.+)/$', PasswordResetConfirm.as_view(), name='password_reset_confirm'), # /account/password-reset/complete/ url(r'^password-reset/complete/$', PasswordResetComplete.as_view(), name='password_reset_complete'), ] settings.py STATIC_URL = '/static/' … -
Extraction datas from forms
I've just start to learn Django and now I'm trying understand how to insert datas in db, how to work with datas from templates and ect. My question is about extracting datas from form(Meta class) in template. Here is my code: model class Worker(models.Model): POSITION_SHOICE = ( ('MANAGER', 'MANAGER'), ('developer', 'DEVELOPER'), ('teamlead', 'TEAMLEAD'), ('pm', 'PM'), ('hr', 'HR'), ) f_name = models.CharField(max_length=50) s_name = models.CharField(max_length=50) position = models.CharField(max_length=10, choices=POSITION_SHOICE, default='developer') work_time = models.DecimalField(max_digits=1000, decimal_places=0) cost_in_hour = models.DecimalField(max_digits=1000, decimal_places=2) salary = models.DecimalField(max_digits=10000000, decimal_places=2, default=0) before inserting datas salaty should be calculate in this way: salary = work_time*cost_in_hour form class WorkerForm(forms.ModelForm): class Meta: model = Worker fields = { 'f_name', 's_name', 'position', 'work_time', 'cost_in_hour', } view def worker_create_view(request): form = WorkerForm(request.POST or None) if form.is_valid(): form.save() form = WorkerForm() context = { 'form': form } return render(request, "workers/worker_create.html", context) I actually cannot understand how can I extract datas from dictionary items with name 'work_time' and 'cost_in_hour'. then calculate salary, insert into dictionary and send to database. P.S. if you can explain or write a resource where can i read about how does inserting datas work in Django it'd be cool -
Dynamically create website from new models in Django
I have a model, displayed on an html, everything working fine. The problem is that for each object I need Django to automatically and dynamically create a link and display information from that model using I assume a template. so whenever someone clicks on the link, that template with the model info is displayed. Hopefully my explanation was clear enough ! thank you very much. -
Django: ModuleNotFoundError: No module named 'mysite.notes'
I try to create a django project. I have some problems with url configurations. The modules that I need, can't be found. Here is my directory's hierarchy: . ├── db.sqlite3 ├── manage.py ├── mysite │ ├── asgi.py │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ ├── settings.cpython-37.pyc │ │ ├── urls.cpython-37.pyc │ │ └── wsgi.cpython-37.pyc │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── notes │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ ├── 0001_initial.py │ │ ├── __init__.py │ │ └── __pycache__ │ │ ├── 0001_initial.cpython-37.pyc │ │ └── __init__.cpython-37.pyc │ ├── models.py │ ├── __pycache__ │ │ ├── admin.cpython-37.pyc │ │ ├── __init__.cpython-37.pyc │ │ ├── models.cpython-37.pyc │ │ └── views.cpython-37.pyc │ ├── tests.py │ └── views.py └── static └── templates ├── __init__.py └── note.html I have edited the urls.py file: from django.contrib import admin from django.urls import path, include from mysite.notes import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name="home") ] When I try to run my server, it says: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/home/alpaca/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/alpaca/.local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute … -
Django - How can I adjust the page permission according to the member role?
I'm using django-groups-manager. Screenshot I can set the page permission according to the user in the group in the decorator below. So how can I set this up for the member's role? Thus, only the member with this role can see the page. I'm waiting for your help. decorators.py def sahip_only(view_func): def wrapper_function(request, *args, **kwargs): group = None if request.user.groups.exists(): group = request.member.groups.all()[0].name if group == 'Lol': return redirect('home') if group == 'Bilgisayar': return view_func(request, *args, **kwargs) else: return HttpResponse('You are not authorized to access this page.') return wrapper_function views.py @login_required(login_url='/accounts/login/') @sahip_only def calisan(request): queryset = request.user.groups form = CalisanForm(request.POST or None, group_qs=queryset) if form.is_valid(): user = form.save() group = form.cleaned_data['group'] user.groups.add(AGroup.objects.get(name=group)) username = form.cleaned_data['username'] member = Member.objects.create(first_name=username) group = Group.objects.get(name=form.cleaned_data['group']) group.add_member(member, [form.cleaned_data.get('roles')]) user.save() password = form.cleaned_data.get('password1') new_user = authenticate(username=user.username, password=password) return redirect('home') return render(request, 'accounts/calisan/calisan.html', {'form': form, 'title': 'Üye Ol'}) forms.py class CalisanForm(UserCreationForm): username = forms.CharField(max_length=100, label='Kullanıcı Adı') email = forms.EmailField(max_length=200, help_text='Required') password1 = forms.CharField(max_length=100, label='Parola', widget=forms.PasswordInput) password2 = forms.CharField(max_length=100, label='Parola Doğrulama', widget=forms.PasswordInput) group = forms.ModelChoiceField(queryset=Group.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None) roles = forms.ModelChoiceField(queryset=GroupMemberRole.objects.all(), widget=forms.widgets.RadioSelect(), empty_label=None) def __init__(self, *args, **kwargs): qs = kwargs.pop("group_qs") super().__init__(*args, **kwargs) self.fields["group"].queryset = qs class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2', 'group', 'roles', … -
Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order:
I know this question has been asked before, but I haven't found an answer that solves my situation. I'm looking at the Django tutorial, and I've set up the first URLs exactly as the tutorial has it, word for word, but when I go to http://127.0.0.1:8000, it gives me this error: Using the URLconf defined in first_project.urls, Django tried these URL patterns, in this order: ^$ [name='index'] admin/ The empty path didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. I'm using Django 2.2.5 and Python 3.8. Here is the code I have in relevant url and view files: In mysite views.py: from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): return HttpResponse("Hello World!") In mysite urls.py: from django.contrib import admin from django.urls import path from first_app import views urlpatterns = [ path(r'^$',views.index,name='index'), path('admin/', admin.site.urls), ] In mysite setting.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'first_app', ] What's going on? Why am I getting 404s? -
Why is JQuery not passing the post_id and post_type from replacement div
I fixed the like/unlike functions and now they work, but if you click "Unlike" after clicking "Like" (or visa versa) without reloading the page, the post_id and post_type don't get passed to the view. I tried to pass them to the html that replaces the buttons and I can see them on the new div but that didn't get passed to the view from there either. I'm not sure what to do since I don't understand how the data is getting lost. I also put two div tags in the replacement html that hold the id and type as values because I needed a script in the replacement html (didn't know that) for the button to work. Why is the JS not able to grab the data from the replacement html? The code is fairly long so I apologize in advance feed.html (snippet of the main html) <div class="like-stuff"> {% if not request.user|user_liked_post:post %} <button class='like-post-btn' value="{{like_btn_val}}"> <span class="glyphicon glyphicon-thumbs-up"></span> Like </button> {% else %} <button class='like-post-btn' value="{{like_btn_val}}"> <span class="glyphicon glyphicon-thumbs-up"></span> Unlike </button> {% endif %} <div class="like-count">{{post.like_count}}<div> {% if not request.user|user_disliked_post:post %} <button class='dislike-post-btn' value="{{dislike_btn_val}}"> <span class="glyphicon glyphicon-thumbs-down"></span> Dislike </button> {% else %} <button class='dislike-post-btn' value="{{dislike_btn_val}}"> <span class="glyphicon glyphicon-thumbs-down"></span> … -
Insert RichText into CKEditor using Lodash
I have add and edit functionality on my webpage. When a user clicks add, one of the fields is CKEditor. But when the user clicks Edit button I am currently using lodash template to setData() in the textarea of ckeditor but the text is unformatted. Please go through the following image. Current edit functionality when Edit is clicked upon which a modal opens :- Desired functionality:- My HTML page with Lodash <textarea name="editor1" id="editor1" value="<%- data.description %>"></textarea> <script> CKEDITOR.replace( 'editor1' ); val = "<%- data.description %>" CKEDITOR.instances.editor1.setData(val); </script> -
How to maintain the TCP gRPC connection in Django?
I have a grpc server and a Django app as a client who calls this server. Currently for every single request I connect to grpc channel and close after completion as shown below. def checkStatus(): channel=grpc.insecure_channel('localhost:50051') stub = api_pb2_grpc.RAPIStub(channel) status = stub.checkStatus(api_pb2.Empty()) print(status) channel.close() But actually I want to connect to the server and maintain the connection as in indirectly I am asking to making the stub variable above global. Because Django runs in WSGI configuration in production, there are multiple processes spawning but I cannot use the connection variable across other processes as it was instantiated theirs. So is there any way I can connect and maintain the grpc connection for all requests rather than making separate connections for every request. -
Django has stopped creating objects of model
I have unusual problem. My django app has stopped creating the objects of model. It does not return any error, just new object does not appear in the admin panel. I deleted the old db and created new one and this started happening. It's even hard for me to show any code as it just worked as intended before the above action. What might be the reason ? -
Django Attribute Error: "AttributeError: module 'django.db.models' has no attribute 'ManytoManyField' "
I am executing this line of code in my terminal: python manage.py makemigrations I get this as output: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 112, in populate app_config.import_models() File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "C:\Users\Bryan\AppData\Local\Programs\Python\Python37-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\Bryan\Desktop\wisdompets\adoptions\models.py", line 3, in <module> class Pet(models.Model): File "C:\Users\Bryan\Desktop\wisdompets\adoptions\models.py", line 13, in Pet vaccinations = models.ManytoManyField('Vaccine', blank=True) **AttributeError: module 'django.db.models' has no attribute 'ManytoManyField'** Can anyone let me know what I am doing wrong? -
How to sum the list in template django?
I want to get the sum of the moneylog_set.price so i try to assign total_pay but the error occur view.py def all_moneybooks(request): current_user = request.user if current_user.is_authenticated: current_user_moneybooks = current_user.owner.all() total_pay = 0 book_total_pay_list = [] for current_user_moneybook in current_user_moneybooks: moneylog_set = current_user_moneybook.moneylog_set.all() for moneylog in moneylog_set: total_pay += moneylog.price book_total_pay_list.append( (moneylog.moneybook.id, moneylog.price)) print(dir(moneylog_set)) print(book_total_pay_list) return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks, "current_user_moneybooks": current_user_moneybooks, "total_pay": total_pay, "book_total_pay_list": book_total_pay_list}) else: return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks}) home.html {% for current_user_moneybook in current_user_moneybooks %} <a href="{% url "moneybooks:detail" current_user_moneybook.pk %}"> <div class="border-gray-400 border-t border-b border-l border-r"> <div class="container flex mx-auto"> <div class="w-1/5 my-10"> <p class="text-center text-gray-900">{{current_user_moneybook.country}}</p> </div> <div class="w-3/5 my-3"> <div class="inline-block align-middle text-gray-900 font-bold text-xl mb-2">{{current_user_moneybook.name}}</div> <div class="text-gray-700 text-sm">{{current_user_moneybook.companion.all}}</div> <div class="text-gray-900 text-sm">{{current_user_moneybook.start_date|date:"Y년 m월 d일"}} ~ {{current_user_moneybook.end_date|date:"Y년 m월 d일"}}</div> </div> <div class="w-1/5 my-10"> <div class="text-center text-gray-900 text-gray-900 font-bold text-xl mb-2"> {{book_total_pay_list[current_user_moneybook.pk:2].sum()}} </div> </div> </div> </div> </a> {% endfor %} Could not parse the remainder: '[current_user_moneybook.pk:2]' from 'book_total_pay_list[current_user_moneybook.pk:2]' is there any other method or more query way? also, I guessenter code here .sum() method is not working. is there other method to sum this price list? -
Extends Django User Model with my Model User
Already seen some documents and read some posts about this matter but I cant seem to undersatand maybe someone could help me out. I want to extend Django user model with my model "User". This is my model user: from django.db import models from django.contrib.auth.models import User as UserDJANGO from django.db.models.signals import post_save from django.dispatch import receiver class User(models.Model): user_django = models.OneToOneField(UserDJANGO, on_delete=models.CASCADE) user_animals = models.ManyToManyField(Animal, blank=True) def __str__(self): return self.user_django.email my signup view: def signup(request): auth_logout(request) form = UserCreationForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) auth_login(request, user) return redirect("home") return render(request, 'signup.html', {'form': form}) and my form in the template: <form method="post" class="form-signin"> {% csrf_token %} <img class="mb-4" src="{% static 'images/logo_transparent.png' %}" alt="" width="300" height="300"> <h1 class="h3 mb-3 font-weight-normal text-white">Registar-se</h1> <label for="id_username" class="sr-only">Endereço de Email</label> <input type="email" name="username" maxlength="150" autocapitalize="none" autocomplete="username" autofocus="" required="" id="id_username" class="form-control" placeholder="Endereço de Email"> <label for="id_password1" class="sr-only">Password</label> <input type="password" name="password1" autocomplete="new-password" required="" id="id_password1" class="form-control" placeholder="Password"> <label for="id_password2" class="sr-only">Password</label> <input type="password" name="password2" autocomplete="new-password" required="" id="id_password2" class="form-control" placeholder="Confirme a Password"> <p class="mb-3 font-weight-normal text-white">Já possui conta? <a class="text-white" href="/login">Inicie sessão</a> </p> <button class="btn btn-lg btn-primary btn-block" type="submit">Registar</button> <!--<p class="mt-5 mb-3 text-white">&copy; 2017-2019</p>--> </form> How can I … -
Django website deployment is raising an ImproperlyConfigured error
I am configuring a new Django web site using Cpanel. After completing the whole procedures and run this code python manage.py collectstatic I am getting the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line utility.execute() File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 195, in fetch_command klass = load_command_class(app_name, subcommand) File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 40, in load_command_class return module.Command() File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 32, in __init__ self.storage.path('') File "/home/massvnrc/virtualenv/mysite/3.7/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 48, in path raise ImproperlyConfigured("You're using the staticfiles app " django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. Bellow is the configuration that is raising the error: STATIC_URL = '/static/' MEDIA_URL='/media/' STATICFILES_DIRS=[BASE_DIR+"/assets",] MEDIA_ROOT='/home/****/public_html/media' STATIC_ROOT='/home/****/public_html/static' I honestly don't know where is the erro and the similar issues do not help me to solve the problem. Please assist me -
specify timezone for django datetimefield with gmt offset from jquery datetimepicker
I have a model form from a model with a datetimefield. models.py timestamp = models.DateTimeField('Date UTC') script on formpage <script> jQuery('#id_timestamp').datetimepicker({ format:'d/m/Y H:i O', inline:false, lang:'eng', theme:'dark', datepicker: true, timepicker:true, todayButton:true, step: 30, uselocaltimezone: false }); </script> This gives me a nice jquery datetimepicker. I need users to be able to specify a timezone (i.e. the machine they are on might not be in the same timezone of the datetime they need to populate. The above jquery populates my field as example: 16/01/2020 23:00+0000 I have two issues: 1) this fails the django modelform validation. 2) this does not allow the user to specify a timezone - it picks the timezone from the users machine. I see this page: How can I set a timezone in the datetimepicker? helped me to find the O option in formatting. So my questions: 1) I can't see in the django docs how the datetimefield is validated, so I'm not sure how to modify the format in jquery to make it valid? 2) I'm looking for ideas on how best to have the user set the timezone manually. -
what is the difference between reverse, reverse_lazy, resolve and redirect? [Django]
what is the difference between those next terms: reverse, reverse_lazy, resolve and redirect I think when I have to use return then I have to use redirect but if this is true?; why I can't use reverse instead of redirect? also, when I should use these methods? -
Having problem on 'KeyError at /new_search 0' on Django
I got stuck when I was building a django project which is a clone of craigslist. I made a search bar and Search model and added it to views. But when ever I tried to search anything in my website, it throws me a error called "KeyError at /new_search 0" Other details are... Request Method: POST Request URL: http://127.0.0.1:8000/new_search Django Version: 2.2.7 Exception Type: KeyError Exception Value: 0 Exception Location: C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages\bs4\element.py in getitem, line 1321 Python Executable: C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python.exe Python Version: 3.7.1 Python Path: ["D:\Users\Admin\Desktop\Mugdho's List\mugdhos_list", 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\python37.zip', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\DLLs', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32', 'C:\Users\Admin\AppData\Roaming\Python\Python37\site-packages', 'C:\Users\Admin\AppData\Local\Programs\Python\Python37-32\lib\site-packages'] Here is my views.py import requests from requests.compat import quote_plus from django.shortcuts import render from bs4 import BeautifulSoup from . import models BASE_CRAIGSLIST_URL = 'https://losangeles.craigslist.org/search/?query={}' # Create your views here. def home(request): return render(request, 'base.html') def new_search(request): search = request.POST.get('search') models.Search.objects.create(search = search) final_url = BASE_CRAIGSLIST_URL.format(quote_plus(search)) response = requests.get(final_url) data = response.text soup = BeautifulSoup(data, features='html.parser') post_listings = soup.find_all('li',{'class': 'result-row'}) final_postings = [] for post in post_listings: post_title = post[0].find(class_='result-title').text post_url = post[0].find('a').get('href') post_price = post[0].find(class_='result-price').text final_postings.append((post_title, post_url, post_price)) stuff_for_frontend = { 'search' : search, 'final_postings' : final_postings } return render(request, 'my_app/new_search.html', stuff_for_frontend) Here is my new_search.html {% extends "base.html" %} {% block content %} <h3 class="center">{{ search | … -
TypeError at /email-signup Object of type 'WSGIRequest' is not JSON serializable
Currently trying to make an email newsletter work with django 2.2 and MailChimp. Got the code from a youtube video, I thought I unterstood it, but then I faced the error in the title. I have tried various things such as just passing data=data in the subscribe function, but nothing I tried worked. The thing that concerns me is that it worked just fine in the video, and since it's not old I don't think that django has changed significantly. Any help/explanation would be greatly appreciated. views.py (not all imports) from django.conf import settings from .forms import EmailSignupForm from django.http import HttpResponseRedirect import json import requests MAILCHIMP_API_KEY = settings.MAILCHIMP_API_KEY MAILCHIMP_DATA_CENTER = settings.MAILCHIMP_DATA_CENTER MAILCHIMP_EMAIL_LIST_ID = settings.MAILCHIMP_EMAIL_LIST_ID api_url = 'https://{dc}.api.mailchimp.com/3.0'.format(dc=MAILCHIMP_DATA_CENTER) members_endpoint = '{api_url}/lists/{list_id}/members'.format( api_url=api_url, list_id=MAILCHIMP_EMAIL_LIST_ID ) def subscribe(email): data = { "email_address": email, "status": "subscribed", } print(data) print(data[]) r = requests.post( members_endpoint, auth=("", MAILCHIMP_API_KEY), data=json.dumps(data), # I think the error is caused here ) return r.status_code, r.json() def email_list_signup(request): form = EmailSignupForm(request.POST or None) if request.method == "POST": if form.is_valid(): email_signup_qs = Signup.objects.filter(email=form.instance.email) if email_signup_qs.exists(): messages.info(request, "You are already subscribed") else: subscribe(form.instance.email) messages.success(request, "You have subscribed successfully!") form.save() return HttpResponseRedirect(request.META.get('HTTP_REFERER')) class HomeView(ListView): template_name = "home.html" model = Post form_class=EmailSignupForm def get_context_data(self, **kwargs): … -
Moving model from third-party app to project app while being compatible with environments with applied migrations
I'm using a single model from a third-party Django application that I want to move into a new app inside of my project. The problem is that I have a some of my models that have foreign keys to the old model that I would like to simply point to the new model. The migrations for these then have dependencies to the old app and I can't keep the old app since it is not compatible with new versions of Django which causes Django commands to raise errors. Basically there are three apps that are of interest here, old_app, new_app and dependent_app. dependent_app currently depends on old_app and should be changed to depend on new_app. If I change the dependency list in the migration of dependent_app from: dependencies = [ ('old_app', '0001_initial'), ] to dependencies = [ ('new_app', '0001_initial'), ] I get the following error in environments using the old_app: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration dependent_app.0001_initial is applied before its dependency new_app.0001_initial on database 'default'. Also, I've setup the new model to have the same table name using Meta.db_table to not have to bother with updating any of the foreign keys in the dependent app to the new model. -
Try to assign variable in template 'with' expected at least one variable assignment
I want to get the sum of the moneylog_set.price so i try to assign total_pay but the error occur view.py def all_moneybooks(request): current_user = request.user if current_user.is_authenticated: current_user_moneybooks = current_user.owner.all return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks, "current_user_moneybooks": current_user_moneybooks}) else: return render(request, "home.html", context={"current_user": current_user, "all_moneybooks": all_moneybooks}) home.html {% for moneylog_set in current_user_moneybook.moneylog_set.all %} <div class="text-center text-gray-900 text-gray-900 font-bold text-xl mb-2"> {% with total_pay+=moneylog_set.price %} {{total_pay}} {% endwith %} </div> {% endfor %} 'with' expected at least one variable assignment is there any other method or more query way? -
I am trying to develop a scoring system site that allows users to submit target scores (one time) for given metrics. More in description
I am very new to this and this is a bit of a complicated app, so please bear with me. I am creating 2 pages: 'submittargets' and 'entertargetdata'. Within the 'submittargets' page, you will be prompted to select an account from a list, which will grab the ID of the account object, pass it to the URL, and have the object name appear in a drop down on the next page. I am doing this so I know that the appropriate object has been passed. On the 'entertargetdata' page, 'questions' appear in a for loop, and you will enter target scores (from 1 to 100) for each question, also in the for loop. Then click submit: this will post the account, questions for the account, and scores for the question to a sqlite database. I am utterly stuck. I do not know how to pass the account object to the enter data page. I do not know how to take simple input fields and use a form to collect that data. I do not know how to get the account, and questions and scores to join and appear in the database table. I'm struggling so hard. Current error is page … -
Limit queryset in generic views to objects with request.user as foreign key
I've had to add a method to just about UpdateView, DetailView, ListView, and DeleteView class in views.py to limit the queryset to only return objects that the logged in user is allowed to see (which in my case, means they are the foreignkey user on the object's model) def get_queryset(self): base_qs = super(ViewName, self).get_queryset() return base_qs.filter(user=self.request.user) Is there a more efficient way to do this with a Mixin or anything? -
EmailMessage django
I am using EmailMessage class to send mail, but I am getting the following error AttributeError: 'list' object has no attribute 'send_messages' EmailMessage The minimal code to reproduce the result is as follows: def send_mails(subject, html_message, sender_mail, recipient_list, bcc_list, cc_list, reply_to): email = EmailMessage(subject, html_message, sender_mail, recipient_list, bcc_list, cc_list, reply_to=reply_to) email.content_subtype = 'html' email.send() send_mails(request.data['subject'], html_message, request.data['sender_mail'], request.data['recipient_list'], request.data['bcc_list'], request.data['cc_list'], request.data['reply_to']) from django.template import loader html_message = loader.render_to_string( 'send/base.html', { 'product_name': request.data['product_name'], 'sender': request.data['sender_mail'], 'body': request.data['body'], 'bgcolor': bgcolor, 'product_url': request.data['product_url'], 'bg_img': bg_img }) Also, how to handle if I don't get some fields like cc, bcc in some request? Any help is highly appreciated. -
Running python (django) script with relative imports as daemon in background on Ubuntu (linux)
I've searched around and found a plethora of answers and can get none to fit. Currently I'm running a Ubuntu server for my django website. The main folder's filepath inside the project is: '/var/www/mysite/main' Inside that directory sits 'tasks.py' which I would like to run continuously in the background even when exiting the SSH terminal. For reference, tasks.py below. All imports are currently in the same (/main) as tasks.py, but if possible I'd like to be able to place some in other directories inside /main: #!/usr/bin/env python from .db_service import * from .pricer_inventory import * from .propdb import * from .inventory import * import time import schedule import json import os from threading import Thread def write_list_info_to_db(): print('Starting writing list info to db') dir_name = os.path.dirname(__file__) file_path = os.path.join(dir_name, 'propdb/inventory_pricing.json') list_response = generate_list_info(get_list_of_inventory_styles(), 30, True) with open(file_path, 'r') as file: jdata = json.load(file) for style in list_response.keys(): jdata.update({style: list_response[style]}) with open(file_path, 'w') as outfile: json.dump(jdata, outfile) write_list_info_to_db() #schedule.every().day.at('08:30').do(write_list_info_to_db) #schedule.every(1).to(2).hours.do(write_list_info_to_db) class SchedulerThread(Thread): @classmethod def run(cls): while True: schedule.run_pending() time.sleep(10) SchedulerThread().start() I also have a service config file in '/lib/systemd/system/' named 'tasks.service' [Unit] Description=Database Service After=multi-user.target Conflicts=getty@tty1.service [Service] Type=simple ExecStart=/usr/bin/python3 /var/www/mysite/main/tasks.py StandardInput=tty-force [Install] WantedBy=multi-user.target Note I've also tried storing tasks.py in /usr/bin … -
it is secure to have a plain text password for my PostgreSQL connection in Django?
I am not sure if it is not secure to have a plain text password for my PostgreSQL database connection. i.e In my "settings.py" file: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'my_database', # database name 'USER': 'username', # P.user 'PASSWORD': 'plaintext password goes here', 'HOST': 'localhost', # where is locate our database? 'PORT': '', } } If it is not secure please give more information about how to handle this situation. Note: I am using https for my webpage but I'm just wanna know if I have to secure this also even if the connection is locally.