Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model' in Django
I have been trying to post data in my Django application using ajax post. The data is getting saved but in the terminal I am coming up against the following error: AttributeError: 'ModelFormOptions' object has no attribute 'concrete_model' Here are the relevant codes intended to achieve my goal: Views.py: def saveMaterial(request): if request.is_ajax and request.method == "POST": form = CreateMaterialForm(request.POST) # It's a ModelForm mat_bom_list = CreateBomMatListFormset(request.POST, request.FILES) # Using Inline formset factory if form.is_valid(): form = form.save(commit=False) mat_bom_list = CreateBomMatListFormset(request.POST, request.FILES) if mat_bom_list.is_valid(): form.save() mat_bom_list.save() ser_instance = serializers.serialize('json', [ form, mat_bom_list, ]) return JsonResponse({"instance": ser_instance}, status=200) else: return JsonResponse({"error": form.errors}, status=400) return JsonResponse({"error": "Error"}, status=400) else: form = CreateMaterialForm() mat_bom_list = CreateBomMatListFormset() return render(request, "material_create.html", {"form": form, "mat_bom_list": mat_bom_list}) Ajax script: $('#materialListForm').submit(function(e) { e.preventDefault(); var serializedData = $(this).serialize(); console.log(serializedData); $.ajax({ url: "{% url 'material_create' %}", type: 'POST', data: serializedData, success: function() { console.log('Data Saved'); }, error: function (response, status, error) { alert(response.responseText); } }); }); The traceback: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/views/generic/base.py", line 69, in view return … -
Django chatroom sends message to another chatroom
I am trying to implement a chatroom consisting of only two users. One user should be present in all chatroom while the other user will be unique to each chatroom. more of like server chatting with one client at time. I am experiencing an issue. what is currently happening in my program is once two user are connected to server it sends all the message to second user (user connected later). I am using memurai as it supports redis API for windows. Here's my consumer.py and two html files trying to communicate to it. Consumer.py import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from channels.generic.websocket import WebsocketConsumer class WebConsumer(AsyncConsumer): global server_conn async def websocket_connect(self, event): server_conn.append(self) await self.send({ "type" : "websocket.accept" }) other_user = self.scope['url_route']['kwargs']['username'] print(other_user) user = self.scope['user'] print(user) await self.send({ "type" : "websocket.send", "text":"Hello World" }) chat_room = str(user) + str(other_user) print(event,' to ', chat_room) self.chat_room = chat_room await self.channel_layer.group_add( chat_room, self.channel_name ) async def websocket_receive(self, event): print('recieved', event) print(event['text']) await self.channel_layer.group_send( self.chat_room, { 'type':'chat_message', 'message': str(self.chat_room) } ) async def chat_message(self,event): print('message',event) await self.send({ "type":"websocket.send", "text": event['message'] }) async def websocket_disconnect(self, event): print('disconnected', event) index.html <html> <head> </head> <script> … -
Update and Filtering in Django using Tuple
For example I have a table in MySQL called EmployeeData that has columns Emp_ID, Comp_ID, Status. I want to bulk update the "Status" column using filtering. I have a list of tuples Emp_ID and Comp_ID: id_to_update = [(Emp_ID_1, Comp_ID_1),(Emp_ID_2, Comp_ID_2),...] For example: id_to_update = [(2, 10),(3, 30),...] How to do that in using Python Django? Thanks! -
Django Template Tags
I'm trying to create a link in my site that goes to a user's profile page, but right now when logged in it instead goes to the logged in users' profile page. The link is an author's name and I want it so that when clicked on goes to the authors profile page, instead of the logged in users' profile page. I think the problem is in my url template tag for the link (the first tag in post_index.html ) but I don't know what to do. post_index.html {% for post in post_list %} <article class="media content-section"> <img class= "rounded-circle article-img" src="{{ post.author.profile.profile_pic.url }}"> <div class="media-body"> <div class="article-metadata"> #Here! <a class="mr-2" href="{% url 'profile' %}">{{ post.author }}</a> <small class="text-muted">{{ post.published_date }}</small> </div> <h2><a class="article-title" href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p class="article-content">{{ post.text }}</p> </div> </article> {% endfor %} views.py @login_required def profile(request): if request.method == "POST": u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f"Your Account Has Been Updated! ") return redirect("profile") else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) return render(request, 'users/profile.html', {"u_form": u_form, "p_form": p_form}) models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(default="default.jpg", upload_to="profile_pics") def __str__(self): return … -
how to properly set a specific permission in different account type Saleor
This is the if statement for the user, i also want to set a specific permission. if account_type == "orderStaff": existing_account = OrderAccount.objects.filter(user=user).first() if existing_account is None: existing_account = OrderAccount.objects.create( user.userPermissions(OrderPermissions.MANAGE_ORDERS), // not working user=user ) -
How to improve approach on save form
I want to save a form, that gets some data initially set/edited before saving: class ProductCreateView( CreateView): model = Product form_class = ProductForm template_name = "store/create.html" def get_initial(self): return {"remark": "testnote"} def get_success_url(self): return reverse_lazy("index") def form_valid(self, form): self.object = form.save(commit=False) Product.objects.create(name = self.object.name, price = 99, remark = "NOTE",) return HttpResponseRedirect(self.get_success_url()) this works just fine, I have two questions though: I thought I could simply add data with get_initial but this is None when printing self.object.remark in form_valid. is this in general a smart approach? I need a new pk and this way I thought I can avoid guessing one (nogo ...). I was not able to populate the fields in the forms.py. -
Why Django query does not provide correct info
I need to query a data by first_name, last_name and dob. However, in a result view I am getting all names and dob from database; and not specific person. My view.py is: class SearchResulsView(generic.ListView): model = Patient template_name = 'admissions/search_results.html' def get_queryset(self): firstname = self.request.GET.get('firstname', '') lastname = self.request.GET.get('lastname', '') dob = self.request.GET.get('dob', '') object_list = Patient.objects.filter( Q(dob__icontains=dob) & Q(first_name__icontains=firstname) | Q( last_name__icontains=lastname) ) return object_list My form.html is: <form action="{% url 'search_results' %}" method="get"> <input type="text" name="dob" placeholder="dob"> <input type="text" name="firstname" placeholder="first name"> <input type="text" name="lastname" placeholder="last name"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> Here is a search result (all dob's are imaginable and not belong to a particular person): Jose Rodriguez Jan. 22, 1956 Jose Rodriguez Jan. 26, 1958 Jose Rodriguez April 24, 1983 Jose Rodriguez Feb. 22, 1958 Jose Rodriguez Oct. 22, 1979 Jose Rodriguez Sept. 21, 1967 -
Steps to track the time spend on a Page for a Django Project
I am trying to understand how tracking the time spend on a page work. I tried to implement it but got lost so I am looking for a simplified step by step guide to add it to my Django project. I have got the solution from here https://stackoverflow.com/a/28256223/13176726 but I do not know how to implement it. Step 1 Add the following script for all HTML templates: <script src="timeme.js"></script> <script type="text/javascript"> TimeMe.setIdleDurationInSeconds(15); TimeMe.setCurrentPageName("my-home-page"); TimeMe.initialize(); window.onload = function(){ setInterval(function(){ var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); document.getElementById('timeInSeconds').textContent = timeSpentOnPage.toFixed(2); }, 25); } </script> Step 2 I am not sure exactly to place the below code to send the data to the backend to be read in Django Admin to know which user has been spending on each page xmlhttp=new XMLHttpRequest(); xmlhttp.open("POST","ENTER_URL_HERE",true); xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds(); xmlhttp.send(timeSpentOnPage); I am not sure what are the correct steps and where to place the codes in order to implement users time tracking for each page on my Django Project so I need some guidance in this regard -
how to showing python code inside html template div without process it as a tag code in Django
i want to add hint in my html form text , to let the users use predefined python variable, for example : <div> note : you can use " {{company_name}} " tag in your input text to show the company name ! </div> but the " {{company_name}} " not showing up in html output as a text , i see insted : "" note : you can use " " tag in your input text to show the company name ! "" so how let Django template ignore " {{company_name}} " tag and process it as a text not as a code ? -
How to calculate total working hours in Django?
I created the following model: class Timesheet(models.Model): date = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data") entry = models.TimeField(auto_now=False, auto_now_add=False, verbose_name="Hora Entrada") lunch = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Início do Almoço") lunch_end = models.TimeField(auto_now=False, auto_now_add=False, null=True, blank=True, verbose_name="Fim do Almoço") out = models.TimeField(auto_now=False, auto_now_add=False, verbose_name="Hora de Saída") This is then returned in a table, that has an extra field called "Total Hours", in which I need to calculate the total worked hours. Each entry refers to the same day. And I have the following view: def timesheet(request): c = Timesheet.objects.all() context = {'c': c} return render(request, "tracker/timesheet.html", context) The calculation I need to do is: (out - entry) - (lunch_end - lunch). How can I achieve this? -
How to link a project to Django
I am trying to link a colour detection project with a Django Project, but I don't know how to do it correctly. Here is the function that I am trying to link the colours in the image to Post.colors and I want to make it generated directly once the image is uploaded Here is the models.py: class Post(models.Model): title = models.TextField(max_length=100) design = models.ImageField( blank=False, null=True, upload_to='new designs') date_posted = models.DateTimeField(default=timezone.now) colors= models.TextField(max_length=10,blank=True, null=True) def __str__(self): return self.title def imagecolors(self, *args, **kwargs): img = Image.open(self.design) size = w, h = img.size data = img.load() colors = [] for x in range(w): for y in range(h): color = data[x, y] hex_color_lower = ''.join([hex(c)[2:].rjust(2, '0') for c in color]) hex_color = hex_color_lower.upper() colors.append(hex_color) total = w * h color_hex = [] color_count = [] color_percent = [] df = pd.DataFrame() for color, count in Counter(colors).items(): percent = count / total * \ 100 # Do not make it int. Majority of colors are < 1%, unless you want >= 1% if percent > 1: color_hex.append(color) color_count.append(count) color_percent.append(percent) Post.colors=color_hex print(Post.colors) with the above it showing none in the template: {% for post in posts %} {{ post.colors }} {% endfor %} -
Why is Django object manager returning objects instead of their values?
I have two similar Django models inside an app called 'account' that I create and populate using migrations. When I query the contents of each table, one returns the expected values while the other returns 'objects' and I don't understand why. I start with two models: # models.py class AccountType(models.Model): type = models.CharField(max_length=25) def __str_(self): return self.type class MemberType(models.Model): type = models.CharField(max_length=16) label = models.CharField(max_length=32) def __str__(self): return self.label I populate them with these migrations: # 0001_create_table_accounttype.py class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='AccountType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=25)), ], ), ] # 0002_insert_accounttypes.py class Migration(migrations.Migration): dependencies = [ ('account', '0001_create_table_accounttype'), ] operations = [ migrations.RunSQL( sql=[ "INSERT INTO account_accounttype (type) VALUES ('Business');"], reverse_sql=[ "DELETE FROM account_accounttype WHERE type = 'Business';"], ), migrations.RunSQL( sql=[ "INSERT INTO account_accounttype (type) VALUES ('Personal');"], reverse_sql=[ "DELETE FROM account_accounttype WHERE type = 'Personal';"], ), ] # 0003_create_table_membertype.py class Migration(migrations.Migration): dependencies = [ ('account', '0002_insert_accounttypes'), ] operations = [ migrations.CreateModel( name='MemberType', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('type', models.CharField(max_length=16)), ('label', models.CharField(max_length=32)), ], ), ] # 0004_insert_membertypes.py class Migration(migrations.Migration): dependencies = [ ('account', '0003_create_table_membertype'), ] operations = [ migrations.RunSQL( sql=[ "INSERT INTO account_membertype (type, label) VALUES ('f', … -
Django admin panel is looking weird after deploy on elastic beanstalk... is expecting a nav_bar css and js files
Hi I just deployed a Django app on elastic beanstalk but just realized that the admin panel layout is broken. After looking in the browser console I have found that is expecting for nav_bar.js and nav_bar.css files. This error does not happen locally, as it is not expecting for those files. I would like to know what could be the reason for this to happen. Thank you in advance! Descriptive image -
Stop Django in Celery from opening new db connections for each task
I have multiple celery worker apps that receive tasks from redis and each task fetches data and/or saves data from/to the database using Django Models. import os from django.conf import settings from django.db import transaction from celery import Celery from .models import MyModel os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'workerapp.settings') import django django.setup() # Example task (I have multiple tasks in my celery each doing similar kind of thing) @app.task(bind=True, name='my_task') @transaction.atomic def my_task(task,model_pk): my_model = MyModel.objects.get(pk=model_pk) my_model.field_1 = True my_model.save() As I have muliple of these workers (6 of them) running at the same time with each having multiple tasks of their own, in many of the workers the following error is logged: fatal: remaining connection slots are reserved for non-replication superuser connections I am assuming for each task it is opening a new database connection. Is there a way to open a connection once and all tasks it receives run in the same connection? Or a better way to do it? By the way, new tasks are constantly being added to redis to be received by workers in shoots of several minutes each, every once in a while. -
customer_user() missing 1 required positional argument: 'create' IN SIGNALS
i have a view and signal called with post_save, it seems it is missing something but I cannot see what... I tried bunch of things... And I don't see the answer to question, there's even a lot of solved on positional arguments missing, but non to help my case. It must be simple enough so I can't see it... from .models import Customer from django.contrib.auth.forms import User from django.db.models.signals import post_save def customer_user(sender, instance, create, **kwargs): if created: group = Group.objects.get(name = 'customer') instance.groups.add(group) Mate.objects.create( user = instance, ) post_save.connect(customer_user, sender=User) Views: ... @unauthenticated_user def registerPage(request): form = CreateUserForm() err = '' if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() return redirect('login') else: err = form.error_messages context = {} return render(request, 'accounts/register.html', context) ... -
Getting trouble while deploying Django ASGI application on ubuntu server. NGINX has been used as webserver
I am facing a lot of trouble while deploying my Django ASGI application. I have tried all the solutions out there. In my ngix/error.log file, the error is: 2020/11/05 21:37:48 [error] 6716#6716: *31 connect() failed (111: Connection refused) while connecting to upstream, client: 103.144.89.98, server: 156.67.219.10, request: "GET /ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/ HTTP/1.1", upstream: "http://[::1]:9001/ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/", host: "156.67.219.10" In web-browser console, I am getting the following error: WebSocket connection to 'ws://156.67.219.10/ws/chat/bbd7182cd0ee95488f1a1e6f3fe0d8f94ed0d14e4db1dce713fe82a3231c523d/' failed: Error during WebSocket handshake: Unexpected response code: 400 Here is my settings.py file: WSGI_APPLICATION = 'thinkgroupy.wsgi.application' ASGI_APPLICATION = "thinkgroupy.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("0.0.0.0", 6379)], }, }, } Here is the file of nginx configuration: /etc/nginx/sites-available/thinkgroupy: #added this block upstream channels-backend { server localhost:9001; } server { listen 80; server_name 156.67.219.10; client_max_body_size 4G; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/admin/thinkgroupy/staticfiles/; } location /media/ { root /home/admin/thinkgoupy; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } #path to proxy my WebSocket requests location /ws/ { proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection “upgrade”; proxy_redirect off; proxy_set_header Host $host; } } Here is the supervisor file: /etc/supervisor/conf.d/thinkgroupy.conf: [program:asgi] # TCP socket used by Nginx backend upstream socket=tcp://localhost:9001 # Directory … -
Hackathon preparation [closed]
I have a hackathon coming up, although it is not really specified what we will be doing. My team and I have decided on building a web application. How best can we allocate the work between 3 people and work efficiently to make a great application within 24 hours -
Deploying Django web app - 503 Service Unavailable
I'm trying to deploy a Django web application. I'm deploying it using cPanel and the functionality "Setup Python App". The application is working on localhost on my machine. However, when deployed I keep getting a 503 error saying Service Unavailable! The server is temporarily busy, try again later! I have added my domain name into the ALLOWED_HOSTS list in settings.py, so that's not the issue. I have also tried deploying an empty Django app but the result was the same. Using an SSH connection, I tried running python manage.py runserver and there were no issues. Therefore, I guess the problem is not in the app. After an attempt to the URL I get the following in the error log: 2020-11-04 18:49:21.400909 [INFO] [2117345] [<ip>#APVH_www.<domain_name>.com:443] connection to [uds://tmp/lshttpd/APVH_www.<domain_name>.com:443:Django_Project-master_.sock] on request #0, confirmed, 0, associated process: 0, running: 0, error: No such file or directory! 2020-11-04 18:49:21.400923 [INFO] [2117345] [<ip>#APVH_www.<domain_name>.com:443] connection to [uds://tmp/lshttpd/APVH_www.<domain_name>.com:443:Django_Project-master_.sock] on request #0, confirmed, 0, associated process: 0, running: 0, error: No such file or directory! 2020-11-04 18:49:21.400929 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] Max retries has been reached, 503! 2020-11-04 18:49:21.401018 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] oops! 503 Service Unavailable 2020-11-04 18:49:21.401020 [NOTICE] [2117345] [<ip>#APVH_www.<domain_name>.com:443] Content len: 0, Request line: 'GET /djangotest/ HTTP/1.1' … -
404 Error: unable to serve static react build with django rest framework, unless I go to /index.html
I have a React front end that I turned into static files. I used npm run build to make the folder. Then I configured my Django Rest Framework: settings.py FRONTEND_ROOT = os.path.abspath(os.path.join(BASE_DIR, '..', 'frontend', 'build')) urls.py re_path(r'^(?P<path>.*)$', serve, { 'document_root': settings.FRONTEND_ROOT }), when I got to the localhost:8000, I get a 404 page. If howerver, i got to localhost:8000/index.html, then I dont get a 404 but the react app. The css and html are not loaded though. Is this a proper way to connect the static react to my django backend? Am I missing a step? -
Find an object in Django using a list inside JSONField
I have such a model in Django: class Event(models.Model): EVENT_TYPE_CHOICES = [(e, e.value) for e in EVENT_TYPE] event_type = models.TextField(choices=EVENT_TYPE_CHOICES) date_of_event = models.DateTimeField(default=timezone.now, db_index=True) event_data = JSONField() And there is the event_data JSONField there which has the following structure: 'project_id': project_id, 'family_id': family_id, 'variant_data': variant_data_list, 'username': user.username, 'email': user.email, Where variant_data_list is a list of such dict objects with 3 str values: {'xpos': xpos, 'ref': ref, 'alt': alt} Now, I need a way to find unique Event model object based on the supplied variant_data_list (each object inside of it should be found within a single Events' variant_data_list, is it possible to achieve somehow? The number of items in variant_data_list is from 1 to 3. Otherwise I am thinking of generating unique ids based on the variant_data_list each time it is written to postgres (but not sure how to make it either). Any suggestions would be greatly appreciated. -
django custom user field won't appear in admin form
I created a custom user model in django with an additional field. However although I can see it appear in the list view in Django's admin it won't appear in the form to create or update a user, even though I've amended these. models.py from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): # Need to support codes with leading 0, hence CharField secret = models.CharField(max_length=5) def __str__(self): return self.username forms.py from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = ('username', 'email', 'secret') class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email', 'secret') admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from .forms import CustomUserCreationForm, CustomUserChangeForm from .models import CustomUser class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['email', 'username', 'secret'] admin.site.register(CustomUser, CustomUserAdmin) -
Error when I delete instances in the django panel
I created a duplicate function in order to create a new and equal instance from an other. But when I try to delete the instance the next error appears: FOREIGN KEY constraint failed What must I do in my function for to solve it? My duplicate function is: def duplicate(scn): id_original = scn.id scn.id = Scenario.objects.order_by('id')[Scenario.objects.all().count()-1].id + 1 scn.name = scn.name + '_dup' scn.save() #ahora scn es el nuevo scn_original = Scenario.objects.filter(id=id_original)[0] return None -
Do I need different URLs for options for years selected to play a game? Made with python3 and Django
I'm trying to make a game with Django where you can select different episodes of a game show to play, and have a database with different episodes over the years. I want to have the user select the year, month, and specific episode that they want to play. If the years are 1990-2000, would I need to have a different URL (for example in urls.py: path('years/1997', views.1997, name = 'game-1997', repeat for all 1990-2000) in the list in Django for each year and access that with a get/post, or is there a way to just carry the selected year onto the page listing the months, and have that be used as a parameter for which set of months to display? For context, the code below would be what I would have in my views.py if I don't need to have a different page URL for each possible year: def months(request): request.GET.get('year_choice') episodes = clues.objects.order_by('airdate').distinct('airdate') months = [] for episode in episodes: episode.airdate = episode.airdate[6:7] month = calendar.month_name[int(episode.airdate)] if month not in months: months.append(month) context = { 'months': months } return render(request, 'game/months.html', context) If this doesn't make sense, please feel free to ask any questions. This is my first time … -
How to add limit to the line break in django template filter?
Here i am trying to add some filters to the post body content, I am using safe filter and truncatechars filter and i also want to use linebrake filter , if there is a single line break than don't show the content after that line break or if the number of chars exceed to the 200 than just show 200 hundred char if there is no line break. if the line break is after 50 chars than just show 50 chars i want to do the following thing but obvious right now this is wrong and showing me an error <p class="small text-muted">{{post.body|safe|truncatechars:200|linebreaksbr:1}}</p> -
'ascii' codec can't encode character '\u2019' in position 36: ordinal not in range(128)
i working on email confirmation in django, i want make token with PasswordResetTokenGenerator: tokens.py class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self, user, timestamp): return (text_type(user.pk) + text_type(timestamp) + text_type(user.is_active)) account_activation_token = TokenGenerator() views.py class Register(CreateView): form_class = SignupForm template_name = 'registration/register.html' def form_valid(self, form): if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(self.request) mail_subject = 'Activate your blog account.' message = render_to_string('registration/acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') and i get this error: Traceback (most recent call last): File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\base.py", line 97, in dispatch return handler(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\edit.py", line 172, in post return super().post(request, *args, **kwargs) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\views\generic\edit.py", line 142, in post return self.form_valid(form) File "C:\Users\user1\Desktop\config\mysite\account\views.py", line 63, in form_valid email.send() File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "C:\Users\user1\Desktop\config\myvenv\lib\site-packages\django\core\mail\backends\smtp.py", line 69, in open self.connection.login(self.username, …