Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Emitting a subquery in the FROM in Django
I am trying to produce SQL like so: SELECT ... FROM bigtable INNER JOIN ( SELECT DISTINCT key FROM smalltable WHERE smalltable.x = 'user_input' ) subq ON bigtable.key = subq.key I have tried a handful of stuff with Django, and so far I've got: subq = Smalltable.objects.filter(x='%s').values("key").distinct("key") queryset = Bigtable.objects.extra( tables=[f"({subq.query}) subq"], where=["bigtable.key = smalltable.key"], params=["user_input"], ) The goal here is a cross join on bigtable and the DISTINCT smalltable. The ON clause is then replaced by a condition in the WHERE. In other words, a valid old-school inner join. And Django ALMOST has it. It is producing SQL like so: SELECT ... FROM bigtable, "(SELECT DISTINCT ...) subq" WHERE (bigtable.key = subq.key) Note the double quotes - Django expects a table literal only there and is escaping it as so. How can I get this query done, in either this way or another way? It is important for me that it's an actual join vs IN or EXISTS for query planning purposes. -
Django 4 - depending on choices , how show different fields using admin
Anyone please tell me depending on choices , show to fields using admin === Models.py from django.db import models class Project(models.Model): A = 'A' B = 'B' PROJECT_TYPE_CHOICES = ( (A, 'Plan Type A'), (B, 'Plan Type B'), ) project_type = models.CharField(max_length=100, choices=PROJECT_TYPE_CHOICES) name = models.CharField(max_length=500) business = models.CharField(max_length=500) === admin.py from django.contrib import admin from .models import Project admin.site.register(Project, ProjectAdmin) i want if i choices A show fields name if i choices B show fields business Thanks -
CustomAccounManager.create_user() missing 1 required positional argument: 'email'
I am trying creating a custom user model in django - which I am using as a backend. On django admin I can create users without issue. My problem arises when I try to register a new account via postman. In postman I have the email field filled out in the body, yet I still get the error missing 1 required positional argument: 'email'. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomAccounManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(self, email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique = True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccounManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': … -
Use python eval() in method calls
I have used eval() before but I'm trying to use it in a method call and it's not working. if level == 'info': logging.info( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'warning': logging.warning( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'error': logging.error( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'critical': logging.critical( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) How do I make less code by using something like: level == 'info': logging.eval(level)( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) I really thought this last one was gonna work: level = 'info' log = f"{logging}.{eval(level)}" eval(log)(f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}") Anyone knows a way to make this work? -
How to create re-send verification code system in Django?
I have a problem and that is whenever a user creates her/his account and doesn't enter her/his code(it means the code is expired) the user can't get code again because the account can be created once. I want to know how can I change this code to work in a way that the user can get the verification code again and again. serilizer.py: class RegisterationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, help_text=_("Enter a valid password")) repeated_password = serializers.CharField(write_only=True, required=True, help_text=_("Enter your password again")) class Meta: model = User fields = ["email", "username", "name", "password", "repeated_password"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'username': {'help_text': _("Enter your username")}, 'name': {'help_text': _("Enter your name"), 'required': False, 'allow_blank': True}, } def validate(self, data): print(User.objects.filter(email=data["email"], is_active=False)) if data["password"] and data["repeated_password"] and data["password"] != data["repeated_password"]: raise serializers.ValidationError(_("Password and repeated password must be the same")) if data["email"].strip() == data["username"].strip(): raise serializers.ValidationError(_("Email and username must be different")) return data class ConfirmCodeSerializer(serializers.ModelSerializer): email = serializers.EmailField(write_only=True, max_length=220, min_length=6, help_text=_("Enter your email")) class Meta: model = VerficationCode fields = ["email","code"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'code': {'help_text': _("Enter your code")}, } views.py: class RegisterationApiView(APIView): """ Get username, email, name, and password from the user and save it in … -
How can I solve the problem as mentioned below?
I am new to Django and while I was doing some stuff with Django Framework, I came across some problems My Python Code [views.py] def create(request): if request.method == "POST": print(request.POST) and My JavaScript Code is const formdata = new FormData() formdata.append('itemOne', itemValue) formdata.append('itemTwo', itemValue) fetch("/create", { method: 'POST', credentials: 'same-origin', body: formdata, headers:{ // 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': getCookie("csrftoken") }, }) .then(response => response.json()) .then(response => { console.log(response) }) .catch(err => { console.log(err) }) when I make a POST request as above from my JavaScript code, I get an empty dictionary. What might be the problem here? this is my urls.py files' code from django.urls import path, include from . import views urlpatterns=[ path('', views.index, name='home'), path('create', views.create, name='backend') ] How can I resolve the problem? I tried solutions from different websites and videos and none of them worked. -
Django wont upload images to media directory
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description. I wonder why when I set up my media files So I make my news in this view: class NewsCreate(views.CreateView): template_name = 'web/create_news.html' model = News fields = ('title', 'image', 'description') success_url = reverse_lazy('home') Here is the model: class News(models.Model): TITLE_MAX_LENGTH = 30 title = models.CharField( max_length=TITLE_MAX_LENGTH ) image = models.ImageField( upload_to='news/', blank=True ) description = models.TextField() Here is the set-up in settings.py: MEDIA_ROOT = BASE_DIR / 'mediafiles' MEDIA_URL = '/media/' Here is the urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('University_Faculty.web.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder -
Convert from dash html to regular html string
I've been using plotly to generate a few charts and used dash to render them on a simple heroku server. Now I am moving the dash component to Django, I have a very nice html layout generated with dash function, which is composed of some charts and some styling with it. I am trying to read it as html so that I can use a function in view to call the page. When I checked the layout data type, it is dash.html.Div.Div rather than html, or string of "html". I am wondering if I can convert it directly into HTML, so that I can render it like normal html code. Thanks -
{% block contents %} conditional on a variable Django template inheritance
I am using Django's template inheritance from a base file called base.html. All of my apps, except one, require that {% block contents %} {% endblock %} is present in that file, which is problematic. I am trying to find away to make the inclusion {% block contents %} {% endblock %} conditional on a variable. What I have so far tried in base.html: {% if some_variable %} {% block contents %} {% endblock %} {% endif %} But that doesn't seem to work. I have also tried: {% if some_variable %} {% with 'base_block_content.html' as path %} {% include path %} {% endwith %} {% endif %} base_block_content.html being simply: ''' {% block contents %} {% endblock %} ''' But that doesn't work either. My only other option is to write a completely separate base.html for the one app, which doesn't quite fit in with the 'DRY' concept. -
How to pass tuple with one element as param in sql query Python?
How can I pass tuple with only one element as param in sql query Python? I have tried this solution suggested here: imploding a list for use in a python MySQLDB IN clause ids = [(UUID('1232a4df-5849-46c2-8c76-74fe74168d82'),)] # list of ids cursor.execute(''' SELECT ... WHERE id IN %(ids)s AND created_at > %(start_dt)s ''', { 'ids': tuple(ids), 'start_dt': '2019-10-31 00:00:00' }) but this solution does not work in python 3 and mysql-connector-python 8.0.21. I get this error: An error "Python tuple cannot be converted to MySQL type" is returned. -
Django celery page is giving 404
I'm trying to acces https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html but getting 404. Is celery not officially available? -
Unable to add a placeholder in django-ckeditor?
I have integrated django-ckeditor in my blog, i have added placeholder with the help of widget in my forms.py like this from blog.models import Contact from ckeditor.widgets import CKEditorWidget class ContactFrom(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget(attrs={'placeholder':"Type.."})) class Meta: model = Contact fields = ("content",) Even i can see placeholder in my textarea through inspect but not showing in my ckeditor what should i do? -
send email on model create - django
I want to send an email automatically when I create an invoice. Is that possible? What I'm after. I have a invoice model and I put send_email code in it "def save(self):", I'm making perfex CRM invoice system, so I'm using the foregin key in invoice model to get a customer, but whenever I create new invoice it says "The invoices “INV-b066” was added successfully." but in invoice model it shows nothing like it's empty model I even tried to open invoice using index number and restarted the server and migrations stuff and it didn't worked but if I remove def save(self): function it works perfectly fine I'm trying to send an email automatically on model create Customer model class Customers(models.Model): Your_Name = models.CharField(max_length=220) Email_Address = models.EmailField(max_length=220) Profession = models.CharField(max_length=220) phone = PhoneNumberField(unique=True) No_of_Persons = models.IntegerField() Packages = models.CharField(choices=PAKAGES, max_length=100) Address = models.CharField(max_length=220) City = models.CharField(choices=CITIES, max_length=10) Time = models.CharField(choices=TIME, max_length=10) Date = models.DateTimeField() Message = models.TextField() def __str__(self): return f'{self.Your_Name}' Invoice model class Invoice(models.Model): Customer = models.ForeignKey(Customers, on_delete=models.CASCADE) Invoice_Number = models.CharField(default=inv_num, max_length=10) Recurring = models.CharField(choices=Recurrings, max_length=12) Invoice_date = models.DateField() Due_date = models.DateField() Packages = models.CharField(choices=PAKAGES, max_length=100) Package_name = models.CharField(max_length=50) Package_description = models.TextField() Package_Quantity = models.IntegerField() Package_Price = models.IntegerField() def … -
How to filter queryset using item inside a list in a JSON file in Django?
I have JSON files that are structured like this in my database: } "user" : { "contacts" : [ { "type" : "email", "data" : "aaa@foo.com" }, { "type" : "phone_number", "data" : "4444-4444" }, { "type" : "email", "data" : "bbb@foo.com" }, ... ], "name" : "Bob" } } What I want is to filter the queryset so I end up only having users that have an account with an email registered. Anyone knows how to make this work? I am aware of user__contacts__0__type=email but the list doesn't have a fixed size. -
How do I configure my media files to upload on AWS S3 Bucket in Django?
I've created a Blogging App using Django and Heroku-Postgres as Database. The user uploaded images gets removed in Heroku-Postgres after redeployment I think and it just disappears from the website. I tried fixing this using AWS S3 Bucket but I'm not able to configure the settings in my Django App, the user uploaded files are uploaded to media/images/ according to my models.py models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) article_image = models.ImageField(null=True, blank=True, upload_to="images/") settings.py AWS_STORAGE_BUCKET_NAME = '#####' AWS_S3_REGION_NAME = 'us-east-1' AWS_ACCESS_KEY_ID = '####' AWS_SECRET_ACCESS_KEY = '####' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DISABLE_COLLECTSTATIC=1 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Now, what am I supposed to remove/keep from these so that the user uploaded images which are now stored in media/images/ are stored in AWS S3 Bucket? -
Javascript infinite scroll that updates new divs when reached to the bottom of screen not working
I am trying out a web app using Django from the edX course CS50 Web Programming. Below is the javascript for an infinite scroll that updates 20 posts every time reaching the bottom of the screen but it just stopped after reaching 20th post. <script> // Start with first post let counter = 1; // Load posts 20 at a time const quantity = 20; // When DOM loads, render the first 20 posts document.addEventListener('DOMContentLoaded', load); window.onscroll = function(ev) { if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) { load(); } }; // Load next set of posts function load() { // Set start and end post numbers, and update counter const start = counter; const end = start + quantity - 1; counter = end + 1; // Get new posts and add posts fetch(`/users/home/posts?start=${start}&end=${end}`) .then(response => response.json()) .then(data => { data.posts.forEach(add_post); }) }; // Add a new post with given contents to DOM function add_post(contents) { // Create new post const post = document.createElement('div'); post.className = 'post'; post.innerHTML = contents; // Add post to DOM document.querySelector('#posts').append(post); }; </script> Below is posts function in python from views.py def posts(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse("users:login")) # Get start and end points start … -
Bootstrap button doesn't display properly in django form
EDIT: Just realized how bloated this question is and how poorly formated my html. Sorry I didn't catch it before posting. Working on fixing it now So, as you can probably see in the images, I'm having trouble getting a bootstrap button to display in my Django template properly. It's meant to submit a user registration form but as you can see I've tried putting it in a few places to see if a container is affecting it:Bootstrap buttons as they appear in my project and, of course, it should look like this: enter image description here Here's the relevant template, with the button repeated in a few places: <!-- my base template --> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <title>Short Thoughts Posted Publicly Online</title> </head> <body> <!-- I've got a navbar here, but I can't imagine that's relevant --> <div class="container"> <div class="columns"> {% block content %} {% endblock content %} </div> </div> <script src="{% static 'js/bootstrap.bundle.js' %}"></script> </body> </html> <!-- my registration template --> {% extends 'base.html' %} {% block content %} <button type="button" class="btn btn-default">Register</button> <div class="row"> <div class="shadow-none p-3 mb-5 … -
How to register with django on template?
I have a small project. There is a ready registration form in the project. I want to register on this registration form. I don't want to create inputs with python codes in forms.py. I want to record with imputs in existing HTML codes. I hope I was able to explain what I wanted. I will be glad if you help me. register.html {% extends 'partials/_base.html' %} {% load static %} {% block content %} <!-- BREADCRUMB --> <div id="breadcrumb"> <div class="container"> <ul class="breadcrumb"> <li><a href="#">Home</a></li> <li class="active">Register</li> </ul> </div> </div> <!-- /BREADCRUMB --> <!--REGISTER FORM--> <div style="width: 500px;" class="container"> <form class="form-horizontal" role="form" method="post"> {% csrf_token %} <br> <div class="form-group"> <label for="firstName" class="col-sm-3 control-label">Ad</label> <div class="col-sm-9"> <input type="text" id="firstName" placeholder="First Name" class="form- control" autofocus> </div> </div> <div class="form-group"> <label for="firstName" class="col-sm-3 control-label">Soyad</label> <div class="col-sm-9"> <input type="text" id="lastName" placeholder="Last Name" class="form- control" autofocus> </div> </div> <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Email" class="form-control"> </div> </div> <div class="form-group"> <label for="email" class="col-sm-3 control-label">Nömrə</label> <div class="col-sm-9"> <input type="text" id="phone" placeholder="Phone" class="form-control"> </div> </div> <div class="form-group"> <label for="password" class="col-sm-3 control-label">Şifrə</label> <div class="col-sm-9"> <input type="password" id="password" placeholder="Password" class="form- control"> </div> </div> <div class="form-group"> <label for="birthDate" class="col-sm-3 control-label">Doğum tarixi</label> <div class="col-sm-9"> <input type="date" … -
Why is only some context data available in django template?
I'm having trouble accessing some of the context data in a django template, probably due to a basic misunderstanding on my part. Please see abbreviated code below. My view is: class UserCourseListView(LoginRequiredMixin, generic.ListView): model = CustomUser template_name = 'account/course/list.html' context_object_name = 'puser_course_list' def get_queryset(self): return CustomUser.objects.filter(username=self.request.user.username) My model is: class CustomUser(AbstractUser): email = models.EmailField(max_length=254, blank=False,) course = models.ManyToManyField(Course, related_name="course", blank=True) firstname = models.TextField(max_length=254, blank=True ) surname = models.TextField(max_length=254, blank=True ) nickname = models.TextField(max_length=254, blank=True ) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse('patient_user_detail', args=[str(self.id)]) And template is: {% for pcourse in puser_course_list %} <dt>{{ pcourse.courses_joined.all }}</dt> <dt>{{ pcourse.id }}</dt> <dt>{{ pcourse.username }}</dt> <dt>{{ pcourse.firstname }}</dt> <dt>{{ pcourse.surname }}</dt> {% endfor %} I am able to acces the user id, username and retrieve a queryset from a related model (using related name 'courses_joined'), but can't retrieve the firstname and surname? Any thoughts or help would be most appreciated. I'm assuming a context processor isn't required in this scenario as all of the data should be in the context_object? -
How to limit the number of threads to one
How can this function be changed so that it only executes on one thread? Is it possible? Should I have a separate function for this? I tried to create a dictionary and count each loop, but it doesn't make sense because after using import pdb;pdb set_trace () I can see that more threads are used "<Thread(Thread-4 (eventFunc), initial daemon)>" Code: def event(codeName=None, context=None, attachments=None, is_thread=True, **kwarks): if settings.IS_EVENT_ACTIVE: #print(u"Event [{}]".format(codeName)) # logger.debug(u"Event [{}] {}".format(codeName,traceback.print_exc())) logger.debug(u"Event [{}]".format(codeName)) if portalSetting.EVENT_THREAD and is_thread: x = threading.Thread(target=eventFunc, args=(codeName, context, attachments, ), kwargs=kwarks) # import pdb;pdb.set_trace() x.start() else: eventFunc(codeName=codeName, context=context, attachments=attachments, **kwarks) -
AttributeError: 'NoneType' object has no attribute 'as_sql'
that's ok to makemigrations, but it's error when I migrate. Please give me some advise, I didn't find the same case "as_sql" in Google. Thank you. This is my models class ClinicInfo(models.Model): name_cn = models.CharField(max_length=100, verbose_name=_('Chinese Name')) name_en = models.CharField(max_length=100, verbose_name=_('English Name')) short_name = models.CharField(max_length=10, unique=True, verbose_name=_('Short Name')) address_cn = models.CharField(max_length=200, verbose_name=_('Chinese Address')) address_en = models.CharField(max_length=200, verbose_name=_('English Address')) telnum_1 = models.CharField(max_length=20, verbose_name=_('1st Tel No.')) telnum_2 = models.CharField(max_length=20, blank=True, verbose_name=_('2nd Tel No.')) email = models.EmailField(max_length=254, blank=True, verbose_name=_('Email')) fax = models.CharField(max_length=20, blank=True, verbose_name=_('Fax')) class meta: verbose_name = _('Clinic Information') verbose_name_plural = _('Clinic Information') def __str__(self): return self.name_cn class DoctorArg(models.Model): weekday_list = ( (0, _('Monday')), (1, _('Tuesday')), (2, _('Wednesday')), (3, _('Thursday')), (4, _('Friday')), (5, _('Saturday')), (6, _('Sunday')) ) period_list = ( ('full', _('Full Day')), ('am', _('AM')), ('pm', _('PM')) ) clinic = models.ForeignKey(ClinicInfo, on_delete=models.CASCADE, verbose_name=_('Clinic')) weekday = models.IntegerField( choices=weekday_list, verbose_name=_('Weekday')) period = models.CharField(max_length=4, choices=period_list, default='full', verbose_name=_('Period')) ''' doctor = models.ForeignKey( MyUser, limit_choices_to={'role': 'Doctor'}, on_delete=models.CASCADE, verbose_name=_('Doctor')) ''' class Meta: verbose_name = _('Doctor Arrangement') verbose_name_plural = _('Doctor Arrangements') # unique_together = [['weekday', 'period', 'doctor']] def __str__(self): return 'Doctor arrangements' I didn't find the same case "as_sql" in Google. I tried to trace this error according to this way link, but didn't get debug print. -
What 'namespace' is used for in Django urls?
I have namespace parameter in the urls.py of project, like this: path('blog/', include('blog.urls', namespace='blog')), And then I have app_name = blog in the urls.py of the blog application. I do that because that's what I've learned to do without actually understanding what namespace is doing when app_name is defined? -
What form action should i use to solve error 405 on post?
##html <form id="schedule-form" action="#" method="POST"> {% csrf_token %} .... <input type="submit" id="submit-horario" value="Confirmar" class="btn button-raised btn-green text-white text-uppercase fw-600 me-md-1 mt-3" onclick="gtag_confirmar_horario('S_{{ prestadorservicos.prestadorservicoid }}', '{{ servicoregioes.as_string|escapejs }}', '{{ menor_desconto.get_tipo_de_desconto_display|escapejs }}', '{{ menor_desconto.preco_desconto }}', '{{ prestadorunidade.as_string|escapejs }}', '{{ prestador.parceiro }}', '{{ prestadorservicos.preco }}')"/> </div> </form> ##urls from django.conf.urls import url from django.urls import path from . views import BuscaHorarios, AgendaHorario app_name = "agendamento" urlpatterns = [ url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$', BuscaHorarios.as_view(), name='horarios', ), url('/', AgendaHorario.as_view(), name="agenda_horario"), ] When i submit this form i get 405 http error on console. There is no problem loading (get) this page [25/Mar/2022 11:55:38] "GET /agendamento/11749/1341/ HTTP/1.1" 200 19435 only to submit (post) [25/Mar/2022 11:56:51] "POST /agendamento/11749/1341/ HTTP/1.1" 405 0 -
Using HTML if statements to return results
I am trying to print a list of courses that a user has uploaded onto their account but am having trouble figuring out how to do that. I have tried to print {{ course.student_course }} and {{user.username}} and they both appear to print the same thing. But when I do the comparison in the if statement, nothing returns. Here is the html snippet <div class="container h-100"> <div class="row justify-content-center"> {% if courses_list %} {% for course in courses_list %} {% if course.student_course == user.username %} <button type="button" class="btn btn-outline-primary">{{ subject }} </button> <p>{{ subject }}</p> {% endif %} {% endfor %} {% else %} <p>No courses have been uploaded.</p> {% endif %} </div> </div> And here is the fields of my model that I am trying to access. class Course(models.Model): subject = models.CharField(max_length=4) course_number = models.CharField(max_length=4, default='') course_name = models.CharField(max_length=100, default='') course_section = models.CharField(max_length=3, default='') student_course = models.OneToOneField(User, on_delete=models.CASCADE, default='') def __str__(self): return self.subject + " " + self.course_number Like I said, I tried to print each field being compared and they both turned the same thing but when I try to do the comparison it returns nothing. -
Please critique my Django app (for entry level resume)
Link: https://coleabell05.pythonanywhere.com/home/ Entry level Python/Django oriented programmer here and I just finished a sort of first draft of a simple inventory app linked above I'm planning to use on my resume, launched on pythonanywhere. If anyone has some time, would you mind giving it a look? Hoping for advice on what additional functionality I could work on adding and how I could make it more appealing to recruiters? Also if its structure is confusing at all and what I could change to clarify it's function. As it stands now, it's intended to be a functioning register and inventory manager for a pizzeria. The user makes an account and then has the power to add or delete entrees and ingredients to the kitchen as well as close the register for the day and make purchases. Thanks for any help!