Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can you print the scrapped values in a paragraph format? Django
One quick question. I'm building a scrapper that outputs emails. For now the emails get printed in a CSV file. But I want the emails to be outputted in a paragraph format on another URL. I've tried doing some things but it doesn't work out. Here is the code: views.py from django.shortcuts import render from django.shortcuts import render from . scrapper import EmailCrawler def index(request): return render(request, 'leadfinderapp/scrap.html') def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) crawl.crawl() return render(request, 'leadfinderapp/results.html') Here is the html fie where I'm trying to output the emails (ignore the code) (results.html): {% load static %} <html> {% for email in scrap %} <p>{{ result }}</p> {% endfor %} </html> -
django-allauth not redirecting me to the next page after
I'm working with Django 3.0.9 and the django-allauth 0.42.0 package. I've implemented the login, signup, reset password and logout pages. And in all of them, when I click the corresponding form button, I'm not being redirected to the next page. However, the action is being done -- if I refresh the page manually I can see I'm logged in/out, etc. I'm not getting any error or warning message anywhere, anytime, either from the browser of from the Django logs. This is how my code looks for the login page, for example. I'm stripping away lots of CSS, HTML, etc. for clarity: login.html: {% load static i18n %} {% load i18n %} {% load account socialaccount %} {% load crispy_forms_tags %} {% get_providers as socialaccount_providers %} {% if socialaccount_providers %} <p>{% blocktrans with site.name as site_name %}Please sign in with one of your existing third party accounts. Or, <a href="{{ signup_url }}">sign up</a> for a {{ site_name }} account and sign in below:{% endblocktrans %}</p> <div class="socialaccount_ballot"> <ul class="socialaccount_providers"> {% include "socialaccount/snippets/provider_list.html" with process="login" %} </ul> <div class="login-or">{% trans 'or' %}</div> </div> {% include "socialaccount/snippets/login_extra.html" %} {% else %} <p>{% blocktrans %}If you have not created an account yet, then please … -
Django elasticsearch - how to implement functional (non-native to Elasticsearch, but common in Django) filters/lookups?
I am integrating elasticsearch into my Django project. Currently, it works to find the exact match only: s = MovieDocument.search().query("match", title=search_query) But I want to be able to use Django's contains. How should I modify my document to do this? @registry.register_document class MovieDocument(Document): class Index: # Name of the Elasticsearch index name = 'movie' # See Elasticsearch Indices API reference for available settings settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Movie # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'title', ] -
Send Email From Logged in User Django
Let’s suppose I have an app where all users have an email address and password in the User model. And let’s also also assume that all the users use the same email host and port. Is it possible to set the EMAIL_HOST_USER and EMAIL_HOST_PASSWORD shown below to be variables that pull from the user model? This way when a logged in user uses an email sending functionality, it comes from their email instead of some single email account defined in settings.py as shown below? ‘’’ EMAIL_HOST = 'smtp.sendgrid.net' EMAIL_PORT = 587 EMAIL_HOST_USER = 'parsifal_app' EMAIL_HOST_PASSWORD = 'mys3cr3tp4ssw0rd' EMAIL_USE_TLS = True ‘’’ -
IntegrityError at /new_entry/3/ NOT NULL constraint failed: learning_logs_entry.user_id
[enter image description here][1] [1]: https://i.stack.imgur.com/84zxH.png(Please see the picture) My new_entry() function was working fine lately but now it is not saving the form and shows error at new_entry.save(). I don't understand why the error is happening. My function def new_entry(request, topic_id): """Add a new entry for a particular topic""" topic= Topic.objects.get(id=topic_id) if request.method != 'POST': #No data submitted: create a blank form. form = EntryForm() else: # POST data submitted ; create a blank form. form = EntryForm(data=request.POST) if form.is_valid(): new_entry= form.save(commit=False) new_entry.topic = topic new_entry.owner=request.user new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html',context) My models. from django.db import models from django.contrib.auth.models import User # Create your models here. class Topic(models.Model): """A topic user is learning about""" text=models.CharField(max_length=200) date_added=models.DateTimeField(auto_now_add=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about the topic""" topic=models.ForeignKey('Topic',on_delete=models.CASCADE) text=models.TextField() date_added=models.DateTimeField(auto_now_add=True) user= models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural='entries' def __str__(self): """Return a string representation of model""" return self.text[:50] +"..." my template {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <p> <a href="{% url 'learning_logs:new_entry' topic.id %}">add new entry</a> </p> <ul> {% for entry in entries %} … -
Django DateTime Issue - Server ahead of timezone
I was working on an app and I can't solve the issue of date and time. In setting.py file I have set the timezone to UTC. TIME_ZONE = "UTC" USE_I18N = True USE_L10N = True USE_TZ = True I live in UTC+05 so when I publish a blog the date and time is 5 hours into the future so the blog can only publish after 5 hours. Is there a way to automatically detect the time zone of users to either add or subtract hours relative to UTC or anything that can automatically solve this issue. models.py class blog(models.Model): blog_text = models.CharField(max_length=1000) pub_date = models.DateTimeField("date published") def __str__(self): return self.blog_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now was_published_recently.admin_order_field = "pub_date" was_published_recently.boolean = True was_published_recently.short_description = "Published recently?" -
Using a model manager isn't working but querying using a filter in in the view does, where am I going wrong?
I am trying to create a view to show all friend requests for a user. I am able to render the requests in a view if I use a plain filter method but moving to the model and using a model manager doesn't find the objects that are found by the filter method in the view. To me, they seem the same, so I must be misunderstanding something. Trying to use the model manager in the view to query, the query doesn't return anything like so: profile = get_object_or_404(Profile, user=request.user) rec_req = FriendRequest.objects.received_requests(to_user=profile.user) However, if I use the filter method in the view directly I get the objects like so: profile = get_object_or_404(Profile, user=request.user) rec_req = FriendRequest.objects.filter( to_user=profile.user ) #models.py class FriendRequestManager(models.Manager): def received_requests(self, to_user): rec_req = FriendRequest.objects.filter(to_user=to_user, status='requested') return rec_req class FriendRequest(models.Model): to_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_user') created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=9, choices=STATUS_CHOICES) is_family = models.BooleanField(default=False) objects = FriendRequestManager() I'd really appreciate the help because I am stuck. TIA -
Django User model overrides profile picture and menu data
I created a view to display user profiles. The associated view grabs the username parameter from the URL and gets the user using the get_queryset() function. The problem is: I have the profile picture of the currently logged in user displaying at the top right of my menu as well as a link to their profile. Now, if I type in a username in the webbrowser[!, I successfully land on their profile but at the same time, the profile picture inside the menu as well as the link which should direct the user to their own profile gets overwritten with the data from the user profile that is currently displayed. Below is the class that I use to display a user profile. class ProfileView(LoginRequiredMixin, DetailView): model = User template_name = 'users/profile.html' def get_object(self): return get_object_or_404(User, username=self.kwargs.get('username')) def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return User.objects.filter(username=user).first() Here is a picture of the menu as a reference. I use the user.username object inside my template to display the link of the currently logged in user. Now, I found a way to basically fix this problem by using the request.user.username which successfully shows me the link and the profile picture of the currently logged … -
how make a conditions in django annotate?
i'm, trying to do something like this : c = if x > y return x else return y inner annotate function class factura (models.MODEL): price = Model.integerField(max_length=50, null=False) articles = Models.charField(Max_length=50, default=0, null=False) iva = Models.integerField(max_length=50) discount = Model.integerField((max_length=50) factura.objects.annotate( total = if total_articles > price return iva else return thnks -
Module Not Found Error inside virtual environment
I am working on a project inside virtual environment and suddenly I got this error: (env) D:\django3_by_example\env\Scripts>pip install markdown3.2.1 Traceback (most recent call last): File "c:\users\lenovo\appdata\local\programs\python\python39\lib\runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\lenovo\appdata\local\programs\python\python39\lib\runpy.py", line 87, in run_code exec(code, run_globals) File "D:\django3_by_example\env\Scripts\pip3.exe_main.py", line 4, in ModuleNotFoundError: No module named 'pip' It was working fine till now and after a moment it gave me this error. I checked the path from 'where pip' command and it showed me its installed inside virtual environment. -
Issue with dates when displaying on Page
The issue I have is the following: When I display dates on the page, they show up 1 day less than what is stored on the database. How do I fix this issue? -
DjangoRelatedObjectDoesNotExist at /profile/
I've been through in similar topics for days for a possible solution, however none of them solved my issue which seems pretty simple to me but I stucked on this error right after I created a user: RelatedObjectDoesNotExist at /profile/ Error I'm getting I know there must be something missing in my singlas.py which does not create the Profile after creation of a User but I'm lost in solutions after tried many. Any help will make my day after long frustration period; In project main folder; settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '7aa*ng4p*o!9h4%hyfgu=9xy69aumg6hzbz3g)1mf^4!+gi+e0' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition DEFAULT_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'apps.daily_brief', 'apps.users', 'apps.crm', ] THIRD_PARTY_APPS = [ 'crispy_forms', 'django_cleanup', 'social_django', ] LOCAL_APPS = [] INSTALLED_APPS = DEFAULT_APPS + THIRD_PARTY_APPS + LOCAL_APPS 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', 'social_django.middleware.SocialAuthExceptionMiddleware', ] ROOT_URLCONF = 'project_folder.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR … -
Email confirmation class view
I'm currently trying to display a confirmation html page when a user clicks the link in their email. The URL I send in the email is http://localhost:8000/confirm/?email=hello@example.com&conf_num=639836786717 My class view for this, in order to validate if it's the right conf_number and email is as such class ConfirmView(DetailView): template_name = 'confirm.html' def get(self, request, **kwargs): context = super(ConfirmView, self).get_context_data(**kwargs) email = request.GET['email'] sub = Newsletter.objects.get(email=email) if sub.conf_num == request.GET['conf_num']: sub.confirmed = True sub.save() action = "added" else: action = 'denied' context["email"] = email context['action'] = action return context but I get this error AttributeError: 'ConfirmView' object has no attribute 'object' now I'm unsure that's because I'm calling Super on my custom class view? -
Django - jinja syntax help - how do i pass the value of {{ title }} into the href url args?
so i have this html : {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} <h1>{{ title }}</h1> {% autoescape off %} <p>{{ entry|safe }}</p> {% endautoescape%} <br> <a href="{% url 'edit' 'cat' %}"><button type="button" name="button">Edit</button></a> {% endblock %} i want the url 'edit' to also get the value of the {{ title}} - instead of 'cat' ..i just used this value to test the rest of the code, but i don`t want to hard code it like that ... here are my urls.py: urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.title, name="title"), path("edit/<str:title>", views.edit, name="edit"), path("error/", views.error, name="error"), path("new/", views.new, name="new"), ] this is the code in views.py : def title(request, title): entry = util.get_entry(title) if entry == None: return redirect("error") entry_html = md.convert(entry) return render(request, "encyclopedia/title.html", { "entry": entry_html }) def edit(request, title): if request.method == "POST": # get the changes from the user form = EditEntryForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] # save the entry and redirect to the updated page util.save_entry(title, content) return redirect("title", title=title) else: redirect("edit", title=title) entry = util.get_entry(title) form = EditEntryForm(initial={'content': entry}) return render(request, "encyclopedia/edit.html", { "form": form }) as i said the code … -
Create unique id by combining Charfield and ForeignKey from other model
I am having trouble with setting up the flow of my site with manytomany relationships. For example, there are many models that have many types and vice versa. I am thinking I can circumvent this by creating variables that literally link the model to type to let it be used as a foreign key by another model. However, I am having trouble pulling the values. If there is an easier way to solve this problem please let me know! class typed(models.Model): typed = models.CharField(max_length=200, help_text='Enter MFG - Type') model = models.ForeignKey('model', on_delete=models.SET_NULL, null=True) model_type = model + typed def get_absolute_url(self): return reverse('typed-detail', args=[str(self.model), str(self.model_type)]) def __str__(self): return self.model_type I get this error: TypeError: unsupported operand type(s) for +: 'ForeignKey' and 'CharField' -
Django, allow business admin to set 12/24 hour clock?
Hi everyone I am working through a issue I've been dealing with to allow business admin to change their company's system time clock from either 12 hour to 24, and vice versa. I have tried a couple different ways, but unable to find a way to display the change in the view. I have 2 views, a basic display View and an UpdateView class DateTimeConfig(View): def get(self, request): business = Business.objects.filter(**get instance here) business_tz = business.timezone # Default to 12 hour clock current_time = datetime.datetime.now().strftime(f"%m/%d/%Y, %I:%M%p") context = { 'timezone': business_tz, 'current_time': current_time } return JsonResponse(context, status=200) class DateTimeConfigUpdate(UpdateView): model = Business form_class = SystemUpdateForm def get_object(self, queryset=None): business = self.get_queryset().filter(**get instance here) return company def form_valid(self, form): form.save() return JsonResponse({'message': 'Business date/time updated successfully.'}, status=200) I have a simple form here, to change the Timezone and a dropdown for 12, or 24. class SystemUpdateForm(ModelForm): clock = forms.ChoiceField(choices=(('12', '12'), ('24', '24'))) class Meta: model = Business fields = ['timezone', 'clock'] def save(self, commit=True): if self.cleaned_data.get('clock') == '24': logger.debug('24 hour clock') else: logger.debug('12 hour clock') Now, I know the form does work, because the appropriate logged message changes based on the 12, and 24 dropdown. My issue is figuring a way … -
How do I implement multiple user types with Django-allauth
I am trying to implement multiple user types in Django-allauth while using a Profile model. How do I g about it? I am creating a model StudentProfile with a OnetoOne relationship with the User model. How do I have both forms on the same template, and save them both (and also check for errors in both forms? -
How best to capture variables from within a for-loop in Django template
I have two querysets: type and age_group. type queryset: <QuerySet [<Type: Cat>, <Type: Dog>, <Type: Other>]> age_group queryset: <QuerySet [<AgeGroup: Young>, <AgeGroup: Baby>, <AgeGroup: Adult>, <AgeGroup: Senior>]> I loop through these from within my template form so that I can grab the pk when one has been selected, but I cannot capture the variable from within the for loop. How do I capture a variable from within a for loop when using Django? Template: {% extends 'base.html' %} {% block content %} <h1>Animal Search</h1> <form class="form-inline" action= '.' method="post"> {% csrf_token %} <select name= "TypeSearch" class="custom-select my-1 mr-sm-2" id="animal_list_type"> <label class="sr-only type" for="animal_list_type">SEARCH</label> {% for i in animal_type_list %} <option value="{{i.pk}}">{{i}}</option> #how to capture the selected pk?? {% endfor %} </select> <select name="AgeSearch" class="custom-select my-1 mr-sm-2" id="animal_list_ageGroup"> <label class="sr-only ageLabel" for="animal_list_ageGroup">SEARCH</label> {% for j in age_group_list %} <option value="{{j.pk}}">{{j}}</option> #how to capture the selected pk?? {% endfor %} </select> <input type="submit" value="SEARCH" onclick="window.location='{% url 'animals:matches_list' pk=4 %}'; return false;"> <input type="submit" onclick="window.location='{% url 'animals:animals' %}'; return false;" value="Cancel"> </form> {% endblock %} Outside of Django, this would be a simple problem to solve. How do I capture a variable from within a for loop when using Django? I have tried … -
Django Product Filter Queryset
my current problem is that when a customer accesses my product page, I want them to first see all the available colors for the product and then after they select the color, I want them to see all the sizes in which the product is available in that color. In my database I store the data with the following model: class Stock(models.Model): class Meta: unique_together = (("product","color","size"),) product = models.ForeignKey(Product, on_delete=models.CASCADE) color = models.ForeignKey(Color, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.CASCADE) stock = models.PositiveIntegerField() -
django-allauth Google login not working on iOS
I'm building a PWA with django and have this issue with django-allauth Google login. Everything works well on a Windows PC with Chrome and Edge. But when trying to login with Google on iOS devices, I get the social network login failure with code: 'unknown', exception: 'PermissionDenied()' Any ideas what could be the reason or where to search for it? -
No ready() function when starting django with uvicorn
I have a problem because when starting a Django application by uvicorn, Django's AppConfig don't seem to be running ready() function. Can you help me to overcome this problem? -
How to make DecimalField use only whole numbers in some cases?
class TransactionHistory(models.Model): from_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='from_account' ) to_account = models.ForeignKey( 'Account', on_delete=models.CASCADE, related_name='to_account' ) amount = models.DecimalField( max_digits=12, decimal_places=2, ) created_at = models.DateTimeField(default=timezone.now) I am using a DecimalField to represent account's balance. It's ok if I want to represent USD using it, but if I want to represent currencies like BTC, I need to save it as an integer, representing it as the number of satoshi. Also I could use decimal_places=6 to represent bitcoin, but how to make decimal_places set dynamically, based on account currency? -
How can I fetch data where my condition uses data from another row of same table?
I have this table: | id | created_at | updated_at | visited_page | visited_date | user_id | +----+----------------------------+----------------------------+-------------------+--------------+----- | 1 | 2020-12-28 18:09:40.243560 | 2020-12-28 18:09:40.244170 | 1 | 2020-12-28 | 78557 | | 2 | 2020-12-28 18:10:41.290824 | 2020-12-28 18:10:41.291217 | 1 | 2020-12-29 | 78557 | | 3 | 2020-12-28 18:19:36.948853 | 2020-12-28 18:19:36.949289 | 3 | 2020-12-29 | 78557 | +----+----------------------------+----------------------------+-------------------+--------------+----- Here I want to fetch user_ids where the updated_at difference between two different pages visited by the same user is greater than 6 minutes on a particular date (in above tables case date = 2020-12-29). Please answer how can I fetch this information using a single query in Django? Also, please explain how this query will look in SQL? -
Django - Deduplicate based on multiple attributes
I have a model representing an answer (can be correct or incorrect) to a question. A user might give multiple incorrect and multiple correct answers. class Answer(models.Model): match_event_id = models.UUIDField( primary_key=True, default=uuid.uuid4 ) user_profile = models.ForeignKey(UserProfile, null=True, on_delete=models.SET_NULL) test_session = models.ForeignKey(TestSession, null=True, on_delete=models.SET_NULL) question = models.ForeignKey(Question, null=True, on_delete=models.SET_NULL) # The actual text answer provided by the user event_text = models.TextField(default="") # Indicate if the answer is correct or not match_success = models.BooleanField(default=False) # Client name client = models.TextField(default="Unknown") I'd like to create a query which counts the number of correctly answere questions but not the number of correct answers. Currently my basic query looks like this: count_success = Answer.objects.filter(user_profile=self.user_profile_id, match_success=True).count() This gives me the number of all correct answers but since there might be multiple correct answers per question this is not what I want. How can I do some kind of deduplication based on user_profile, test_session, question and match_success? So whenever there is one correct answer by the user to one question in a test session I'd like to add 1 to the count. Thank you !! -
Django: using data from entries for many views functions
I'm new in Django and now I'm working on my first project. My home.html file includes form (bootstrap class) with contains entries to fill with data. These data are integer type. In views, in function home, where this home.html file is used , data from entries are taken by 'get' method and used for calculations and results are displaying in labels in mentioned form. My question is how can I use these data from entries or results of calculations or both of them by another function in views called some_view with generates PDF file using ReportsLab. Thanks home.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous"> <title>Title</title> <style> body { margin: 40px } .my-container { border: 1px solid green} .my-row { border: 2px solid blue} .my-col { border: 2px solid red} btn-primary { margin-left: 50px} .align-right { text-align: center; border: 0; } </style> </head> <body> <div class="container my-container"> <form method="get"> <div class= "row my-row"> <div class="col-3 my-col"> <input type="text" placeholder="0" name="li200" size="1" /> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if liczba %} {{ liczba }} {% endif %} </span></h3> </div> <div class="col my-col"> <h3><span class="badge badge-secondary"> {% if ls %} {{ ls }} {% endif %} …