Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use @property in models choices?
My model: **class SomeModel(models.Model): ... models.CharField(max_length=255, choices=BookPage.choices)** My choices: from enum import Enum class BookPage(Enum): MAIN = "Main" SIDEBAR = "Sidebar" @property def choices(self): return [(key.value, key.name) for key in self] I got this error Where I'm wrong? choices' must be an iterable (e.g., a list or tuple). -
How to display value form database with javascript in django
So i have this dropdown field in a form that comes from a model that consists of foreign keys, and i want to display the values from database based on that foreign key when i chose the dropdown field in the form with Javascript, but i really have zero knowledge in javascript. So i was wondering if anyone could help me This is my forms class DssPostForm(forms.ModelForm): class Meta: model = Simulation fields = ['cpu_name'] my model class Simulation(models.Model): build_name = models.CharField(blank=False, max_length=150) mtb_name = models.ForeignKey(Motherboard, on_delete=models.CASCADE) cpu_name = models.ForeignKey(Cpu, on_delete=models.CASCADE) vga_name = models.ForeignKey(Vga, on_delete=models.CASCADE) ram_name = models.ForeignKey(Ram, on_delete=models.CASCADE) str_name = models.ForeignKey(Storage, on_delete=models.CASCADE) def __str__(self): return self.build_name my views def DssPostView(request): if request.user.is_authenticated: form = DssPostForm() return render(request, "dss_form.html", {'form': form}) else: messages.info(request, 'Silahkan Login Terlebih Dahulu.') return redirect('accounts:login') and my templates <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% bootstrap_form form %} <button type="submit" class="btn btn-secondary">Add CPU</button> </form> -
DRF Custom throttle rate doesn't work, default rate works
I'm trying to set up the throttle rate for all users to 100 requests per 15 minutes. The problem is that when I override AnonRateThrottle and UserRateThrottle, the throttling doesn't work at all. REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { # I've lowered the rates to test it 'anon': '2/min', 'user': '2/min' } } Works perfectly. This does not work: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS': ['django_filters.rest_framework.DjangoFilterBackend'], 'DEFAULT_THROTTLE_CLASSES': [ 'api.throttle_rates.AnonHundredPerFifteenMinutesThrottle', 'api.throttle_rates.UserHundredPerFifteenMinutesThrottle', ], } api.throttle_rates from rest_framework.throttling import AnonRateThrottle, UserRateThrottle class AnonHundredPerFifteenMinutesThrottle(AnonRateThrottle): def parse_rate(self, rate): return (2, 60) class UserHundredPerFifteenMinutesThrottle(UserRateThrottle): def parse_rate(self, rate): return (2,60) Do you know where is the problem? -
How can I display many to many field as a drop down in filter?
fillter snapshot This is what I am getting in filter, I want it as a drop down list to look nicer. The codes I have tried until now is: filters.py class WinsFilter(django_filters.FilterSet): class Meta: model = Wins fields = ['playerdetail',] my views.py looks like below class MatchWinsView(ListView): model = models.Wins template_name = 'match_wins.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = WinsFilter(self.request.GET, queryset=self.queryset) return context And below is the model I have created. class Wins(models.Model): matchdetail = models.ManyToManyField(Matches) playerdetail = models.ManyToManyField(Players) I have tried referring documentations but I am not able to get the correct solution yet? What changes should I do to make proper drop down in my filter? -
What {% %} and {{ }} mean in HTML?
I have recently started to learn Django, so I came across with some HTML templates, but those are pretty unfamiliar for me, they mostly consist of {% and {{ For example: <h1>{{ question.question_text }}</h1> <ul> {% for choice in question.choice_set.all %} <li>{{ choice.choice_text }} -- {{ choice.votes }} vote{{ choice.votes|pluralize }}</li> {% endfor %} </ul> <a href="{% url 'polls:detail' question.id %}">Vote again?</a> What are they? Implementations from other languages or HTML syntax? I'd be happy to get some docs, websites or examples too. -
Django pages load slow
I'm pretty new to Django and I'm trying to develop a streaming service application. I'm running into a problem with the page load times. In my main python file, I have a loop that runs through my Cassandra db and retrieves all content in there. Each 'content' is stored as a dictionary. So when I pass the content to my templates, I'm essentially passing a dictionary of dictionaries. I'm sending in a max of 15 dictionaries at a time (for bandwidth conservation), but I'm experiencing page load times up to 8 seconds. This causes the videos to buffer before playing, and a poor user experience. Am I sending too much to the templates? Or is there a way to speed up the process? -
How to automatically show selected field in MultiSelectField in Django?
Let's say I have a model with MultiSelectField from django-multislectfield as shown below. User can check as many fields as they want to and then they submit the form. Now what I want is that when they come back to form page the fields that user checked before remain there the same. How can I do that? example of model and form class class Test(models.Model): names = MultiSelectField(choices=....) class TestForm(forms.ModelForm): Class Meta; model = Test fields = '__all__' -
Unable to import PIL with Pillow installed - Django project under venv
I've been struggling for hours trying to debug this and none of the solutions I've found worked for me. I have a Django project running in a virtual env and installed Pillow to use Image. The problem is that I can't import it. VScode tells me that it is "Unable to import 'PIL'" I have other packages like crispy_forms that are installed and work perfectly fine. If I open the Python shell using py manage.py shell then run from PIL import Image I get no errors. Furthermore if I now type Image It returns the correct infos : <module 'PIL.Image' from 'C:\\Users\\XXXX\\Documents\\webDev\\djangoProjects\\env\\lib\\site-packages\\pillow-7.2.0-py3.8-win32.egg\\PIL\\Image.py'> I tried to uninstall Pillow then reinstall it, even using easy_install Pillow. This is clearly not a problem of pathing or different versions of Python as I'm in my virtual env AND as show above I can run the import on my shell and find the files. Thanks for your help. -
form is not saving changes in dialog modal (popup) Django
I’m really new in Django and I need your help, please I’m trying to implement Modal dialog using forms. The problem is that even when I make some changes in my form, this changes are not shown in database… I have no idea why. When I test form outside Modal dialog, form is working… Here is my form.py: class anomalie_location_form(ModelForm): class Meta: model = Anomalie fields = ['localization', ] here is my view.py @login_required(login_url='login') def fix_anomalie_stock(request, pk, type_anomalie): anomalie_pk = Anomalie.objects.get(id=pk) # form to change anomalie position form_location = anomalie_location_form(instance=anomalie_pk) if request.method == 'POST': print('printinng anomalie_location_form POST ', request.POST) form_location = anomalie_location_form( request.POST, instance=anomalie_pk) if form_location.is_valid(): form_location.save() return redirect('/') context = {'anomalie_pk': anomalie_pk, 'form_location': form_location} return render(request, "anomalie/fix_anomalie_stock.html", context) and my html: <div class="modal fade" id="myModal2" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <h4>{{product.product_name }} </h4> </div> <form action="" method="POST"> {% csrf_token %} <div class="modal-body"> {{form_location}} </div> <div class="modal-footer"> <input type="submit" class="btn btn-primary" value="Treter" data-dismiss="modal"> </div> </form> </div> </div> </div> So the question is why form is working outside of Dialog Modal ? I would appreciate your help. Thanks a lot -
i am calling django server from angular js but cors error is occuring while executing so what should i do to call django url from angular js?
Here is the angular js code where URL is of Django server and I am calling testapi URL from that. ''' app.service('$reportsService', ['$http', function($http) { this.getReport = function(moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime, toReportTime, reportID ,phononUUID,attemptID,requestID,queueIds,flowIds,callStatus) { return new Promise((resolve, reject) => { $http({ url:"http://localhost:8000/testapi/", method: "POST", data: { reportStandardName: moduleName, moduleKey, reportFormat, intervalFromDays, intervalToDays, fromReportTime: moment(fromReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), toReportTime: moment(toReportTime, "HH:mm:ss").format('HH:mm:ssZZ'), reportID, phononUUID, attemptID, requestID, queueIds, flowIds, callStatus, sourceOfRequest: "API", priority: 1, reportTime: new Date().toLocaleTimeString(), } }).then(function(res) { if (res.status === 200) { console.log('getReport fetched : ', res.data); resolve(res.data); } }).catch(e => { console.error("getReport failed with error: ", e); reject(); }) }) } ''' Here is my djago urls file urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^testapi/', views.getResponse) ] Pls give me the solution of the above cors error that occurs when i am calling django server from angular server. Both file are on the same machine. -
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://repo.anaconda.com/pkgs/main/win-64/current_repodata.json>
I'm trying to create, a virtual environment for setting up Django. I face this issue when I try to create a virtual environment using the command "conda create --name (Userdefined Name)". I have tried this in command prompt and in Anaconda prompt. It works in Anaconda prompt, but not in command prompt and I want to know why. This is the error: -
How to Upload Image in React js and Django?
I am trying to upload an image using react js on django backend but i don't why all the time when i submitted for its shows uploaded but all the time image shows null, Here is my code so far what i did. here is also a link of code sandbox link .https://codesandbox.io/s/thirsty-varahamihira-fnusu?file=/src/App.js:0-1494. import React, { Component } from "react"; import "./styles.css"; class App extends Component { constructor(props) { super(props); this.state = { image: null }; } handleInputChange = async (event) => { await this.setState({ [event.target.name]: event.target.files[0] // image: event.target.files[0] }); }; handleSubmit = (e) => { e.preventDefault(); const formdata = new FormData(); formdata("image", this.state.image); fetch(`https://inback.herokuapp.com/api/1/blog/image/list/`, { method: "POST", headers: { // Accept: "application/json, text/plain, */*", "Content-Type": "multipart/form-data", "Content-Disposition": "form-data", "Accept-Language": window.localStorage.i18nextLng, Authorization: "Bearer 6tEg0RinS5rxyZ8TX84Vc6qXuR2Xxw" }, body: formdata }) .then((response) => { if (response.ok) { alert("Success"); } else { alert("error"); } }) .catch((err) => { console.log(err); }); }; render() { return ( <div id="other" className=""> <p className="mod" style={{ marginTop: "10px" }}> Uplaod </p> <hr></hr> <form onSubmit={this.handleSubmit}> <input type="file" name="image" onChange={this.handleInputChange} /> <button>Submit</button> </form> </div> ); } } export default App; -
DRF - ERROR - you cannot alter to or from M2M fields, or add or remove through= on M2M fields
I am developing a twitter app, the model makes nested tweets through the parent/child approach. I don't want to create a separate class Retweet. Is there a solution to this problem? class TweetLike(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) tweet = models.ForeignKey("Tweet", on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) class Tweet(models.Model): id = models.AutoField(primary_key=True) parent = models.ForeignKey("self", null=True, on_delete=models.SET_NULL) user = models.ForeignKey('auth.User', on_delete=models.CASCADE) content = models.TextField(blank=True, null=True) image = models.FileField(upload_to='images/', blank=True, null=True) likes = models.ManyToManyField(User, default=0, related_name='tweet_user', blank=True, through=TweetLike) timestamp = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-id'] Error on ./manage.py migrate ValueError: Cannot alter field tweets.Tweet.likes into tweets. Tweet.likes - they are not compatible types (you cannot alter to or from M2M fields, or add or remove through= on M2M fields) -
Register/Login/Logout/Password Reset a User Django
Question 1: How to Register/Login/Logout/Password Reset a User. ie. I am using Django-Rest-Framework-SimpleJWT for JSONWebTokenAuthentication. Question 2: Should I use JWT Authentication in the first place? -
I have 3 models, say model A , model B and model C in django
model B is related to model A with foreign key, model C is related to model B with foreign key . How could i query and access objects of model C from model A -
Django user login is not getting logged in
def login_page(request): login_form = loginform(request.POST or None) context = { "form": login_form } print("user logged in is") print(request.user.is_authenticated) if login_form.is_valid(): print(login_form.cleaned_data) Username = login_form.cleaned_data.get("username'") Password = login_form.cleaned_data.get("password") user = authenticate(request, username=Username, password=Password) if user is not None: login(request, user) print(request.user.is_authenticated) context['form'] = loginform() # A backend authenticated the credentials else: # No backend authenticated the credentials print("error") return render(request, "auth/login.html", context) output as : user logged in is False {'username': 'asd', 'password': '123'} error -
django.template.base.VariableDoesNotExist: Failed lookup for key
I have a Django application which works fine for sometime after every deployment but after some time I get this error, [Wed Sep 09 14:05:54.904163 2020] [wsgi:error] [pid 5256] [remote 10.0.2.132:60756] django.template.base.VariableDoesNotExist: Failed lookup for key [exception_type] in [{'True': True, 'False': False, 'None': None}, {'is_email': True, 'unicode_hint': '', 'frames': [], 'request': <WSGIRequest: POST '/api/jsonws/invoke'>, 'user_str': '[unable to retrieve the current user]', and users are unable to login. It's an API only application. I am using djangorestframework==3.10.3 and Django==2.2.7. Please suggest the solution to this issue. -
How can i style the form errors of the USerCreationForm in django?
I m working on a project i have made a registration form by using USerCreationForm , I want to style the form errors cause the errors look very ugly in my template image of my form and how error looks like So what i want is that it shouldn't display that of which field the error is it should directly display the error. My registration form <form action="{% url 'registration_pg' %}" method="post"> {% csrf_token %} <div class="name-container"> <!-- < id="first_name " class="form-control" name="first_name" placeholder="first name" required> --> {{form.first_name}} {{form.last_name}} </div> <div class="username-container form-inputs"> {{form.username}} </div> <div class="student-info"> {{form.std}} {{form.div}} {{form.rollno}} </div> <div class="user-fields"> {{form.email}} {{form.password1}} {{form.password2}} </div> <div class="form-errors"> {{form.errors}} </div> <button class="btn btn-block btn-info ripple-effect" type="submit" name="Submit" alt="sign in" style="background:#0277bd;">Submit</button> </form> My forms.py file class StudentCreationForm(UserCreationForm): first_name = forms.CharField(max_length=30, widget=forms.TextInput(attrs={'id': 'first_name', 'class': 'form-control', 'placeholder': 'first name'})) last_name = forms.CharField(max_length=50, widget=forms.TextInput(attrs={'id': 'last_name', 'class': 'form-control', 'placeholder': 'last name'})) username = forms.CharField(max_length=100, widget=forms.TextInput(attrs={'id': 'username', 'class': 'form-control', 'placeholder': 'username eg (jhon16)'})) std = forms.IntegerField(widget=forms.NumberInput(attrs={'id': 'std', 'class': 'form-control stu-info', 'placeholder': 'std'})) div = forms.CharField(max_length=1, widget=forms.TextInput(attrs={'id': 'div', 'class': 'form-control stu-info', 'placeholder': 'division'})) rollno = forms.IntegerField(widget=forms.NumberInput(attrs={'id': 'rollno', 'class': 'form-control stu-info', 'placeholder': 'roll no'})) email = forms.EmailField(widget=forms.EmailInput(attrs={'id': 'email', 'class': 'form-control', 'placeholder': 'email'})) password1 = forms.CharField(max_length=100, widget=forms.PasswordInput(attrs={'id': 'password1', … -
RelatedObjectDoesNotExist at /profile/ User has no profile
I want to create a profile for each user but I received this error message and this my function in : views.py : @login_required def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES ,instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): user_from =u_form.save() profile_form= p_form.save(False) user_from=profile_form profile_form.save() messages.success(request, f'Your account has been created! You are now able to log in') return redirect('list') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) #instance=request.user.profile) args = {} args['u_form'] = u_form args['p_form'] = p_form return render(request, 'users/profile.html',args) register user : def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) why this code don't working? I'm trying to create a registration form for users. -
Responsive onesite website padding to centre
Im currently working on making onesie scrolling website but i came accross the problem. I want my text be on the centre of first "page" but i cant make it to looks good on phone and desktop at the same time. With padding-top: 50% it looks good at mobile but terrible at desktop, on the other hand padding-top: 7 looks good on desktop but not much at phone. Can someone help me finding the golden mean? my html code: <div class="main"> <section class="page1"> <h1> ABOUT ME <li class="notnav"> I am John, 19 years old computer science student. Mainly coding in python, but I am quick lerner and flexible person. I am currently intrested in Artificial Intelligence, Big Data and Design </li> </h1> <h2> <a class="read-more" href='/about'>Read More</a> </h2> </section> <section class="page2"> <h1> PROJECTS </h1> </section> <section class="page3"> <h1> CONTACT </h1> </section> my css code: section { width: 100%; height: 100vh; } .main section.page1 { background: #81D4FA; } .main section.page2 { background: #F5F5F5; } .main section.page3 { background: #81D4FA; } h1 { font-size: 8vw; color: #efefef; text-align: top; padding-top: 50%; padding-left: 15%; } h2 { list-style-type: none; font-size: 4vw; color: #efefef; text-align: center; padding-top: 2%; } a.read-more{ border: 2px solid #efefef; … -
Logging with Django : traceback too many calls
So I'm trying to do the simplest logger for my project, so I've defined the following logger : LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)-8s\t%(asctime)s\t[%(pathname)s:%(funcName)s():%(lineno)d]\n%(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': 'P:/gestion_KyliaErreurs.log', 'formatter': 'verbose', }, 'mail_admins': { 'level': 'ERROR', 'class': 'django.utils.log.AdminEmailHandler', 'formatter': 'simple' }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'ERROR', 'propagate': True, }, 'django.request': { 'handlers': ['mail_admins'], 'level': 'ERROR', 'propagate': True, }, }, } But the lineno and pathname are polluted with django exception handling : File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\core\handlers\exception.py", line 39, in inner response = get_response(request) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python34\lib\site-packages\django-1.10-py3.4.egg\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) Do you know how I could get rid of the first calls, and get only the most recent one ? Thanks ! -
Is it possible to add inlineform in User admin form?
I use Django I have a entity model that imply 3 models: User -- Profile -- Site I have register my models and User models is registered by default. I wonder if it is possible (probably it is) to insert Profile admin form inside User admin form as a inlineform? models.py class Profile(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE pro_ide = models.AutoField(primary_key = True) user = models.OneToOneField(User, on_delete = models.CASCADE) site = models.ForeignKey(Site, on_delete = models.CASCADE) ... -
Django let user retry on login popup
On the page /home I created a login button in my navbar and when you click on it it will open a kind of a popup with changing display to block. But my problem is that I cant find out how the user could stay on the page when logging in with wrong data. At the moment it just returns me to the /home page and if I click again on the navbar button the login window opens with the "error" message but I want it to either redirect me to the /home page but the login popup is still opened or just don't redirect me anywhere. Here is my part of the views.py: def post(self, request, *args, **kwargs): # form = UserCreationForm(request.POST) # print(form.errors) # <process form cleaned data> username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: print(user, "has successfully logged in") login(request, user) return HttpResponseRedirect('/recipes/all') else: messages.error(request,"Password or username is incorrect") return HttpResponseRedirect('/recipes/all') And here is the part of my HTML file: <div class="login-popup-box" id="login-popup-box"> <div class="user-card-login"> <div class="close-button-box"> <button class="close-button" onclick="document.getElementById('login-popup-box').style.display='none'" title="Close" > <i class="fa fa-close close-button-icon"></i> </button> </div> <h1 class="login-title">Login</h1> {% for message in messages %} <div class="alert … -
Getting model object context from one view to be passed on to another view
I have a django view called pending_today which displays a set of objects in the html page def pending_today(request): pending = [] pen_full = [] date = '03-Aug-2020' doctorobj = Account.objects.get(username=request.user) for model in Visitor.objects.all(): if model.doctor == doctorobj: if (model.timestamp.find(date) != -1): if model.is_completed == 'N': pending.append(model) pen_len = len(pending) for i in range(0,pen_len,3): if (i+3) < pen_len: pencol = pending[i:i+3] else: pencol = pending[i:pen_len] pen_full.append(pencol) context = { 'pending' : pen_full, 'todaydate' :date, } return render(request,'doctorvisitor/today_pending.html',context) The pending view html page objects displaying part: {% for entry in pending %} <div class="row container-fluid center"> {% for card in entry %} <div class="col-md-4"> <div class="card hvr-radial-out" style="box-shadow: 1px 3px 13px rgb(204, 202, 202);"> <div class="card-body pb-0"> <h2 class="mb-2 text-center text-uppercase" style="font-family: 'Poppins', sans-serif;">Name : {{ card.name }}</h2> <div class="text-center"> <div class="avatar avatar-xxl" style="width: 15em;height: 15em;"> <img src={{ card.image.url }} alt="..." class="avatar-img rounded-circle"> </div> </div> <br> <p class="text-center hvr-radial-out:before" style="font-family: 'Poppins', sans-serif;">Phone No : {{ card.phone_number }} <br> Temperature : {{ card.temperature }}</p> <div class="text-center"> <button type="button" class="btn btn-danger btn-rounded mb-3" data-toggle="modal" data-target="#exampleModalCenter2"> <a href="{% url 'editstatus' %}" style="color: white;">Edit Status</a> </button> </div> </div> </div> </div> {% endfor %} </div> {% endfor %} So now if they press the button,whatever … -
Django : value has the correct format (YYYY-MM-DD) but it is an invalid date
I'm working with Nepali date and the following date is correct but django don't let me run the query. search_range = Trans.objects.filter(tr_date__gte='2077-04-01', tr_date__lte='2077-04-32') I've following code which is working fine if i give date upto 2077-04-30. But according to Nepali calender 4th month has 32 days. When i try to run the query with day 32 django returns following error. ValidationError at /trans/list/search/ ['“2077-04-32” value has the correct format (YYYY-MM-DD) but it is an invalid date.'] Request Method: GET Request URL: http://127.0.0.1:8000/trans/list/search/ Django Version: 3.1 Exception Type: ValidationError Exception Value: ['“2077-04-32” value has the correct format (YYYY-MM-DD) but it is an invalid date.'] How can i get the data within mentioned range? Any suggestion is highly appreciated.