Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django app doesn't validate JWT token or doesn't see JWT token from microsoft Azure via React-front
There is an application - front on React, back on Django. There is also an application on Microsoft Azure for user authentication. I use this tutorial to validate the token: Validating JSON web tokens (JWTs) from Azure AD, in Python Following it, 2 files are created. demo.py: import jwt from jwksutils import rsa_pem_from_jwk # To run this example, follow the instructions in the project README # obtain jwks as you wish: configuration file, HTTP GET request to the endpoint returning them; jwks = { "keys": [ { "kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk", "nbf": 1493763266, "use": "sig", "kty": "RSA", "e": "AQAB", "n": "tVKUtcx_n9rt5afY_2WFNvU6PlFMggCatsZ3l4RjKxH0jgdLq6CScb0P3ZGXYbPzXvmmLiWZizpb-h0qup5jznOvOr-Dhw9908584BSgC83YacjWNqEK3urxhyE2jWjwRm2N95WGgb5mzE5XmZIvkvyXnn7X8dvgFPF5QwIngGsDG8LyHuJWlaDhr_EPLMW4wHvH0zZCuRMARIJmmqiMy3VD4ftq4nS5s8vJL0pVSrkuNojtokp84AtkADCDU_BUhrc2sIgfnvZ03koCQRoZmWiHu86SuJZYkDFstVTVSR0hiXudFlfQ2rOhPlpObmku68lXw-7V-P7jwrQRFfQVXw" } ] } # configuration, these can be seen in valid JWTs from Azure B2C: valid_audiences = ['d7f48c21-2a19-4bdb-ace8-48928bff0eb5'] # id of the application prepared previously issuer = 'https://ugrose.b2clogin.com/9c2984ff-d596-4e5c-8e74-672be7b592e3/v2.0/' # iss class InvalidAuthorizationToken(Exception): def __init__(self, details): super().__init__('Invalid authorization token: ' + details) def get_kid(token): headers = jwt.get_unverified_header(token) if not headers: raise InvalidAuthorizationToken('missing headers') try: return headers['kid'] except KeyError: raise InvalidAuthorizationToken('missing kid') def get_jwk(kid): for jwk in jwks.get('keys'): if jwk.get('kid') == kid: return jwk raise InvalidAuthorizationToken('kid not recognized') def get_public_key(token): return rsa_pem_from_jwk(get_jwk(get_kid(token))) def validate_jwt(jwt_to_validate): public_key = get_public_key(jwt_to_validate) decoded = jwt.decode(jwt_to_validate, public_key, verify=True, algorithms=['RS256'], audience=valid_audiences, issuer=issuer) # do what you wish with decoded token: … -
How to filter ForeignKey choices in a Django admin inline form (TabularInline)?
I have these 4 models: class Model_A(models.Model): ... class Model_B(models.Model): model_a = models.OneToOneField("Model_A", primary_key=True) model_c_fk = models.ForeignKey("Model_C") model_d_fk = models.ForeignKey("Model_D") class Model_C(models.Model): choice_c = models.CharField() class Model_D(models.Model): model_c_fk = models.ForeignKey("Model_C") choice_d = models.CharField() In the admin form of the Model_A I want to filter the choices on Model_D based on the selected ForeignKey model_c_fk on Model_B_Inline. class Model_B_Inline(admin.TabularInline): model = Model_B def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == "model_d_fk": kwargs["queryset"] = Model_D.objects.filter(model_c_fk=1) # Should be model_c_fk="Model_B.model_c_fk" return super().formfield_for_foreignkey(db_field, request, **kwargs) @admin.register(Model_A) class Model_A_Admin(admin.ModelAdmin): inlines = [Model_B_Inline] It works with the formfield_for_foreignkey method if I pass just the id as an integer for testing purpose, but I don't know how I could access the value of the selected ForeignKey model_c_fk on Model_B. How could I achieve that? -
How to login to Django Admin panel with user I created in this panel? User model was extended
the model itself: from django.db import models from django.contrib.auth.models import AbstractUser class UserModel(AbstractUser): class UserType(models.TextChoices): MANAGER = 'm', 'Manager' CUSTOMER = 'c', 'Customer' first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) type = models.CharField(choices=UserType.choices, max_length=1) USER_MODEL is registered in setting in admin.py it's registered as: from django.contrib import admin from .models import UserModel admin.site.register(UserModel) I can create new model in the panel with existing superuesr I have. i.e. - it works. I can add new super users with manage.py and they appear in the same place in the panel. But later on I can't login with users I created in that panel. saff status - checked. The problem might be with passwords, because those created with createsuperuser shown hashed in the panel. or idk even. If I did smth completely wrong - let me know, I only need to extend users to have a couple of additional fields. django version 3.2 -
How to add new fields in custom user model?
I made a custom user model and It works perfectly. But Problem is, I tried many times to add new fields like first_name, last_name, phone_number, and so on but not working. It shows an error. What will be the relevant solution for it, how can I fix this and add new fields to the custom user model? models.py: class User(AbstractUser): email = models.EmailField( max_length=150,unique=True,error_messages={"unique":"The email must be unique."}) REQUIRES_FIELDS = ["email"] objects = CustomeUserManager() def __str__(self): return str(self.pk) + "." + self.username form.py: from django import forms from .models import User class UserRegistrations(forms.ModelForm): class Meta: model = User fields = ("username", "email", "password",) def clean_username(self): username = self.cleaned_data.get('username') model = self.Meta.model user = model.objects.filter(username__iexact=username) if user.exists(): raise forms.ValidationError( "Ther User already exist with the given username") return self.cleaned_data.get('username') def clean_email(self): email = self.cleaned_data.get('email') model = self.Meta.model user = model.objects.filter(email__iexact=email) if user.exists(): raise forms.ValidationError( "The email already exist with the given email") return self.cleaned_data.get('email') def clean_password(self): password = self.cleaned_data.get('password') confirm_password = self.data.get('confirm_password') if password != confirm_password: raise forms.ValidationError("Password do not match!") return self.cleaned_data.get('password') manager.py: from django.contrib.auth.base_user import BaseUserManager class CustomeUserManager(BaseUserManager): def create_user(self, username, email, password, **extra_fields): if not username: raise ValueError("The user must be set") if not email: raise ValueError("The email … -
How to add multiple rows of data to a single column of an existing instance of a model? Django
view linked to a form, to a model. I'd like to make it so that when I update one of those fields (current-command). It adds that data to another field (Executed_Commands). So then when I add another command later to that models via the form, which will update the Current_Commands field. It will simply add another row entry to the Executed_commands column. Rather then delete the data already in that column and replace it. models.py (relevant section) CHOICES = [ ('Sleep', "Sleep"), ('Open SSH_Tunnel', 'Open SSH_Tunnel'), ('Close SSH_Tunnel', 'Close SSH_Tunnel'), ('Open TCP_Tunnel', 'Open TCP_Tunnel'), ('Close TCP_Tunnel', 'Close TCP_Tunnel'), ('Open Dynamic', 'Open Dynamic'), ('Close Dynamic', 'Close Dynamic'), ('Task', 'Task'), ] class Command_Node(models.Model): host_id = models.ForeignKey(Beacon, on_delete=models.CASCADE) current_commands = models.CharField(choices=CHOICES, max_length=50, null=True), Executed_Commands = models.CharField('Executed_Commands', max_length=2000, null=True) def __str__(self): return str(self.host_id) forms.py (relevant section) class Command_Form(ModelForm): class Meta: model = Command_Node fields = ( 'host_id', 'current_commands' ) host_id = forms.ModelChoiceField( required=True, queryset=Beacon.objects.all(), widget=forms.SelectMultiple( attrs={ 'class': 'form-control' }, ) ) current_comamnds = forms.ChoiceField( required=True, choices=CHOICES ) views.py (relevant section) def update(request, host_id): host_id = Command_Node.objects.get(pk=host_id) form = Command_Form(request.POST or None, instance=host_id) if form.is_valid(): form.save() return redirect('home') return render (request, 'update.html', {'host_id':host_id,'form':form}) Any idea on how I would do this?. As I can find … -
Docker permissions issue with Django Tutorial. RUN pip throws error
I am following a Docker / Django tutorial. I am getting an error with RUN pip install -r requirements.txt . from within the Dockerfile. The error is: The command '/bin/sh -c pip install -r requirements.txt .' returned a non-zero code: 1 Here is my docker file: #Set enviornment variables ENV PIP-DISABLE_PIPVERSION_CHECK 1 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 #Set work directory WORKDIR /code #Install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt . #Copy project COPY . . -
How to show subcategories under category type
I need to get the child list under the parent list as a group. class ServiceSerializer(serializers.ModelSerializer): cleaning_type = serializers.CharField(source='cleaning_type.cleaning_type_name') class Meta: model = Service fields = ('id', 'cleaning_type','service_name') class ServiceTypeViewSet(ModelViewSet): serializer_class = ServiceSerializer http_method_names = ["get"] queryset = Service.objects.all() def get_queryset(self): """ This view should return a list of all the service types. """ servicename_list = Service.objects.all() return servicename_list It shows: [ { "id": 1, "cleaning_type": "Lite service", "service_name": "Floors", }, { "id": 2, "cleaning_type": "Lite service", "service_name": "Bathrooms", }, { "id": 3, "cleaning_type": "Lite service", "service_name": "Kitchen", } ] I want this to be in the following format: [ { id: 1, cleaning_type: 'Lite service', service_name: ['Floors', 'bathroom', 'kitchen'], }, { id: 2, cleaning_type: 'Moving cleaning', service_name: ['Kitchen Including All Appliances And Cabinets'], }, ] That means all child elements will be under a separate parent list. Not separate by separate. models.py is here: Cleaning Type Model: class CleaningType(models.Model): cleaning_type_name = models.CharField( _("Select Cleaning Type"), blank=True, null=True, max_length=255) price = models.DecimalField(default=0,max_digits=6, decimal_places=2) def __str__(self): return self.cleaning_type_name Service Model: class Service(models.Model): cleaning_type = models.ForeignKey( CleaningType, on_delete=models.CASCADE) service_name = models.CharField( _("Service Name"), blank=True, null=True, max_length=255) #string type added def __str__(self): return str(self.service_name) I want sub categories under parent caterories. Here cleaning_type … -
django get URL of ImageField
I have model with ImageField: class Category(models.Model): name = models.CharField(max_length=50, null=True, blank=True) icon = models.ImageField(upload_to='images/', blank=True, null=True) In settings.py initialized 2 variables: MEDIA_ULR = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'skyeng/media') in views.py get method: def get(self, request): query_set = Category.objects.all() items_data = [{ 'id': item.id, 'name': item.name, 'icon': item.icon.url} for item in query_set] return JsonResponse(items_data, safe=False) It should return the response as in the example: [ { "id": 1, "name": "Category1", "icon": "http://icon/url" } ] So how i need change my code that icon.url in get method was like in response example? -
how to view page only if the user pass another page first?
what I want to do is when the user wants to access the update and delete View he must to verify his identity by passing his right password if was right will open the views else won't but my problem is how to know if the user has verified himself in the update and delete views urls: app_name = "users" urlpatterns = [ path("login/", UsersLoginView.as_view(), name="login"), path("logout/", UserLogoutView.as_view(), name="logout"), path("register/", UserRegisterView.as_view(), name="register"), path("<str:username>/", UserAccountDetailView.as_view(), name="account"), path( "<str:username>/verify/edit", UserAccountEditView.as_view(), name="verify-edit" ), path( "<str:username>/verify/delete", UserAccountEditView.as_view(), name="verify-delete", ), path("<str:username>/edit/", UserAccountEditView.as_view(), name="edit"), path("<str:username>/delete/", UserAccountDeleteView.as_view(), name="delete"), ] mixins: from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.http import Http404 from django.contrib.auth import get_user_model from django.views.generic import FormView from django.urls import reverse_lazy from django.contrib import messages from django.shortcuts import redirect # Local Imports from . import forms User = get_user_model() class UserPassesHimselfMixin(LoginRequiredMixin, UserPassesTestMixin): """Test if the User who Sent the Reqeust he is the Logged in User""" def test_func(self): return self.request.user == self.get_object() def get_object(self, queryset=None): username = self.kwargs.get("username") qs = User.objects.filter(username=username) if qs.exists(): return qs.first() else: raise Http404("User Not Found") class VerifyUserIdentity(UserPassesHimselfMixin, FormView): """Verify User Identity By Form and Redirect to another Page - provide Form that has ```verify()``` mehtod that return bool value - else Raise … -
What limits are there on the number of fields on a Django model?
What practical limits are there on the number of fields a Django model can have? I'm thinking both at the code level, and at the database level (particularly both Sqlite and Postgres). If the specific version of anything is required then let's say we are talking about the latest LTS version (or nearest equivalent) of everything running on Ubuntu Server. -
Display index of each item of a sorted list in view Django DRF
I am developing an application with a Django backend and the DRF framework for my api. At a given url I would like to display the index (the rank) of each user once the list is sorted on my view. I can't explain it very well so I put two examples at the end of my message. I have not found anything on the internet about how to do this without modifying the template to add a field (I cannot use this solution). Would you have an idea? Thanks ! Below my view : class RankBestPurchaserViewset(viewsets.ViewSet): def list(self, request): queryset = User.objects.all() serializer = RankUserAllPurchaseSerializer(queryset, many=True) sortedList = sorted(serializer.data, key=itemgetter( 'amount'), reverse=True) return Response(sortedList) Below my serializer : class RankUserAllPurchaseSerializer(serializers.BaseSerializer): def to_representation(self, instance): return { 'id': instance.id, 'username': instance.username, 'surname': instance.surname, 'amount': float(SaleProduct.objects.filter(sale__sender__username=instance.username).aggregate(Sum('price'))['price__sum'] or 0), 'qty_amount': SaleProduct.objects.filter(sale__sender__username=instance.username).count(), } Below the result : [ { "id": 3, "username": "An20", "surname": "Khalvin", "amount": 426.7, "qty_amount": 110 }, { "id": 1, "username": "AA_ENS", "surname": "gum", "amount": 0.0, "qty_amount": 0 }, { "id": 4, "username": "in22", "surname": "gum", "amount": 0.0, "qty_amount": 0 } ] desired result [ { "index":1, "id": 3, "username": "An20", "surname": "Khalvin", "amount": 426.7, "qty_amount": 110 }, { "index":2, "id": 1, … -
Django admin broken template when using uwsgi
When I start my application using python3 manage.py run server 0.0.0.0:8000 I can access Django admin just fine. However, when I run it using uwsgi the Django admin template is broken. The application works fine, but the website is displayed as simple text, no templates at all. For instance, here's the login page: How can I fix this? This my uwsgi.ini: [uwsgi] chdir = ./src http = :8000 enable-threads = true #harakiri = 300 master = true module = config.wsgi:application #processes = $(UWSGI_PROCESSES) #threads = $(UWSGI_THREADS) #max-worker-lifetime = $(UWSGI_MAX_WORKER_LIFE) workers = 32 thunder-lock = true vacuum = true workdir = ./src add-header = Connection: Keep-Alive http-keepalive = 65000 max-requests = 50000 max-requests-delta = 10000 max-worker-lifetime = 360000000000 ; Restart workers after this many seconds reload-on-rss = 2048 ; Restart workers after this much resident memory worker-reload-mercy = 60 ; How long to wait before forcefully killing workers # Increment the timeout to reach the target app. # http-timeout = 60 lazy-apps = true single-interpreter = true ignore-sigpipe = true ignore-write-errors = true http-auto-chunked = true disable-write-exception = true This is the settings.py for my app: """ Django settings for config project. Generated by 'django-admin startproject' using Django 3.2.7. For more … -
Problems with if statement and _set.all Django
I tried two ways to make a filter in the django template, but neither worked for me, I don't know if I'm sending the arguments wrong or if I'm missing something. I need to show a part of the template only if the 'user' is also part of the 'teacher' model (teacher has FK to User). My template: {% if user in user.teacher_set.all %} <tr> <td class="table-text typo-grey"><label class="float-left">Rol</label></td> <td class="rol centered"> <div class="ui input"> <select type="text" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}"> {% for rol in form.rol.field.queryset %} <option value="{{rol.pk}}">{{rol.name}}</option> {% endfor %} </select> </div> </td> </tr> {% endif %} This brings a empty queryset. I also tried creating a templatetag: @register.simple_tag def get_teachers_user(user): teacheruser = models.Teacher.objects.filter( user=user, active=True ) return {'teacheruser': teacheruser.latest('pk')} And then in template: {% get_teachers_user user as teacher_user %} {% if not user in teacher_user.teacheruser %} <tr> <td class="table-text typo-grey"><label class="float-left">Rol {{teacher_user.teacheruser}}</label></td> <td class="rol centered"> <div class="ui input"> <select type="text" id="id_{{form.rol.html_name}}" name="{{form.rol.html_name}}"> {% for rol in form.rol.field.queryset %} <option value="{{rol.pk}}">{{rol.name}}</option> {% endfor %} </select> </div> </td> </tr> {% endif %} Doesn't work either. Please if you have any advice please comment, also this template is for a FormView. Thanks -
Django/Apache2 CORS Error with CORS_ALLOWED_ORIGINS and Header in apache conf defined
I have my apache conf below: <VirtualHost *:80> Header set Access-Control-Allow-Origin "*" ServerAdmin ... ServerName semanticspace.io ServerAlias www.semanticspace.io ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/cuneyttyler/knowledgebase/knowledge-base-django/static <Directory /home/cuneyttyler/knowledgebase/knowledge-base-django/static> Require all granted </Directory> Alias /media /home/cuneyttyler/knowledgebase/knowledge-base-django/media <Directory /home/cuneyttlyer/knowledgebase/knowledge-base-django/media> Require all granted </Directory> <Directory /home/cuneyttyler/knowledgebase/knowledge-base-django/knowledgebase_python> <Files wsgi.py> Require all granted </Files> </Directory> WSGIPassAuthorization On WSGIDaemonProcess knowledge-base-django python-path=/home/cuneyttyler/knowledgebase/knowledge-base-django python-home=/home/cuneyttyler/knowle> WSGIProcessGroup knowledge-base-django WSGIScriptAlias / /home/cuneyttyler/knowledgebase/knowledge-base-django/knowledgebase_python/wsgi.py </VirtualHost> And my CORS_ALLOWED_ORIGINS in settings.py : CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080', 'http://semanticspace.io', 'http://www.semanticspace.io' ] Despite these, my requests from semanticspace.io results with CORS error. What's the cause of that? -
How to run custom openedx project in localhost
I have the edx-platform, ecommerce, ecommerce-themes, credentials and edx-theme directories. I have installed successfully tutor and devstack but I didn't find the way to replace these custom directories. So, what is the correct way to replace them ? After devstack runned successfully, I tried replacing the default directories with the custom ones but when I runned make dev.provision and then make dev.up but it didn't work, and then the logs said that there were some missing dependencies. -
Django and Nginx are redirecting in response
I have a project with Django and it is running using Nginx, gunicorn. And the URL of the Project is https://myweb/myapp(this I got from our IT). The problem is if I type my URL https://myweb/myapp/ it redirects to https://myweb/login (which doesn't exist and I got a 404 error), but actually, I want to have https://myweb/myapp/login, if I add to the URL /myapp/ it works for the first time, but it redirects again to https://myweb/dashboard/, again I want to have https://myweb/myapp/dashboard/, and so on. How can I properly redirect? or should say how to prevent Django from removing the prefix URL? the Nginx file: server { listen 127.0.0.1:100; server_name hammbwdsc02; client_max_body_size 4G; access_log /home/webapps/culturecrawler/logs/nginx-access.log; error_log /home/webapps/culturecrawler/logs/nginx-error.log; location /static/ { alias /home/webapps/culturecrawler/culture_crawler/static/; } location /media/ { alias /home/webapps/culturecrawler/culture_crawler/media/; } location /{ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; proxy_buffering on; proxy_buffer_size 128k; proxy_buffers 4 256k; proxy_busy_buffers_size 256k; proxy_connect_timeout 300s; proxy_read_timeout 300s; if (!-f $request_filename) { proxy_pass http://culture_crawler_app; break; } } # Error pages error_page 500 502 503 504 /500.html; location = /404.html { root /home/webapps/culturecrawler/culture_crawler/templates/; } and the gnicorn file: #!/bin/bash NAME="culture-crawler" # Name of the application DJANGODIR=/home/webapps/culturecrawler/culture_crawler # Django project directory SOCKFILE=/home/webapps/culturecrawler/run/gunicorn.sock # we will communicte using … -
Creating a double log in system for department and user
I'm using django to create an webapp. I have been asked if I can look at creating a sort of double log in system. For example: A nurse on the ward will open up my webapp and will be met with a login page for their ward. So all nurses on that ward will have that generic log in. Once they've logged in they will be met with a second login page where they can enter their normal user credentials that only they know. I'm quite stuck at how to achieve this currently - or if someone could suggest an alternative method I'd be grateful! -
Django loop through json object
How to loop through a JSON object in Django template? JSON: "data": { "node-A": { "test1": "val1A", "test2": "val2A", "progress": { "conf": "conf123A" "loc": "loc123A" }, "test3": "val3A" }, "node-B": { "test1B": "val1B", "test2B": "val2B", "progress": { "conf": "conf123B" "loc": "loc123B" }, "test3": "val3B" } } I am having trouble accessing the nested values "conf" and "lock" inside "progress". How can I access them in Django template if the data is passed as context i.e. return (request, 'monitor.html', {"data_context": json_data['data']})? -
django objects method is not responding in views.py
I am trying to make a django project with sqlite3 db. Currently, I am building a page which I want to get data from db but it is not responding :( this is my mdoels.py from django.db import models class BookBoardModel(models.Model): title = models.CharField(max_length=30, null=False) content = models.TextField() #to be updated after the sign up page pub_date= models.DateTimeField('date published') writer = models.CharField(max_length=20, null=True) this is my views.py from django.shortcuts import render,redirect from .models import BookBoardModel def bookHome(request): books = BookBoardModel.objects return render(request, 'index.html', {'books': books}) this is my index.html {% for data in books %} <h1>{{ data.title }}</h1> {% endfor %} it is not showing at all :(v But in the web page, it only shows this I checked the .objects are not responding. Is there any hints? -
how to filter foreign key
Hello their i have two table one is StudentData and other is Enrollment. Below are the codes for them class StudentData(models.Model): user = models.OneToOneField(CustomUser,on_delete=models.CASCADE) student_name = models.CharField(max_length=30, default=1) department = models.ForeignKey(Department,on_delete=models.CASCADE) program = models.ForeignKey(Program, on_delete=models.CASCADE) is_admitted = models.BooleanField(default=True) is_closed = models.BooleanField(default=False) class Enrollment(models.Model): student = models.ForeignKey(StudentData,on_delete=models.CASCADE) faculty = models.ForeignKey(TeachingSemester,on_delete=models.CASCADE) When student logins , the website shows data according to logged user , below is the code log_user = request.user student_information = StudentData.objects.filter(user=log_user) What can i do so that the Enrollment of only logged in is shown on the page? -
How do I add <a> tags to a Django HTML Email template?
I'm trying to set up a view to reset passwords. The HTML email template works fine, until I add a anchor tag which causes the emails to no longer be sent. I'm not getting any error messages so I'm not sure what the problem is. Is it not possible to send hyperlinks in an email? I want to try and create a button in the email so that a user will be redirected to reset their password when they click on it. in views.py: class CustomPasswordResetView(PasswordResetView): template_name = "accounts/password_reset.html" email_template_name = "accounts/password_reset_email.html" html_email_template_name = "accounts/password_reset_html_email.html" subject_template_name = "accounts/password_reset_subject.txt" success_url = reverse_lazy("accounts:password-reset-done") password_reset_html_email.html <!DOCTYPE html> <html> <head> </head> <body> {% autoescape off %} <div> <p><b>A password reset was requested for</b> {{ user.email }} If you did not request this, then disregard the email. To reset your password click on the link below.</p> <h1>HTML VERSION</h1> <a href="{% url 'accounts:password-reset-confirm' uidb64=uid token=token %}">Verify Email</a> <p> The link will expire in 24 hours. If clicking the link above doesn't work, please copy and paste the URL in a new browser window instead. </p> </div> {% endautoescape %} </body> </html> -
question about forms, how do i get instant user in a form field pyhton django
i have build some user to user message function. i have sender, receiver and text see below. The user now must choose his email and then the email where the message should go. But what i want is that the user dont need tho choose it self i need a form function that query instantly request.user. but i dont know how to implement that on form. And that the user is not shown in the receiver list. Srry for my bad english hope you understand me. views.py def mailEMployee(request): mail = Mailsysthem.objects.filter(ontvanger=request.user) receiver = Mailsysthem.objects.filter(ontvanger=request.user) sender = Mailsysthem.objects.filter(zender=request.user) user = CustomUser.objects.filter(email=request.user) form = Mailsythemform() if request.method == 'POST': form = Mailsythemform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('mail') context={ 'form':form, 'receiver':receiver, 'sender':sender.all, 'mail':mail, 'user':user } return render(request,'emp/mail.html', context) Forms.py class Mailsythemform(forms.ModelForm): class Meta: model= Mailsysthem fields= ['zender','ontvanger','subject','text'] models.py class Mailsysthem(models.Model): zender = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Zender') ontvanger = models.ForeignKey(to=CustomUser, null=True, on_delete=models.SET_NULL,related_name='Ontvanger') subject = models.CharField(null=True, max_length=200) text = models.TextField(max_length=300, null=True, blank=True, verbose_name='Bericht') date = models.DateTimeField(auto_now_add=True, blank=True) solftdelete = models.BooleanField(default=False) mail_opened = models.BooleanField(default=False) url.py path('mailemployee/', views.mailEMployee, name='mail'), -
Django email verification link goes to page not found
I am using conventional email code generation to verify email users. During development when I send the verification link to console and paste in browser it works fine but during production it says page not found.. Have tried all possible option no result. Kindly check the code below Validation view def activate(request, uidb64, token): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except(TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.save() messages.success(request, 'Thank you for your email confirmation. Now you can login your account.') return redirect('user-login') URL path('activate/(P<uidb64>[0-9A-Za-z_\-]+)/(P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/', user_views.activate, name='activate'), Email code format Please click on the link to confirm your registration, http://riflogistik.com/activate/(PMTI%5B0-9A-Za-z_%5C-%5D+)/(Pb6ymqe-66b9346a42751b6d94e729b4050698ba%5B0-9A-Za-z%5D%7B1,13%7D-%5B0-9A-Za-z%5D%7B1,20%7D)/ Kindly assist with the issue -
GCP App Engine w/Django: big pandas load in views is causing server error
One of my page views in GCP App Engine (standard) is failing to load. I've determined that the issue occurs when Django temporarily loads a large pandas dataframe from cache (30mb). This is necessary in order for my charts to grab a subset of the data for charts before page rendering (it is not being injected into the html at all). def myView(request): baseTable = cache.get("somecachekey") #issue is here chartDiv = makeChart(baseTable) return render(request, template_name = 'myView.html', context = {'chart' : chartDiv}) Interestingly, there are no server errors. The logs seem fine. Also, this view works successfully when I am locally hosting Django on my laptop. Any advice here? -
Use email created on cpanel to send message in django
i try to make setting for send message to user when they create account or rest password ( i use all auth ) ,, but when try to create acc to ex the page just still loading , it don't do anything how to fix it # email message send EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST= 'mail.filltasks.live' EMAIL_HOST_USER= 'no-reply@filltasks.live' EMAIL_HOST_PASSWORD= 'mypass_namecheap_acc' EMAIL_USE_TLS= True EMAIL_PORT= 465 DEFAULT_FROM_EMAIL = EMAIL_HOST_USER