Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - error while saving an object in `TabularInline` while the primary key is a string and is readonly
I have the following models: class Parent(models.Model): name = models.CharField(max_length=255) class Child(models.Model): id = models.CharField(primary_key=True, max_length=255) name = models.CharField(max_length=255) parent = models.ForeignKey(Parent, on_delete=models.CASCADE) The Child model has a primary key (ID) of type string. Now I'm trying to display the children in a TabularInline inline inside the Parent admin form and I want the ID field to be readonly: class ChildMemberLinkAdmin(admin.TabularInline): model = Child extra = 0 fields = ("id", "name") readonly_fields = ("id",) @admin.register(Parent) class ParentAdmin(admin.ModelAdmin): fields = ("name",) inlines = (ChildMemberLinkAdmin,) I created a parent and a child in Django Shell, and verified each has an ID and name. They're displayed correctly in Django Admin. However, when I click the Save button in the Parent form (even without changing anything) I get an error "Please correct the errors below.". When I debugged it I noticed that child's id is somehow missing, which is weird because my Child instance already has an ID which is displayed as readonly in the TabularInline in the form. When I remove id from the ChildMemberLinkAdmin.readonly_fields everything works correctly. Any idea how to fix this? I'm using the latest Django version: 3.2 -
Filter booked appointments by business working hour
Business working hours(TimeField) are stored for everyday in UTC time. BusinessHours table business = models.ForeignKey(Business) day = models.CharField(max_length=10) opening_time = models.TimeField() closing_time = models.TimeField() Appointment table appointment_time = models.DateTimeField() I'm trying to get particular day's appointments for the stored business hours range(between opening_time and closing_time). Here is the query appointments = models.Appointments.objects.filter(service_start_time__week_day=3, service_start_time__gte=datetime.utcnow(), service_start_time__time__range=(day_obj.opening_time, day_obj.closing_time)) Sometimes the closing_time may be greater than the opening_time. Above query is not getting the records due to this reason. For 03:00(opening) Indian standard Time to UTC is 22:30 and 20:00(closing) corresponding UTC is 14:30. In this case closing time seems greater than closing time. Query doesn't filter anything even though appointments available. How to solve this problem? -
Create a django program where data is input in a form, a python code creates a graph using the data, and the graph is displayed beneath the same form
I'm very new to Django and wish to write a program that does the following. The user gives inputs into a form. On clicking submit a graph is displayed underneath the form (the user must not be redirected to a different page). This graph must be created by a python code using the inputs that were originally submitted in the form. So far I've been able to make a program where the graph is created and displayed in a different html page. But I want it to be displayed in the same page underneath the form. I'm using matplotlib to make the graph. The graph is saved as a png image. Is there some way to go about this using only django? Thanking all responses in advance. -
Django JS autocomplete with Materialize
I'm trying to get the Materialize autocomplete function to work with a django. But for some reason the content won't show I did allot of debugging but I can't seem to find why it is not working and showing the options. Im using the following view: def search_companies(request): """ Search for relations on company names basis. """ companies = Relation.objects.all() data = [] for company in companies: data.append(company.company_name) return JsonResponse({'data': data}) And the following JavaScript in the template function autocompleted(){ fetch('/orders/search_companies/') .then(response => response.json()) .then(data => { var my_data = data.data; let myConvertedData = {}; $.each(my_data, function (index, value) { myConvertedData[value] = null; }); document.addEventListener('DOMContentLoaded', function () { const inputField = document.querySelector('.autocomplete'); M.Autocomplete.init(inputField, { data: myConvertedData, limit: 50, minLength: 1, }); }); }); } autocompleted(); -
Storing Data Temporarily in Django to be accessed across multiple Devices
I am working on an e-learning platform I have a scenario where a student is doing an timed exam and either their computer crashes or power failure, and hence so computer shuts down What would be a good way to store this information, such that when the user logs in again to their computer or a different device, they can continue from where they left, with the already answered questions. Thanks in advance -
instance error while saving Django form input to model
This error showing when tried to save inputs to model Cannot assign "3380786777": "Registration.nid" must be a "Nid" instance. I am using MySQL database in this project. Tried for hours to fix this. Already inserted values in Nid table and the Nid I tried to insert in Registration table does exist in Nid table. Here is my model: class Nid(models.Model): id = models.BigIntegerField(primary_key=True) fname = models.CharField(db_column='FName', max_length=100, blank=True, null=True) # Field name made lowercase. lname = models.CharField(db_column='LName', max_length=100, blank=True, null=True) # Field name made lowercase. dob = models.DateField() fathers_name = models.CharField(db_column='Fathers_Name', max_length=150, blank=True, null=True) # Field name made lowercase. mothers_name = models.CharField(db_column='Mothers_Name', max_length=150, blank=True, null=True) # Field name made lowercase. address = models.ForeignKey(Address, models.DO_NOTHING, db_column='Address_ID', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'nid' class Registration(models.Model): nid = models.OneToOneField(Nid, models.DO_NOTHING, db_column='NID', primary_key=True) # Field name made lowercase. date = models.DateTimeField(db_column='Date') # Field name made lowercase. center = models.ForeignKey(Center, models.DO_NOTHING, db_column='Center_ID', blank=True, null=True) # Field name made lowercase. mobile_no = models.IntegerField(db_column='Mobile_No', blank=True, null=True) # Field name made lowercase. age = models.IntegerField(db_column='Age') # Field name made lowercase. class Meta: managed = False db_table = 'registration' unique_together = (('mobile_no', 'center'),) Form: class PostForm(forms.Form): NID = forms.IntegerField() Date_of_Birth … -
Trouble Creating QuerySet of Django model objects with self-referential ForeignKey
Simply put I have two models A dialogue model: class Dialogue(models.Model): content = models.TextField() created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) And a choice model: class Choice(models.Model): option = models.CharField(max_length = 255) content = models.TextField() dialogue = models.ForeignKey( Dialogue, related_name = "choices", blank = True, null = True, on_delete = models.CASCADE ) subChoices = models.ForeignKey( "self", related_name = "parent", blank = True, null = True, on_delete = models.CASCADE ) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) You may have noticed the recursive ForeignKey "Choice.subChoices". This is where my issue lies. If I attempt to use the add() method via the instance of this model that I want to be added to a Choice's list of further choices, I get a "'Choice' object has no attribute 'add'". If I attempt to the the reverse and add an instance of the Choice model to a Choice's parents attribute it overwrites instead of creating a query set. Examples of both below: choice1 = Choice.objects.get(id = 1) choice2 = Choice.objects.get(id = 2) choice3 = Choice.objects.get(id = 3) choice1.subChoices.add(choice2) >>> AttributeError: 'Choice' object has no attribute 'add' choice2.parent.add(choice1) choice3.parent.add(choice2) print(choice1.subChoices) >>> Choice object(3) A print statement of choice1.subChoices.all() returns … -
celery app.delay() is keep on waiting for the response, not working
I am trying to experiment with celery with Redis broker in my Django application, but I am having a hard time getting it write can anyone point me where I am missing things my init.py from __future__ import absolute_import from .celery import app as celery_app __all__ = ('celery_app', ) my base_settings.py CELERY_BROKER_URL = 'redis://localhost:6379/' CELERY_RESULT_BACKEND = 'redis://localhost:6379/' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Asia/Kolkata' CELERY_ALWAYS_EAGER = True my celery.py from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') app = Celery('myapp') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.enable_utc = False app.conf.update(timezone='Asia/Kolkata', task_always_eager=True) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) In my views.py @app.task(name="test celery") def add(a, b): print(a, b, a + b) @api_view(['GET']) def testcelery(request): a = request.GET.get('a', 0) b = request.GET.get('b', 0) add.delay(a, b) the output of my celery worker >celery -A lylo worker --loglevel=info -c 5 -------------- celery@LAPTOP-VQHQANA1 v5.1.1 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2021-09-08 22:00:46 - *** --- * --- - ** ---------- [config] - ** … -
valueerror invalid model reference, how can i reference correctly
I had to change a number of my ManyToMany relations to reference a string instead of importing the model into the file so to avoid a number of circular importing errors. but when trying to run, now I am getting this error. ValueError: Invalid model reference 'dsi.administration.libraries.Library'. String model references must be of the form 'app_label.ModelName'. I don't know what would be the best way to reference this and I'd love to get anyone's input on this. the reference in question models.ManyToManyField("dsi.administration.libraries.Library", verbose_name='library choices') settings.py installed modules SHARED_APPS = ( "storages", "django_tenants", # mandatory 'dsi.events.event', 'dsi.administration.libraries', 'dsi.account' ) the app folder structure ├── dsi │ ├── account │ │ ├──__init__.py │ │ ├── models.py │ ├── events │ │ ├── event | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├──__init__.py │ ├── administration │ │ ├── libraries | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── general | │ │ ├── __init__.py | │ │ ├── models.py │ │ ├── __init__.py │ ├── __init__.py │ ├── urls.py │ └── settings.py ├── manage.py -
django server error (500) when DEBUG=False
This is base.py file from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent.parent SECRET_KEY = 'h@1lneuTr@lt1P - Holla!!! this is something crazy, $2423$#@$#@E@e#R3\e[' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ # typical django code... MIDDLEWARE = [ # typical django code... ] ROOT_URLCONF = 'neutraltip.urls' TEMPLATES = [ # typical django code... ] WSGI_APPLICATION = 'neutraltip.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ # typical django code... ] STATIC_URL = '/static/' # Static settings STATICFILES_DIRS = [ BASE_DIR / 'static', ] # Media settings MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' This is production.py from .base import * import environ import django_heroku env = environ.Env( DEBUG=(bool, False), ) SECRET_KEY = 'lol' # right now for convenience I've hard-coded these # despite having environ package DEBUG = False ALLOWED_HOSTS = ['*'] MIDDLEWARE.insert(1, 'whitenoise.middleware.WhiteNoiseMiddleware') DATABASES['default']['CONN_MAX_AGE'] = 60 STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' # Activate Django-Heroku. django_heroku.settings(locals()) I've renamed the original settings.py to base.py, and extended it to production.py. And also updated manage.py, wsgi.py and asgi.py. Basically following this approach -> https://simpleisbetterthancomplex.com/tips/2017/07/03/django-tip-20-working-with-multiple-settings-modules.html Everything looks just fine … -
No reverse match when rendering an email template with uid/token variable
I wrote a view for user signup including email verification. However, once the view tries to render the mail template, it breaks due to the below error. I don't even understand the error itself. Insights would be appreciated. According to some googling it may be that the uid is no string? NoReverseMatch at /signup/ Reverse for 'activate' with keyword arguments '{'uidb64': 'MTE', 'token': 'asnwwr-550108ae10aa04da212561866c8d1ae3'}' not found. 1 pattern(s) tried: ['activate/(?P[0-9A-Za-z_\-]+)/(?P[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$'] Mail template {% autoescape off %} Hi {{ user.username }}, Please click on the link below to confirm your registration: http://{{ domain }}{% url 'activate' uidb64=uid token=token %} {% endautoescape %} View def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) subject = 'Activate your Poller Account' message = render_to_string('userprofile/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), # Issue might sit here? 'token': account_activation_token.make_token(user), }) user.email_user(subject, message) return redirect('account_activation_sent') -
How to check if a user exists in the model that I made in Django?
I'm making login page and data is already saved in model I made and not usercreateform... and instead of searching the user in my model(UserAuthentication), it searches in Users ... view.py def loginpage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is UserAuthentication: #UserAuthentication is my model where data is stored login(request, user) return redirect('index') else: messages.warning(request, "Username OR Password is incorrect!") return redirect('login') else: return render(request, "HTML/login.html", context={}) login.html <form action="#" method="POST"> {%csrf_token %} <input class="text" type="text" name="username" placeholder="Username" required="" /> <br /> <br /> <input class="text" type="password" name="password" placeholder="Password" required="" /> <br /> <br /> {%for message in messages%} <p id="messages">{{message}}</p> <br /> {% endfor %} <input type="submit" value="LOGIN" /> </form> -
Django - "check_token" always returns TRUE
When a user registers on my app, an account verification link is sent to his email. When clicking on the link the first time, everything is fine and the account is verified, but when clicking on the same link again, the validation goes through, whereas it should raise an "authentication failed" error, since the "check_token" should return false, right? Here's the verification serializer: class VerifyAccountSerializer(serializers.Serializer): uid = serializers.CharField(min_length=1, write_only=True) token = serializers.CharField(min_length=1, write_only=True) class Meta: fields = ['uid', 'token'] def validate(self, attrs): uid = attrs.get('uid') token = attrs.get('token') uidb64 = force_text(urlsafe_base64_decode(uid)) user = UserAccount.objects.get(pk=uidb64) if user is None: raise AuthenticationFailed('Invalid account. Please contant support') if not PasswordResetTokenGenerator().check_token(user, token): raise AuthenticationFailed('Account verify link is invalid. Please contant support.') user.is_guest = False user.save() return user And the view function: @api_view(['POST']) def verify_account(request): if request.method == 'POST': data = {} serializer = VerifyAccountSerializer(data=request.data) if serializer.is_valid(): user = serializer.validated_data data['user'] = UserSerializer(user).data data['token'] = AuthToken.objects.create(user)[1] # delete previous token tokens = AuthToken.objects.filter(user=user.id) if len(tokens) > 1: tokens[0].delete() return Response(data, status=status.HTTP_200_OK) data = serializer.errors return Response(data, status=status.HTTP_400_BAD_REQUEST It's kinda weird why it's not raising an error, because, in my other serializer for resetting the password via a link as well, I have the exact same … -
Django .raw query doesn't return translations in Mysql, but does in SQLite
I have the following query in Django: available_vouchers = Vouchers.objects.raw( 'SELECT count(shops_shops.id) as total_coupons, * ' 'FROM vouchers_vouchers ' 'INNER JOIN shops_shops ON ' 'vouchers_vouchers.shop_id = shops_shops.id ' 'WHERE vouchers_vouchers.voucher_code <> vouchers_vouchers.voucher_parent ' 'AND vouchers_vouchers.voucher_aquired = 0 ' 'GROUP BY vouchers_vouchers.voucher_parent' ) The query is performed on 2 tables, that both have translations, using django.parler. This query works absolutely fine on SQLite3, and returns the translated fields (voucher_name) normally, even if its not in the query. (When running this query against SQLite directly, its doesn't show the voucher_name which is a translated field, so i guess the ORM takes care of that) While migrating to Mysql8, the query translates to this: available_vouchers = Vouchers.objects.raw( 'SELECT 1 as id, count(shops_shops.id) as total_coupons, vouchers_vouchers.* ' 'FROM vouchers_vouchers ' 'INNER JOIN shops_shops ON ' 'vouchers_vouchers.shop_id = shops_shops.id ' 'WHERE vouchers_vouchers.voucher_code <> vouchers_vouchers.voucher_parent ' 'AND vouchers_vouchers.voucher_aquired = 0 ' 'GROUP BY vouchers_vouchers.voucher_parent' ) The weird "1 as id" is needed by Django ORM, as the primary key need to be returned always in raw queries. But here, the translated fields are not returned. Running both queries against their respective database outside Django, return the same columns. Anybody ever encountered something like this? Django > … -
carousel not working inside for loop django
i have a posts that iterate and display them my images is showing but my carousel's button next and prev are not working.i spend more time on finding solutions but nothing... and i notice it works fine without the for loop but with for loop it is a problem .this is what i have tried so far it is not working at all... {% for post in posts %} <div class="w3-container w3-card w3-white w3-round"> <!-- skip --> <!-- my problem starts here --> {% with posts=post.imageprofilepost_set.all %} {% if posts %} {% if posts.count > 1 %} <div id="myCarousel{{ post.pk }}" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> {% for i in posts %} {% if not forloop.counter0 %} <li data-target="#myCarousel{{ post.pk }}" data-slide-to="{{ forloop.counter0 }}" class="active"></li> {% else %} <li data-target="#myCarousel{{ post.pk }}" data-slide-to="{{ forloop.counter0 }}"></li> {% endif %} {% endfor %} </ol> <div class="carousel-inner"> {% for i in posts %} {% if not forloop.counter0 %} <div class="item active"> <div class="imgbox"> <a href="{{ i.images.url }}"> <img class="center-fit" src="{{ i.images.url }}"></a></div> </div> {% else %} <div class="item"> <div class="imgbox"> <a href="{{ i.images.url }}"> <img class="center-fit" src="{{ i.images.url }}"></a></div> </div> {% endif %} {% endfor %} </div> <a class="left carousel-control" href="#myCarousel{{ post.pk }}" … -
Learning PynamoDB and it's integration with Django
How can I learn PynamoDB from scratch? Is it necessary to learn Amazon SES before approaching PynamoDB? -
Why won’t the images automatically size when I upload them from the Django site
I’m new and don’t know CSS. I used a template on my Django site. When I add image links directly on the html page, they automatically size into the picture grid. However, when I add code and upload the pictures from the website, they all display with different sizes. I want them all consistent and fitting the pre-determined box size. -
Define constraints on the default through table of a ManyToManyField from meta class
I want to add some constraints to the meta class of a model that is an auto-created through model of a ManyToManyField. I followed the official docs here, and also implemented a meta class that sets the constraints successfully on the Meta class of the through model (assured by getting Model.many_to_many_field.through._meta.constraints value using the Django shell itself). The problem here is that the migration does not detect any changes on the mentioned through model hence no migration is created for the defined constraint. The question is then, is there any way to change the meta options of a through model without implementing them explicitly? -
Issues with CSRF on login form with React SPA and Django
I am building a React SPA with Django backend and Oauth using Django OAuth toolkit and have been asked by someone in the security team to implement CSRF protection on the login form of the app. No CSRF cookie will be present as Django is not serving the frontend app nor will users be logging in via Django sessions. I have created an API endpoint to provide CSRF tokens - to some degree following the instructions in this guide: https://www.stackhawk.com/blog/react-csrf-protection-guide-examples-and-how-to-enable-it/ The React app makes a call to this endpoint to retrieve a CSRF token. To add the CSRF protection on the login url - provided by Oauth toolkit /o/token I have subclassed the Oauth toolkit TokenView and pointed my login URL at it. I have used a decorator to add csrf protection: @method_decorator(csrf_protect, name="dispatch") class GetToken(TokenView): pass This seems to work correctly but when making the login request I cannot seem to get Django to accept the CSRF token I have retrieved from my endpoint - I am trying to provide it in the request body (as csrfmiddlewaretoken) and as a HTTP header (X-CSRFToken). When I make the request and debug Django CSRF middleware I can see that the request … -
When trying to add a link to the label of a form field an __init __ () got an unexpected keyword argument 'initial' error occurs
When I try to add a link to the label of a UserCreationForm field, I get the error __init __ () got an unexpected keyword argument 'initial'. My code looks like this: #forms.py class RegisterUserForm(UserCreationForm): email = forms.EmailField(required=True, label='Адрес электронной почты') check = forms.BooleanField() def __init__(self): super(RegisterUserForm, self).__init__() self.fields['check'].label = 'Принимаю политику конфиденциальности' % reverse('user:privacy') class Meta: model = AdvUser fields = ('username', 'email', 'password1', 'password2', 'check') views.py look like this: #views.py class RegisterUserView(SuccessMessageMixin, CreateView): model = AdvUser template_name = 'users/register_user.html' form_class = RegisterUserForm success_url = reverse_lazy('articles:list_view') success_message = 'Вы успешно зарегистрировались!' def form_valid(self, form): valid = super(RegisterUserView, self).form_valid(form) username, password = form.cleaned_data.get('username'), form.cleaned_data.get('password1') new_user = authenticate(username=username, password=password) login(self.request, new_user) return valid def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # 5 тегов с наибольшим количеством публикаций context['tags_list'] = Tag.objects.annotate(articles_quantiy=Count('taggit_taggeditem_items')).order_by( '-articles_quantiy')[:10] context['securities_types_list'] = StocksETFsBonds.objects.all() return context How can I solve this problem? -
Django Sending Email : SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed
I am trying to send email to an AOL account via Django and I am getting the following error: Traceback (most recent call last): File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Dom\Documents\Python_Projects\Django\TDD_with_Python_and_Django\superlists\accounts\views.py", line 21, in send_login_email [email], File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\__init__.py", line 62, in send_mail return mail.send() File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\message.py", line 348, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 104, in send_messages new_conn_created = self.open() File "C:\Users\Dom\.virtualenvs\superlists\lib\site-packages\django\core\mail\backends\smtp.py", line 71, in open self.connection.login(force_str(self.username), force_str(self.password)) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 721, in login initial_response_ok=initial_response_ok) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 631, in auth (code, resp) = self.docmd("AUTH", mechanism + " " + response) File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 421, in docmd return self.getreply() File "C:\Users\Dom\AppData\Local\Programs\Python\Python36_64\lib\smtplib.py", line 391, in getreply + str(e)) smtplib.SMTPServerDisconnected: Connection unexpectedly closed: [WinError 10054] An existing connection was forcibly closed by the remote host "POST /accounts/send_email HTTP/1.1" 500 130728 Here are my settings: EMAIL_HOST = 'smtp.aol.com' EMAIL_HOST_USER = 'myemail@aol.com' EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD') EMAIL_PORT = 465 EMAIL_USE_SSL = True I am following along with the book TDD with Python on Chapter 18, which has a custom authentication backend: class PasswordlessAuthenticationBackend(object): def authenticate(self, uid): print('uid', uid, file=sys.stderr) … -
Django application not working in Docker Container
I have a django website, works fine on local server, but when I build a docker image with it and run it as a container it gives me this error - 'TemplateDoesNotExist at /base.html ' My settings and file structure is correctly configured, proved by the fact that it is working locally, i'm not sure if something is changing the file structure during the containerization process Here is my dockerfile - `FROM python:3.9 WORKDIR /myapp ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN pip install pipenv COPY Pipfile . COPY Pipfile.lock . RUN pipenv install COPY . /myapp EXPOSE 8000 CMD ["pipenv", "run" ,"python", "manage.py", "runserver", "0.0.0.0:8000"] ` Template settings - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'main', 'templates', 'main')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] My templates are stored in 'app/main/templates/main' with app being the project folder and main being the folder for the app. -
Django 3.2 wsgi:error Not Found: /pwa-worker.js
I recently set up a new instance of django fresh under apache. All I have added is the admin page and the urls to the various authentication pages. The only app I installed is django-bootstrap-v5 (but its not currently installed in settings). I saw that the error log has Not Found: /pwa-worker.js when any of the pages are loaded. For example when this simple password reset is loaded {% block content %} <form action="" method="post"> {% csrf_token %} {% if form.email.errors %} {{ form.email.errors }} {% endif %} <p>{{ form.email }}</p> <input type="submit" class="btn btn-default btn-lg" value="Reset password"> </form> {% endblock %} I just didn't expect to see errors on a fresh install. Any idea what this file is or how to resolve it? -
Is there a way to grab specific "fields" from request.data sent to the Django REST framework API in a POST method
I've got a Project model, with a project_code field. When the API receives a POST request, the request.data will also contain a project_code. I then want to filter my Project model objects based on the project_code inside the request.data Once I've linked to request.data project_code to the Project model's project_code field, I want to save my Ticket model object to the database. Inside my Ticket model, there is a field called project which is related with a ForeignKey to the Project model. Thus in essence the project_code inside the POST request.data needs to be used in order to save my Ticket model to the database with the correct Project model foreign Key. Here are my models: from django.db import models class Project(models.Model): project_code = models.TextField(blank=True) project_description = models.TextField(blank=True) def __str__(self): return self.project_code class Ticket(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) ticket_url = models.TextField(blank=True) time_submitted = models.DateField(blank=True, auto_now_add=True) description = models.TextField(blank=True) user = models.TextField(blank=True) type = models.TextField(blank=True) def __str__(self): return self.description Here are my serializers: from rest_framework import serializers from ticketing_app_api.models import Ticket, Project class TicketSerializer(serializers.ModelSerializer): class Meta: model = Ticket fields = ['id', 'ticket_url', 'description', 'user', 'type'] And here are my views: from ticketing_app_api.models import Ticket from ticketing_app_api.serializers import TicketSerializer from rest_framework … -
Is there a way to upload prepared list of books to my library django app? Or a have to input every book separately?
I'm making my own Library computer application in Django and I am wondering if is there some json file or some database from which I can take prepared list of books with authors and some other informations or I have to input it on my own? And how about book's covers? Can I use it in my website or it woudl infringe the copyright?