Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
Configure nginx/gunicorn django behind a load balancer
I set up an nginx/gunicorn server with this tutorial. This worked like a charm with a local docker-compose file. Then I pushed the containers to AWS fargate, and set up a load balancer in front of the nginx. This worked too, but I got a "CSRF failed" exception, when trying to login to django admin. This is because the host, port and protocol are not correctly forwarded from the user request though the load balancer and the nginx proxy to django gunicorn. How do I have to configure nginx and django? -
django channels function call not working
I am trying to implement a user notification feature. I update the user's status after he has connected to a room, but when I call self.update_user_incr(self,self.user,1) or self.update_user_decr(self.user,0) nothing happens. Why can't I call any function? What am I missing? consumers.py: class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name self.user = self.scope["user"] print('connect') self.update_user_incr(self,self.user,1)// not working ?? # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): print('disconnect') self.update_user_decr(self.user,0)// not working ?? # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'user': str(self.user), 'time' : str(localtime().now().strftime("%I:%M%p")), } ) # Receive message from room group async def chat_message(self, event): message = event['message'] username = event['user'] time = event['time'] print(self.user.username) # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username' : username, 'time' : str(time), })) @database_sync_to_async def update_user_incr(self,user,num): print('increment') Profile.objects.filter(pk=user.pk).update(status=num) @database_sync_to_async def update_user_decr(self,user,num): Profile.objects.filter(pk=user.pk).update(status=num) -
How to connect Kafka consumer to Django app? Should I use a new thread for consumer or new process or new docker container?
I have Django app which should consume Kafka messages and handle it with my handlers and existing models. I use https://kafka-python.readthedocs.io/en/master/usage.html library. What is the right way to connect KafkaConsumer to Django app. Should I user a new daemon thread? Or a new process? Or a separate docker container maybe? Where to place the code (new Django app?) and how to start it automatically when Django app is ready. And how to update topics which it listen dynamically: should I kill old consumer and start new one each time in new thread? -
How to get an image from the server with django and graphql?
I already managed to make the mutations to upload, update and print the images. But how can I get the images files on in base64 in the query? class Image(models.Model): image = models.ImageField(blank=True, null=True, upload_to="uploads/images") product = models.ForeignKey(Product, on_delete=models.CASCADE, blank=True, null=True) -
Django, Assigning FileField value without saving
I am trying to assign a file from URL in django without automatically save after i initialize the object "household_profile" import urllib.request #___________________________________________________________________ # to hold all unsaved collection "household_profile" #____________________________________________________________________ of_household_profile_collection = []; for per in data["results"]: download_url = per['_attachments'][0]['download_url']; opener = urllib.request.build_opener() opener.addheaders = [('Authorization', Authorization)] urllib.request.install_opener(opener) attachment = urllib.request.urlretrieve(download_url); attachment_fname = os.path.basename(download_url) of_household_profile = household_profile( kobo_user_id=per['_id'], first_name=per['First_Name'], last_name=per['Name'], middle_name=per['Middle_Name'], phone_number=per['Mobile_Number'], email=per['Email'], purok=per['Purok'], barangay=per['Barangay'], qr_id=per['_uuid'] ); of_file = open(attachment[0]); #___________________________________________________________________ # i just want to assign it for a purpose not to save it automatically #____________________________________________________________________ of_household_profile\ .verification_file\ .save(attachment_fname, File(of_file)) Is there way that i should know ? -
Django admin not working on server after adding 'django.contrib.sites'
Site was working fine on local server. But the same thing when deployed on server. Admin CSS misbehaves Admin panel screenshot on server admin panel site also working fine on mobile responsive view -
How can i create multiple django project on pycharm without one conflicting with other port
I create a django project called Polls and i have one project called registration but anytime i run my polls server it always go to the registration server and display things there also my migrations doesnt go to the polls server -
Deleting values connected to each other in the database
My database models.py looks like this: class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() slug = models.SlugField(unique=True) description = models.TextField() quantity = models.IntegerField(default=1) class Bike(models.Model): item = models.OneToOneField(Item, on_delete=models.CASCADE) image = models.ImageField(upload_to='bikes') When I am deleting an entry in the table Item it also deletes everything that is associated in the table Bike. But when I am deleting an entry in the Bike table it doesn't delete any data in the Item table. Is there any possible way to delete all data in the Item table, when you delete an entry in the Bike table? -
How to check if field is unique in models of Django?
I'm new to Django. In car/models.py, I'm creating a new class: class Car(models.Model): name = models.CharField(max_length=100) This is being created in the admin section of Django. I want name to be unique. How can I verify that this name was not already used? -
Access Django API via Heroku returns "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in request."
I deployed my Django project on Heroku with gunicorn. It's basically only the api (no templates). When I deploy heroku and access <heroku url>/api/login for example in the browser and post login data already in json format, it always returns "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in request." But when I do the same on localhost, the user gets authenticated and I receive a response with user data... post data example for login: { "email": "ana@test.com", "password": "ana1234567890" } The parser_classes = [JSONParser] is added on every view where I don't have images or files (there I am using FileUploadParser). I deployed on Heroku with gunicorn, because on localhost I permanently received "Unauthorized" from backend ( Permission Class is "isAuthenticated" for most of my views). After some research I figured out that probably the authorization header is not sent (here the APACHE WSGIPassAuthorization On would be a solution) but I don't have an apache server running and I don't want no webserver running on my machine. I thought if I would deploy it on heroku with gunicorn, I could continue with the development without the "Unautorized" header but instead I run in other errors, like "detail": "Unsupported media type \"application/x-www-form-urlencoded\" in …