Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django makemigrations - No installed app with label '<appname>'
Beginner to Django Web Frameworks here...when I try to run python manage.py makemigration courses, it throws this error: $ python manage.py makemigrations courses ←[31;1mNo installed app with label 'courses'. Here is what I have in settings.py for INSTALLED_APPS INSTALLED_APPS = [ 'courses.apps', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] This is in my apps.py file: from django.apps import AppConfig class CoursesConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Courses' Here is what python manage.py showmigrations gives: $ python manage.py showmigrations ←[1madmin ←[0m [X] 0001_initial [X] 0002_logentry_remove_auto_add [X] 0003_logentry_add_action_flag_choices ←[1mauth ←[0m [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 [X] 0007_alter_validators_add_error_messages [X] 0008_alter_user_username_max_length [X] 0009_alter_user_last_name_max_length [X] 0010_alter_group_name_max_length [X] 0011_update_proxy_permissions [X] 0012_alter_user_first_name_max_length ←[1mcontenttypes ←[0m [X] 0001_initial [X] 0002_remove_content_type_name ←[1msessions ←[0m [X] 0001_initial Also, why do I have these '←[31;1m' and '←[0m' symbols in the output on my terminal? I am using VSCode Thankyou! -
Django some css not working in production
I have a django app. In production I ran collectstatic and all good except a small piece of css. This css thing is a question mark which on hover shows some tips about the app feature. This also could be a nginx configuration issue maybe. But again, just this piece of css does not work properly. html <div class="help-tip"> <p> some text </p> </div> css /*------------------------- Inline help tip --------------------------*/ .help-tip-wrapper{ padding-top: 15px; padding-left: 5px; } .help-tip{ text-align: center; background-color: #BCDBEA; border-radius: 50%; width: 24px; height: 24px; font-size: 14px; line-height: 26px; cursor: default; } .help-tip:before{ content:'?'; font-weight: bold; color:#fff; } .help-tip:hover p{ display:block; -webkit-animation: fadeIn 0.3s ease-in-out; animation: fadeIn 0.3s ease-in-out; } .help-tip p{ display: none; background-color: #1E2021; padding: 20px; width: 300px; border-radius: 3px; right: -4px; color: #FFF; font-weight: normal; font-size: 10px; z-index: 100; line-height: 1.4; position: relative; } .help-tip p:before{ content: ''; width:0; height: 0; border:6px solid transparent; border-bottom-color:#1E2021; right:10px; top:-12px; } .help-tip p:after{ width:100%; height:40px; content:''; top:-40px; left:0; } settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' All css working fine except this one. -
I have an error: 'NoneType' object has no attribute 'price' error by rendering the template
I have these models: class Product(models.Model): name = models.CharField(max_length=200) category = models.CharField(max_length=300, choices=TOTAL) subcategory = models.CharField(max_length=300, choices=SUBPRODUCT) price = models.FloatField() image = models.ImageField(null=True, blank=True) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url class Order(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False) transaction_id = models.CharField(max_length=100, null=True) def __str__(self): return str(self.id) @property def shipping(self): shipping = False orderitems = self.orderitem_set.all() for i in orderitems: if i.product.digital == False: shipping = True return shipping @property def get_cart_total(self): orderitems = self.orderitem_set.all() total = sum([item.get_total for item in orderitems]) return total @property def get_cart_items(self): orderitems = self.orderitem_set.all() total = sum([item.quantity for item in orderitems]) return total class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) @property def get_total(self): total = self.product.price * self.quantity return total My views.py: def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] context = {'cartItems':cartItems, 'order':order, 'items':items} return render(request, 'store/store.html', context) It's my template: <div class="bottom"> <div class="total"> <span>Total</span> <span class="total-amount">${{order.get_cart_total|floatformat:2}}</span> </div> <a href="{ url 'checkout' }" class="btn animate">Checkout</a> </div> </div> As I mentioned above, I have this error: 'NoneType' object … -
after clearing cookies and other site data login with twitter is working
SOME of the clients are getting the following error while login in with Twitter. 403 Client Error: Forbidden for URL: https://api.twitter.com/oauth/request_token - can't sign in with Twitter The error does not come/resolved after clearing "Browser cookies and other site data". And in some of the client its work extremely good. So can you please help us out with the solution? We try all the troubleshooting, but it didn't resolve the problem. We are using this package pip install social-auth-app-django. -
Django: Provide count for related model's fields
I'm trying to design an API that would give me details about all models in the database with their fields and other statistics/count. These are the two related models: class Subject(models.Model): name = models.CharField() class Student(models.Model): name = models.CharField() join_year = models.IntegerField() graduate_year = models.IntegerField() strand = models.ForeignKey(Subject, on_delete=models.SET_NULL) This is how the API data for all Subjects is being generated at the moment: [ { "name": subject.name, "years": [ { "joined": Student.objects.filter(strand=subject).values("join_year").annotate(joined=Count("join_year")).order_by("join_year"), "graduated": Student.objects.filter(strand=subject).values("graduate_year").annotate(graduated=Count("graduate_year")).order_by("gradaute_year"), } ], } for subject in Subject.objects.all() ] This results in: [ "name": "Medicine", "years": [ { "joined": { "join_year": 2000, "joined": 123, }, "graduated": { "graduate_year": 2001, "graduated": 543 } }, { "joined": { "join_year": 2002, "joined": 123 }, "graduated": { "graduate_year": 2002, "graduated": 543 } } ] ] However, what I want is: [ "name": "Medicine", "years": [ { "year": 2000, "joined": 123, "graduated": 0, }, { "year": 2001, "joined": 0, "graduated": 543, }, { "year": 2002, "joined": 123, "graduated": 543, } ] ] -
running pinry inside docker on windows 10
I want to run a Pinry server on my local network so I can make pin boards in private. As per the instructions I installed docker and pulled the Pinry container: docker pull getpinry/pinry And then run it pointing to a local folder for it to store data docker run -d=true -p=8080:80 -v=c:\PinryData\:/data getpinry/pinry When I open a commandline inside the container, the file /data/local_settings.py already has the setting ALLOW_NEW_REGISTRATIONS = True. I see it running in docker but when I try to go to the localhost:8080 it does not respond. Why isnt Pinry running correctly / cant I access Pinry? I have not used any of the components (django, docker) before so it might be something simple. -
Custom validators in BaseSerializer
I want to use custom validators in BaseSerializer. First attempt: Custom validator: class UserIdExists: def __init__(self): self.MESSAGE_INCORRECT_USER = 'No user with this id.' def __call__(self, user_id): exists = User.objects.filter(id=user_id).exists() if not exists: message = self.MESSAGE_INCORRECT_USER raise serializers.ValidationError(message, code='invalid') and BaseSerializer: class QuestionBaseSerializer(serializers.BaseSerializer): def to_internal_value(self, data): user_id = data.get('user_id') user_validator = UserIdExists() user_validator(user_id=user_id) In case of a validation error, I received a message: '["No user with this id."]' But I would like to receive such a message: '{"user_id": "No user with this id."}' Second attempt: Custom validator: class UserIdExists: def __init__(self): self.MESSAGE_INCORRECT_USER = 'No user with this id.' def __call__(self, user_id, field=None): exists = User.objects.filter(id=user_id).exists() if not exists: if field: message = {field: self.MESSAGE_INCORRECT_USER} raise serializers.ValidationError(message, code='invalid') else: if not field: message = self.MESSAGE_INCORRECT_USER raise serializers.ValidationError(message, code='invalid') And BaseSerializer: class QuestionBaseSerializer(serializers.BaseSerializer): def to_internal_value(self, data): user_id = data.get('user_id') user_validator = UserIdExists() user_validator(user_id=user_id, field='user_id') I get the expected message: '{"user_id": "No user with this id."}' Am I doing the right thing? Can it be done more correctly? -
Social login in flutter
I'm trying to implement social login in my application, the front-end is built with Flutter and my backend with Django and Django rest framework. In flutter i'm using Google_sign_in package to connect users when i get access token i send it to the backend. after this i request informations of my user from google with the access token if the user exits in Django database i return authentication token if not i create new user and i return authentication token. My question is: is it safe or are there better ways to do it? -
I am unable to make migrations , its showing conflicting migrations
I cloned my proj from the repository to a different computer, but after DB restore now there are conflicting migrations, I have looked into other answers they have mentioned about chain dependency , i am having trouble understanding how will it fix this Below are my last 2 migration files class Migration(migrations.Migration): dependencies = [ ('orders', '0016_auto_20210817_1851'), ] operations = [ migrations.AlterField( model_name='placedorder', name='order_time', field=models.DateTimeField(auto_now_add=True), ), ] class Migration(migrations.Migration): dependencies = [ ('orders', '0016_merge_20210828_1519'), ('orders', '0017_alter_placedorder_order_time'), ] operations = [ ] Traceback (most recent call last): File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 22, in <module> main() File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\commands\makemigrations.py", line 149, in handle loader.project_state(), File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\loader.py", line 335, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\migration.py", line 89, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\db\migrations\operations\fields.py", line 162, in state_forwards old_field = model_state.fields.pop(self.name) KeyError: 'session_id' -
Django cannot serve files after moving to compose
Context Hi, we have a big project in Django. Up until now, we have used Vagrant to run it. Now, we have decided to move to a container and use docker compose. Everything has worked out fine except for the serving of static files. We have a directory called web where we have all our static assets. Inside there, there are more subdirectories with more static assets. Problem Right now static files are not being served. Is curious because only some files are being served. I think the ones from the web directory are not working for some reason. Current django config This config has worked well before moving to docker. # this is necessary because our settings file are stored inside a directoy PROJECT_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) PUBLIC_DIR = os.path.join(PROJECT_DIR, 'public') STATIC_ROOT = os.path.join(PUBLIC_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(PROJECT_DIR, 'web'), ) STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) Additional information We are using django-1.11 and python 3.6.9. I know, it's not the latest. Compose configuration version: '3' services: web: image: "dev" container_name: web ports: - "8000:8000" volumes: - ./:/app depends_on: - db networks: - djangonetwork db: image: "postgres" container_name: db ports: - "5432:5432" networks: - djangonetwork networks: … -
Django music player not working in Heroku
I have a music player inside a django app, that uses js to fetch track url links from an api, the track files are uploaded into a AWS S3 bucket, when the app runs locally it works fine when loading tracks but after deployed to Heroku the tracks don't load, the music player just seems to be stuck on loading. Not sure what could be wrong? It may be something to do with the communication between AWS and Heroku, but not 100% sure, would appreciate some experienced advice. -
Django template: not showing product if the product has already been shown
Really sorry about the disturbing title, my case is a bit tricky to explain (and i'm not that good in english). I'll try to do my best. I have a django app where users can save paired food products - the first is the "product_to_substitute" and the second one is the "substitute_product". But the thing is that the "product_to_substitute" can actually have multiples "substitute_product". Here is what my "favorites" DB table can looklike (numbers are products IDs) : product_to_substitute_id substitute_product_id 3 5 3 50 3 45 58 124 12 98 So what I would like to do on my favorites html page is to show one section with the "product_to_substitute" and a second section that shows all the "substitute_product" that are paired with the "product_to_substitute". Here is a little bit of my code: {% for product in favorites %} {% if product.product_to_substitute %} ### Block where I want to show only once the product to substitute ### <section style="background-image: url('{{ product.product_to_substitute.image_url }}')"> ... </section> ### Block where I want to show all the substitutes products that are paired with the product to substitute ### <section> <img class="img-fluid" src="{{ product.substitute_product.image_url }}" alt="..." /> </section> {% endif %} {% endfor %} By … -
Javascript can't find static files passed on from Django template
I have an issue with passing on my css files to javascript code. I tried using the answer from Django {% static 'path' %} in javascript file however it seems not to work for me. I basically have a script, seen in the first picture who sets some colors based on css files. In order to provide access to these files I added the variables seen in a script tag as the answer from the mention question suggests, the second picture and use them in the script itself. In the tag I call the {% load static %} command, and the files have been collected with load static and I can see them in the root folder. When I try to use them in my website however, I get a 404 error "/PersonalWebsite/css/color/*.css not found". Any suggestions what's going wrong? -
Search controller is fetching the wrong template in Django
I'm trying to write the controller to search for articles. But the search does not find anything and a template appears that is not specified in the views.py. # views.py class SearchView(ListView): template_name = 'search_view.html' def get_queryset(self): query = self.request.GET.get('q') object_list = Article.objects.filter(Q(title__icontains=query)) return object_list # urls.py urlpatterns = [ ... path('search/', SearchView.as_view(), name='search_view'), ] #search_view.html {% extends 'layout/basic.html' %} {% block content %} {{ object_list }} {% endblock %} The form looks like this <form action="{% url 'articles:search_view' %}" method="get"> <input type="text" name="q" placeholder="Search..."> </form> What am I doing wrong? -
Django Calculations within Model.py don't update without a Server Reset
I have a few calculations within my Models file. The premise of this is that I have a 'rate' which is updated on a weekly basis, and this has an impact upon 2/3 columns within my eventual HTML table. I bring forward the latest rate as such: class Hedge_rate(models.Model): id = models.IntegerField(primary_key=True) Hedge_rate = models.DecimalField(max_digits=10, decimal_places=5) def __str__(self): return "%s" % (self.Hedge_rate) V = Hedge_rate.objects.all().first() latest_rate = V.Hedge_rate Then, my primary calculations are as follows: @property def spot_amount(self): return self.usd_amount/latest_rate The problem I am facing is that, let's say the "latest rate" is current "2" - If I then update this figure to "5", the numbers within the calculation (as well as if I 'print' Latest Rate') will remain as if the Latest rate is still 2. It only updates to 5 upon a server reset. I suspect this is some sort of Caching issue? Is there a way I can trigger a cache 'wipe' upon each form submission when updating the rate? What is the best way to resolve this? -
Heroku django.core.exceptions.ImproperlyConfigured: Set the SECRET_KEY environment variable
I am trying to run a django command on my heroku production server, but get the following error: Note: The same command works fine in my local dev environment. I took the following steps: ssh onto my django server: heroku ps:exec -a library-backend I run my custom command: python manage.py test_command Receive error above My environment variables are set in my settings.py as follows: import environ # Setting environment variables env = environ.Env(DEBUG=(bool, False)) environ.Env.read_env() DEBUG = env('DEBUG') SECRET_KEY = env('SECRET_KEY') DATABASE_URL = env('DATABASE_URL') My django app runs normally on the heroku server. I am only getting this error when I try to run a custom django management command. Can anyone see where I'm going wrong? For reference, the management command is specified in library/management/commands/test_command.py: from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): print("Testing management command") -
Facebook Final Check For Login
I have created a django app where i am checking that my social login for facebook is workingor not. When i click on my Facebook Button from Frontend its not getting login i am facing security connection problem though i have used ngrok link for creating a secure tunnel but still i am unable to login .. i am using django-all-auth library settings.py ALLOWED_HOSTS = ["582b-2405-201-a006-70b4-35e2-8cb3-b7e2-b9ec.ngrok.io"] LOGIN_REDIRECT_URL= 'dashboard' settings for facebook login inside the installed apps 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.twitter' site_id SITE_ID = 12 urls.py for django-all-auth path('socialaccounts/', include('allauth.urls')), register.html {% load socialaccount %} {% providers_media_js %} <a href="{% provider_login_url 'facebook' method='oauth2' %}" class="btn btn-primary form-btn w-100 mt-3">Facebook</a>`r code here images This is the error i am getting Provided a Valid OAuth Redirect URIs Basic settings for app inside facebook developers page -
Django no movie found matching the query
Hello i have this error , what is problem ? can not find Models.py # Create your models here. CATEGORY_CHOICES = ( ("A","ACTION"), ("D","DRAMA"), ("C","COMEDY"), ("R",'ROMANCE'), ) LANGUAGE_CHOICES = ( ("EN","ENGLISH"), ("GR","GERMAN") ) STATUS_CHOICES = ( ("RA","RECENTLY ADDED"), ('MW','MOST WATCHED'), ("TR",'TOP RATED'), ) class Movie(models.Model): title = models.CharField(max_length=100) title_english = models.CharField(max_length=100) descritpion = models.TextField(max_length=1000) image = models.ImageField(upload_to="movies") category = models.CharField(choices=CATEGORY_CHOICES,max_length=1) language = models.CharField(choices=LANGUAGE_CHOICES,max_length=3) status = models.CharField(choices=STATUS_CHOICES,max_length=2) year_of_production = models.TextField(max_length=1000) view_count = models.IntegerField(default=0) def __str__(self): return self.title Link_choice = ( ("D","Download LINK"), ("W","WATCH LINK"), ) class Movielinks(models.Model): movie = models.ForeignKey(Movie,related_name="movie_watch_link",on_delete=models.CASCADE) type = models.CharField(choices=Link_choice,max_length=1) link = models.URLField() def __str__(self): return str(self.movie) and this is views.py , what is problem? Views.py from django.views.generic import ListView,DetailView from .models import Movie,Movielinks class MovieList(ListView): model = Movie template_name = 'index.html' class MovieDetail(DetailView): model = Movie def get_object(self): object = super(MovieDetail,self).get_object() return object def get_context_data(self, **kwargs): context = super(MovieDetail,self).get_context_data(**kwargs) context["links"] = Movielinks.objects.first(movie=self.get_object()) return context i try everything but not working , when i change MovieDetail class as ListView working, but do not need this , error ; No movie found matching the query No movie found matching the query No movie found matching the query No movie found matching the query No movie found matching the query … -
Celery Beat and doesn't work correctly With Django orm
I have configured celery and celery beat in Django and they are working correctly except for one problem, When celery beat picks up my task and hand it to the celery worker, my query inside the task has no result, but when I check it myself it has results, below is my task: @shared_task def remove_expired_pending_task(): call_command("remove_pending") and below is the "remove_pending" command handle method: def handle(self, *args, **options): try: aware = pytz.timezone("Asia/Tehran") min_date = aware.localize(jdatetime.datetime.now() - jdatetime.timedelta(hours=7)) max_date = aware.localize(jdatetime.datetime.now() + jdatetime.timedelta(hours=7)) q = Payment.objects.filter( is_completed=False, date__range=(min_date, max_date) ) c = q.count() q.delete() self.stdout.write( f"{c} pending Payament deleted between\ {min_date.strftime('%Y/%m/%d %H-%M-%S')} | \ {max_date.strftime('%Y/%m/%d %H-%M-%S')}") except Exception as exc: self.stderr.write( f"Exception happend in 'Remove pendings'\n: {exc}") and in the celery.py file after the celery app declaration I added this: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(1000.0, remove_expired_pending_task.s(), name='remove_expired_pendings') as I told, celery find and execute the task, but the query returns empty Queryset, but when I run: python manage.py remove_pending it works and Qeuryset is not empty and delete them successfully. do you know why this happens? thank you. -
Django forloop change template after x element
Hi, I try to achieve custom grid with bootstrap 4 using forloop counter. Unfortunately for me something causes the elements to fall apart. I know Im close to achieve this but I try do this for several hours and still I failed to do this. My code: {% for article in healtharticles %} <div class="col-lg-4 col-md-12 mb-4 mb-lg-0"> <!-- News block --> {% if forloop.counter0 < 1 %} <div> <!-- Featured image --> <div class="bg-image hover-overlay shadow-1-strong ripple rounded-5 mb-4" data-mdb-ripple-color="light"> <img src="https://mdbootstrap.com/img/new/fluid/city/113.jpg" class="img-fluid" /> <a href="#!"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div> </a> </div> <!-- Article data --> <div class="row mb-3"> <div class="col-6"> <a href="" class="text-info"> <i class="fas fa-plane"></i> Travels </a> </div> <div class="col-6 text-end"> <u> 15.07.2020</u> </div> </div> <!-- Article title and description --> <a href="" class="text-dark"> <h5>This is title of the news</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, iste aliquid. Sed id nihil magni, sint vero provident esse numquam perferendis ducimus dicta adipisci iusto nam temporibus modi animi laboriosam? </p> </a> {% else %} <hr /> <!-- News --> <a href="" class="text-dark"> <div class="row mb-4 border-bottom pb-2"> <div class="col-3"> <img src="https://mdbootstrap.com/img/new/standard/city/041.jpg" class="img-fluid shadow-1-strong rounded" alt="" /> </div> <div class="col-9"> <p class="mb-2"><strong>Lorem ipsum … -
How can I compare two dates in the database so that the next one starts with the previous one?
I have model "Education" where the user must enter the years of study at the university. So I just wanna that when the user adds the year of the beginning of studing, the year of the end of studing cannot be lower than the year of the beginning of studing and must be within +10 years from the year of the beginning of studing. Now my models looks like that: My models: def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Education(models.Model): name_university=models.CharField('University',max_length=300, blank=True) degree_of_edu=models.CharField('Degree of Education', max_length=25, blank=True) start_year=models.IntegerField('Start year',default=current_year(), validators=[MinValueValidator(1945), max_value_current_year]) end_year=models.IntegerField('End year', default=current_year()+1,validators=[MinValueValidator(1945), MaxValueValidator(2100)]) speciality=models.CharField('Speciality', default='Engineer', max_length=250, blank=True) def __str__(self): return '{}'.format(self.name_university) I have understood that IntegerFields can't compere with each other, because i have gotten an error already like this: '>' not supported between instances of 'int' and 'IntegerField' So for example: if u choosed or wrote: 2021, u would able to choose the end of studing only 2022-2031 Or is it possible to do this at all only at the form stage? -
Why am I very-occasionally getting an ImportError using django-constance?
Once every few hundred thousand requests I see one of these: ImportError at / cannot import name 'Config' from partially initialized module 'constance.base' (most likely due to a circular import) (/usr/local/lib/python3.9/site-packages/constance/base.py) I cannot identify any rhyme or reason. It doesn't correspond with accessing constance admin, just randomly occurs. My best guess is it's something to do with the LazyObject in constance's __init__.py, and maybe random race-conditions in restarting expired gunicorn workers or something?! I'm using: Python 3.9.2 Django 3.2 django-constance = {extras = ["database"],version = "==2.8.*"} "constance" and "constance.backends.database" in INSTALLED_APPS (at top) CONSTANCE_BACKEND = "constance.backends.database.DatabaseBackend" "constance.context_processors.config" in TEMPLATES[0]["OPTIONS"]["context_processors"] All my code does is from constance import config and access config attributes in the standard way in python code and Django templates. For what it's worth, we've been using django-constance on this site for years, but never saw this error until we upgraded to 2.8.0 (from 2.6.0). We were using Django 3.1 when it first appeared, but has also occurred since upgrading to 3.2. I cannot find any similar error reports on https://github.com/jazzband/django-constance/ Any ideas what could be causing this and how to resolve it? -
Django and bootstrap contact form not working
I'm trying to make a Django contact form with bootstrap styles, but it's not working. I tried in the views with send_mail instead of EmailMessage but still not work. When I click on the "Send" button, the page just get reloaded and nothing more happens, I don't get any email. Note that I have changed the email address and password for security purposes but it is a gmail account. Here are my files: home.html <footer class="bg-dark text-white pt-3" id="contact"> <div class="row text-center col-lg-12"> <div> <h3>Contact</h3> <img src="{% static 'home_app/img/contact.png' %}" class="img-fluid"> </div> </div> <div class="col-lg-12 mx-auto"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-6 col-sm-3" > <input type="text" class="form-control" name="name" placeholder="Name and last name" required> </div> <div class="col-lg-6 col-sm-3"> <input type="tel" class="form-control" name="subject" placeholder="Subject" required> </div> <div class="col-lg-12 col-sm-6"> <input type="text" class="form-control" name="email" placeholder="email@example.com" required> </div> <div class="col-lg-12 col-sm-6"> <textarea class="form-control" name="text" placeholder="Write your message" rows="5"></textarea> </div> <div class="col-lg-12"> <button type="Submit" class="btn btn-primary w-100 fs-5">Send</button> </div> </div> </form> </div> </footer> views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.mail import send_mail def contact(request): if request.method == "POST": name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('text') return redirect('contact') email=EmailMessage("Message from Django", "User: {} … -
Struggling to see the utility of custom Django Model Managers
I do not have any code for this question, so this will be more about the utility of customer Managers, more so than it is an implementation question. I have read the documentation, many blog posts and tried to implement some myself, but I cannot find the utility in Django custom model Managers. I understand that they can help segment code and can help with DRY principles, but I struggle to see how. So this question can be broken down into a few subpoints How does this help with DRY principles? How does this help with code segmentation? What can managers do that views or model methods cannot do? -
Django Queryset over multiple ForeignKeys
I am struggling with building a QuerySet to get all objects belonging to the current logged-in user. The bills are assigned to a Customer, and CustomerUser objects are assigned to the Customer: ┌──────┐ ┌──────────┐ │ Bill │ ───► │ Customer │ └──────┘ FK └──────────┘ ▲ │ │ FK ┌──────────────┐ │ CustomerUser │ └──────────────┘ │ │ FK ▼ ┌──────────────────────────┐ │ contrib.auth.models.User │ └──────────────────────────┘ Models: class Bill(models.Model): date = models.DateField(blank=False) total = models.FloatField(blank=False, null=False, default=0.0) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) class Customer(models.Model): name = models.CharField(max_length=25, blank=False, null=False) class CustomerUser(models.Model): first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) Basically I want to craft a QuerySet that returns the Bill objects the CustomerUser has access to. Can this be done with a single QuerySet?