Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Query data linked via Foreign key
I have 2 models linked 'Project' and 'Event'. Event has an FK to Project I want to return all events that are related only to the project. I have a basic view that returns the specific project and im trying to include the event list within that view. def show_project_details(request,project_id): today = now().date() project = Project.objects.get(pk=project_id) events = Event.objects.event_list = Event.objects.filter(event_date__gte=today).order_by('event_date') events_list = Event.objects.get(project_name_id=project_id) form = ProjectForm(request.POST or None, instance=project) return render(request, 'pages/project_details.html', {"project": project, "form": form, "events": events, 'events_list':events_list}) but it returns Event matching query does not exist. Any ideas? -
Django choice field(dropdown) restrict according to user type for multiuser type
I have multi user types in my django app where the user can change the status of something usertype a has options to perform create a task,close(choice fields) while usertype b has option to accept the task created by usertype a and mark finish. how do i restrict them in the form according to the user type when the usertype a clicks on form he should see only close under dropdown whereas the usertype b has to see only accept and finish option in dropdown. models.py class todo(models.Model): title = models.CharField(max_length=200) info = models.TextField() created_by = models.ForeignKey(User,related_name = 'created_by',blank=True,null=True,on_delete=models.CASCADE) STATUS_CHOICES = ( (0,opened), ('1','Accepted'), ('2','Completed'), ('3','finish') ) status = models.CharField('Status',choices=STATUS_CHOICES,max_length = 100,default = 'Open') forms.py class CreateForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info') class EditForm(forms.ModelForm): class Meta: model = Model fields = ('title', 'info','status') -
Django, Python: Can't filter products with passing values true the get request and order the products
I'm trying to filter some products and order the filtered products by price ascending and descending. This is my code in the view: def is_valid_queryparam(param): return param != '' and param is not None def filter(request): if request.GET: price_min = request.GET.get('priceMin') price_max = request.GET.get('priceMax') sort_by = request.GET.get("sort", "l2h") if is_valid_queryparam(price_min): if sort_by == "l2h": products = Product.objects.filter(price__gte=price_min).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__gte=price_min).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() if is_valid_queryparam(price_max): if sort_by == "l2h": products = Product.objects.filter(price__lte=price_max).order_by('price') elif sort_by == "h2l": products = Product.objects.filter(price__lte=price_max).order_by('-price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() else: products = Product.objects.all().order_by('price') paginator = Paginator(products, 9) page = request.GET.get('page') paged_products = paginator.get_page(page) product_count = products.count() context={ 'products': paged_products, 'product_count': product_count, } return render(request, 'store.html', context) If I try to filter based on the min and max price it works, but when I'm trying to sort or if there is no filter apply I get this UnboundLocalError: UnboundLocalError at /store/ local variable 'paged_products' referenced before assignment Request Method: GET Request URL: http://127.0.0.1:8000/store/?sort=h2l Django Version: 3.1 Exception Type: UnboundLocalError Exception Value: local variable 'paged_products' referenced before assignment Exception Location: C:\Users\store\views.py, line 299, in filter … -
Duplication of id values in another column in same table django
I am working on one python(django framework) project in which i have one user model which has 1000 users. I want to make one another column named priority id and need to put default id values in that priority id column accordingly (you can see it below). id username email priority_id 1 abc abc@gmail.com 1 2 xyz xyz@gmail.com 2 ofcourse i can do it manually but for 1000 users it is time consuming. how do i change models.py or admin.py or something else to achieve this? -
FileNotFoundError: [Errno 2] No such file or directory in Django
I'm working on a Django project where I need to send a file to the client via my system by email. But when I put the file name in the attach_file() field, I get the error of not finding the file. This is my code: def email_sender(request): if request.method == "GET": subject = 'welcome to GFG world' email_from = settings.EMAIL_HOST_USER recipient_list = ["example@gmail.com", ] to = 'example@gmail.com' text_content = 'This is an important message.' msg = EmailMultiAlternatives(subject, text_content, email_from, [to]) msg.attach_file('file.file') msg.send() And this is my exception: FileNotFoundError: [Errno 2] No such file or directory: 'file.file' [08/Dec/2021 11:52:52] "GET /email/send/ HTTP/1.1" 500 83111 This is my setting.py: ... STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] ... This is my project structure: src \_emailsender \_ urls.py \_ views.py \_ setting.py \_ static \_ file.file Thanks for your help. -
the name 'title' is not defined, [closed]
I'm trying to make a search bar using Django/Python, and have a small problem with the views.py its telling me that 'name 'title' is not defined' i sure I made a mistake but don't know where, be very happy if someone can help me out def search_post(request): if request.method == "POST": searched = request.POST.get('searched') const title = post = Post.objects.filter(name_contains=title) return render(request, 'Blog/search_post.html', {'searched':searched}) else: return render(request, 'Blog/search_post.html', {}) -
Django datalist not accepting any input as valid
I am trying to use a datalist input field to allow users to enter their own ingredients on Create a Recipe form. Ideally users can select a GlobalIngredient like salt, pepper, chicken, etc. already in the database or create their own. However, regardless of whether I enter a new ingredient or select a pre-existing ingredient, I am getting the following error: "Select a valid choice. That choice is not one of the available choices.". Unsure why I am getting this error? Visual: models.py class Recipe(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) websiteURL = models.CharField(max_length=200, blank=True, null=True) image = models.ImageField(upload_to='image/', blank=True, null=True) name = models.CharField(max_length=220) # grilled chicken pasta description = models.TextField(blank=True, null=True) notes = models.TextField(blank=True, null=True) serves = models.CharField(max_length=30, blank=True, null=True) prepTime = models.CharField(max_length=50, blank=True, null=True) cookTime = models.CharField(max_length=50, blank=True, null=True) class Ingredient(models.Model): name = models.CharField(max_length=220) def __str__(self): return self.name class GlobalIngredient(Ingredient): pass # pre-populated ingredients e.g. salt, sugar, flour, tomato class UserCreatedIngredient(Ingredient): # ingredients user adds, e.g. Big Tomatoes user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) class RecipeIngredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, null=True, on_delete=models.SET_NULL) description = models.TextField(blank=True, null=True) quantity = models.CharField(max_length=50, blank=True, null=True) # 400 unit = models.CharField(max_length=50, blank=True, null=True) # pounds, lbs, oz ,grams, etc forms.py class RecipeIngredientForm(forms.ModelForm): def __init__(self, … -
I came into the world of programmng and im confused as hell, Im lost, I need help or some advice
Good day, pls im a 16 years old guy, i got intreted in programming and how thing work, i started by learning HTML, CSS, JAVASCRIPT in a place they took those courses, then i decided not to pay for more courses because i felt i wanst taught as i should, since then ive been able to learn orther languages (python, solidity) and get familiar with framework like (Django), but still i cant put anything together. i felt React will be cool to learn and use so i downloaded react native courses from "edx.org" still i wasnt really understanding and i had some issues understandig the "Javascript intro" for the course especially "Javascript classes and construstors". Ive been working with a team(my freinds), to build something and i am to handle the website but im confused as hell, im using django to build it, but i still get confused on stuffs like "Positioning boxes(css) and some little things". I really wanna be a developer, although my mum said "Maybe if you stop looking at the people on the screen everytime and face your life or the physical world, life will be much better" I dont wanna mind that and im not … -
Why can't I pass a list comprehension to Django RelatedManager add()?
Given: class Game(models.Model): rengo_black_team = models.ManyToManyField(Player) class OpenChallenge(CommonChallenge): rengo_black_team = models.ManyToManyField(Player) game = models.ForeignKey(Game, on_delete=models.CASCADE) This OpenChallenge method code works: for p in self.rengo_black_team.all(): self.game.rengo_black_team.add(p) But this code does not: self.game.rengo_black_team.add([x for x in self.rengo_black_team.all()]) Based on the last example in the docs , >>> john = Author.objects.create(name="John") >>> paul = Author.objects.create(name="Paul") >>> george = Author.objects.create(name="George") >>> ringo = Author.objects.create(name="Ringo") >>> entry.authors.add(john, paul, george, ringo) it seems like my example should work, but I get "Field 'id' expected a number but got [<Player: anoek>]" -
Adding new site language in Django admin
Is it possible to control site languages from django admin? if we need new language we should add in settings.py like that: settings.py LANGUAGES = ( ("ru", _("Russian")), ("en", _("English")) ) But is there any way to allow admin to add new supported language using django admin panel? -
Django not serving static file because of i18n prefix in url
I wanted to have i18n internationalization on my project and whenever I need to serve some static file/image, I kept on getting this error. Does anyone know how to fix the url prefix so it know where to redirect? [08/Dec/2021 14:11:09] "GET /admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg HTTP/1.1" 302 0 Not Found: /en/admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg [08/Dec/2021 14:11:09] "GET /en/admin-interface/logo/photo_2021-12-07_21-08-39_Gp96iY6.jpg HTTP/1.1" 404 6917 This is what my urls.py looked like from django.urls import path, include from django.conf.urls.i18n import i18n_patterns from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('', admin.site.urls), ) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) -
PDF package without dependencies
I'm trying to deploy a site PaaS service. In one of my APIs I convert html to pdf. But the package has some dependencies which are not installed on the server. That's why I cannot deploy my site. If I want to deploy it using docker I also need to configure nginx myself and i don't want to fall into nginx difficulties. Does anybody know a html-to-pdf package in python that doesn't require any dependencies? -
Django SimpleJWT: Some questions with token authentication
I am implementing authentication in Django using SimpleJWT, and have a few questions regarding the same. To give some background I have multiple domains with my backend, some with normal login (username and password), and some with SSO logins. Question 1: For normal login, I pass username and password in the payload to TokenObtainPairView API, and it gives me access and refresh tokens. How can I get the access and refresh tokens in SSO login, since it does not have any password? Question 2: Suppose, I store the access tokens in local storage and send the access token to all APIs, and I'm also refreshing it before it expires. But what will happen if the user closes the browser, and we are not able to refresh the access token. The access token expires and the user gets logged out. How can we keep the user logged in for a certain amount of time (say 30 days)? Question 3: The username and password passed in the payload are visible in the curl, is this a security issue? How can I deal with this? -
How to write if and else conditions in Django
I wanted to save email in email Model if email is coming from frontend,, else save phone number in phone model if phone is coming else send error def post(self,request): if request.data['email']: serializeObj = EmailSerializer(data = request.data) if serializeObj.is_valid(): serializeObj.save() return Response('Email success') else: serializeObj = PhoneSerializer(data = request.data) if serializeObj.is_valid(): serializeObj.save() return Response('Phone success') return Response(send error) -
How to remove %20%20%20 in url? (Django)
The following url: <a href="{% url 'view' i.value %}" >VIEW DETAILS</a> directs to: http://localhost:8000/view/value%20%20%20 Instead it should direct to http://localhost:8000/view/value How to solve this? -
can someone please send me a link to a video that explains how you can use 2 or more languages together? [closed]
ummm... i just wanna know how to use different languages i learnt like python, html and css or javascript together like they do in those coding livestreams. like i heard there is django for python but i dont understand how theyre connected and how i can implement them for making a server for a website project im doing. Thanks alot for your time God bless you -
how to create an instance of one to one , before the main object will be create - django
i've these two models : class Payment(models.Model): admin = models.ForeignKey(User,on_delete=models.PROTECT) client_seller = models.ForeignKey(ClientCompany,on_delete=models.PROTECT,blank=True) next_payment = models.OneToOneField(NextPayment,blank=True,null=True,related_name='next_payments',on_delete=models.PROTECT) #others class NextPayment(models.Model): next_payment = models.DateTimeField() status = models.BooleanField(default=True) i want to create NextPayment instance before Payment instance will be create , and assign the NextPayment object to Payment > next_payment field ! here is my views.py @login_required def create_payment(request): main_form = PaymentForm() next_paymentform = NextPaymentForm() next_payment= request.GET.get('next_payment') print(next_payment) if request.method == 'POST' and request.is_ajax(): main_form = PaymentForm(request.POST) next_paymentform = NextPaymentForm(request.POST) if main_form.is_valid(): main_obj = main_form.save(commit=False) main_obj.admin = request.user if next_payment: date_next = next_paymentform(next_payment=next_payment) #date_next = NextPayment(next_payment=next_payment,status=True) also tried this date_next.save() main_obj.next_payment= date_next main_obj.save() else: main_obj.save() data = { 'id':main_obj.id } return JsonResponse({'success':True,'data':data}) else: return JsonResponse({'success':False,'error_msg':main_form.errors,'next_paymentform':next_paymentform.errors}) return render(request,'payments/pay.html',{'main_form':main_form,'next_paymentform':next_paymentform}) my forms.py class NextPaymentForm(forms.ModelForm): next_payment = forms.DateTimeField(input_formats=['%Y-%m-%dT%H:%M'],widget=forms.DateTimeInput(attrs={'type':'datetime-local','class':'form-control'}),required=False) class Meta: model = NextPayment fields = ['next_payment'] class PaymentForm(forms.ModelForm): class Meta: model = Payment fields = ['client_seller','type_of_payment','price','note','discount','discount_note'] next_payment prints None ! but it wasnt None but doesnt work , and only saves the main form ! i need to check if the next_payment exists then create an instance of NextPayment and assign that new instance to Payment model ? any idea much appreciated .. thank you in advance .. -
React Django WebSocket connection challenge
The challenge I am facing is in trying to connect my Django backend with React frontend app. The error that I am getting is: WebSocket connection to 'ws://localhost:8000/ws/week/' failed: _callee$ @ Week.jsx:77 Here is the Week.jsx code: export default function Week(props) { const [scoops, setScoops] = useState([]); const ws = useRef(null); useEffect(async () => { ws.current = new WebSocket("ws://" + window.location.host + "/ws/week/"); ws.current.onopen = () => console.log("ws opened"); const res = await fetch("/api/scoops/week/"); const data = await res.json(); setScoops(data); }, []); const rows = []; for (let i = 0; i < scoops.length; i++) { rows.push(createData(i, scoops[i]?.rank, scoops[i]?.title, scoops[i]?.url)); } return <Base rows={rows} duration="Week" />; } Here is the server terminal log: System check identified no issues (0 silenced). December 08, 2021 - 10:59:59 Django version 3.2.8, using settings 'app.settings' Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. HTTP GET /week/ 200 [0.02, 127.0.0.1:62685] HTTP GET /api/scoops/week/ 200 [0.14, 127.0.0.1:62685] WebSocket HANDSHAKING /ws/week/ [127.0.0.1:62695] WebSocket DISCONNECT /ws/week/ [127.0.0.1:62695] Any help would be truly appreciated. Thank you! -
Build custom filtering feature to support complex queries for Django
The API filtering has to allow using parenthesis for defining operations precedence and use any combination of the available fields. The supported operations include or, and, eq (equals), ne (not equals), gt (greater than),lt (lower than). Example -> "(date eq 2016-05-01) AND ((distance gt 20) OR (distance lt 10))" Example 2 -> "distance lt 10" Interface should look like this: def parse_search_phrase(allowed_fields, phrase): ... return Q(...) so I can use it like: search_filter = parse_search_phrase(allowed_fields, search_phrase) queryset = MyModel.objects.filter(search_filter) -
How to connect payment to order in django
i'm trying to do something. i'm trying to do something in my code that once the payment is confirmed, the order would be stored in the database. i was following this tutorial but i got lost because we are using different payment gateway he is using stripe, i'm using flutterwave my codes javascript document.addEventListener("DOMContentLoaded", (event) => { // Add an event listener for when the user clicks the submit button to pay document.getElementById("submit").addEventListener("click", (e) => { e.preventDefault(); const PBFKey = "xxxxxxxxxxxxxxxxxxxx"; // paste in the public key from your dashboard here const txRef = ''+Math.floor((Math.random() * 1000000000) + 1); //Generate a random id for the transaction reference const email = document.getElementById('email').value; var fullname= document.getElementById('fullName').value; var address1= document.getElementById('custAdd').value; var address2= document.getElementById('custAdd2').value; var country= document.getElementById('country').value; var state= document.getElementById('state').value; var address1= document.getElementById('postCode').value; const amount= document.getElementById('total').value; var CSRF_TOKEN = '{{ csrf_token }}'; const payload = { 'firstName': $('#fullName').val(), 'address': $('#custAdd').val() + ', ' + $('#custAdd2').val() + ', ' + $('#state').val() + ', ' + $('#country').val(), 'postcode': $('#postCode').val(), 'email': $('#email').val(), } getpaidSetup({ PBFPubKey: PBFKey, customer_email: email, amount:"{{cart.get_total_price}}", currency: "USD", // Select the currency. leaving it empty defaults to NGN txref: txRef, // Pass your UNIQUE TRANSACTION REFERENCE HERE. onclose: function() {}, callback: function(response) { flw_ref … -
How to fix 504 Gateway Time-out while connecting to google calendar api
I have created project which fetch one month events of all the calendars in my calendar list. To do this, I followed google calendar api documentation Quickstart. This is function which connect to google api. def connect_google_api(): creds = None if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json') if not creds or not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) else: flow = InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES) creds = flow.run_local_server(port=0) with open('token.json','w') as token: token.write(creds.to_json()) service = build('calendar','v3',credentials=creds) I hosted the website using Apache and all the pages are working except google calendar. I first thought that there might be some problem while reading credentials.json so I use this to find out data = None with open('credentials.json') as f: data = json.load(f) qw = data Website is still in debug mode so I made some error to check local variable and I found out that data and qw variable contains credentails.json. I think the problem is happening because of the below two lines flow = InstalledAppFlow.from_client_secrets_file('credentials.json',SCOPES) creds = flow.run_local_server(port=0) I opened credentails.json and i found this redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"] I changed http://localhost to http://test.example.com/. I dont know what to put at the place of http://localhost. I want to find out what changes are required in this code … -
How to get the authentication process for the hikevision cctv dvr setup for my python application
i am into integrating the hike vision CCTV into my python application can anybody help me with the starting authentication and how i can get the IP of the device without taking it from the connected devices. -
how to obtain the registration_id for FCM-Django push notifications (flutter app)
I am using django as my back end for my flutter app. And just wanted to learn how to implement push notifications. is there a way to get the registration_id of a device to send push notifications without adding the firebase_messaging/firebase_core packages to my flutter package? I feel like its excessive to get those packages to just register the device token. Or is this the only way^ I am using the FCM-django package to send notifications but need to save the registration_id of the device for each user in my database. -
Django collectStatic command failed on Deploy to ElasticBeastalk with S3
I am attempting to change my Django application to use S3 for static and media storage. It is working without issue on a local machine and I'm able to run "collectstatic" locally. When I deploy to the Elastic Beanstalk instance I get this error: ERROR Instance deployment failed. For details, see 'eb-engine.log'. INFO Command execution completed on all instances. Summary: [Successful: 0, Failed: 1]. ERROR Failed to deploy application. In eb-engine.log: [ERROR] An error occurred during execution of command [app-deploy] - [PostBuildEbExtension]. Stop running the command. Error: container commands build failed. Please refer to /var/log/cfn-init.log for more details. In cfn-init.log [INFO] -----------------------Starting build----------------------- [INFO] Running configSets: Infra-EmbeddedPostBuild [INFO] Running configSet Infra-EmbeddedPostBuild [INFO] Running config postbuild_0_LocalEyes_WebApp [ERROR] Command 00_collectstatic (source /var/app/venv/*/bin/activate && python3 manage.py collectstatic --noinput) failed [ERROR] Error encountered during build of postbuild_0_LocalEyes_WebApp: Command 00_collectstatic failed Traceback (most recent call last): File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 573, in run_config CloudFormationCarpenter(config, self._auth_config).build(worklog) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 273, in build self._config.commands) File "/usr/lib/python3.7/site-packages/cfnbootstrap/command_tool.py", line 127, in apply raise ToolError(u"Command %s failed" % name) cfnbootstrap.construction_errors.ToolError: Command 00_collectstatic failed [ERROR] -----------------------BUILD FAILED!------------------------ [ERROR] Unhandled exception during build: Command 00_collectstatic failed Traceback (most recent call last): File "/opt/aws/bin/cfn-init", line 176, in <module> worklog.build(metadata, configSets) File "/usr/lib/python3.7/site-packages/cfnbootstrap/construction.py", line 135, … -
How to use one application in two different projects in Django
'''I made testapp application in baseproject here I create urls.py in testapp and include in base project , Now I just copy paste the testapp in derivedproject with all urls.py file and views.py , when I add the testapp urls in derived project urls.py using include function it is showing error... I want to inform you that I made two projects in same directory and manage.py is inside the projects Now I am pasting the whole error.....''' PS C:\Users\hp\Desktop\For Django\day2\derivedproject> python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self._args, **self._kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\hp\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen …