Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django templates - string concatenation to variable name
I'd like to use a variable in a django template and this variable should be concatenated from 2 strings. Here's an example: I'd like to do: {% for item in ObjSearch %} ... but the ObjSearch variable should be concatenated from the Obj string and from the field variable. To get the string it works like this: {{ "Obj"|add:field }} but unfortunately it's not working like this: {% for item in "Obj"|add:field %} . How can I achieve this? -
Set a variable through a drop down list in django
def scan(request): scan = Stock.objects.all() hammer = Stock.objects.filter(Hammer=100) belthold = Stock.objects.filter(Belthold=100) context = {'All':scan, 'Belthold':belthold, 'Hammer':hammer } return render(request, 'scanner/scan.html', context) This is my views.py file. I want to add a dropdown list to my html page containing the context dictionary. And changes the query filters according. This is my current html page: {% for i in Hammer %} <tr> <td>{{i.script}}</td> <td>{{i.open}}</td> <td>{{i.high}}</td> <td>{{i.low}}</td> <td>{{i.close}}</td> <td>{{i.Volume}}</td> <td>{{i.Change}}</td> </tr> {% endfor %} The 'Hammer' need to be replaced by the whatever selection is made from the dropdown list. THANKS!! -
Django crontab doesnot execute at specific time
I am schedulling cron job at specific time but code below doesn't work ('22 20 * * *', 'sentimentor.cron.sentiment') THe above code should execute at 8:22 pm UTC daily But if I change the code to the following it works ('*/1 * * * *', 'sentimentor.cron.sentiment') The above code will execute every 1 minute which is not required I tried many different things please help me if any solution avilable for this. -
why we use local file settings when initalizing celery app
Most of the places i see from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings.local') --> ?? app = Celery('mysite') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() what is the use of exporting local settings in project, i have seen this in many projects in production we are using local settings, although local mostly inherit base settings where all celery config is defined, by why not mysite.settings.production ? -
Django : Can I use CreateView to create a User object where User is just Django's built in User model?
I am trying to create a simple user login system where a user gets to sign up on one page and then use those credentials to login to the website on another page. Here's my sign-up and login views: class SignupView(CreateView): model = User form_class = SignupForm template_name = 'journal_app/signup.html' success_url = reverse_lazy('home') class LoginUserView(LoginView): template_name = 'journal_app/login.html' As you can see I'm using the CreateView to create User objects. After the user signs up I can see that the record is successfully updated in the Users group in my Admin console. The problem is that when I try to login, it always throws me a username/password don't match error. Any ideas what could be the reason? I am a beginner at Django so it could be something pretty simple. -
How to add a pre-loader to a django web site?
i had made a web app in django that takes some input through form, performs some long computation in django views, store the results in context and renders the results in other template.In between taking submitting input and displaying result i want to display a loading page ,but i didn't found any resource that could explain me in some simple step by step manner. Any resource or reference will be helpful. Thanks -
Django REST Framework update date Created
i have a blog app which is connected to a Django REST Framework API. I am able to create, delete and update posts using API calls but im struggeling with updating the time created field. What i want to do is to update the time with the current time when the post is edited. So if the post was created 21 juli 2020 10PM, and then it was edited 21 juli 2020 10:05PM i want the time to change according to the time it was edited. Any ideas on how i can do that. Im using this a fetch call to make the updates. var url = "http://127.0.0.1:8000/api/blogs/"; var type = "POST"; if (active != null) { url = `http://127.0.0.1:8000/api/blogs/${active.id}/`; type = "PUT"; } fetch(url, { method: type, headers: { "Content-type": "application/json", "X-CSRFToken": csrftoken, }, body: JSON.stringify({ 'title': form.title.value, 'body': form.body.value, 'user': user, }) }).then(function (response) { handlePosts() location.reload() form.reset() }) }) Ive tried sending new Date() inn the body but it doesnt seem to work. Any help is appretiated :D -
how to send post description as mail in django?
I am trying to send mail about new post update to the user through email using django signals but post description is not showing properly in the gmail I am using RichtextEditor to create postContent i am getting mail like this "test" when i directly send mail like def sendUpdateMail(sender,created,instance,**kwargs): if created: if instance.status == 'Published': subject=instance.postTitle from_email=settings.EMAIL_HOST_USER email=list(NewsletterUser.objects.values('email')) recepients=[] for i in range(0,len(email)): recepients.append(email[i]['email']) msg=EmailMultiAlternatives(subject=subject,body=instance.postContent, from_email=from_email,to=recepients) msg.send() and then i tried EmailMultiAlternatives but its not showing {{instance.postContent|safe}} in mail signal code with EmailMultiAlternatives: def sendUpdateMail(sender,created,instance,**kwargs): if created: if instance.status == 'Published': subject=instance.postTitle from_email=settings.EMAIL_HOST_USER email=list(NewsletterUser.objects.values('email')) recepients=[] for i in range(0,len(email)): recepients.append(email[i]['email']) msg=EmailMultiAlternatives(subject=subject,body=instance.postContent, from_email=from_email,to=recepients) html_template=get_template("blog/postUpdateMail.html").render() msg.attach_alternative(html_template,"text/html") msg.send() postUpdateMail.html <html lang="en" dir="ltr"> <head> </head> <body> <h1>New post Click here</h1> {{instance.postImage}} </body> </html> with this I am getting only the text inside tag -
How to get my Django REST api to interact with Angular front-end be hosted over an nginx server
I am trying to launch my web app with Django, Angular, and Nginx. During the development phase I made services within Angular that send requests to 127.0.0.1:8000 I was able to get my Angular project to display over my domain name. However, when I try to log into my app over another network it won't work. Is this because I am pointing at 127.0.0.1:8000? Do I need to configure a web server gateway or api gateway for Django? Do I need to point the services in Angular to a different address? Or did I configure something wrong within Nginx? if anyone can help me I would greatly appreciate it. upstream django_server{ server 127.0.0.1:8000; } server{ listen 80; listen 443 ssl; server_name example.com www.example.com; ssl_certificate C:/Certbot/live/example.com/fullchain.pem; ssl_certificate_key C:/Certbot/live/example.com/privkey.pem; root /nginx_test/www1/example.com; index index.html; location = /favicon.ico { return 204; access_log off; log_not_found off; } location /app-token/ { proxy_pass http://django_server/api-token/; proxy_http_version 1.1; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } -
Django when is concrete inheritance appropriate
Let me start by stating that I have looked at django-polymorphic for this and still have questions. I have item models and many subtypes for items. Currently, my models look like this. class Item(models.Model): pass class Television(Item): upc = models.CharField(max_length=12, null=True) title = models.CharField(max_length=255, null=True) brand = models.ForeignKey(Brand) screen_size = models.IntegerField() class Fridge(Item): upc = models.CharField(max_length=12, null=True) title = models.CharField(max_length=255, null=True) brand = models.ForeignKey(Brand) stuff_about_fridge = models.CharField(max_length=255, null=True) I did this at first because then I wouldn't worry about all of the left joins when querying different item types that would be caused if my models looked like this: class Item(models.Model): upc = models.CharField(max_length=12, null=True) title = models.CharField(max_length=255, null=True) brand = models.ForeignKey(Brand) class Television(Item): screen_size = models.IntegerField() class Fridge(Item): stuff_about_fridge = models.CharField(max_length=255, null=True) I am now reaching a point where I realize that I very often query all of the Item models together and have to left join information from the subtypes instead, so I am not really saving myself there. My question is, even if I used something like django-polymorphic, would it make sense to A) put everything that is shared in the parent model and just specific things in the child models or to B) have it like … -
Django json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
I'm tyring to use the django login functionality, but ever since i added the login and sign_up route, I started getting this error. Anytime i try to access the sign_up or login route, I kept getting this error...json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) Traceback (most recent call last): File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JOSHUA\Downloads\Python stuff\Harvard lessons\Lesson 7\project3\Pizza-project3\orders\views.py", line 51, in get_item item_details_str = json.loads(item_details) File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\JOSHUA\AppData\Local\Programs\Python\Python38-32\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) I don't understand why the get_item function is interfering with the other functions. def sign_up(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = User.objects.create_user(username = username, password = password) user.save() return HttpResponseRedirect(reverse(index)) else: return render(request, "orders/register.html") def login_view(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username = username, password = password) if user is not … -
How to store data of multiple respondents in a session? (who answer a survey simultaneously)
I want to store data of multiple respondents of a Django survey in a session, so that I can later save the data. If one respondent answers the survey, I can easily store the data with request.session['age'] = form.cleaned_data['age'] saving_all = survey.objects.create( age=request.session['age'],) saving_all.save() However, I am collecting the input data (age, gender, etc.) on multiple urls and at the end, I create survey objects and save the data. But if another respondent answers the survey simultaneously, then the data which is stored in request.session is overwritten. How can I create individual sessions, so that multiple respondents can participate in the survey simultaneously? One of my functions looks like that: def home(request): # Trying to create multiple/unique sessions here global user_id user_id = random.randint(0,10000) # this was added because someone suggested it as a solution. However, I dont understand it 100%, especially what initial does request.session['user_id'] = user_id initial={user_id:request.session.get(user_id, None)} # SURVEY form = SurveyForm(request.POST or None, initial=initial) if request.method == 'POST': # Save input data in session if form.is_valid(): request.session['age'] = form.cleaned_data['age'] request.session['gender'] = form.cleaned_data['gender'] request.session['education'] = form.cleaned_data['education'] request.session['alternative1'] = 0 request.session['alternative2'] = 0 request.session['alternative3'] = 0 request.session['alternative4'] = 0 request.session['alternative5'] = 0 request.session['alternative6'] = 0 request.session['alternative7'] = 0 … -
Gunicorn Has no installation Configuration?
I am setting up a django web app on a DigitalOcean, ubuntu server. I am getting this error when I do sudo systemctl enable gunicorn.socket The unit files have no installation config (WantedBy, RequiredBy, Also, Alias settings in the [Install] section, and DefaultInstance for template units). This means they are not meant to be enabled using systemctl. Possible reasons for having this kind of units are: 1) A unit may be statically enabled by being symlinked from another unit's .wants/ or .requires/ directory. 2) A unit's purpose may be to act as a helper for some other unit which has a requirement dependency on it. 3) A unit may be started when needed via activation (socket, path, timer, D-Bus, udev, scripted systemctl call, ...). 4) In case of template units, the unit is meant to be enabled with some instance name specified. my gunicorn.socket: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] Wantedby=sockets.target and my gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=zak Group=zak EnvironmentFile=/home/zak/dlt_crm/environ WorkingDirectory=/home/zak/dlt_crm/ ExecStart=/home/zak/django/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ dlt_crm.wsgi:application [Install] WantedBy=multi-user.target I am following this Guide: https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 and that video: https://www.youtube.com/watch?v=US9BkvzuIxw I don't see the problem. Thank you so much. I would be … -
Django __in return both the object and which items object was in with distinct
I've got a Django 3.0 query that looks like this: from django.db import models from django.db.models import Count class Foo(models.Model): id = models.AutoField(primary_key=True) bar = models.ForeignKey(Bar) blah = models.ForeignKey(Blah) class Blah(models.Model): id = models.AutoField(pk=True) name = models.CharField(...) blah = models.CharField(...) bar_ids: List[Int] = [0,1,2,3] queryset = Foo.objects.annotate(blah_count=Count("blah_id")).filter(bar_id__in=bar_ids).order_by("-blah_count").values_list("blah__name", "blah__blah").distinct() The purpose of the distinct method is so that there are distinct blah objects so that a single blah object only appears once. How would I annotate the queryset so that I also get the bar_id that the object was in. For example, if I only had an object Foo(bar_id=2, blah_id=1) and another object Foo(bar_id=3, blah_id=1), I'd only expect to see one result. The question is: how would I get the bar_ids that the objects had? I tried adding in "bar_id" into values_list, but then I've lost the distinct() part of this (in which I just want distinct blah objects so that a single blah object only appears once). Thank you for helping! -
custom paths to static files with create-react-app?
I've been working on a Django-React app for some time and finally got it pushed to Heroku today. I used a technique I saw in a DjangoCon-talk to serve my SPA from the Django Template view. I build the react-app manually and then target the index.html. I'm also using AWS S3 to store my static-files, and here is where my I'm stuck. When I push to Heroku, the collectstatic will add my static files to AWS. However, the only way for me to access those static files is if I push the app, copy the static urls from AWS, paste them in the stylesheet/script-tags in my index.html and then push again. Is there a way to dynamically create these when running npm run build? Something like https://my-bucket.s3.amazonaws.com/static/js/{my_js_file}.chunk.js? If this is impossible, is there any other solutions for this? Tips will be greatly appreciated. -
Dango Matching query does not exist for male
Basically I can update for the contact part where male,female and contact are in same form in 3 different columns.I have three models for them.And the problem arises when I try to update the male or female column inputs where I can update the contact.Help please. When I try , I get DoesNotExist at /update/40/ Male matching query does not exist. [![enter image description here][1]][1] views.py def update(request,pk_test): male = Male.objects.get(id=pk_test) m_form = maleForm(instance=male) if request.method == 'POST': m_form = maleForm(request.POST,instance=male) if m_form.is_valid() and c_form.is_valid(): m_form.save() return redirect('info') context = { 'm_form' : m_form } template_name = 'add.html' return render(request , template_name , context) forms.py class maleForm(forms.ModelForm): class Meta: model = Male fields = ('chest' , 'neck' , 'full_shoulder_width' ,'right_sleeve' , 'left_sleeve' ,'bicep' ) urls.py path('update/<int:pk_test>/', views.update, name='update'),``` models.py class Male(models.Model): contact1 = models.ForeignKey(Contact, on_delete=models.CASCADE,null=True) chest = models.CharField(max_length=30 , blank=True) neck = models.CharField(max_length=30 , blank=True) full_shoulder_width = models.CharField(max_length=30 , blank=True) right_sleeve = models.CharField(max_length=30 , blank=True) left_sleeve = models.CharField(max_length=30 , blank=True) bicep = models.CharField(max_length=30 , blank=True) def __str__(self): return str(self.contact1) [1]: https://i.stack.imgur.com/U49o9.png -
Dropdown list to filter using query in django
I have fed my django database some information on stock prices, and the result of machine learnt code that displays 100 if a pattern is formed and 0 if it isn't. I have rendered out just the essential stock prices to my html page, and now want to add a dropdown menu with pattern names which filters and present the stocks that hv met the condition i.e. =100. Since the pattern data is not available on the html, I tried working with query function in the views.py to render back the results In my views.py file I tried to work with the context variable but that didn't seem to workout (the page loaded without data). Or maybe I couldn't render it to the html properly. def scan(request): scan = Stock.objects.all() marubozu = Stock.objects.filter(Marubozu=100) context = {'All':scan, 'Marubozu':marubozu } return render(request, 'scanner/scan.html', context) Little help will be dearly appreciated! -
Django: stripe must provide source or customer
I am new to stripe, I want to process the payment by stripe, and it show error:must provide source or customer. Someone can help? Views.py: def payment_process(request): if request.method == 'POST': token = request.POST.get('stripeToken') order = Order.objects.get(user=request.user, ordered=False) amount = int(order.get_total() * 100) charge = stripe.Charge.create( amount=amount, currency="usd", source=token, ) payment = Payment() payment.stripe_charge_id = charge['id'] payment.user = request.user payment.amount = order.get_total() payment.save() order.ordered = True order.payment = payment order.save() messages.success(request, "Payment Succeed") return redirect('/') else: return render(request, 'payment.html') -
Django: How to get user id on forms.py
I would like to get the current logged in user id in my forms.py. I want to filter different form fields based on logged in user. I am trying to query like this : class ProcessForm(forms.ModelForm): company_objective = CompanyObjectives.objects.get(user_rel_objectives=request.user.id) I get an error NameError: name 'request' is not defined. This makes sense but I have no idea how to get the id here. Plz, advise. -
How to create unique/multiple sessions that allow simultaneous answering of a Django-based survey?
I am doing a survey with Django and everything runs fine. The only problem I get is when multiple respondents answer the survey simultaneously. Then, the current session, in which the user-data is stored, is being overwritten and some strange effects take place. How can I create a unique session for every respondent so that more than one can answer the survey at the same time? If the survey is answered by one person at a time, everything is fine. Doesn't user_id = random.randint(0,10000) initial={user_id:request.session.get(user_id, None)} create a unique session for every respondent to allow simultaneous answering? Somehow respondent 2 overwrites some data of respondent 1, if respondent 1 is still doing the survey and hasn't finished yet. Thanks in advance! def home(request): user_id = random.randint(0,10000) initial={user_id:request.session.get(user_id, None)} form = SurveyForm(request.POST or None, initial=initial) if request.method == 'POST': # Save input data in session if form.is_valid(): request.session['age'] = form.cleaned_data['age'] request.session['gender'] = form.cleaned_data['gender'] request.session['education'] = form.cleaned_data['education'] return redirect('heat_tech_survey:InformationDCE') else: return render(request, 'heat_tech_survey/home.html', {'form': form}) else: return render(request, 'heat_tech_survey/home.html', {'form': form}) def RandomDCE(request): # Create independent Counters for every Choice Set, so people # can use the "Back-Button" in the Browser without increasing the counter # "count" for every website-reload in the … -
Sending data to the server via XML in Django
I am designing a web app where users can post content to a feed. I usually send the post and the post data to the server via an XMLHttpRequest. request = new XMLHttpRequest() var user = 'current user' var post = 'some text' request.open("POST", "/sent_new_post?x=" + post + "&user=" + user) request.setRequestHeader("X-CSRFToken", csrftoken); request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8"); request. onload = () => { // do stuff when response comes back } request.send() On the server I then access the data with x = request.GET['x'] But I have run into some problems using this method especially when the post text contains an '#'. I was wondering if I can send the data using request.send(data) But I don't know how to access that data in the view function... How can I access data in my view function that has been send to the server using request.send(data)???? -
Return multiple values in Subquery in Django ORM
Question is regarding Subquery and ArrayAgg in Django ORM. For example I have 2 models without any relationship one to another: class Example1(models.Model): ident = Integerfield() class Example2(models.Model): ident = IntegerField() email = EmailField() There is no connection between 2 models file FK, M2M, O2O, but field ident might be same integer in both models (which is a connection in a way)and in general for 1 instance of Example1 there are multiple instances of Example2 with same ident. I want to make a subquery or arrayagg (db Postgres) or any way outside RAWSQL to make an annotation like this: Example1.objects.annotate( cls2=Subquery( Example2.objects.filter( ident=OuterRef(‘ident’ ).values_list(‘email’, flat=True). #or Example1.objects.annotate( cls2=StringAgg( something here???, delimeter=’, ‘, distinct=True,) Sure that this does not work as Subquery returns multiple rows and it seems like it impossible to use StringAgg as we dont have any connections between models(nothing to put inside StringAgg). Any ideas how to annotate Example1 with emails from Example2 in one queryset? This will be used in CASE expression. Thanks... -
Change login label in Django auth form
I'm trying to change the login username label but without any success. Here is the website: What I'd like to do is print "Usuário and e-mail" instead of just "Usuário" label: I didn't customize the login form, in this way, I'm using all standard auth process. #template <form action="{% url 'login' %}" method="post"> {{ form.as_p }} {% csrf_token %} <input type="hidden" name="next" value="{{ next }}" /> <p><input type="submit" value="Login"></p> </form> If you guys have any suggestion modifying the input field through CSS style, it's welcome as well! Thanks! -
How to send mail along with update method in viewsets in Django Rest Framework?
I am working on a simple performance management system with react on frontend and django on the backend. They are supervisors who can give reviews to supervisees and supervisees can respond. I want all employees to receive email when They receive and supervisors to receive email when their reviews are responded. For reviews and responses I am using two different serializers but same model. Model for review is: class Review(models.Model): supervisor = models.ForeignKey( get_user_model(), # to_field='email', related_name="reviews", on_delete=models.CASCADE, null=True, ) supervisee = models.ForeignKey( get_user_model(), # from_fields=['self.supervisee'], # to_fields=['id','email','first_name','last_name'], # to_field='email', related_name="responses", on_delete=models.SET_NULL, null=True ) review_text = models.TextField(max_length=3000, blank=True, null=True) response_text = models.TextField(max_length=3000, blank=True, null=True) date_of_review = models.DateTimeField(auto_now_add=True) date_of_response = models.DateTimeField(null=True, blank=True) is_archived = models.BooleanField(default=False, help_text="boolean field to decide whether the review is archied.") review_type = models.TextField(max_length=20, default='1:1') Serializer for review is: class ReviewSerializer(serializers.ModelSerializer): supervisor_name = serializers.SerializerMethodField('get_supervisor_name') supervisor_email = serializers.SerializerMethodField('get_supervisor_email') supervisee_name = serializers.SerializerMethodField('get_supervisee_name') supervisee_email = serializers.SerializerMethodField('get_supervisee_email') class Meta: model = Review fields = ( 'id', 'review_text', 'response_text', 'date_of_review', 'date_of_response', 'supervisor', 'supervisor_name', 'supervisor_email', 'supervisee', 'supervisee_name', 'supervisee_email', 'is_archived','review_type') read_only_fields = ('response_text', 'date_of_response', 'is_archived') # order_by = 'date_of_review' def get_supervisor_name(self, obj): return obj.supervisor.first_name + " " + obj.supervisor.last_name def get_supervisor_email(self, obj): return obj.supervisor.email def get_supervisee_name(self, obj): return obj.supervisee.first_name + " " + obj.supervisee.last_name def … -
Async worker for converting html to pdf
I have a problem with understanding of async tasks in Django. I need a simple async worker in my Django project which must convert files from html to pdf, using wkhtmltopdf, but I don't know how I should make it asynchronically. Please, help me