Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files are not loading after app deployment on Heroku
from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent #BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-&(o=gy@^4mq_8%b%)7%9-34s45hp^0t0nxa#&l(-x+u50d3(+m' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['127.0.0.1','kiranfazaldjango.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'myapp.apps.MyappConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'myproject.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR / "templates"], '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', ], }, }, ] WSGI_APPLICATION = 'myproject.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.2/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles'), ] MEDIA_URL = … -
Im trying to update the email of a default user in django
I'm trying to update the default user model email with a Model Form and I messed something up in my views. How can I change the email to the input from the form. heres my views @login_required(login_url='home:login') def ChangeEmailView(request): if request.method == 'POST': form = EmailChangingForm(request.POST) if form.is_valid(): emailvalue = User.objects.get(pk=request.user.id) form = EmailChangingForm(instance=emailvalue) return redirect('home:profilesettings') else: form = EmailChangingForm() context = {'form': form} return render(request, 'home/email_settings.html', context) -
Django Rest Framework - Receive Primary Key in POST Response body
I try to build a rest api with Django Restframework. In this Api i use a Model called Event. models.py class Event(models.Model): key = models.IntegerField(auto_created=True, primary_key=True) start_date = models.DateTimeField() end_date = models.DateTimeField() subject = models.TextField(max_length=250) description = models.TextField(max_length=2500) created = models.DateTimeField(default=django.utils.timezone.now) host = models.ForeignKey('auth.User', related_name='host', on_delete=models.CASCADE, null=True) serializers.py class EventSerializer(serializers.HyperlinkedModelSerializer): host = serializers.StringRelatedField() key = serializers.IntegerField(read_only=True) class Meta: model = Event fields = ['url', 'key', 'start_date', 'end_date', 'subject', 'description', 'host'] views.py class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer @action(detail=True) def skills(self, request, *args, **kwargs): return get_key_values(TblClsOne=EventSkills, TblClsTwo=Skills, table_one_column_name="event_id", table_one_fk_name='skill_id', table_two_column_name="skill_id", table_one_filter_value=kwargs["pk"]) def perform_create(self, serializer): serializer.save(host=self.request.user) When I want to see the Details from a event i call GET /events/<id>/ GET /events/502/ Example { "url": "http://127.0.0.1:8000/events/502/", "key": 502, "start_date": "2021-09-23T20:00:00Z", "end_date": "2021-09-23T21:00:00Z", ... "host": null } But if i will create a new Event via POST /events/ i will receive empty fields für keyand url. How can i integrate the created values for this two fields? Theire are mandatory for navigating to the detail view. -
django.db.utils.ProgrammingError: (1146, "Table 'test_x.xxx' doesn't exist")
When I run tests in django app I get this error django.db.utils.ProgrammingError: (1146, "Table 'test_x.xxx' doesn't exist") I tried python manage.py makemigrations and migrate but it doesn't work. Where can be the problem? -
Why won't my django docker container connect to my postgresql container database? Psycopg2 issues?
I just started using django cookiecutter for a project I already made previously. I followed the instructions found here --> https://justdjango.com/blog/django-docker-tutorial to make sure I had the right folders and files to dockerize my project. I'm able to create the containers successfully docker-compose -f local.yml build command prompt log: [+] Building 13.2s (30/30) FINISHED => [tat_local_django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.96kB 0.0s => [tat_production_postgres internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 321B 0.0s => [tat_local_django internal] load .dockerignore 0.0s => => transferring context: 32B 0.0s => [tat_production_postgres internal] load .dockerignore 0.0s => => transferring context: 32B 0.0s => [tat_local_django internal] load metadata for docker.io/library/python:3.9-slim-buster 10.8s => [tat_production_postgres internal] load metadata for docker.io/library/postgres:13.2 10.8s => [auth] library/postgres:pull token for registry-1.docker.io 0.0s => [auth] library/python:pull token for registry-1.docker.io 0.0s => [tat_production_postgres internal] load build context 0.0s => => transferring context: 760B 0.0s => [tat_production_postgres 1/4] FROM docker.io/library/postgres:13.2@sha256:0eee5caa50478ef50b89062903a5b901eb8 0.0s => [tat_local_django internal] load build context 1.1s => => transferring context: 750.89kB 1.1s => CACHED [tat_production_postgres 2/4] COPY ./compose/production/postgres/maintenance /usr/local/bin/maintenanc 0.0s => CACHED [tat_production_postgres 3/4] RUN chmod +x /usr/local/bin/maintenance/* 0.0s => CACHED [tat_production_postgres 4/4] RUN mv /usr/local/bin/maintenance/* /usr/local/bin && rmdir /usr/loc 0.0s => … -
I have the following issue running my django homepage
Using the URLconf defined in naijastreets.urls, Django tried these URL patterns, in this order: admin/ The current path, Quit, didn’t match any of these. -
The 'user_image' attribute has no file associated with it | Djanfo
CODE EXPLANATION In the following code, I had created a user dashboard which is displayed after user creates an account. On dashboard user image is also displayed whether user has uploaded or not. If the user hasn't uploaded the image then a default image is displayed which can be seen below in the code. But it is showing error if user has not uploaded image and works fine if user has uploaded an image. CODE {% if values.user_image.url %} <a class="image" href="{% url 'setting' %}"><img src="{{ values.user_image.url }}" alt=""></a> {% else %} <a class="image" href="{% url 'setting' %}"><img src="{% static 'img/user.png' %}" alt=""></a> {% endif %} ERROR ValueError at /user/setting The 'user_image' attribute has no file associated with it. Request Method: GET Request URL: http://127.0.0.1:8000/user/setting Django Version: 3.2.6 Exception Type: ValueError Exception Value: The 'user_image' attribute has no file associated with it. Exception Location: C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\db\models\fields\files.py, line 40, in _require_file Python Executable: C:\Users\Qasim Iftikhar\anaconda3\python.exe Python Version: 3.8.5 Python Path: ['C:\\xampp\\htdocs\\Projects\\Barter', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\python38.zip', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\DLLs', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\win32\\lib', 'C:\\Users\\Qasim Iftikhar\\anaconda3\\lib\\site-packages\\Pythonwin'] Server time: Sat, 25 Sep 2021 14:38:10 +0000 -
Django Template URL not recognize global value
Starting from a Class based update view (Header table), I call a Class based List View to recover all the details lines created (Lines table) for my Header. It works fine, I can add lines if they don't exist and I can update lines without problems. I have created a GLOBAL val that contains the key value of my Header and here also it works, my List View contains only the lines corresponding to that value. Now I would like to insert a button in the html associated to my List View to return to my Header. The URL works perfectly if hardcode the Header key value but if I try to insert Global variable it doesn't work, it seems that the Global value is empty and obviously I receive errore messages related to a wrong Url. I cannot find the right syntax, I tried a lot of different possibilities without success. Could someone help me? Thanks in advance. Urls.py: urlpatterns = [ path('fttlapphome/', views.fttlapphome, name='fttlapphome'), path('headfttlog/', HeadfttlogListView.as_view(), name='headfttlog_list'), path('headfttlog/add/', HeadfttlogCreateView.as_view(), name='headfttlog_add'), path('headfttlog/<str:pk>/', HeadfttlogUpdateView.as_view(), name='headfttlog_update'), path('deafttlog/', DeafttlogListView.as_view(), name='deafttlog_list'), path('deafttlog/add/', DeafttlogCreateView.as_view(), name='deafttlog_add'), path('deafttlog/<str:pk>/', DeafttlogUpdateView.as_view(), name='deafttlog_update'), path('debfttlog/', DebfttlogListView.as_view(), name='debfttlog_list'), path('debfttlog/add/', DebfttlogCreateView.as_view(), name='debfttlog_add'), path('debfttlog/<str:pk>/', DebfttlogUpdateView.as_view(), name='debfttlog_update'), path('decfttlog/', DecfttlogListView.as_view(), name='decfttlog_list'), path('decfttlog/add/', DecfttlogCreateView.as_view(), name='decfttlog_add'), path('decfttlog/<str:pk>/', … -
Should I create a model to contain another model instances? (Django)
I'm new to django so I'm not sure of the proper way to do things (or the convention). Say I want to make a project which contains my everyday notes. I'm going to create multiple notes every day (where each note is going to be an instance of a "Note" model). I want in my project-frontend to have containers, where I start with containers, each of a specific year (say 2020, 2021, ...) and each of these containers contains month containers (Jan, Feb, ...) and each of those contains day containers (1, 2, ..) and each of those contains the notes of this specific day. Now my question is should, in my backend, make a NoteYear model which has instances of a NoteMonth model which has instances of NoteDay model which has instances of Note model? The reason I thought of this is because it should be faster filtering to get to a specific day. (Of course I'll have a DateTimeField for each Note instance anyways). I'd love to hear your opinions! -
'while', expected 'endblock'. Did you forget to register or load this tag?
I'm working on an ebay like website. On the homepage I would like to render a bootstrap carousel with the most recent postings. I'm using a while loop to cycle through the images I send through to the Django template, but I keep getting this error I think I've properly checked my block tags for typeos, so I'm not sure what would be causing this error. I've also tried moving the endwith tag to after the endwith tag, to no avail. HTML {% extends "auctions/layout.html" %} {% block body %} <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script> <h2>Active Listings</h2> <div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel"> <ol class="carousel-indicators"> <li data-target="#carouselExampleIndicators" data-slide-to="0" class="active"></li> {% with i=0 %} {% endwith %} {% while i < images.count: %} <li data-target="#carouselExampleIndicators" data-slide-to="{{ i }}"></li> {% i+=1 %} {% endwhile %} </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="d-block w-100" src="/static/auctions/images/products.jpeg" alt="First slide"> <div class="carousel-caption d-none d-md-block"> <h5>Check Out What's New</h5> <p>Find these new items below!</p> </div> </div> {% for image in images %} <div class="carousel-item"> <img class="d-block w-100" src="{{ image.url }}" alt="Second slide"> </div> {% endfor %} </div> <a class="carousel-control-prev" href="#carouselExampleIndicators" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a class="carousel-control-next" … -
Django - Cannot access user profile from search query
I am trying to access the profile (OneToOne linked to CustomUser), however, I am not able to. When I try to call {{ user_element.profile.university }} it returns None. But my call request.user.profile.university works just fine. Surprisingly, {{ user_element.first_name }} works fine again. Hence, the issue must be somehow that I am unable to access profile. However, if I type profile wrong (e.g. profile2), it returns "" instead of None. What did I do wrong? models.py: class CustomUser(AbstractUser): pass class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="profile") highschool_or_university = models.CharField(max_length=6, choices=(("school", "Highschool"), ("uni", "University")), blank=True, null=True) date_of_birth = models.DateField(blank=True, null=True) image = models.ImageField(upload_to='users/%Y/%m/%d/', blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) university = models.ForeignKey(University, on_delete=models.SET_NULL, null=True) views.py: class SearchResultsView(ListView): model = CustomUser template_name = 'network/search.html' def get_queryset(self): query = self.request.GET.get('q') ret = CustomUser.objects.annotate(full_name=Concat('first_name', V(' '), 'last_name')).filter( full_name__icontains=query) req_email = self.request.user.email ret = ret.exclude(email=req_email) return ret urls.py: urlpatterns = [ path('feed', views.home, name="home"), path('', views.landing, name="landing"), path('about', views.about, name="about"), path('search/', login_required(SearchResultsView.as_view()), name='search'), path('profile_detail/<int:id>/', views.profile_detail, name='profile_detail'), ] search.html: {% extends "base.html" %} {% load static %} {% block title %}Search{% endblock %} {% block content %} <div class="w3-card w3-round w3-white" style="margin: 4px"> <div class="w3-container w3-padding"> <h4>Search Results</h4> </div> {% for user_element in object_list %} <a href="{% … -
Django test OperationalError can't create table
When I'm trying to run my tests in django I get this error django.db.utils.OperationalError: (1005, 'Can\'t create table `test_grocerycheck`.`grocery_check_customuser_groups` (errno: 150 "Foreign key constraint is incorrectly formed")') This table is automatically created by AbstractUser. What should I do in this situation? -
How can I send only notification requests in docker
I am developing a website where there is a buyer and seller. They can chat each other. I know there is a library in django thats called Django channels. But I dont want to use it. I builded such a thing on my own. Every thing works fine. But when i try to integrate a notification system the server loads a lot. Everything seems. But I got a plan to solve this issue. But I dont know it will work. Thats why I am posting a qustion about the idea. For Notification system I requested GET method in every pages. So Is it possible to send all the reuqests to docker so that i could reduce the load. Or can someone give me an idea to solve this Issue? -
How to generate an XML file from serialized data?
I have created an endpoint following a tutorial which returns the response in XML format: class MyxmlRenderer(XMLRenderer): root_tag_name = 'License' item_tag_name = 'Details' class xmlView(APIView): renderer_classes = [MyxmlRenderer, ] def get(self, request): queryset = Details.objects.all() xml_serializer = DetailSerializer(queryset, many=True) return Response(xml_serializer.data) I was able to create json file from json_serialized data using: with open('data.json', 'w') as f: json.dump(json_serializer.data, f, indent=4) But I'm having difficulty in creating an xml file as xml_serializer data is of type ReturnList and not str. Any help would be greatly appreciated. Thanks. -
Why django form valdation error does not work in my form
I want to show user validation error but seems that this is not working in my login form here is the code my forms.py class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput()) password = forms.CharField(widget=forms.PasswordInput()) remember_me = forms.BooleanField(required=False, label='Remember Me',help_text='Keep me logged in.',widget=forms.CheckboxInput()) def clean(self, *args, **kwargs): username = self.cleaned_data.get("username") password = self.cleaned_data.get("password") if username and password: user = authenticate(username=username, password=password) if not user: raise forms.ValidationError("This user doesn't exist") if not user.check_password(password): raise forms.ValidationError("Incorrect Password") if not user.is_active: raise forms.ValidationError("User no longer Active") return super(LoginForm,self).clean(*args,**kwargs) my views.py for login def my_login(request): if 'next' in request.GET: messages.add_message(request, messages.WARNING, 'To Continue, Please login here!') if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] remember_me = form.cleaned_data['remember_me'] user = authenticate(username=username, password=password) if user: login(request, user) if not remember_me: request.session.set_expiry(0) return redirect('accounts:home') else: request.session.set_expiry(1209600) return redirect('accounts:home') else: messages.info(request, 'Please check your credentials.') return redirect('accounts:login') else: form = LoginForm() return render(request, "login.html", {'form': form}) i know i am redirecting the form if form credential is wrong but if i don't i will throw error didn't return a httpresponse it return none instead also want to what is the best way to redirect or show exact validation error of which credential is wrong -
passs list to django template
hi I'm having a problem moving list in view.py to charts.html this is my view.py and my charts.py i'm not sure what the problem is the label data format is str and data is integer. Thanks in advance for your help -
Cannot resolve keyword 'phone' into field django
I added a new field name phone for phone number in my registration form, but now it throws error when i submit it throws Cannot resolve keyword 'phone' into field. Choices are: address, date_joined, email, first_name, groups, id, is_active, is_staff, is_superuser, last_login, last_name, logentry, notifications, order, password, profile, user_permissions, username this error i am using Django default usercreation forms here is my forms.py class SignUpForm(UserCreationForm): phone_regex = RegexValidator(regex=r'^\+?1?\d{10}$', message="Inform a valid phone number.") email = forms.EmailField(max_length=254, required=True, help_text='Required. Inform a valid email address.') phone = forms.CharField(validators=[phone_regex], max_length=10, required=True, help_text='Required. Inform a valid phone number.') class Meta: model = User fields = ('username', 'email', 'phone', 'password1', 'password2',) def clean_email(self): email = self.cleaned_data['email'] qs = User.objects.exclude(pk=self.instance.pk).filter(email__iexact=email) if qs.exists(): raise ValidationError('A user with this email address already exists') return email def clean_phone(self): phone = self.cleaned_data['phone'] qs = User.objects.exclude(pk=self.instance.pk).filter(phone__iexact=phone) if qs.exists(): raise ValidationError('A user with same phone number already exists') return phone views.py class SignUpView(View): form_class = SignUpForm template_name = 'register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate … -
Django `output_type` for PostgreSQL row constructors
As part of some custom cursor-based pagination code, I'm expressing the below SQL that compares tuples/row constructors WHERE (col_a, col_b) > (%s, %s) ORDER BY col_a, col_b by using the Django ORM, and specifically using Func with alias, similar to this answer from django.db.models import F, Func, TextField col_a_col_b = Func(F('col_a'), F('col_b'), function='ROW', output_type=TextField()) col_a_col_b_from = Func(col_a_value, col_b_value, function='ROW') filtered_queryset = queryset .alias(col_a_col_b=col_a_col_b) .filter(col_a_col_b__gt=col_a_col_b_from) .order_by('col_a', 'col_b') It looks like for the Func, output_type is required, otherwise it throws the exception: Expression contains mixed types. You must set output_field It seems a bit odd to use TextField for this, but it works and I can see nothing better. Is there a more appropriate output_type to use, or a way to avoid having to set it? -
Django - User Registration with Modal Ajax
my user registration with modal form does not validate/save. It only just close immediately when you save and nothing happens. this is the views.py from django.template.loader import render_to_string from django.http import JsonResponse from authentication.forms import CustomUserCreationForm from django.contrib import messages def CreateUser(request): data = dict() if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): form.save() data["form_is_valid"] = True username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! You are now able to log in') return redirect('home/manage-users.html') else: data["form_is_valid"] = False else: form = CustomUserCreationForm() context = {'form': form} data["html_form"] = render_to_string('partial_modal/create-user.html', context, request=request) return JsonResponse(data) Any tips how can I work this my code? Thank you. -
Gain time intervals in Django
I created a model in Django that records user visits to the product. I want to check if the user's previous visit, for example, was an hour ago, another visit is recorded in the model. How can I get this time interval ?? -
Templates does not exist
How to specify a path to base_site.html that would have views the blog saw it. enter image description here -
how to reference a foreign key when making a command
I am trying to make a custom command that I can call up within my Django project but am running into an issue referencing the foreign key it references. How do I correctly reference the created instance in order to complete the command? Any help would be appreciated. models.py class Client(models.Model): name = models.CharField(max_length=50) class Project(models.Model): schema_name = models.CharField(max_length=50) client = models.ForeignKey(Client, on_delete=models.CASCADE) command class Command(BaseCommand): help = ( "commands, --create_public" ) def add_arguments(self, parser): parser.add_argument( '--create_public', action='store_true', help='creates public tenant' ) def handle(self, *args, **options): if options['create_public']: # create your public tenant client = Client(name='client1') client.save() tenant = Project(schema_name='public', client='client1', ) tenant.save() error ValueError: Cannot assign "client": "Project.client" must be a "Client" instance. -
How to change default password reset email in djoser
I want to change the default email template of djoser for sending password reset email, I saw one answer in stackoverflow for changing the activation mail but i don't know how to use that for password reset email code to change default email for activation: base/reset_email.py from djoser import email class ActivationEmail(email.ActivationEmail): template_name = 'base/resetPasswordMail.html' settings.py DJOSER = { 'EMAIL': { 'activation': 'base.reset_email.ActivationEmail' }, } how to replace this code for password reset functionality -
Django heroku Image issue
I m new to Django and Heroku, I would like to know if I could in Django upload pictures in a specific folder in Cloudinary? and then recall them in my HTML files later ? I have seen this option online? model.py : background_image = CloudinaryField(null=True, folder='01-categories/') do you have any idea? how I could upload from my admin page and then that upload to Cloudinary and then recall in HTML pages ?? -
Filter by date in django
I am trying to filter the delivery instruction table by date. Especially only in Delivery Instructions, table data will be removed after 7 days after the creation. So in its model, I used DateTimeField as a date-time format. But in other models (e.g Part), I used DateField, and in views.py I write the same function as below and it works. But the issue with Delivery instructions is filtered by date is not working. filters.py class DIFilter(django_filters.FilterSet): created_date = django_filters.CharFilter( widget=forms.TextInput(attrs={ 'placeholder': 'YYYY-MM-DD'})) class Meta: model = DeliveryIns fields = ['product','supplier', 'created_date'] views.py def get_queryset(self): queryset = self.model.objects.all().order_by('-id') if self.request.GET.get('supplier'): queryset = queryset.filter(supplier_id=self.request.GET.get('supplier')) elif self.request.GET.get('product'): queryset = queryset.filter(product_id=self.request.GET.get('product')) elif self.request.GET.get('created_date'): queryset = queryset.filter(created_date=self.request.GET['created_date']) return queryset models.py class EventManager(models.Manager): def get_queryset(self): return super().get_queryset().filter( created_date__gte=timezone.now()-timezone.timedelta(days=7) ) class DeliveryIns(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateTimeField(default=timezone.now) objects = EventManager() class Part(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) created_date = models.DateField(auto_now_add=True) Can anyone help me out whats the matter? Thank you in advanced