Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Am trying to display only the appointments that the current logged in user has made, but i end up fetching all the appointments from the database
this the views.py file how can i display the appointments made the current logged in user def user(request): client = Client.objects.all() appointments = Appointment.objects.all() context = {'appointments': appointments, 'client': client, } return render(request, 'users/user.html', context) -
What is the best way to host a React Native mobile app with a Django backend on AWS?
I want to build a mobile app using React Native (frontend) and Django (backend). I've never done this but ideally my application would have a simple frontend UI that displays data retrieved from Django (backend) which retrieves it from the MySQL database. I am trying to grasp how I could host this using AWS but am having trouble as I cannot find the same question online. I have lots of programming experience but am a beginner when it comes to actually deploying code. I could be thinking about this completely wrong, I am pretty lost, so any help would be very useful. Thank you in advance! -
AWS SES sending email from Django App fails
I am trying to send mail with using SES and already setup the mail configuration. Now SES running on production mode -not sandbox-. But in Django App, when I try to send mail nothing happens. it's only keep trying to send, no error. in setting.py made the configuration. INSTALLED_APPS = [ 'django_ses', ] EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = config('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = config('AWS_SECRET_ACCESS_KEY') AWS_SES_REGION_NAME = 'ap-northeast-1' AWS_SES_REGION_ENDPOINT = 'email-smtp.ap-northeast-1.amazonaws.com' and email method. def send_mail(request, user, emails, subject, path): current_site = get_current_site(request) message = render_to_string(f"store/emails/{path}.html", { "some": "context" }) send_email = EmailMessage(subject, message, "info@mydomain.com", to=emails) send_email.send() By the way I already verified the info@mydomain.com in SES console. And when I try to send email from the SES console using send test email option, I can send without a problem. But in Django App. I can't. Is there any other settings should I do. Because I can't see any error popping when I try to send mail. It's only keep trying to send. But it can't. -
How to send javascript list from template to request.POST (django framework)
I have the javascript below that gets all checked box and it works well. <script> function addlist() { var array = [] var checkboxes = document.querySelectorAll('input[type=checkbox]:checked') for (var i = 0; i < checkboxes.length; i++) { array.push(checkboxes[i].value); } document.write(array); } </script> I want to know how to submit the list array to views.py and get it via request.POST[''] Any suggestions? -
Datalist with free text error "Select a valid choice. That choice is not one of the available choices."
I am building a Create a Recipe form using crispy forms and I am trying to use a datalist input field for users to enter their own ingredients, like 'Big Tomato' or select from GlobalIngredients already in the database like 'tomato' or 'chicken'. However, regardless of whether I enter a new ingredient or select a pre-existing one, I am getting the following error: "Select a valid choice. That choice is not one of the available choices.". How do I fix 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 … -
django models related manager
I want to develop DJANGO Application for rooms booking. I want to use following TWO models. class Room(models.Model): room_no = models.IntegerField() remarks = models.CharField(max_length=100) def __str__(self): return self.remarks class Roombooking(models.Model): room = models.ForeignKey(Room, related_name= 'roombookingforroom', on_delete=models.CASCADE) booked_for_date = models.DateField(blank=True, null=True) booked_by = models.TextField(max_length=1000, default='') remarks = models.CharField(max_length=100,) class Meta: constraints = [ models.UniqueConstraint( fields=["suit", "booked_for_date"], name="unique_room_date", ), ] def __str__(self): return self.room.remarks To avoid assigning one room to 2 different persons on any day, “ UniqueConstraint” is used. Now, how to query the list of rooms which are vacant from DATE1 to DATE2 -
Why can't django find the environment.py file?
I've been running a django project locally by running the following command environment.py -r When I tried running the project locally again I got the following message The system cannot find the path specified. Why am I receiving this message in the command prompt when the path for this file exists in my repository? -
How to send data to a flask template as a string with \n in it
My code is supposed to send data taken from a json file and then take a specific element of the json and send it to a flask template. There, it will be put into a CodeMirror object and sent to a div. My problem is that when i do {{ context }} it actually puts the return in there. <header> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.css"></link> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/codemirror/5.52.2/codemirror.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </header> <body> <div id="ff-cool" style= "border: 1px solid #ddd" name="code"></div> <div id="mydiv" dataa="{{ context }}"> </div> <script type="text/javascript"> var t = CodeMirror(document.querySelector('#ff-cool'), { lineNumbers: true, tabSize: 2, value: $("#mydiv").data("dataa") }); //alert("{{context.code}}"); </script> </body> @app.route('/n/<note>') def no(note): global js try: f = js[note] except: return "no" context = {"code": f["code"]} #problem is in templates/display.html return render_template("display.html", context = context) {"5XqPNXl": {"title": "De", "code": "hi\nfw\nfwe", "user": "De", "pass": "de", "priv": true}} There are no error messages because this is a problem with the html itself. -
Django table.objects.filter(__icontain) return wrong data (sometimes)
I start Django fews days ago (Django 3.2.9) for a personnal project with sqlite3. I have a table with 10000+ entries about card, with specific id_card, name, description... I made pages for listing and searching cards my problem came with the searching "engine" : My search is made with a query in URL (named 'query') but I got the same problem if I use post data. My views.py looks like this : def search(request): query = request.GET.get('query') if not query: all_cards= Cards.objects.all() context = { 'card_list': all_cards, 'paginate': True, } return render(request, 'collection/search.html', context) else: # title contains the query is and query is not sensitive to case. spe_cards = Cards.objects.filter(name__icontains=query).order_by('-type_card') if not spe_cards .exists(): spe_cards = Cards.objects.filter(name_en__icontains=query) else: spe_cards = Cards.objects.filter(desc__icontains=query) title = "Résultats pour la requête %s"%query context = { 'liste_carte': spe_cards, 'title': title, 'paginate': True, } The problem is on this line spe_cards = Cards.objects.filter(name__icontains=query).order_by('-type_card') the filter "__contains" or "__icontains" work only for fews requests with partial response. I take three search with : One request correct with all the cards searched One request incorrect with 0 cards returned One request incorrect with few good cards returned but not all Each request work in django shell but … -
Not getting input from form Django
I'm using Django's forms.py method for building a form, but am not getting any data when trying to user request.POST.get('value') on it. For every print statement that gave a response, I put a comment next to the command with whatever it returned in the terminal. Additionally, I do not understand what the action = "address" is meant for in the form. Finally, the csrf verification was not working and kept returning CSRF verification failed so I disabled it, but if anyone knows how to get this working I would appreciate it. forms.py from django import forms class NameForm(forms.Form): your_name = forms.CharField(label='Enter name:', max_length=100) views.py @csrf_exempt def blank(request): if request.method == 'POST': get = request.POST.get print(f"get: {get}") # get: <bound method MultiValueDict.get of <QueryDict: {}>> print(f"your_name: {request.POST.get('your_name')}") # your_name: None form = NameForm(request.POST) if form.is_valid(): your_name = form.cleaned_data["your_name"] print(f"your_name cleaned: {your_name}") return HttpResponseRedirect('/thanks/') else: form = NameForm() return render(request, 'blank.html', {'form': form}) blank.html <!DOCTYPE html> <html lang="en"> <head> </head> <body> <form action="" method="post"> {{ form }} <input type="submit" value="Submit"> </form> </body> </html> -
Using 2 different models on a same html Forms
How will the view code part based on Class-based view will look like if i have for example this 2 models Class Student with two columns name and last_name Class City name and street The form will be in a html file, in this case it will have the 4 inputs,