Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django filter gte and lte on one property of one model
I have a User model with age property my models.py class User(models.Model): age = models.IntegerField() i need to output all users between 25 and 35 i can only make query which won't exclude others users first_query = User.objects.filter(age__gte=25) second_query = User.objects.filter(age__lte=35) can i output users between 25 and 35 and exclude others, in one query? -
Dockerfile not being found for Google cloud run
I've hit another bug. I'm now trying to set up continuous deployment for Google Cloud Run from my GitHub, and it's not finding my Dockerfile. I've tried various combinations with my file paths, but it still gives me the Already have image (with digest): gcr.io/cloud-builders/docker unable to prepare context: unable to evaluate symlinks in Dockerfile path: lstat /workspace/Dockerfile: no such file or directory error. This is my file structure from VSCode, and if I run the command from the first Exeplore folder, it finds the Dockerfile The source directory is public, so I just can't figure out why it's not finding the Dockerfile. https://github.com/Pierre-siddall/exeplore Any advice at all would be greatly appreciated, thank you! -
django eventstream / channels return HTML
I have a working application where I use django-eventstream to show info/error messages to users. All works well with send_event(): send_event("ok_message", "message_ok", msg) send_event("error_message", "message_error", msg) but what I actually want to do is send some html directly to the frontend. Is this possible? send_event("ok_message", "message_ok", {"html": "<h1>test</h1>"}) -
How to add item to cart after the user login ? #django
I'm completely new to Django and I tried to create a simple eCommerce web application. In my code, when the user is not logged, items are easily added to the cart and displayed to the web application but when the same user logged into the application and tries to add the item to the cart it is not displayed in the frontend but the item is added to user from backend. I tried the logic if user.is_authenticated but I was not able to succeed. from carts.models import Cart, CartItem def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create( cart_id = _cart_id(request) ) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product = product, quantity = 1, cart = cart, ) cart_item.save() return redirect('cart') This is Django code adding items to the cart before the user login. -
NEED TO SHOW PROGRESS BAR OF FILE SPLITER FUNCTON IN PYTHON
I have a web application that split large CSV into multiple CSV. But I need to show the progress of function processing to the user on front end. Can anyone help me with that, I am using python and Django -
How to extend multiple bases or conditional {% extends %} in one html page in django?
{% if request.user.profile.emp_desi in qa_list %} {% extends "qa_base.html" %} {% elif request.user.profile.emp_desi in mgr_list %} {% extends "manager_base.html" %} {% else %} {% extends "common_base.html" %} {% endif %} How can I solve this problem?? based on designation I want to extend different different bases. -
Why Django doesn't update an object?
I have a model Profile, which connects with User. For example I have Testuser. When I try to update his field 'money', nothing happens. I suppose it may be because I use User, instead of Profile in get_object. But if I change it to Profile, there is an error, that Profile doesn't have username field. How can I solve this problem? model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) money = models.IntegerField(default=0) form: class AddMoneyForm(forms.ModelForm): class Meta: model = Profile fields = ('money',) view: class AddMoneyView(UpdateView): model = Profile template_name = 'users/money.html' fields = ['money'] def get_object(self, queryset=None): return get_object_or_404(User, username=self.kwargs.get('username'), pk=self.request.user.pk) def get_success_url(self): return reverse('account', kwargs={'username': self.request.user.username}) url: path('account/<str:username>/money/', AddMoneyView.as_view(), name='money'), -
How to use the result of a graphene resolved field in another field
I have this use case: class ProjectType(graphene.objectType): tasks = graphene.List(TaskType) duration = graphene.Int() # days def resolve_tasks(): return self.tasks.all() def resolve_duration(): return get_duration_from_tasks(self.tasks.all()) A project can have many tasks, so self.tasks.all() can be an expensive db query to do twice. -
Is it necessary to do threading for sending emails in django
I am not sure that if it is necessary to use thraeding for sending emails in django or not ? If we need to do it so Can i just use the threading library instead of Celery or rabbitmq ? -
Django Form | Group Model | MultiSelect | getting only single value from the form by using MultiSelect widget
I am trying to get input from the user in a template, I am showing list of Groups in template available from the Group model in Django Auth Models and expecting multiple values. But it is only returning single value even selecting multiple options from django.contrib.auth.models import Group class MyForm(forms.ModelForm): the_choices = forms.ModelMultipleChoiceField(queryset=Group.objects.all(), required=False, widget=forms.CheckboxSelectMultiple) class Meta: model = Group exclude = ['name', 'permissions'] def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) image references below Template - Input Form Image Output in Console kindly refer to image 2, I expect 1 and 2 (group name preffered) in console but its returning only 2. -
JWT with Django Rest Framework not working in production
My application uses Django Rest Framework for the APIs and JWT for authenticating the users. Everything was working fine in my local machine. I started having problems after a deployed it to an EC2 instance. The only things that still work are the login, registration and tokens refresh. That is, when I try to log in, I receive the tokens back from the back-end, which are successfully stored in the local storage; when I try to sign up, the back-end creates the new user; and from time to time the tokens are also successfully updated. But all the other API calls fail. At the beginning, when I made an API call, I was getting back "401 Unauthorized". I believe the reason was because Apache wasn't forwarding the Authorization-Headers. So I added "WSGIPassAuthorization On" to the Apache configuration. Now I am getting "500 Internal Server Error" instead. As I already said, only API calls to login, tokens refresh and registration are working. For login and tokens refresh, I am using the default "TokenObtainPairView" and "TokenRefreshView". from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('log-in/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('refresh-token/', TokenRefreshView.as_view(), name='token_refresh'), ] For the registration, this is the view I am using: class … -
django - disable button in javascript based on text input
I've got problem to disable submit button conditionally. My js code is as follows: function disableButton() { var btnSubmit = document.getElementById('sub_butt'); if (document.getElementsByName('submitted').value == "yes") { btnSubmit.disabled = true; } else { btnSubmit.disabled = false; } } In django I have updateForm with formset and I would like to disable button based on value text field with name "submitted". I've tried the code above but nothing's changed. Field "submitted" is already filled out with value 'yes' -
ModelFormset in Django CreateView
I'm still new to Django & I would like to know how can allow user to add more than 1 ReferrerMember on Registration form as I wanted to achieve similar to the image url below https://imgur.com/a/2HJug5G I applied modelformset but so far it's giving me an error where "membership_id" violates not-null constraint the moment I submitted the form. I've searched almost everywhere to find how to implement this properly especially on class-based view instead of function based view but still no luck. If possible please help me point out on any mistakes I did or any useful resources I can refer to models.py class RegisterMember(models.Model): name = models.CharField(max_length=128) email = models.EmailField() class ReferrerMember(models.Model): contact_name = models.CharField(max_length=100) company_name = models.CharField(max_length=100) membership = models.ForeignKey(RegisterMember, on_delete=models.CASCADE) forms.py class RegisterMemberForm(ModelForm): class Meta: model = RegisterMember fields = ['name', 'email', ] class ReferrerForm(ModelForm): class Meta: model = ReferrerMember fields = ['contact_name ', 'company_name ', ] ReferrerMemberFormset = modelformset_factory(ReferrerMember, form=RegisterMemberForm, fields=['contact_name ', 'company_name ', ], max_num=2, validate_max=True, extra=2) views.py class RegisterMemberView(CreateView): form_class = RegisterMemberForm template_name = 'register.html' def post(self, request, *args, **kwargs): member_formset = ReferrerMemberFormset (request.POST, queryset=ReferrerMember.objects.none()) if member_formset .is_valid(): return self.form_valid(member_formset ) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['member_formset'] = ReferrerMember(queryset=ReferrerMember.objects.none()) return context register.html <form … -
How store csv file details into a django model
how solve this? how to store the csv file details(not csv file data) like file name,uploaded name,No. of rows into a another django table or model. -
how do i see data by using django listview at chrome
I used listview and confirmed that there was a query set in the terminal. I want to see that data on the Internet. However, even though there is data, row of the table is not added. What should I do? It's so frustrating. I couldn't do anything for five hours because of this. plz heeeeelp me...! # html {% extends 'branches/package-create.html' %} {% block nav %} <form method="get" enctype="multipart/form-data"> {% csrf_token %} {% for i in ps %} <tr class="content-tr"> <td class="td1">{{ i.package_recommandation_date }}</td> <td class="td2">{{ i.package_payment_date }}</td> ... </tr> {% endfor %} </form> {% endblock %} # MODELS.PY class PayHistory(models.Model): branch = models.ForeignKey(Branch, on_delete=models.CASCADE, null=True) package_recommandation_date = models.DateField(null=True) package_payment_date = models.DateField(null=True) ... # views.py class PackageListView(ListView): template_name = 'branches/package-get.html' model = PayHistory def get_queryset(self): p=PayHistory.objects.all() print(p) return p # TERMINAL <QuerySet [<PayHistory: PayHistory object (1)>, <PayHistory: PayHistory object (2)>]> -
dajango AttributeError at / 'WSGIRequest' object has no attribute 'get'
This is my views.py from django.shortcuts import render import requests # Create your views here. def mainfun(requests): city="London" url=f"http://api.weatherapi.com/v1/current.json?key=69528a98f894438b88982548221507&q={city}&aqi=no" data= requests.get(url) return render(requests,"index.html",{'d':data}) This is my settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'weatherapp', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'weather.urls' requests is not working when try to get data from the api.. How to solve this problem..? -
Django selenium: StaticLiveServerTestCase => 'admin' user can not login
I try to use StaticLiveServerTestCase and fixtures. I have created 7 users using fixture and one of them, 'admin' is_superuser=True. My tests pass for all of users except admin that failed to login. I've checked password of admin at the begining of the test method, and I don't know how but (1) password do not correspond to the password set in fixture and (2) password change every runs. That explain failed in login but why only this user has such a behavior? If I try to connect in my dev environnement, using database containing fixtures datas, it works... I try to change is_superuser to false, or 'admin' username with 'myadmin' if there could be a side effect but none works... tests.py class L_access_menu_creation_patient_TestCase(StaticLiveServerTestCase): fixtures = ['dumpdata.json'] @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(1) cls.selenium.maximize_window() cls.date_saisie = timezone.now() cls.selenium.get(cls.live_server_url) # le menu "Ajouter un patient" est disponible (id=menucreate) def test_menu_create_available_admin(self): # ----------------------------------------- connexion ------------------------------- self.admin = User.objects.get(username='admin') print('admin',self.admin.username,self.admin.password) # envoie de données d'identification username_input = self.selenium.find_element_by_name("username") username_input.send_keys('admin') password_input = self.selenium.find_element_by_name("password") password_input.send_keys('admin') fixture dumpdata.json ... { "model": "auth.user", "fields": { "password": "pbkdf2_sha256$150000$qe1v2XJKkik8$jF6iFZ+4GpK1JzBdHzRG0H3XsYY+YphYpxc9Cbgg+7Y=", "last_login": null, "is_superuser": true, "username": "admin", "first_name": "", "last_name": "", "email": "", "is_staff": true, "is_active": true, "date_joined": "2022-03-15T08:32:13.528Z", "groups": … -
Django Mnagement Command conditional command
I am trying to give the command like this, I could not successfully implemmented this bold text condition. (if blacklist == true and active is = false ) (else: no action) 'from django.core.management import BaseCommand from wm_data_collection.models import roses class Command(BaseCommand): help = "Blacklist_TRUE then Active_FALSE." def handle(self, *args, **options): roses.objects.filter(active=False).update(blacklist=True)' -
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my Django request is failing
I am using a service now API for fetching the incident details, but the service now is SSO enabled and my request is failing. Please let me know how to authenticate the APIs -
Django modelform clean_password2
Stumbled this def clean_password2 ModelForm. My question is does every time this we run this view. Does it will automatically run clean_password2 to check the password or do we need to explicitly call it? Form.py class RegisterForm(forms.ModelForm): """A form for creating new users. Includes all the required fields, plus a repeated password.""" password1 = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput) class Meta: model = User fields = ('full_name', 'email',) #'full_name',) def clean_password2(self): # Check that the two password entries match password1 = self.cleaned_data.get("password1") password2 = self.cleaned_data.get("password2") if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords don't match") return password2 def save(self, commit=True): # Save the provided password in hashed format user = super(RegisterForm, self).save(commit=False) user.set_password(self.cleaned_data["password1"]) user.is_active = False # send confirmation email via signals # obj = EmailActivation.objects.create(user=user) # obj.send_activation_email() if commit: user.save() return user https://docs.djangoproject.com/en/4.0/topics/auth/customizing/#a-full-example -
How do i efficiently use redux in react making request to backend server?
I am new to using react and also new to redux, I am working on a project which uses Django for Back-end and React for Front-end. I want to use redux for data state management but i can not seem to be doing it right. Here is my action transaction.js function: import axios from "axios"; export const CREATE_TRANSACTION = "CREATE_TRANSACTION"; export const VIEW_TRANSACTION = "VIEW_TRANSACTION"; export const UPDATE_TRANSACTION = "UPDATE_TRANSACTION"; export const LIST_TRANSACTIONS = "LIST_TRANSACTIONS"; export const DELETE_TRANSACTION = "DELETE+TRANSACTION"; export const GET_TRANSACTIONLIST_DATA = "GET_TRANSACTIONLIST_DATA"; const ROOT_URL = "http://127.0.0.1:8000/api/"; export const getTransactionList = () => (dispatch) => { axios .get(`${ROOT_URL}transactions/`, { headers: { "Content-Type": "application/json", }, }) .then((response) => { dispatch({ type: LIST_TRANSACTIONS, payload: response.data }); console.log(response.data); }); }; Here is my reducer transactions.js function: import { LIST_TRANSACTIONS } from "../actions/transaction"; export function TransactionReducer(state = {}, action) { switch (action.type) { case LIST_TRANSACTIONS: return action.payload; default: return state; } } My store.js: import { createStore, applyMiddleware, compose } from "redux"; import thunk from "redux-thunk"; import rootReducer from "./reducers"; const initialState = {}; const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({ latency: 0 }) : compose; const store = createStore( rootReducer, initialState, composeEnhancers(applyMiddleware(thunk)) ); export default store; Trying to display data using useSelector() … -
Python/Django - Input radiobutton to autosend email
I'm trying to set up a radiobutton input that let's you choose to send email automatically. What I want is a form that gives input: manual or auto. This will the one row I have in the sqlite3 database for this: class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") So eventually what I want is that in AutoSendMail the type is set to manual or auto, depending on the radiobutton input. I got as far as this: mailindex.html <form action="." method="post" class="card"> {% csrf_token %} <div class="card-body"> <div class="form-group text-right"> <label class="form-label">Send E-mail Automatically</label> <!--<input type="email" class="form-control" placeholder="reply to" value="{{mail.replyTo}}" name="replyTo">--> <input type="radio" name="sendauto" value="On"> Manual <input type="radio" name="sendauto" value="Off"> Auto {{ form.type }} </div> <div class="card-footer text-right"> <input type="submit" value="Submit" name="autoapprove" class="btn btn-primary" /> </div> </div> </form> urls.py path('mailbox/auto_send/', login_required(views.AutoSendView.as_view()), name='auto_send'), forms.py class SendMailSetting(ModelForm): class Meta: model = AutoSendMail fields = ['auto', 'manual', 'type'] widgets = { "manual": DjangoToggleSwitchWidget(klass="django-toggle-switch-dark-primary"), "auto": DjangoToggleSwitchWidget(round=True, klass="django-toggle-switch-success"), 'type': forms.RadioSelect() } models.py class AutoSendMail(models.Model): auto = models.BooleanField(default=False) manual = models.BooleanField(default=True) send_type = ( ('manual', 'MANUAL'), ('auto', 'AUTO') ) type = models.CharField(max_length=6, choices=send_type, default="manual") views.py class AutoSendView(generic.TemplateView): form_class = SendMailSetting model = AutoSendMail … -
Django: base.html "TemplateDoesNotExist at / error" and project structure
When in my home.html (or any other .html) I try to extend my base.html file with this {% extends "static/src/base.html" %} I get this error: TemplateDoesNotExist at / error Also, I'm about to start my first "serious" project and so I'm trying to do things a little less amateurish starting with my project structure. This is what I've come so far following the clues I got from other site, but I'd like to have some opinion from people with more experience than me if this is a good way to start the project. In particular, I'm a little confused about where to put the base.html file. Is it ok to put it in the src folder or should I put it with the navbar.html/footer.html/etc page or navbar.html/footer.html/etc should go in the src folder instead? This is my project structure: website_name - core (where is the settings.py and where I put homepage, news page, contact and about us page...) - app name_1 (like members) - app name_2 - media -- img -- upload (user ulploaded excel file) --- excel_file.csv -- download (for user to download file) - static -- src --- base.html --- style.css -- dist --- style.css -- node_modules -- … -
Is Django or Flask better for implementing "tracker nodes" and "seeder nodes" for p2p content sharing application?
The image below shows an architecture for video sharing based on the p2p BitTorrent protocol. The video player access the "content tracker" for "video" info The content tracker responds with "content node" info. The video is served from the nearest one or two nodes How should I approach building this network? Should I create a BitTorrent client at content nodes and give them a private "content tracker" address? If I have to expand the three-node structure to 10, what should be the approach while building this kind of software. Which tech stack would be best? If you can share some resources, that would be helpful. I am a newbie; kindly be kind. :) -
Django "ImageField" form value is None
I'm trying to implement profile picture field for users. The following is the code for each file for the implementation I tried, forms.py, models.py, views.py, and urls.py. I use a IDE (vscode) to debug django, and I placed a breakpoint on the user.avatar = form.cleaned_data['avatar'] line in views.py below, to quickly check if cleaned_data['avatar'] is filled as user input, as I expect. However, even after I upload a file on the url, submit, the line shows None while expected a image object, and of course it doesn't save anything so no change to the database either. # # forms.py # accounts/forms.py # from accounts.models import UserProfile # .. class UserProfileForm(forms.ModelForm): avatar = forms.ImageField(label=_('Avatar')) class Meta: model = UserProfile fields = [ 'avatar', ] def __init__(self, *args, **kwargs): super(UserProfileForm, self).__init__(*args, **kwargs) self.fields['avatar'].required = False # # models.py # accounts/models.py # from django.contrib.auth.models import User from PIL import Image class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(upload_to="images", blank=True, null=True) # note: I also did "python manage.py makemigrations accounts; python manage.py migrate accounts;" # # views.py # accounts/views.py # class UserProfileView(FormView): template_name = 'accounts/profile/change_picture.html' form_class = UserProfileForm def form_valid(self, form): user = self.request.user user.avatar = form.cleaned_data['avatar'] user.save() messages.success(self.request, _('Profile picture has been …