Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use SMTP to send email using python on Godaddy servers
I have build a website using django,and it uses smtp to send me a mail containing details filled out on a form on the same site,But SMTP is not working on Godaddy servers,Below is the code i used: import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMETe sender_address = 'user@gmail.com' receiver_address = 'userto@gmail.com' sender_pass = '123' #Setup the MIME message = MIMEMultipart() message['From'] = sender_address message['To'] = receiver_address message['Subject'] = 'N' #The subject line #The body and the attachments for the mail message.attach(MIMEText(mail_content, 'plain')) #Create SMTP session for sending the mail session = smtplib.SMTP('localhost', 25) #use gmail with port session.starttls() #enable security session.login(sender_addres, sender_pass) #login with mail_id and text = message.as_string() session.sendmail(sender_address, receiver_address, text) session.quit() print('Mail Sent') it just gives me the error: SMTPAuthenticationError (535, b'Incorrect authentication data') My username and password are correct,i have used localhost and port 25 as said in one of thier documentation Thanks in Advance -
How to use another python project function into your project
I'm working with Django in a project, I want to use a python function from a project in Github, I can't install this project as a library with pip install dicom-exporter because it doesn' work. The project I want to use: https://github.com/KitwareMedical/dicom-exporter/ the function I want to use : dicom-exporter <path/to/dicom/folder> <path/to/output.vti> The project contain setup.py file where there is script entry-point, Please How can use this project in my django project. -
What should I do so that the result of filter() function is the dictionary mapping result
I have a model like this: class BNetworkEdge(models.Model): id = models.AutoField(unique=True, primary_key=True) source = models.IntegerField() target = models.IntegerField() edge_type = models.IntegerField() class Meta: managed = True db_table = 'b_network_edge' I have a dictionary like this: {0:'direct', 1:'no-direct'} How do I get the function 'BNetworkEdge.objects.all()' is directly the dictionary mapping result? Thanks! -
Delete django data without RuntimeWarning: DateTimeField received a naive datetime
I am trying to delete 3 years old data in my python django db. Here is code: from datetime import datetime from dateutil.relativedelta import relativedelta def db_cleanup(): cleanup_start = datetime.utcnow().date() three_years_ago = cleanup_start - relativedelta(years=3) MyData.objects.filter(create_date__lt=three_years_ago).delete() however I receive RuntimeWarning: DateTimeField received a naive datetime . How to do it properly? -
Can someone explain to me how this code works? Django Python [closed]
I have this code here in models.py which I don't exactly know how it works. models.py: from django.db import models from django.contrib.auth.models import User class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to="profile_pic", blank=True) def __str__(self): return self.user.username The User here what does it do. Does OneToOneField link user to User. Is the user.username a table automatically created when I migrate "user = models.OneToOneField(User, on_delete=models.CASCADE)". I do understand the code somewhat but want to understand it better. Please any explanation would be much appreciated. -
"Contact Me" form that sends emails to me
I have the following HTML page: {% load static %} <!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title>Contact Me</title> <link rel="stylesheet" href="{% static 'projects/style_contact.css' %}"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <div class="container"> <div class="text">Contact Me</div> <form method="POST"> {% csrf_token %} <div class="form-row"> <div class="input-data"> <div class="underline"></div> <input type="text" name="name" required placeholder="Name"> </div> <div class="input-data"> <div class="underline"></div> <input type="text" name="email" required placeholder="Email Address"> </div> </div> <div class="form-row"> <div class="input-data"> <div class="underline"></div> <input type="password" name="password"required placeholder="Password"> </div> </div> <div class="form-row"> <div class="input-data textarea"> <div class="underline"></div> <input type="text" name="message" required placeholder="Write your message"> </div> </div> <div class="form-row submit-btn"> <div class="input-data"> <div class="inner"></div> <input type="submit" value="submit"> </div> </div> </form> </div> </body> </html> I want to be able to send emails from that form. I know that all the Email configurations need to go inside the settings.py file, but how would i make sure that the legitimate owner of that email sends the message. The form needs to get the correct password of that specific email address so that the legitimate owner is the only one who can actually send the message. Any ideas?? -
Are these (performance) concerns valid when loading images via https from an external website?
Running a website with lots of images from external websites*, I have an option to either A) Download the images myself and serving them or B) Loading them via https from the external website image URL. I'm thinking of going with option B, as it saves computations by not downloading the images. However, serving images from external websites also gives me a couple of concerns: How can I check if there actually is an image on the URL, when I don't download the image? Note: I'm using Python Will the size of the external images affect my performance? When I download the images, I can make sure that they have a specific (small) size that fits my pages. I will load a lot of images, e.g. 20 30x30 size images in a grid, on a single page. External images may be a lot larger than the intended size on my page, so I will have to implement height:30px;width:30px; or similar in the HTML. Won't the performance (page load time) take a huge hit, as the original images are actually 10x or 20x the size? Is there a way to solve this? *Note: ignore the concern of image rights, as that … -
unable to find timezone in django
What I am doing. I am working on a very basic django project. what is my problem. When I am loading my webpage (locally) it is showing following error on webpage. A server error occurred. Please contact the administrator and error that I saw on terminal is zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key utc' -
Login to django admin via requests
I want to log in on the django admin site via a python script using requests library. From another posts' answer (here) i figured using a requests.Session() would be appropriate. However upon trying the following code, i get an 403 - forbidden status code. url = 'url_to_django_admin' payload = {'username': 'some_username', 'password': 'some_password'} with reqeuests.Session() as s: r = s.post(url, data=payload) print(r) >>> <Response [403]> I checked credentials in the browser, so that should be fine. For the keys in the payload dict i tried both values of the forms input fields keys name and id (i think name would be correct) -
DRF serializer does not send the correct data from the request
I build an API endpoint that talks an image as input and print it on the screen, the problem is when I print the request.data it gives me the correct data, but when I pass this data to the serializer, DRF change it! serializer: class TestUploadImageSerializer(serializers.Serializer): images = serializers.ImageField() views: class TestUploadImageApi(APIView): def post(self, request): serializer = TestUploadImageSerializer(data=request.data) serializer.is_valid(raise_exception=True) print(f'request.data = {request.data} \n') print(f'serializer.data = {serializer.data} \n') return Response(status=status.HTTP_200_OK) I'm using Postman to send the image: This is the output for request.data and serializer.data request.data = <QueryDict: {'images': [<InMemoryUploadedFile: ikea3.png (image/png)>]}> serializer.data = {'images': None} So, the question is why serializer.data gives me these result? -
Django: I am unable to login as "user" from the user login page (after manually creating user in the admin page)
I am new to Django and created a project where a separate login page is created for the user. The user credentials are already created in the admin page under Authentication and Authorization >> Users. When I use the same login credentials in the user login page and click "Log In" button, it redirects to the login page again and shows invalid credentials even for correct credentials. Please tell me if I am missing something as I am not able to sort this out after so much research. Project name - Project1 and App name- Authenticator my signin.html file: my settings.py file: from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent SETTINGS_PATH = os.path.dirname(os.path.dirname(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-kr5x253ks#bh&l&7sv11(43#i)v@h-du3$649*9ci@-0*bj4do' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'Authenticator', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Project1.urls' TEMPLATES = [ { 'BACKEND': … -
Can I interrupt Celery task by another one?
I have a view in my project that runs a Celery task on user registration. The task checks if user is verified 3 days after registration: @shared_task() def delete_user_if_not_verified(user_pk: int): user = User.objects.get(pk=user_pk) email = user.email if not user.is_verified: user.delete() return f'Delete {email} user' My idea is that this task will be interrupted with another one in case if user verified much earlier, right after registration, for example. I've already figured out how to catch changes in database but I just don't know how can I pass task or user id of the user that verified to delete_user_if_not_verified(). Is this possible or this idea is bad and I'll be good with one task? -
How to make individual product subscription for the same user in django
I have a website that has some services that has to be subscribed individually. The user has to subscribe the services he wants to avail. Now there are three plans for subscription monthly, quaterly and half-yearly. The user has to choose one of them individually for each service he is opting for. For example, I have three services civil, tax, criminal. Now a user can choose to subscribe Civil for 1 month and Criminal for 6 month hence these will expire too individually. Based on the services he has choosen he will get menus once he logs in. Below is the approach I took to make the models. models.py SUB_CHOICES = ( ('monthly', 'monthly'), ('quaterly', 'quaterly'), ('hf', 'half_yearly'), ('anually', 'anually'), ) class ServiceProduct(models.Model): title = models.CharField(max_length=50, null = True) code = models.IntegerField(null=True, unique= True) price = models.DecimalField(max_digits=10,decimal_places=2,null=True) def __str__(self): return self.title class UserSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) service_choosen = models.ForeignKey(ServiceProduct, on_delete=models.CASCADE, null=True) is_active = models.BooleanField(default= False) subscribed_on = models.DateTimeField(null=True) expiring_on = models.DateTimeField(null=True) Here i connected the usermembership model to customuser with foreign key to make multiple subscription for the same user having is_active class that shall toggle based on the subscription dates and expiring dates. The ServiceProduct models stores the … -
Python Django AttributeError at /visual
Django problem occured while using yfinance python module and requesting a ticker data. 'Index' object has no attribute 'tz_localize' -
Django redirect problems
I'm new in Django and I'm having problems with redirect the user after authorization. Here is 200 code in the console. def user_login(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("test") else: messages.error(request, "Invalid username or password.") else: messages.error(request, "Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form": form}) [27/Jan/2022 14:41:26] "POST /account/login/ HTTP/1.1" 302 0 [27/Jan/2022 14:41:26] "GET /account/test/ HTTP/1.1" 200 136 the same with redirect(reverse("test")) -
Django REST Framework Serializer Initialize variable in init
I am trying to initialize a django model's object inside a Serializer class. Lets say I have 2 models ABCD and WXYZ. I performed a filter on ABCD and send the results to a serializer. The serializer need to get an instance of WXYZ model using a field of ABCD model, and fetch some result. I want to get the WXYZ instance in the init method, so that I can access that across all functions in the serializer class. Models: class ABCD(): col1 = models.Integerfield(...) ... class WXYZ(): col2 = models.Integerfield(...) title = models.Charfield(...) ... views.py: # performed a filter on ABCD model abcd_objects = ABCD.objects.filter(...) results = ABCDserializer(abcd_objects, many=True).data serialzers.py class ABCDserializer(serializers.ModelSerializer): title = serializers.SerializerMethodField('fetch_title') ... def __init__(self, obj): ans = WXYX.objects.get(col2=obj.col1) self.wxyz_obj = ans def fetch_title(self, obj): return self.wxyz_obj.title class Meta: model = ABCD fields = ['title', ...] -
How to generate an id for a newly created model instance using django and DRF?
I am trying to figure out how to create instances of a model in my view. I have written a method in a class outside the view, that I am using to generate a random id for the model instance to be created: def generate_random_id(self, MyModel): """ Picks a random id for an object to be created in POST""" random_object = None if random_object is None: random_object = random.randrange(1, MyModel.objects.all().count() + 1) while MyModel.objects.all().filter(id=random_object).exists(): random_object = random.randrange(1, MyModel.objects.all().count() + 1) return random_object This method has worked for other model instances. I think the problem is in the view itself. views.py ... tag = Tag.objects.create( id=controller.generate_random_id(Tag), name='randomlycreatedtagfor test', language='de') ... I keep getting this error: duplicate key value violates unique constraint "app_tagging_pkey" DETAIL: Key (id)=(57949) already exists. However, here is my code for the model and the serializer. Maybe this is where I am doing something wrong. models.py class Tag(models.Model): name = models.CharField(max_length=256) language = models.CharField(max_length=256) objects = models.Manager() def save(self, *args, **kwargs): if not self.id: self.created = timezone.now() return super().save(*args, **kwargs) def create(self, validated_data): tag_data = validated_data.pop('tag') Tag.objects.create(**tag_data) return tag_data def __str__(self): return self.name or '' serializers.py class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag fields = ('id', 'name', 'language') def … -
Fetch API does not render views from django
This might be a beginner question, I'm new to Django. So I'm trying to create a login button where it would return an HttpResponse and I'm trying to get the strings from the response. I tried printing the result from fetch and it did seem to response with code 200 but for some reason I'm not able to get the content from the HttpResponse. Here's my javascript used to fetch the /login/ url: login-script.js function normalLogin(){ fetch("/login/", { method: "POST", headers: { "X-CSRFToken": getCookie("csrftoken"), 'Accept': 'application/json', 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/json' }, redirect: 'follow', }).then(res => { console.log("Request complete! response:", res); // location.reload(); }); Here is also the code used to redirect users to the dashboard. views.py def login(request): if request.method == "POST": return HttpResponse("Here's a text") I'm trying to get the string from the HttpResponse but to no avail, it returns undefined. I tried res.body and res.header. I also looked at this but it does not work for me. Is there something I did wrong or mistake I make without realizing? Thanks Fetch API post data not receiving in Django view Getting HttpResponse in Django from Javascript fetch -
Django model fields not dynamic
I have this in my models. class School(models.Model): subscribed = models.BooleanField(default=True) invoice_date = models.DateField() remaining_days = models.IntegerField(default=30) def save(self,*args,**kwargs): self.remaining_days = (self.invoice_date - date.today()).days if self.invoice_date <= date.today(): self.subscribed=False else: self.subscribed=True return super().save(*args,**kwargs) The problem is the remaining days do not change dynamically. I thought it would when I was coding this. How can I make it change each new day??? -
Django - category and slug in url
I have a function that addds article to favourites when user hits the button. Everything was fine until I decided to add category to url address. Below you can see the code that I am trying to debug. models.py class Article(models.Model): author = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) title = models.CharField(max_length=254) category = models.ForeignKey(Category, on_delete = models.CASCADE, blank=True, related_name='articles') favourite = models.ManyToManyField(User, default=None, blank=True, related_name='favourite_article') slug = models.SlugField(unique=True, blank=True, max_length=254) def get_absolute_url(self): return reverse("article", kwargs={"category": self.category, "slug": self.slug}) views.py @login_required def FavouriteArticle(request, slug): article = get_object_or_404(Article, slug=slug) favourized = False if article.favourite.filter(id=request.user.id).exists(): article.favourite.remove(request.user) favourized = False else: article.favourite.add(request.user) favourized = True messages.success(request, 'Article is now available in favourites.') return HttpResponseRedirect(reverse('article', args=[str(category), str(slug)])) url.py urlpatterns = [ path('favourite_article/<category>/<slug:slug>', views.FavouriteArticle, name='favourite_article'), ] Could you please let me know what am I doing wong? -
Why is searching in <200 categories slower than searching in >6000 products?
Using line_profiler library to analyse my Django Ecommerce project, I find that searching in less than 200 Product Categories is slower than searching in over 6000 Products. As you can see in the image below, using a .get() method on the ProductCategory objects takes more than double the time of using .filter() on the Products, even though the Product.filter has to look through a list of values (categories__in). Does anyone have an idea as to why this is? :-)) -
I want to send SMS to the registered user regarding weather from fast2sms api
I want to sent SMS to all the registered users that have been saved in the extendeduser table.This table contains users phone number , so weather inforamtion is been getting from openweatherapi and if any city has weather conditions as overcastclouds then all the users will be sent SMS using fast2sms api as you can see the code def printit(): threading.Timer(10, printit).start() for i in user_data: city = i['town'] src = 'http://api.openweathermap.org/data/2.5/weather?appid=APP_ID=' url = src + city list_of_data = requests.get(url).json() temp = list_of_data['main']['temp'] newtmp = round(temp - 273.15, 3) condition = list_of_data['weather'][0]['description'] humidity = list_of_data['main']['humidity'] data = { "city": city, "temp": newtmp, "humidity": humidity, "condition": condition, "icon": str(list_of_data['weather'][0]['icon']), } print(data) if data['condition']=="overcast clouds": euser = extendeduser.objects.values('phone', 'user') q=[] for j in euser: q.append(j['phone']) url = "https://www.fast2sms.com/dev/bulk" querystring = {"authorization": "API_KEY", "sender_id": "ANNADATA", "message": "Overcast Clouds Seen", "language": "english", "route": "p", "numbers":q} headers = { 'cache-control': "no-cache" } response = requests.request("GET", url, headers=headers, params=querystring) print(response.text) print('\n'+city,' user '+str(i['user'])+' overcast condition',end='\n') printit() -
Django display every model owned by user
I have a HTML template file and in this file is the ticket itself (Ticket Model) and need I to display messages that belong to each ticket (TicketMessages Model). How can I do the following: -display me all TicketMessages (messages) that belong to this specific ticket. I need to get the current Ticket then display every user_message of this ticket? Models File class Ticket(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) title = models.CharField(max_length=200) description = models.TextField() ...... def __str__(self): return str(self.id) class TicketMessages(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, default=None, null=True, on_delete=models.CASCADE, ) ticket = models.ForeignKey( Ticket, default=None, null=True, on_delete=models.CASCADE, ) admin_message = models.CharField(max_length=200, blank=True) user_message = models.CharField(max_length=200, blank=True) The Views File already gives me the ID of the current ticket def ticket_system_view(request, id): obj = Ticket.objects.get(id=id) if request.method == 'POST': user_form = TicketMessagesForm( request.POST, instance=TicketMessages(ticket=obj, user=request.user)) if user_form.is_valid(): form_save = user_form.save(commit=False) form_save.ticket = obj form_save.save() else: user_form = TicketMessagesForm() return render(request, 'ticket-system.html', {'obj': obj, 'user_form': user_form, }) My attempt looks like this in the template {% for i in request.user.ticketmessages_set.all %} <div> {% if ... %} {{ i.user_message }} {% endif %} </div> <br /> {% endfor %} The loop displayed nothing and secondly I would get all the … -
How to get time from user for work a function in Django
I write a app and this get price (priceapp) and news (newsapp) form several site. I want get a time like "daily 12:00" or "after 6 h" from user and send this price and news to telegram or other app selected from user. How I set time for get information and how to send result to users. -
how get only fields in django serializers
i used django.core.serializers to get data from model as below code from django.core import serializers ... serializers.serialize('json',production_time.production_items.all()) and i get response as below: [{"model": "BorseBots.exchangemonthlyproductionitem", "pk": 1308, "fields": {'name':'jack',...}} , ...] but i do not need 'model' and 'pk' fields so expect below: [{'name':'jack',...} , ...] or [{"fields": {'name':'jack' , ...}} , ...] how get this? need use loop to extract data in new list? using django2.2.* python3.8