Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ReactJS Api Fetch Request to Django Backend returns "strict-origin-when-cross-origin" error
I tried to make a API call to Django Backend made with djangorestframework and simplejwt from ReactJS and it returns an error. error: "strict-origin-when-cross-origin" I set the cors-headers and It still doesen't working.But when I send the request from postman it works. Here's the fetch request code function handleSubmit(e) { e.preventDefault() const email = emailRef.current.value const password = emailRef.current.value if (!email || !password) return const res = fetch('http://localhost:8000/api/token', { method: "POST", headers: { 'Access-Control-Allow-Origin': '*', 'Content-Type': 'application/json' }, body: JSON.stringify( { username: email, password } ) }) if (res.status !== 200) navigate('/login') } -
Problems with updating a Django form with information from another model
I'm basically building functionality to update a form with values from one table in my models.py, the form will populate the initial values with that table (leads) and upon submitting the information, the form will populate another model (leads) These is my models.py class Leads(models.Model): project_id = models.BigAutoField(primary_key=True, serialize=False) created_at = models.DateTimeField(auto_now_add=True) expected_revenue = MoneyField(decimal_places=2,max_digits=14, default_currency='USD') expected_licenses = models.IntegerField(blank=True) country = CountryField(blank_label='(select_country)') status = models.CharField(choices=[('Open', 'Open'), ('Closed', 'Closed'), ('Canceled', 'Canceled')], max_length=10) estimated_closing_date = models.DateField(blank=True) services = models.CharField(choices=[('Illumination Studies', 'Illumination Studies'), ('Training', 'Training'),('Survey Design Consultancy', 'Survey Design Consultancy'), ('Software License', 'Software License'), ('Software Development','Software Development')], max_length=40) agent = models.ForeignKey(Profile, default='agent',on_delete=models.CASCADE) company = models.ForeignKey(Company,on_delete=models.CASCADE) point_of_contact = models.ForeignKey(Client, default='agent',on_delete=models.CASCADE) updated_at = models.DateTimeField(auto_now=True) class Deal(models.Model): project_id = models.ForeignKey(Leads, on_delete=models.CASCADE, default='id') agent = models.ForeignKey(Profile, on_delete=models.CASCADE, default="agent") service = models.ForeignKey(Leads, on_delete=models.CASCADE, related_name='service') closing_date = models.DateField(auto_now_add=True) client = models.ForeignKey(Client, on_delete=models.CASCADE,default='client') licenses = models.ForeignKey(Leads,on_delete=models.CASCADE, related_name='license') revenue = MoneyField(max_digits=14, decimal_places=2, default_currency='USD') comments = models.TextField(blank=True,null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE) Forms.py class NewDealForm(forms.ModelForm): class Meta: model = Deal fields = ['project_id','agent','client','company','service', 'licenses','revenue','comments'] @login_required def close_lead(request): if request.method == 'POST': deal_form = NewDealForm(request.POST) print(deal_form) if deal_form.is_valid(): deal_form.save() messages.success(request, 'You have successfully updated the status from open to Close') id = request.GET.get('project_id', '') obj = Leads.objects.get(project_id=id) obj.status = "Closed" obj.save(update_fields=['status']) return HttpResponseRedirect(reverse('dashboard')) else: … -
Implementing OAUTH2 with custom user model
I am trying to use custom user model for implementing OAUTH2 and I am having an issue with convert token API. my custom model returns a JWT token and it is defined in settings.py as - AUTH_USER_MODEL = 'user.User' here is name of custom backend- DRFSO2_PROPRIETARY_BACKEND_NAME = "MyAPP" I am not sure if the above step is correct because I just gave it a random name. now I am confused what should I do in- AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) -
How to set variable in python django template from a function call?
I have the following library which returns a dict: {% load path_parts %} I can successfully call the method and print the value: {% path_parts request.get_full_path %} I would like to assign the dict to a variable, but I cannot: {% with paths=path_parts request.get_full_path %} How can I assign a result of a function call to a variable? -
'str' object has no attribute 'user' generated for unknown reason from Django View
I have a view built around the following code: views.py: def create_instance(request): form = InstanceMF() form2 = TextBox() if request.method == 'POST': form = InstanceMF(request.POST) form2 = TextBox(request.POST) if form.is_valid() and form2.is_valid(): content = form2.cleaned_data['content'] form = form.save(commit=False) form.author = request.user scores_dict = analyze(content) When I try to submit data in this view however, I get the error message from the title based on the last line where I attempt to call the analyze function, which is the following: def analyze(content): content = content.translate(remove_punctuation) word_list = content.lower().split() columns = Model1._meta.fields for word in word_list: model = Model1.objects.all() if word in model.filter(word__icontains=word): column = model for key, value in dictionary.items(): selected_columns = columns[value[0]:value[1]:2] if column in selected_columns: instance = dictionary2.get(key) if 'yes' in key: final_score[instance] += 1 elif 'no' in key: final_score[instance] -= 1 return final_score My guess here is that the database query somehow messes up the data structure needed to save InstanceMF in such a way that the current "user" is no longer accessible. How do I correct this? -
Is it possible to refresh an included Django template without refreshing the whole page?
I'm struggling with an issue similar to this one. I've got a Django template that includes a whole bunch of smaller templates with for-loops to render various aspects of my page. I'm wondering what the best way is to go about updating individual little templates to render them in the master template without having to do a whole page refresh. Does Django for example support some kind of React-like virtual dom to rerender only individual sub-templates? I understand that templates are being computed on the server and the generated HTML is then sent to the client for rendering so perhaps it's not possible to render templates in-place? The post above mentions passing data to the server with AJAX to refresh a particular template, but before I start revamping my page, I was wondering if that would work for rendering multiple templates at a time, and if so, if someone could point me to an example where this is explained in some detail; I've been looking, but couldn't find any. Thanks! -
Calling Python function from JS [duplicate]
I have a python django project. And I am trying to call a python function from JS. To start I’ve a html button that runs a JS function. It works fine: <input id="clickMe" type="button" value="clickme" onclick="show();" /> Currently I have this JS function just showing an alert. Like so. function show_eb_variable_table() { alert("Hello! I am an alert box!!"); } What I want to do is to instead of showing this alert I want to call and run a python function from my “plot.py” file in the project. The function I want to call is as so: def printing_something (request): print('hi') return render(request, 'index2.html', {}) Is there a way I can connect the JS to call the Python function? -
Django form validation only validating partially before submit/post
I have a customer registration form within a bootstrap modal, for this reason I would like to do some basic validation before posting. At the moment if you leave a field blank, if the string is too long or if there isn't a @ in the email then an alert appears, which is perfect. But, mismatching passwords, invalid email addresses like example@example submit. Surely that should fail the ValidateEmail regex? The validation failures are picked up fine in views after submission but getting back to the modal is the problem so I'd like them caught by the same pre-submission validation that picks up a blank fields. Or failing that, is it feasible to do an Ajax request on View and refresh the form asynchronously? Getting the form into json wouldn't be fun. Or should I just give up on django and use jquery validation? Forms: class CreateRegistrationForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for f in self.fields: self.fields[f].widget.attrs['class'] = 'form-control' class Meta: model = User fields = ["email", "password1", "password2", "first_name", "last_name"] Models: class User(AbstractBaseUser, PermissionsMixin): class Types(models.TextChoices): CUSTOMER = "CUSTOMER", "Customer" STAFF = "STAFF", "Staff" base_type = Types.CUSTOMER type = models.CharField( _("Type"), max_length=50, choices=Types.choices, default=base_type ) user_name = models.CharField(max_length=150) … -
Add a template folder selection for a django package
I am relatively new to django and am looking for help on custom package templates management. At work, we are using a home-made custom django package that we add to installed apps in our main projects. This package has tools and utilities, as well as the base templates that we derive from in main projects. What's changing? We need to update our frontend and are changing libraries, which has an impact on the templates in this custom package. With a view to avoid multiplying the custom package branches and versions (we already have a couple for different versions of django), and given that the templates in our existing applications will not all be updated at once, we wish to make it so that the main project will use either the old templates or the new version of templates (variable selection or default). What I aim for (if possible): adding a folder level in the custom package templates folder that the project will look in adding a variable (in the project's settings.py file for example) to indicate which template folder the main project needs to look for in the package not having to modify the old templates folder in the package, … -
django documentation user permission ambiguity on object level permission
I am getting my feet wet with django user permission and I am trying to: Create specific permissions for different models I have. Assign to some permissions to some users for only some instances of a specific model. So basically, user_i might have permission_a and permission_b on project_one but only permission_a on project_two. Looking at the documentation, I got that I can define a custom permission on a model by adding the following Meta to the class: class JobProject(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) .... class Meta: permissions = [ ("permission_a", "This is perm a"), ("permission_b", "This is perm b"), ] However, now I am not sure I understand how can I add permission_a to user_a only for a specific instance project_a of the JobProject class. Django documentation is indeed ambiguous on the matter. On one hand it states that I can use the method has_perm(perm, obj=None) to check if a user has a specific perm on a specific obj. On the other hand, there is no hint on how I can specify which specific object I want to add a permission for when I run user_a.user_permissions.add(permission_a) Any idea? I saw that django-guardian could be a valuable alternative but I … -
How to make many to one field reference in Django 3.2?
I'm working on a simple project in Django which is a To Do applictaion. Lately I have add to this project a login/register form, but despite that every user has their own account with their own credentials they access to the same data. I tried to use the models.ForeignKey(User, on_delete=models.CASACADE) but it shows me this error: django.core.exceptions.FieldError: Unsupported lookup 'user' for CharField or join on the field not permitted. To understand it better will show the full code: models.py from django.db import models from django.contrib.auth.models import User from django.db.models.deletion import CASCADE # Create your models here. class todo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.content class User(models.Model): name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) def __str__(self): return self.name views.py from django.http.response import HttpResponse from django.shortcuts import render, redirect from django.utils import timezone from django.db.models import Count from django.contrib.auth.forms import UserCreationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.contrib import messages from .models import * from .models import __str__ from .forms import CreateUserForm # Create your views here. @login_required(login_url='login/') def home(request): user = request.user count_item = todo.objects.count() all_items = todo.objects.filter(content__user=user).order_by("created") context = {'all_items': all_items, 'count_item':count_item} … -
sudo supervisorctl status: gumi gunicorn ERROR (spawn error)
$ sudo supervisorctl status guni:gunicorn FATAL Exited too quickly (process log may have details) Process log details in short: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: all the packages are installed with their latest versions bit still I am getting these above errors after running sudo supervisorctl status output gumi:gunicorn: ERROR (spawn error) Any idea what I am missing? -
An if-statement based on src HTML
I have big html document with various images with href and src. I want to make an if statement based on the output of the src. <img class="img-fluid d-block w-100" src="/static/assets/img/{{ LANGUAGE_CODE }}/actionFlow({% if form.status.value|slugify == '1'%}taak-toegewezen{% else %}{{form.status.value|slugify}}{%endif%}).png" id="workflowVisual"> Example outputs can be: "/static/assets/img/en/actionFlow(taak-toegewezen).png" "/static/assets/img/en/actionFlow(firststep).png" Now, I want to create an if statement like so: {% if src== "/static/assets/img/en/actionFlow(taak-toegewezen).png"}{{instance.reviewer2}} {% else src== "/static/assets/img/en/actionFlow(firststep).png"}{{instance.reviewer1}}{%endif%} How do I do this in HTML? Best, Rob -
Using a ListCharField as a filter field
I am trying to implement an API which you would filter objects using a ListCharField called categories. I want an object to be filtered if any of the values in its categories field matches with the category being searched. With my implementation, objects are being matched only if all the values in the categories match. Example: Consider an object A with categories='fun','party' and B with categories='fun' Then http://127.0.0.1:8000/theme/?categories=fun does not match with A but with B only. Model: class Themes(models.Model): id = models.CharField(max_length=64, unique=True, default=gen_uuid4_th name = models.CharField(max_length=128) description = models.CharField(max_length=512) categories = ListCharField(base_field=models.CharField(max_length=32), size=5, max_length=(6*33), null=True) View: class ThemesView(viewsets.ModelViewSet): serializer_class = AgendaTemplateSerializer permission_classes = (IsMemberUser,) filter_backends = (filters.DjangoFilterBackend,) filterset_fields = ('categories',) def get_permissions(self): ... def get_queryset(self): return Themes.objects.filter(Q(team__isnull=True) | Q(team=self.request.mp.team.teamid), is_archived=False) \ .order_by('-created_at') -
Django CreateView pass additional context data
I have a form in a bootstrap modal, and I want to keep that modal open after submission. I am using CreateView and trying to pass an additional variable to the template in front-end where I could check if the flag is set or not, but the flag is always False even after submission. Here is what I have: views.py from django.urls import reverse from django.views.generic.edit import CreateView from .forms import MescForm from .models import Mesc class MescData(CreateView): model = Mesc form_class = MescForm template_name = 'Materials/mesc_data.html' successful_submit = False # Flag to keep the add entry modal open def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['successful_submit'] = self.successful_submit return context def get_success_url(self): return reverse('mesc') def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) form.was_satisfied = True if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form, **kwargs): # self.successful_submit = True return super(MescData, self).form_valid(form, **kwargs) And in Template, I'm checking it like this: {% if success %} <h1>Flag is set</h1> {% endif %} Is there a way to pass non-form-related data in CreateView to the template without having to change the url.py (i.e. adding variable data to url path)? -
JSON.parse in javascript not converting to array correctly
I have a queryDict in django. I'm serializing it documents = serializers.serialize('json', Documents.objects.filter(id=self.kwargs['pk'])) context['documents'] = json.dumps(documents) When I accept in javascript I got this JSON.parse("{{ documents|escapejs }}") -> &quot;[{&quot;model&quot;: &quot;documents&quot;, &quot;pk&quot;: I need to parse once more time to get correct arrray. Can someone help me? -
django-filter how to style RangeFilter?
I have a problem with styling a range input. I'm using django_filters.RangeFilter class on declaring my filter: parent__length = django_filters.RangeFilter(label="Length") It looks like this I wan't have this length input in one row seperated with "-" sign. I'm using bootstrap grid when im displaying that filters. Thank you in advance -
Create User and UserProfile on user signup with django-allauth
I am using django-allauth for taking car of accounts, login, logout, signup, but I need that on create the user must create a profile and I am using the model UserProfile as it can be seen on the code. The problem is that when I created the custom signup form, now it creates a user with [username, email, first_name, last_name, password] but it does not create a UserProfile. And I have three questions: How to create a User and a UserProfile on signup? How can add styling to the forms that come with django-allauth, i.e. at /accounts /login/ How can I modify so that when the user logs in, it will redirect him to /profiles/ instead of /accounts/profiles or is it better in terms of REST principles to have it /accounts/profiles/ if yes, then is it possible to modify the profiles app so that it can use django-allauth views? My custom signup form: # django_project/profiles/forms.py from django import forms from allauth.account.forms import SignupForm class CustomSignupForm(SignupForm): first_name = forms.CharField(max_length=30, label='First Name') last_name = forms.CharField(max_length=30, label='Last Name') bio = forms.CharField(max_length=255, label='Bio') def save(self, request): user = super(CustomSignupForm, self).save(request) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.bio = self.cleaned_data['bio'] user.save() return user Settings: # … -
How to deserialize a serialized queryset in Django?
views.py def ipd_report_view(request): report=IpdReport.objects.all() myFilter=IpdFilters(request.POST, queryset=report) report=myFilter.qs total1=report.aggregate(Sum('realization__amount_received')) total2=report.aggregate(Sum('realization__deficit_or_surplus_amount')) rp=serializers.serialize('json', report) request.session['report']=rp context={'report': report, 'total1':total1, 'total2':total2, 'myFilter':myFilter} return render(request, 'account/ipdreport.html', context) In another view function, I have to use the data in the session to be able to make the function export the data to an excel file. I did rp=request.session['report'], but this object is a string object, so how do I go about converting this back to a queryset? Or is there any other way to achieve this? -
Restricting access to some pages in Django
In my Django project, I want only the premium users to be able to access the sales page. So if a user's user_type is Trial, he/she can't be able to access sales page. For these non-premium users, I want to display another html (upgrade.html) to them Below is my view class SalesView(TemplateView, SingleTableView): model = Product table_class = ProductTable template_name = 'src/dashboard/sales.html' def get_queryset(self): ... ... def get_context_data(self, **kwargs): # my contexts goes here And this is my url path('sales', SalesView.as_view(), name='sales'), This is the normal view. Now I want to stop Trial users from accessing this page. Please how can I achieve this? My model has a field user_type which tells whether a user is a Trial or Premium user -
how to overwrite data in django?
I have two views where I tried to overwrite the data in one here's the first code: ** tafhist = APIHistory(API_Hist_Id= pi,Status='API has been Submitted',unique_Id='UNID1006',url=url) tafhist.save() ** here first i'm creating data and saving it. now in same location i want to update same column here's the 2nd code of it: ** tafhist = APIHistory(Status='TAF Started').filter(unique_Id=tuid) tafhist.save() ** in this line I was trying to update but not getting how to do that. can someone please explain? -
Can I make a movie theater seat reservation system by linking Django and JavaScript?
Today, when accessing the website of a movie theater, there is a graphic UI that informs the location and number of seats, and there is a function for the user to select a seat. I want to implement such a function, but when I try to do it, I have no idea how to handle it. For example, if there are 10x10 rows of seats, should I create a seat model in Django, create 100 objects there, and choose the method of linking them? First of all, the graphic function is written in JavaScript, but the rest is not progressing. This is my javascript code about seat table. {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="{% static 'movie/bootstrap/bootstrap.min.css' %}" rel="stylesheet" type="text/css"> <title>Pick your seat</title> <link rel="stylesheet" href="{% static 'ticket/css/seat_page.css' %}"> <style> .seat { width: 40px; height: 30px; } .clicked { background-color: #f4a7bb; color: #000000; } </style> </head> <body> <div class="screen-x"> <h2>SCREEN</h2> <div class="seat-table"> <div class="seat-wrapper"></div> </div> </div> </body> <script> let test = []; let selectedSeats = new Array(); let selectedSeatsMap = []; const seatWrapper = document.querySelector(".seat-wrapper"); let clicked = ""; let div = ""; for (let i = 0; i < 18; i++) … -
How to don't save null parameter in table if got parameter with null field in Django
I have table with some parameters like this: class Education(models.Model): title = models.CharField(default=None, max_length=100) content = models.TextField(default=None) In Django request from client maybe content field equals to NULL. So i want to when content parameter is NULL Django does not save it in database but does not show any errors. Maybe already this field has data and in the Update request client just want to change title field. -
Django ORM: ForeignKey=self and on_delete=PROTECT
I have Model with field, where I see next field: some_field = ForeignKey('self', on_delete=PROTECT, blank=true, null=true, editable=false) For what this field exist and what it does? Also I cant delete obj of this model id adminpanel, cause it say " you cant delete obj A, because would require deleting next protected obj: obj A" Reason for this in this some_field? -
Custom permission/restriction with DJANGO REST ModelViewSet
I would like to restrict users to have only limited access/permissions in create or destroy method. Here is the scenario, a user, with admin role can do anything (create, get, update, delete), where as an ordinary user(customer) can only perform those allowed actions(create, get, delete) to its related model. My model looks like this class Material(models.Model): ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) class UserMaterialAllow(models.Model): user = models.ForeignKey(get_user_model()) material = models.ForeignKey('Material, on_delete=models.CASCADE) Here is how I added a custom restriction /views/material.py class MaterialView(viewsets.ModelViewSet): queryset=Material.objects.all() serializer-class = MaterialSerializer def create(self, request, *args, **kwargs): if(not app_admin(request.user)): // the user is not admin return Response(status=status.HTTP_403_FORBIDDEN)// this will forbid non admin user in MateralView, a user cant access if it is not an admin. What I need is, if the user is not an admin, just allow them to perform action but limited only the the material belongs to them app_admin implemtation `def app_admin(user): if user.user_is_admin: return True if user.is_superuser: return True return False Any ideas?