Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Messages enum options
I have a view that handles a variety of forms to manage objects (e.g rename, delete, etc.). For each action I want to define a success and error message such that I do not need to have the message text written directly in the view. Rather I want to do something like this: CURRENT def manage(request): ... if form.is_valid(): ... messages.success(request, 'Instance rename successful') else: messages.error(request, 'Instance rename failed') WHAT I WANT def manage(request): ... if form.is_valid(): ... add_message(request, messages.success.rename) else: add_message(request, messages.error.rename) This is a simple example but I would have more complex messages that I would like to abstract out of the view and simply reference them as shown in the second example. Any thoughts on how I can accomplish this? -
django view sorted by euclidean distance of current model
Wondering if its possible to write a django view sorting models by closest vector/array with Euclidean distance. The distance would change depending on the most recent model updated. The most recently updated model as the baseline, preform similarity calcs on all of the other models and sort via smallest distance. Not sure if I should update a models integer field constantly or if there is a different way to achieve this result. Just wondering if this is possible using F(), or if you cant calculate model to model How to execute arithmetic operations between Model fields in django a model like: class Course(models.Model): name = model.Charfield(max_length=30) vector = ArrayField(ArrayField(models.IntegerField())) currenteuclideandistancefrommostrecent = models.IntegerField(..) I am basically trying to sort models by similarity of vectors. I have a some amount of django experience and trying to wrap my head around solving this is puzzling, not looking for a solution but just some advice to approach this. -
Django keep same language when reopening browser tab
I have a Django application where I can switch text from English to French with links like so: <a href="/en">Engish</a> <a href="/fr">French</a> The translation works fine but if I pick French and close the browser tab and reopen the site, it changes back to English. How can I keep the language previously selected when I reopen the browser tab. -
What are the pros and cons to ListView compared to plain function-based views and vice versa? (Django)
More specifically, is the one more preferable to the other? I know views that extend ListView can maybe have more readable code (and less of it), but even then, function-based views can often be written in like 2 lines of code with everything outlined in them, including the template and the data passed into the template. What are the benefits of each? -
Make button 'login as' in Djang for admin
Please someone tell me how I can create button in admin.py that admin can type username and whit that button login like that user. -
Taking user input and using it to identify appropriate ForeignKey in Django
So I have this for my views.py: from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from account.forms import RegistrationForm, AccountAuthenticationForm, AccountUpdateForm from framework.models import Company # Create your views here. def registration(request): context = {} user = request.user if user.is_authenticated: return redirect("index") if request.POST: updated_request = request.POST.copy() for entity in Company.objects.all(): if entity in Company.objects.all(): updated_request['company'] = Company.objects.get_or_create(entity)[0] form = RegistrationForm(updated_request) if form.is_valid(): form.save() username = form.cleaned_data.get('username') email = form.cleaned_data.get('email') first_name = form.cleaned_data.get('first_name') last_name = form.cleaned_data.get('last_name') raw_password = form.cleaned_data.get('password1') address1 = form.cleaned_data.get('address1') address2 = form.cleaned_data.get('address2') city = form.cleaned_data.get('city') state = form.cleaned_data.get('state') zipcode = form.cleaned_data.get('zipcode') account = authenticate(username=username,password=raw_password) return redirect('index') else: context['registration_form'] = form else: form = RegistrationForm() context['registration_form'] = form return render(request, 'account/register.html' , context) I'm trying to take the user's input in the form of text and compare it against the database to select a Company that they are working for, I will also add an else statement that will create a new one if one that is exact doesn't already exist. I know that this means that user's can just continually create new companies, but this will not be a problem because all accounts will be manually reviewed before being activated, so if someone makes … -
How can I pass an object selected by the user, to another view and retrieve a specific column from that object?
I'm trying to figure out the most efficient way to GET values inside my stock_list column from the current object that's being viewed by a user. BucketDetail is used to retrieve the specific object selected by the user via item = self.kwargs.get('pk') class BucketDetail(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketListSerializer queryset = Bucket.objects.all() def get_object(self, queryset=queryset, **kwargs): item = self.kwargs.get('pk') return get_object_or_404(Bucket, slug=item) How can I pass the object instance, from BucketDetail to BucketData view, followed by getting the column, stock_list, from the current object instance? class BucketData(APIView): permission_classes = [IsAuthenticated] def get(self, request, *args, **kwargs): stocks = Bucket.objects.get(stock_list) ... data = response.json() return Response(data, status=status.HTTP_200_OK) above is what I have so far, stocks = Bucket.objects.get(stock_list) does not work like I thought. models.py class Bucket(models.Model): category_options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() ... slug = models.SlugField(unique=True, blank=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True) ... objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def total_stocks_calc(self): self.stock_count = Bucket.objects.aggregate(Sum('stock_list', distinct=True)) self.save() -
TypeError: list indices must be integers or slices, not str | Django | React | Postman
When using POST on postman it comes back with TypeError: list indices must be integers or slices, not str. If I POST from client side(react) I get a network error 'int' object is not iterable PostMan POST: [ { "time": "2019-12-12", "user": 1, "title": "Test123", "description": "Nice!", "photo": "http://localhost:8000/asd", "activity": [{"name": "hike"}, {"name": "swimming"}] } ] > File "/Users/michaelchisholm/capstone-end/server/vacaplusapi/views/location.py",line 26, in create > user=user, title=data["title"], time=data["time"], description=data["description"], photo=data["photo"] > TypeError: list indices must be integers or slices, not str > "POST /locations HTTP/1.1" 500 89394 Django view Location CREATE def get_queryset(self): location = Location.objects.all() return location def create(self, request): """Handle Location operations for categories""" data = request.data user = VacaUser.objects.get(user=request.auth.user) new_location = Location.objects.create( user=user, title=data["title"], time=data["time"], description=data["description"], photo=data["photo"] ) new_location.save() for activity in data["activity"]: activity_obj = Activity.objects.get(activity_name=activity["activity"]) new_location.activity.add(activity_obj) serializer = LocationSerializer(new_location, context={'request': request}) try: return Response(serializer.data) except ValidationError as ex: return Response({"reason": ex.message}, status=status.HTTP_400_BAD_REQUEST) -
JSONDecodeError: Expecting value: line 1 column 1 (char 0) Django rest_framework
I am getting an error JSONDecodeError: Expecting value: line 1 column 1 (char 0). I'm using rest_framework along with Django. I'm trying to return all the objects of a model to the frontend. I'm fairly new to Django and can't really understand what's wrong. Full Traceback: Traceback (most recent call last): File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 353, in raw_decode obj, end = self.scan_once(s, idx) During handling of the above exception (0), another exception occurred: File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "F:\Project\Project dev\backend\Strix\views.py", line 244, in post body = json.loads(request.body) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads return _default_decoder.decode(s) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "C:\Users\sanda\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None Exception Type: JSONDecodeError at /sprintlist/ Exception Value: Expecting value: line 1 … -
Django Form not raising ValidationError
I am having a Django form, that I try to validate against two values that I compare. def clean(self): cleaned_data = super().clean() if cleaned_data['preferred_communication'] == 'email' and cleaned_data['email']: pass else: print('error error error') raise ValidationError(_('Please type in your email address, if you want to be notified.')) I see the print output in my command line, so the logic works. Still the form.is_valid seems to be True. -
How do I use a models current id to query another model
I have two classes, JobFinancialInfo(models.Model) and another model class with a field called financial_info = models.OneToOneField(JobFinancialInfo, on_delete=models.PROTECT). I'm trying to create an @property on JobFinancialInfo that will return all of the objects from the second model that has the id of self.id(?) of JobFinancialInfo. I want to do this specifically so I can run an aggregation on another field in the second models as a property on the first. Is there a way to do this, or is there a better, more efficient way? -
How to access an authenticated django webapp from a link within an email?
I have a Django webapp on Ubuntu that displays report information. I need to send emails to users that include links to view filtered data in the report depending on the user. I understand that I should generate a unique key for each customer and insert it into the query string of the included URL in the email. I am not sure how to do that. Should I use JWT? Or Oath2? If Oath2, don't I need an account? Could someone please point me to a good reference or an example? I am not sure of the best way to do this. -
Accessing API Key from django settings.py for script tag src in template
I am trying to add my api key from my settings.py to to the src for my script tag. I have been unsuccessful, so I'm hoping someone has an idea I haven't thought of or found online. <script> let GOOGLE_API_KEY='{{GOOGLE_API_KEY}}' console.log(GOOGLE_API_KEY) </script> <script src="https://maps.googleapis.com/maps/api/js?key=GOOGLE_API_KEY&callback=initMap&libraries=&v=weekly" async defer> </script> GOOGLE_API_KEY successfully logs the correct api key from my views.py -
Run batch file by clicking button in django
I have some problem with running the file (which run program from my disc) using a button in django. So this is my batch file which i would like to run: set dir=C:\Users\ciach\Desktop\openpose\bin cd %dir% openposedemo.exe --net_resolution 272x272 --model_folder C:\Users\ciach\Desktop\openpose\models --video C:\Users\ciach\X\Squat\P0.mp4 --write_json C:\Users\ciach\X\JSON This is my run.py file which i run script by python: import subprocess def squat(): subprocess.call(['C:/Users/ciach/Desktop/praca/django/mysite/main/file.bat']) #squat() Django files: views.py: def squat(request): if request.method == 'POST' and 'run_script' in request.POST: from .run import squat squat() return redirect("/home") home.html: {% block content %} <form method="post"> {% csrf_token %} <button type="submit" name="run_script">Run script</button> </form> {% endblock %} After clicking nothing happens. I have tried with only .bat file (without run.py) but doesn't work either. All I want is for the .bath file to start after pressing the button which will run the command as above. Is there any way to run something like that at all? This is based on: How to execute file.py on HTML button press using Django? Python version: 3.5.0 Django version: 2.0.7 -
How to send an email or write a function/logic after Django Rest Framework Throttles a view
I'm building an Authentication system using Django and Django Rest Framework as my backend. I've finally done the throttling to disable Annoymous Users from logging in to the site if it makes 3 Annoymous requests which will help prevent some Brute Force attacks if the user is a hacker or something similiar.. Now my problem is , how will I know if the whole throttling process is completed so that I can send an email to the user checking to see if indeed they really are the one logging in or someone else with their username/email. Summary Anonymous user tries logging in with some email/username Gets blocked for 5mins after 3 Annoymous Request An email gets sent to the respective user warning that user. -
How to make post request with CSRF token from flutter to django. Post Request from Flutter App to Django backend gives CSRF error. How to fix this
I have a flutter app for the frontend and Django for the backend. I wanna make a post request from the flutter app to the Django server. I checked the documentation and found CSRF exempt which is not something I want to do can someone tell me how I can make a post request from a Flutter app? -
How to split a string inside of django template
I am passing a strings consists of characters separated with comma like A, B, C, .. to django template, using javascript. This is my code: <div> {% for tag in wizard.form.tags %} <a href="" ><span class="btn btn-outline-primary btn-xs mb-3"> <span class="h6 text-uppercase"> <div class="badge badge-rounded-circle badge-danger-soft mt-1 mr-0"> <i class="fe fe-check"></i> </div> {{ tag }} </span></span></a> {% endfor %} </div> where {{wizard.form.tags}} returns a long string, however I need to separate it inside of the template to style it. Is there solution for that? P.S. Just note that I can't probably add method to the model as the value inside the {{wizard.form.tags}} are passed by js and not reading from database. -
add built-in filter method in template returns empty string
I am having trouble in Djagno template built-in method of add. When I do <img class="card_image" src="{% static '/image/products/'|add:product.image %}" alt="design"> it returns empty string. and after doing a research, it seems like add method can be only used if a variable is surrounded with strings. ex. does not work {% static '/image/products/'|add:product.image %} does work ? {% static '/image/products/'|add:product.image|add:"closing_string" %} I dont understand why it works this way. and my work around is {% static '' %}image/products/{{product.image}} it works, but personally I just want to know why i cannot concatenate variable at the end using add. let me know if someone can help me understand better. Thank you in advance -
Sums in django gives wrong results
My models: class Leider(models.Model): naam = models.CharField(max_length=100, unique=True) volgorde = models.IntegerField(default=0, blank=True) def __str__(self): return self.naam class Meta: ordering = ['volgorde'] class PrijsKlasse(models.Model): naam = models.CharField(max_length=50, unique=True) normaal = models.DecimalField(max_digits=6, decimal_places=2) zwaar = models.DecimalField(max_digits=6, decimal_places=2) def __str__(self): return self.naam + " - €" + str(self.normaal) + " - €" + str(self.zwaar) class Telling(models.Model): leider = models.ForeignKey(Leider, on_delete=models.CASCADE) aantalNormaal = models.IntegerField(default=0, null=True) aantalZwaar = models.IntegerField(default=0, null=True) prijsKlasse = models.ForeignKey(PrijsKlasse, on_delete=models.PROTECT) datum = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self): return str(self.leider) + ' normaal:' + str(self.aantalNormaal) + ' zwaar:' + str(self.aantalZwaar) class Betaling(models.Model): leider = models.ForeignKey(Leider, on_delete=models.CASCADE) hoeveelheid = models.DecimalField(max_digits=8, decimal_places=2) datum = models.DateTimeField(auto_now_add=True, blank=True) def __str__(self) -> str: return str(self.leider) + " - " + str(self.hoeveelheid) my view code: teBetalen = Leider.objects.values('naam').order_by('volgorde').\ annotate(prijsNormaal=Coalesce(Sum(F('telling__aantalNormaal') * F('telling__prijsKlasse__normaal'), output_field=FloatField()), Value(0))).\ annotate(prijsZwaar=Coalesce(Sum(F('telling__aantalZwaar') * F('telling__prijsKlasse__zwaar'), output_field=FloatField()), Value(0))).\ annotate(totaal=Coalesce(F('prijsNormaal') + F('prijsZwaar'), Value(0))).\ annotate(betaald=Coalesce(Sum('betaling__hoeveelheid'), Value(0))) I am pretty new to django so i may be doing something stupid or to complicated I have tried using distinct in the sums but this didn't solve it. I have rewritten the query used the raw sql and i think it has something to do with the LEFT OUTER JOIN and it multiplying the sum. Just can't figure out how to fix it. I … -
How to use django inlines with a composite key?
and thank you for your help. I'm using inlines in django to display a model in another admin model, it seems like it demmands a primary key, i get this error: OperationalError at /admin/accounts/estadosm/18/change/ (1054, "Unknown column 'flora2estado.id' in 'field list'") But!, the model actually have a composite key, like so: class Flora2Estado(models.Model): estado = models.ForeignKey(EstadosM, models.DO_NOTHING) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) class Meta: managed = False db_table = 'flora2estado' unique_together = (('estado', 'especie'),) How can i fix this, to tell django admin fields to use the composite key?! django.admin: class flora2EstadosInline(admin.TabularInline): model = Flora2Estado fields = ['estado','especie'] extra = 1 def get_extra (self, request, obj=None, **kwargs): """Dynamically sets the number of extra forms. 0 if the related object already exists or the extra configuration otherwise.""" if obj: # Don't add any extra forms if the related object already exists. return 0 return self.extra class EstadosAdmin(admin.ModelAdmin): inlines = [flora2EstadosInline] -
How can I force django.allauth to require an email
In my django project I am using django.allauth to manage my users. I want the user to provide both a user name and an email address. If I use the allauth SignupView it the email field must be filled, however if I override it with my own view, it does not make it mandatory. What am I missing? settings.py # User model AUTH_USER_MODEL = 'accounts.CustomUser' # django-allauth settings AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) LOGIN_REDIRECT_URL = '/home' LOGOUT_REDIRECT_URL = '/home' SITE_ID = 1 ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED = True models.py import json import datetime from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): logged_in = models.BooleanField(default=False) last_active_time = models.DateTimeField(null=True) login_datetime = models.DateTimeField(null=True, blank=True) email_confirmed = models.BooleanField(default=False) date_of_birth = models.DateField(null=True) forms.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import UserCreationForm, UserChangeForm class CustomUserCreationForm(UserCreationForm): class Meta: model = get_user_model() fields = ('username', 'email') urls.py from .views import MySignupView urlpatterns = [ path('signup/', MySignupView.as_view(), name='signup'), ] views.py from .forms import CustomUserCreationForm SIGNUP_SUCCESS = 'You have successfully signed up!' class MySignupView(SignupView): form_class = CustomUserCreationForm success_url = reverse_lazy('home') template_name = 'account/signup.html' def form_valid(self, form): messages.success(self.request, SIGNUP_SUCCESS) return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["button_text"] = 'Sign Up' return … -
How to real-time update React app with data from Django REST API
I have a project that uses React for frontend and Django REST Framework for backend.Simply, when a new comment post for an article, I want to notify other users that are currently reading comments for that specific article. How can I do that? -
How to handle empty values if there is no file in request.FILES[''] in django without using django forms
I want user can fill all information and there is no required field when i try to submit my form without uploading image it gives me error MultiValueDictKeyError at /update-home-content/1/ 'bg_image' this is my models.py from django.db import models # Create your models here. class ImageUpload(models.Model): get_image = models.FileField(upload_to='gallery/new/',null=True) and this is my views.py from upload.models import ImageUpload # Create your views here. def add_image(request): if request.method == "POST": image = request.FILES['bg_image'] -
Gmail sending with currently generated pdf in Django
I am trying to send a pdf as a Gmail attachment in Django, which is just generated by the same view. For generating the pdf, I use to try this tutorial link. my views.py: def submit_report(request, pk): template = get_template('app/pdf_rprt.html') Industry_obj = Industry.objects.get(id=pk) Industry_Report_obj = Industry_obj.industry_report_set.all() report_tableA_obj = report_tableA.objects.filter(industry_report__industry=Industry_obj) context = { 'industry' : Industry_obj, 'Industry_Report' : Industry_Report_obj, 'report_tableA' : report_tableA_obj, } html = template.render(context) pdf = render_to_pdf('app/pdf_rprt.html', context) if pdf: to = "kanchon2199@gmail.com" email = EmailMultiAlternatives( #subject = "final report sending (beta)", #content = 'hello, this is test report sending mail', #from email settings.EMAIL_HOST_USER, #list of recipent [to] ) email.attach_file(pdf) email.send() return redirect('app:index') here the render_to_pdf comes from a custom build function in utils.py: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None But it says error like (for the line email.attach_file(pdf)): TypeError at /submit_report/1/ expected str, bytes or os.PathLike object, not HttpResponse How can I fix it? -
How to find Min(Sum(annotated column)) in Django
I have four tables A, B, C and D. each table is associated in a way A -> B -> C -> D by id column. eg. A.id = B.a_id, B.id = C.b_id and C.id = D.c_id I am trying to achieve something like this SELECT x.id, min(x.total) as mintotal FROM (SELECT “A”.”id", SUM((“D”.”amount” * “D”.”quantity")) AS "total", “C”.”id" AS "qid" FROM “A” LEFT OUTER JOIN “B” ON (“A”.”id" = “B”.”a_id") LEFT OUTER JOIN “C” ON (“B”.”id" = “C”.”c_id") LEFT OUTER JOIN “D” ON (“C”.”id" = “D”.”c_id") GROUP BY “A”.”id", “C”.”id") as x group by x.id ORDER BY mintotal ASC My equivalent django code query1 = A.objects.all().annotate(qid = models.F(‘b__c__id'),total=Sum(models.ExpressionWrapper( models.F(‘b__c__d__amount') *models.F('b__c__d__quantity'), output_field=models.DecimalField()))).order_by('total') it gives me the inner query output, however when I try to select id and Min(total) again it throws error - FieldError: Cannot compute Min('total'): 'total' is an aggregate I am new to Django and I am not sure how I can use subquery or exists to get this result. Any help will be appreciated