Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do you implement Django namespaces
I have started my journey with Django and I am thoroughly loving it. I do have a question about namespaces which I hope someone will be able to help me with and explain why it works like that. I understand namespaces are used to make sure that if you have two pages with the same name that the url and reverse function points to the right page. I have been trying to implement namespaces in a test app I am writing but have not been able to do it. Here is what I have so far (This is without namespaces as I haven't been able to get it to work. Extract from app urls.py from django.urls import path, re_path from . import views urlpatterns = [ path('', views.index, name = "index"), ] project urls.py from django.contrib import admin from django.urls import path, include, re_path import gallery urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), path('index/', include('gallery.urls')), ] And lastly, this is my view.py file in my app folder from django.shortcuts import render from django.urls import reverse # Create your views here. def index(request): return render(request,"gallery/index.html") Any help will be appreciated -
Simple WYSIWYG image uploading
Currently I am using ckeditor to allow users to write blog posts. It does everything I want except the image uploading is awful. Users have to jump through two screen to upload an image and specify dimensions. The images don't auto scale to mobile and overall its a very poor experience. Is there a simple way to allow users to upload images or another WYSIWYG that can handle this. -
Acessing SQLite tables with Django on Ubuntu
I am following the Django official documentation tutorial on how to setup the database, provided here : https://docs.djangoproject.com/en/4.0/intro/tutorial02/ After running the code below I should have any necessary database tables according to the database settings in my mysite/settings.py. $ python manage.py migrate Now I want to check those tables through the terminal (this is my problem -> I can't). The documentation says : If you’re interested, run the command-line client for your database and type \dt (PostgreSQL), SHOW TABLES; (MariaDB, MySQL), .tables (SQLite), or SELECT TABLE_NAME FROM USER_TABLES; (Oracle) to display the tables Django created. None of those commands works on my terminal, my project is setup to be on SQlite, which is just a file on my project folder and SQLite is included in Python, so I shouldn't need to install anything else to support your database My questions is if I can ONLY run that command (.tables) on sqlite special command line and I need to install it or is there any way I can acess it with the terminal Iam using on Django. Any help will be HIGHLY appreciated. -
Django Tutorial - Testing vote(request, question_id)
I am working my way through the django tutorial and I reached part 5 - Introducing automated testing. I want to go beyond and write test for the vote method in views.py, but can't realise how to simulate the behaviour. Is there a way to do this? models.py: class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.pub_date <= now class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text views.py def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice_set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): # Redisplay the question voting form. return render(request, 'polls/detail.html', { 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() # Always return an HttpResponseRedirect after successfully dealing # with POST data. This prevents data from being posted twice if a # user hits the Back button. return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) I've tried multiple stuff in tests.py. This is the latest version - i know choice_vote is currently not what i want, still needs to be filtered: class QuestionVoteTests(TestCase): def test_vote(self): """ Placeholder for vote method test. """ question = create_question(question_text="Question.", days=-5) … -
URL error in Django, being asked to add semicolon in the url link object
I have an HTML link, upon clicking it will direct me to the respective link <div onclick="location.href='{% url 'newscountry' 'Kuwait' %}'"> Kuwait </div> But I am being warned to add ; in the above link (as {% url 'newscountry'; 'Kuwait' %}')as per the attached image. Also, I am getting inconsistent links results too. urls.py as below, path('country/<str:country>/',NewsCountryView.as_view(),name='newscountry'), views.py class NewsCountryView(ListView): model = News template_name = 'newsfront/index.html' # <app>/<model>_<viewtype>.html context_object_name = 'news' ordering = ['-date_posted'] paginate_by = 16 def get_queryset(self): country=self.kwargs.get('country') return News.objects.filter(country=country) -
Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'
When I deployed my project, got these errors: [Fri Dec 31 18:27:56.319749 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Failed to exec Python script file '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.319901 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] mod_wsgi (pid=4064): Exception occurred processing WSGI script '/myproject/myproject/myproject/wsgi.py'. [Fri Dec 31 18:27:56.320220 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] Traceback (most recent call last): [Fri Dec 31 18:27:56.320306 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/myproject/myproject/wsgi.py", line 16, in <module> [Fri Dec 31 18:27:56.320322 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] application = get_wsgi_application() [Fri Dec 31 18:27:56.320346 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Fri Dec 31 18:27:56.320359 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] django.setup(set_prefix=False) [Fri Dec 31 18:27:56.320381 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup [Fri Dec 31 18:27:56.320393 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] apps.populate(settings.INSTALLED_APPS) [Fri Dec 31 18:27:56.320415 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate [Fri Dec 31 18:27:56.320427 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] app_config = AppConfig.create(entry) [Fri Dec 31 18:27:56.320448 2021] [wsgi:error] [pid 4064:tid 140323912808192] [remote 5.238.148.231:53389] File "/myproject/virtualenv/lib/python3.8/site-packages/django/apps/config.py", line 224, in create … -
Can't measure the performance of serializer using cProfile
I'm trying to use cProfile to compare between serializers.ModelSerializer and serializers.Serializer according to this tutorial. Please, check out the tutorial before continuing the reading, it will be useful for you! Serializers: from django.contrib.auth.models import User from rest_framework import serializer class UserModelSerializer(serializers.ModelSerializer): class Meta: model = User fields = [ 'id', 'username', ] class UserSerializer(serializers.Serializer): id = serializers.IntegerField() username = serializers.CharField() Views: from . serializers import UserModelSerializer, UserSerializer from rest_framework.response import Response from rest_framework.views import APIView import cProfile class TestApi(APIView): def get(self, request): u = User.objects.get(username='hamza') assert u.username == 'hamza' # just to ensure it fetches the user data = UserModelSerializer(u).data cProfile.run('for _ in range(5000): data') return Response(data) In views I just create GET endpoint and try to run cProfile but this gives me an error: NameError: name 'data' is not defined but if I comment the line cProfile.run('for _ in range(5000): data') in views and try to access data and send it to the Response without using cProfile it will work fine! So the question is, Why cProfile can't see UserModelSerializer? -
How to make the search-bar return "the post you searched doesn't exist" instead of displaying nothing https://github.com/Ayman-Isam/Class-of-2024-Blog
Here the searched function looks for the title of a post and searches it using the icontains functionality {% extends "blog/base.html" %} {% block content %} <div class="search-results"> {% if searched %} <h1>Results for - {{ searched }} </h1> <br> {% for post in posts %} <a href="{% url 'post-detail' post.id %}">{{ post }} - {{ post.description }}<br></a> {% endfor %} {% else %} <h1 class="find">You forgot to search for a post</h1> {% endif %} </div> {% endblock %} -
Issue with django json response
I have issue with json response. messages.values() gives me user_id instead of username. How to get username? Here is my code: class LivechatMessage(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE, null=True) def getMessages(request): messages =LivechatMessage.objects.all() return JsonResponse({"messages":list(messages.values())}) -
when going to admin giving error site url does not exist
When i am trying to go admin path in the it is giving me error that saying that site matching query does not exist this never happens to me before -
Django complex query with ForeignKey relations
I am using Django 3.1.4 and I have these models: from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.timezone import now class CrowdfundingOffering(models.Model): class PlatformChoices(models.TextChoices): buytheblock = "buytheblock", _("buytheblock") flashfunders = "flashfunders", _("flashfunders") mainvest = "mainvest", _("mainvest") netcapital = "netcapital", _("netcapital") republicco = "republicco", _("republicco") seedinvest = "seedinvest", _("seedinvest") smallchange = "smallchange", _("smallchange") startengine = "startengine", _("startengine") trucrowd = "trucrowd", _("trucrowd") wefunder = "wefunder", _("wefunder") platform = models.CharField( max_length=255, choices=PlatformChoices.choices, ) company_name = models.CharField(max_length=255) description = models.TextField(max_length=3000) url = models.URLField() funding_goal = models.FloatField(default=0) start_date = models.DateField() end_date = models.DateField() class Investment(models.Model): offering = models.ForeignKey( CrowdfundingOffering, on_delete=models.CASCADE, related_name="investments" ) timestamp = models.DateTimeField(default=now) number_of_investors = models.PositiveIntegerField(default=0) amount_invested = models.FloatField(default=0) Problem statement We need to make our data available to our data science team. For now, let’s give them something basic. A simple table like this will do: | Platform Name | Number of offerings | Amount raised total | Success ratio | -------- | -------------- | -------------- | -------------- | |startengine | 34 | 60093134 | 0.45 |wefunder | 56 | 3246765 | 0.4 We can create such a table from our database and save it as a CSV file. You need to implement a function that queries our … -
Creating Gin index for Postgres stored generated column in Django
I want to setup a Postgres "stored generated columns" with indexing to have full text search on two fields of a model. I created the generated column getting help from this tutorial, but when setting gin index on the column, I get this: django.core.exceptions.FieldDoesNotExist: Article has no field named 'vector_column'. The app cache isn't ready yet, so if this is an auto-created related field, it won't be available yet. And my Article model: class Article(models.Model): title = models.CharField(...) content = models.TextField(...) class Meta: indexes = [GinIndex(fields=['vector_column'])] and my custom sql in migration file: operations = [ migrations.RunSQL( sql=''' ALTER TABLE articles_article ADD COLUMN vector_column tsvector GENERATED ALWAYS AS ( setweight(to_tsvector('english', coalesce(title, '')), 'A') || setweight(to_tsvector('english', coalesce(content,'')), 'B') ) STORED; ''', reverse_sql=''' ALTER TABLE articles_article DROP COLUMN vector_column; ''' ), ] Is it possible to set index from Django? Seems Django needs the field to be defined on the model but that's not how generated column works. If not, what's the correct way of setting the proper index (mentioned in this Postgres doc, the on at the end) in migration files? -
Django application with Docker compose, not able to run cron job. Getting "crontab: can't open 'appname': No such file or directory"
This runs fine for me using docker-compose up locally. But when I run it on my EC2 (or locally) instance with docker-compose -f docker-compose.yml up, and then run docker-compose run --rm appname sh -c "python manage.py crontab show" I get crontab: can't open 'appname': No such file or directory, followed by Currently active jobs in crontab: Any ideas? -
FilePathField for Image Path not working with Django Admin Panel
New to Django and web development in general. But I have followed a tutorial for creating my first site. Everything worked fine, until I finished it and wanted to edit the info using the Django admin panel. The main issue is that I have a model shown below that uses FilePathField to describe the image locations. The tutorial had me place the images in /home/pi/mysite/projects/static/img. from django.db import models class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField('/img') def __str__(self): return self.title #or self.title for blog posts This worked fine at first for displaying the images on the website, but once I tried to navigate to the /change/ url from the admin panel, I would get FileNotFoundError at /admin/projects/project/1/change/ [Errno 2] No such file or directory: '/img' So I looked around and found that FilePathField is an absolute path, so tried defining it absolutely with /home/pi/mysite/projects/static/img/. This stopped the error from occurring which let me at least access the /change/ url from the admin panel. The panel now showed the image field with a dropdown that I could use to choose between the different images I had up there, which were located at /home/pi/mysite/projects/static/img/. But … -
Django ManyToOne reference multiple tables
Right now I have the following model that I'd like to be used in different models (I want to store the day of the week and time in different models): class DayTime(models.Model): # Side note: I saw that there is a DurationField and # was considering using that instead of the CharField below day = models.CharField(max_length=9, choices=DaysOfWeekTypeEnum.choices) time = models.TimeField() From the docs, I'd have to create a ForeignKey field in the above model to accommodate the ManyToOne reference. Example: class DayTime(models.Model): day = models.CharField(max_length=9, choices=DaysOfWeekTypeEnum.choices) time = models.TimeField() modelA = models.ForeignKey(ModelA, on_delete=models.SET_NULL) modelB = models.ForeignKey(ModelB, on_delete=models.SET_NULL) This doesn't sound right to me. Should I create different DayTime model instead? Thanks in advance. -
How to auto-refresh data and politely chart Plotly in Django
Hello how to auto refresh and auto updates so I can get realtime data in plotly chart in Django (whithout clicking on refresh button on the browser) Here is my code: in (views.py) from plotly.offline import plot import plotly.graph_objs as go import yfinance as yf def result(request): stock_ticker = request.GET['num1'] period = request.GET['num2'] interval = request.GET['num3'] data = yf.download(tickers=stock_ticker, period = period, interval = interval, auto_adjust = True, threads = True, proxy = None) data['Date'] = data.index def candlestick(): figure = go.FigureWidget(data = [go.Candlestick(x=data['Date'],high=data['High'],low=data['Low'],open=data['Open'],close=data['Close'],)]) figure.update_layout(width=1400, height=800, title=f'{stock_ticker} Historical price', plot_bgcolor="white") figure.update_yaxes(showline=True, linecolor='lightgray', showgrid=True, gridwidth=0.5, gridcolor='lightgray', mirror=True) figure.update_xaxes(showline=True, linecolor='lightgray', mirror=True, rangebreaks=[dict(bounds=["sat", "mon"]), dict(bounds=[16, 9.5], pattern="hour"),]) figure.update_traces(visible=True, selector=dict(type='candlestick')) candlestick_div = plot(figure, output_type='div', config = {"displaylogo": False}) return candlestick_div return render(request, 'index.html', {'candlestick':candlestick()}) also in (index.html) {% block content %} <center> {{ candlestick | safe}} </center> {% endblock %} -
Unable to get relation attribute in Django, many-to-many relationship
models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ManyToManyField(Author) def __str__(self): return self.title I'm able to filter books by the author relation: >>> Book.objects.filter(author__name__contains="Fyodor") <QuerySet [<Book: Crime and Punishment>, <Book: The Brothers Karamazov>]> However, I'm unable to get the book's author: >>> all_books = Book.objects.all() >>> all_books[0].author <django.db.models.fields.related_descriptors.create_forward_many_to_many_manager.<locals>.ManyRelatedManager object at 0x7fdf068a2b20> >>> all_books[0].author.name Any suggestions? -
Django - Add entry to ManyToMany field through class based view
I want to add / remove members from a Team model. Members are specified as a ManyToManyField. I use django-rules to specify permissions, so team owners should be able to add/remove members. # models.py from django.db import models from rules.contrib.models import RulesModel from django.conf import settings class Team(RulesModel): name = models.CharField(max_length=80) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text="Owner can view, change or delete this team.", related_name="team_owner", ) members = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name="team_members" ) The permissions are specified as following: import rules @rules.predicate def is_team_owner(user, obj): return obj.owner == user rules.add_perm("teamapp.change_team", is_team_owner) I've specified some generic views (CreateView, DetailView, UpdateView and DeleteView) to manage the Team. Now I want two separate views to add and remove members on the same. # views.py from django.views.generic import ( CreateView, DetailView, UpdateView, ListView, DeleteView, ) from rules.contrib.views import PermissionRequiredMixin from django.contrib.auth import get_user_model from .models import Team class TeamMemberAddView(PermissionRequiredMixin, UpdateView): model = Team permission_required = "teamapp.change_team" raise_exception = True fields = ["members"] def form_valid(self, form): user = get_user_model() new_member = user.objects.get(pk=1) self.object.members.add(new_member) return super(TeamMemberAddView, self).form_valid(form) Which generic view can I use to add / remove members? Which approach is recommended here? I wanted 1 dedicated view to select an existing User to be added, … -
Store Procedure, tengo una sentencia if else donde se me ejecuta hasta el if
DELIMITER // CREATE PROCEDURE valor() BEGIN IF (select Garantia from repuestos_repuesto where Garantia = 'N' limit 1) = 'N' then Select re.id ,ve.marca, ve.modelo, ve.año, re.Nombre_repuesto from vehiculos_vehiculo as ve inner join repuestos_repuesto as re on re.Vehiculo_id = ve.id where ve.marca='Chevrolet' and ve.modelo='Aveo Family' and ve.año = '2015' and re.Nombre_repuesto = 'Guardachoque' and re.Garantia = 'N' Order By re.Precio Limit 1; else Select re.id ,ve.marca, ve.modelo, ve.año, re.Nombre_repuesto from vehiculos_vehiculo as ve inner join repuestos_repuesto as re on re.Vehiculo_id = ve.id where ve.marca='Chevrolet' and ve.modelo='Aveo Family' and ve.año = '2015' and re.Nombre_repuesto = 'Guardachoque' and re.Garantia = 'S' Order By re.Precio Limit 1; END IF; END // DELIMITER ; call valor() La idea es que en el primer if me devuelva los vehiculos que no tienen garantia y me muestre el precio mas bajo, y en el else los que si tienen garantia.Pero no me muestra ningun dato cuando pasa al else. -
Django form selection box 'jammed' as active so cant make selections
USERS can Upvote or Downvote Posts/Projects posted by Other Users: screenshot of 'jammed' active dropdown selection box THIS CODE DIRECTLY BELOW is the models.py that contains the Project class (model) with the vote_total and vote_ratio fields. It also contains the Review class (model) which is the basis for the ReviewForm in forms.py (code included later) class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) featured_image = models.ImageField(null=True, blank=True, default="default.jpg") demo_link = models.CharField(max_length=2000, null=True, blank=True) source_link = models.CharField(max_length=2000, null=True, blank=True) tags = models.ManyToManyField('Tag', blank=True) vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return self.title class Meta: # ordering = ['-created'] ordering = ['-vote_ratio', 'vote_total', 'title'] AND here is the Review class (model) class Review(models.Model): VOTE_TYPE = ( ('up', 'Up Vote'), ('down', 'Down Vote'), ) owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) body = models.TextField(null=True, blank=True) value = models.CharField(max_length=200, choices=VOTE_TYPE) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Meta: unique_together = [['owner', 'project']] def __str__(self): return self.value Here is the ReviewForm from the forms.py class ReviewForm(ModelForm): class Meta: model = Review fields = ['value', 'body'] labels = { 'value': … -
Django on Heroku: How to fix Server Error 500 only when directing to one specific model of one of the apps in admin?
First off, my Django project has several apps (with several models respectively). After deploying my code on Heroku using PostgreSQL, most things are going well. But when I checked the admin page (on Heroku), every model works fine except one (the model Store in stores app). It (which should be the ListView of the Store model) shows up Server Error (500) and that's it. Then I went to my local codebase for further checking. I replicated the same steps (i.e. going to the admin page and clicking the Store model to reach the list view), but things are working just fine. Perfect list view and no errors shown on the terminal in the local server. Can anyone shed some light on my situation please? What's possibly going wrong? Thanks in advance! (I have made sure all migrations are applied, collectstatic is done etc.) -
Django - Listing first model field values in second model createView form field for logged in user
Trying to add transaction (2nd model) for specific account (1st model) based on logged in user. Either listing available account in transaction creatView or buy clicking account name from rendered html page. details, class Account(models.Model): account_holder_name = models.ForeignKey(User,to_field="username",on_delete=models.CASCADE) other fiedls.... class Transaction(models.Model): account = models.ForeignKey(Account,to_field="account_name",on_delete=models.CASCADE) other fields... I can able to add account successfully using below form_valid function in CreateView def form_valid(self, form): userName = User.objects.get(username=self.request.user.username) form.instance.account_holder_name = userName return super().form_valid(form) And also created listview for accounts related to login user using ListView def get_queryset(self): return Account.objects.filter(account_holder_name=self.request.user.username) Rendering it in html by looping object list showing available acccounts for logged in user. -
TypeError: send_login_mail() got multiple values for argument 'email'
I am learning Celery+Reddis and trying to send email through Celery. I have created a task in which I have encapsulated my send email logic. I am calling the send_login_mail function and passing the keyword arguments using .delay(). #views.py class SignUpOTP(APIView): permission_classes = [AllowAny] def post(self, request): request_email = request.data.get("email",) try: user = User.objects.get(email__iexact = request_email) return Response({"status": "User is already registered."}, status=status.HTTP_403_FORBIDDEN) except: if request_email: send_login_mail.delay(email=request_email, subject="[OTP] New Login for Connect App") return Response({'status':'OTP sent successfully.'},status = status.HTTP_200_OK) else: return Response({"status":"Please enter an email id"},status = status.HTTP_400_BAD_REQUEST) #tasks.py @shared_task(bind=True) def send_login_mail(email=None, subject="[OTP] New Login for Connect App"): print("Wowowofdsofsdojsdjdofdffdojodjodfdfjdoofdods\nsdfjdsfjdsofjdsojdsdsosdoosdjfosdsdfodf") OTP.objects.filter(otp_email__iexact = email).delete() otp = random.randint(100000,999999) msg = EmailMessage(subject, f'<div style="font-family: Helvetica,Arial,sans-serif;min-width:1000px;overflow:auto;line-height:2"><div style="margin:50px auto;width:70%;padding:20px 0"><div style="border-bottom:1px solid #eee"><a href="" style="font-size:2em;color: #FFD243;text-decoration:none;font-weight:600">Connect</a></div><p style="font-size:1.2em">Greetings,</p><p style="font-size:1.2em"> Thank you for creating an account on Connect. You can count on us for quality, service, and selection. Now, we would not like to hold you up, so use the following OTP to complete your Sign Up procedures and order away.<br><b style="text-align: center;display: block;">Note: OTP is only valid for 5 minutes.</b></p><h2 style="font-size: 1.9em;background: #FFD243;margin: 0 auto;width: max-content;padding: 0 15px;color: #fff;border-radius: 4px;">{otp}</h2><p style="font-size:1.2em;">Regards,<br/>Team Connect</p><hr style="border:none;border-top:1px solid #eee" /><div style="float:right;padding:8px 0;color:#aaa;font-size:1.2em;line-height:1;font-weight:500"><p>Connect</p><p>Boys Hostel, Near Girl Hostel AKGEC</p><p>Ghaziabad</p></div></div></div>', 'swaad.info.contact@gmail.com', (email,)) msg.content_subtype = … -
Django - Filter out All Values from one Field in Model and Delete
Part of my django website is that when a user deletes one value from one model it deletes all data within a field of another model. Currently I am having trouble filtering out all values from a field in a model to delete. I know all my other code works because as a test I can do... delete = Data_Repo1.objects.all()filter(user=request.user) delete.delete() This works great when inputed into my code below. My problem is that I need to delete all data from a field called "date1" in a model called "Data_Repo1" not delete all data from all field in a model called "Date_Repo1". I have tired "values("date1")" and "values_list("date1")" in place of ".all()" in the above code but I get the error "Cannot call delete() after .values() or .values_list()". How else can I "filter" out all values from one field from one model in order to delete them?. Code Below. Thanks in advance. def deletefield_repo1(request, pk): context = {} title = get_object_or_404(Field_Repo1, pk=pk) #Title is needed to have the database value to delete context['title'] = Field_Repo1.objects.values_list('title', flat=True).filter(user=request.user).get(pk=pk) #Just to print the name fo the field to delete for the user type = Field_Repo1.objects.values_list('type', flat=True).filter(user=request.user).get(pk=pk) if request.method == "POST": title.delete() if type … -
Django User status not saving during registration
I am using abstract user model. Default is_subscriber value is false is_subscriber = models.BooleanField(default=False). But I am trying to change it ture during registration but I am not understanding why it's not changing false to ture. here is my code: models.py class UserManagement(AbstractUser): is_subscriber = models.BooleanField(default=False) class Subscriber(models.Model): user = models.OneToOneField(UserManagement, on_delete=models.CASCADE, primary_key=True) email = models.EmailField(max_length=1000) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) is_subscriber = models.BooleanField(default=False) forms.py class SubscriberSignUpForm(UserCreationForm): class Meta(UserCreationForm.Meta): model = UserManagement @transaction.atomic def save(self): user = super().save(commit=False) user.is_subscriber = True #here I am changing value False to True user.save() Subscriber.objects.create( user=user, email=self.cleaned_data.get('email'), first_name =self.cleaned_data.get('first_name'), last_name =self.cleaned_data.get('last_name'), ) my_group = Group.objects.get(name='SubscribersGroup') my_group.user_set.add(user) return user views.py class SubscriberSignUpView(CreateView): model = UserManagement form_class = SubscriberSignUpForm template_name = 'members/subscriber-registration.html' def get_context_data(self, **kwargs): kwargs['user_type'] = 'subscriber' return super().get_context_data(**kwargs) def form_valid(self, form): user = form.save() why is_subscriber status not changing False to True?