Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django displaying related objects
I have models for ProjectNotes and for ProjectNotesComments. ProjectNotesComments have a foreign key that is the ProjectNotes id. I am able to save comments on notes. I can see them in the admin panel. However I have not been able to figure out how to display the comments on the notes. Here are the models: class ProjectNotes(models.Model): title = models.CharField(max_length=200) body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) project = models.ForeignKey(Project, default=0, blank=True, on_delete=models.CASCADE, related_name='notes') def __str__(self): return self.title class ProjectNoteComments(models.Model): body = tinymce_models.HTMLField() date = models.DateField(auto_now_add=True) projectnote = models.ForeignKey(ProjectNotes, default=0, blank=True, on_delete=models.CASCADE, related_name='comments') Here is the view: class ProjectNotesDetailView(DetailView): model = ProjectNotes id = ProjectNotes.objects.only('id') template_name = 'company_accounts/project_note_detail.html' comments = ProjectNotes.comments This is the template I am currently using to test getting the comments to display: {% extends 'base.html' %} {% block content %} <div class="section-container container"> <div class="project-entry"> <h2>{{ projectnotes.title }}</h2> <p>{{ projectnotes.body | safe }}</p> </div> <div> </div> {% for comment in comments %} <div class="comments" style="padding: 10px;"> <p class="font-weight-bold"> {{ comment.body | linebreaks }} </div> {% endfor %} <h2><a href="{% url 'add_project_note_comment' projectnotes.pk %}">add note</a></h2> {% endblock content %} -
Clients getting timed out when attempting to connect to the public websocket server (Python)
def first(request): PORT = 7890 print("Server listening on Port " + str(PORT)) async def echo(websocket, path): print("A client just connected") try: async for message in websocket: print("Received message from client: " + message) await websocket.send("Pong: " + message + "\npath - " + path) except websockets.exceptions.ConnectionClosed as e: print("A client just disconnected") loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start_server = websockets.serve(echo, "", PORT) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() return HttpResponse("done") The above mentioned code is a Django request to start the websocket which has been deployed to aws elasticbeanstalk. def main(): async def listen(): url = "http://something.com:7890" # Connect to the server async with websockets.connect(url) as ws: # Send a greeting message await ws.send("Hello oku[dated!") # Stay alive forever, listening to incoming msgs while True: msg = await ws.recv() print(msg) # Start the connection asyncio.get_event_loop().run_until_complete(listen()) The second script is a locally run file to connect the websocket. So I keep getting an error while attempting to connect to the websocket saying asyncio.exceptions.TimeoutError at the last line of the script. So I wanted to know on how this can be made proper. Note: Both the website (websocket server) and client work fine when the code is run locally. The error is being caused only when the … -
Dynamic Url Routing In Django not working
dynamic url routing in post not working . it works properly without dynamic url but shows Page not found (404) Request Method: GET error urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index ,name='index'), path('count', views.count ,name='count'), path('register', views.register ,name='register'), path('login', views.login ,name='login'), path('logout',views.logout , name='logout'), path('post/<str:pk>/', views.post, name='post') ] views.py from django.shortcuts import render , redirect from django.http import HttpResponse from .models import Feature from django.contrib.auth.models import User, auth from django.contrib import messages # Create your views here. def post(request,pk): return render(request,'post.html',{'pk': pk}) post.html <h1>the value of pk is {{pk}}</h1> -
How to redirect any website by clicking an image in html where framework is Django?
Here, I want to redirect www.facebook.com if I click that Facebook logo but as I have a port number of 127.0.0.1:8000 therefore after clicking the image I'm redirecting http://127.0.0.1:8000/www.facebook.com and for that I'm getting Page Not Found(404) Error How can I fix this so that it will only redirect fb or insta? <ul class="nav col-md-4 justify-content-end list-unstyled d-flex"> <li class="ms-3"><a class="text-muted" href="www.facebook.com"><img src="/static/fb.png"></a></li> <li class="ms-3"><a class="text-muted" href="www.instagram.com"><img src="/static/insta.png"></a></li> <li class="ms-3"><a class="text-muted" href="www.twitter.com"><img src="/static/twitter.jpg"></a></li> </ul> -
django.db.utils.DatabaseError: ORA-02267: column type incompatible with referenced column type
Im using Django and Oracle, I have to use some table from another Scehma class ModelTable1(models.Model): official_id = models.CharField(db_column="ID_OFFICIAL", primary_key=True, max_length=20) field_1 = models.CharField(max_length=25, db_column="COLUMN_X", blank=True, null=True) field_2 = models.CharField(max_length=25, db_column="COLUMN_Y", blank=True, null=True) class Meta: db_table = '"SCHEMAX"."TABLE1"' default_permissions = [] managed = False When I try to relationship with a model from my schema and running the migration I have this error: django.db.utils.DatabaseError: ORA-02267: column type incompatible with referenced column type My model definition is: class ModelTable2(AuditDataMixin): id = models.AutoField(db_column='ID', primary_key=True) official_id = models.ForeignKey( ModelTable1, models.DO_NOTHING, db_column="ID_OFFICIAL" ) status = models.CharField(db_column='ESTADO', max_length=2, blank=True, null=True) class Meta: db_table = 'TABLE2' default_permissions = [] When I went to the table I can see the problem, SCHEMAX.Table1.ID_OFFICIAL is type Varchar2(20) and MYSCHEMA.Table2.ID_OFFICIAL is type NVARCHAR2(20). What could I do than When I run migration the FK be created like Varchar2? Thanks!! -
Django views not able to show the dictionary object data
I have the below queryset query_data= <QuerySet [{'month': datetime.date(2022, 1, 1), 'count': 9}, {'month': datetime.date(2021, 12, 1), 'count': 9}]> But when I try to do in views {% for mm in query_data %} <span>{{mm['month'] | date: 'F' }}</span> {%endfor%} It is not showing the data but if I did <span>abcd</span> it is showing the abcd -
Uploding Multiple Imgs in Django-rest-framework using React js
Hey I am trying upload multiple img to django rest framework using react js. However, I tried with only one pic and It's done,but not multiple. I really don't know what's the fields for that. here is my model.py class Notes(models.Model): title = models.CharField(max_length=50) desc = models.TextField() time=models.TimeField(auto_now=True) img = models.ImageField(upload_to='img',null=True) #here I want multiple img src user = models.ForeignKey(User, on_delete=models.CASCADE , related_name='notes') def __str__(self): return self.title Serializer.py class NoteSerializer(serializers.ModelSerializer): class Meta: model = Notes fields = ['id','title','desc','img','time'] views.py class getNotes(ModelViewSet): authentication_classes = [BasicAuthentication ,TokenAuthentication] permission_classes = [checkPermission] parser_classes = (MultiPartParser, FormParser) queryset = Notes.objects.all() serializer_class = NoteSerializer def list(self, request , **kwa): notes = Notes.objects.filter(user=request.user.id) serialzer = NoteSerializer(notes, many=True) return Response(serialzer.data) def create(self, request, **kwargs): notes = NoteSerializer(data=request.data) if notes.is_valid(): print(request.user) notes.save(user=request.user) return Response(notes.data) else: return Response(notes.errors) What should I do for getting multiple img and save them all... Frontend Part function to send img using fetch api let uploadPicture = (e)=>{ console.log(e.target.files); // setImg(e.target.files); let img=[]; let fd = new FormData() for (var index = 0; index < e.target.files.length; index++) { console.log(e.target.files[index]); img.push(e.target.files[index]) } fd.append('pic',e.target.files[0]) console.log("Fd ",fd.get('pic')); setImg(fd.get('pic')) console.log("Cimg ",Cimg); } This is input tag <div className="mb-3"> <label htmlFor="img" className="form-label">Picture</label> <input type="file" multiple className="form-control" placeholder='Enter your img...' onChange={uploadPicture} … -
When I run my Django project developed on Windows on Ubuntu it gives errors as below, even after creating virtualenv and configured properly
Here is the errors I have installed and created virtualenv as same like the one on Windows and replaced it on Ubuntu with that new one. I could activate the virtual but when I do python3 manage.py runserver it gives error as like below. If someone help, it will be grateful. Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 105, in run self.inner_run(None, **options) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/home/pema/.local/lib/python3.6/site-packages/django/core/management/base.py", line 423, in check databases=databases, File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/pema/.local/lib/python3.6/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/pema/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 416, in check for pattern in self.url_patterns: File "/home/pema/.local/lib/python3.6/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/pema/.local/lib/python3.6/site-packages/django/urls/resolvers.py", line 602, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/pema/.local/lib/python3.6/site-packages/django/utils/functional.py", line … -
django For loop in html table want arrange data based on column then go to second row
how make loop for every column in table then move for next row from data retired from model as per photo the next entry come in next row but i need it to come in first row second column <thead> <tr class="bg-light-gray"> <th class="text-uppercase">Time </th> <th class="text-uppercase">Monday</th> <th class="text-uppercase">Tuesday</th> <th class="text-uppercase">Wednesday</th> <th class="text-uppercase">Thursday</th> <th class="text-uppercase">Friday</th> <th class="text-uppercase">Saturday</th> <th class="text-uppercase">Sunday</th> </tr> </thead> <tbody> {% for item in groupcoursesform %} <tr > <td class="align-middle">09:00am</td> <td> {% if item.day == 'Monday' %} <div class="font-size13 text-light-gray">{{item.group_name}}</div> {% endif %} {% if item.day == 'Tuesday' %} <div class="font-size13 text-light-gray">{{item.group_name}}</div> {% endif %} </td> </tr> {% endfor %} for loop -
No installed app with label 'admin' when adding dj_rest_auth
In my django project, i have already included the admin in installed apps like this, INSTALLED_APPS = [ "django.contrib.admin", ] I am already using django admin well. After some time, i needed to install dj_rest_auth module to my project, but whenever i add this module, it raises the error No installed app with label 'admin' File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/project/urls.py", line 21, in <module> path("admin/", admin.site.urls), File "/project/lib/python3.8/site-packages/django/utils/functional.py", line 256, in inner self._setup() File "/project/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 529, in _setup AdminSiteClass = import_string(apps.get_app_config('admin').default_site) File "/project/lib/python3.8/site-packages/django/apps/registry.py", line 162, in get_app_config raise LookupError(message) LookupError: No installed app with label 'admin'. -
Django error. module 'django.http.request' has no attribute 'POST'
I am new to Django and I am trying to create a simple web application. I've created a login form and added a hyperlink for signing up for new users. Unfortunately, I got the following error. module 'django.http.request' has no attribute 'POST' In the bellow you will find view.py code: from django.shortcuts import render from django.http import HttpResponse, request from django.db import connection from django.contrib.auth.decorators import login_required import pyodbc def index(request): if 'Login' in request.POST: rows = [] username = request.POST.get('username') if username.strip() != '': rows = getLogin(username) if len(rows) > 0: return render(request, 'login/welcome.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') else: return render (request, 'login/index.html') def newUser(requset): if 'NewUser' in request.POST: return render(request,'login/newuser.html') def getLogin(UserName=''): command = 'EXEC GetLogin\'' + UserName + '\'' cursor = connection.cursor() cursor.execute(command) rows = [] while True: row = cursor.fetchone() if not row: break userName = row[0] password = row[1] name = row[2] email = row[3] rows.append({'userName': userName, 'password': password, 'name': name, 'email': email}) cursor.close() return rows @login_required(login_url='/') def readLogin(request): if request.user.is_authenticated: rows = getLogin() return render(request, 'login/loginsdata.html', {'rows': rows}) else: return HttpResponse('You are not authenticated</br>') Here urls.py code of the login app: from django.urls import path from . import … -
Django crispy forms and bootstrap - adjust field height
I have a page where user inputs information into a number of inline formsets. these forms are styled with crispy forms and bootstrap. There is also some javascript to allow users to dynamcially add forms I have a slight issues in that one of the forms presents a range slider (concern in the SideEffectFormset which looks slightly off as it is a little shorter than the other input boxes and I havent been able to adjust this using the formset helper. Any advice on how to amend the formset helper or the html much appreciated! forms.py SideeffectFormSet = inlineformset_factory( Case, SideEffect, fields=("se_name", "concern"), widgets={'concern': RangeInput()}, extra=0, min_num=1, validate_min=True, ) class SideEffectFormSetSetHelper(FormHelper): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.form_method = "post" self.form_id = 'id-SideeffectForm' self.form_class = 'blueForms' self.form_show_labels = False self.render_required_fields = True self.form_tag = False self.layout = Layout( Div( Div(Field("se_name", placeholder="Chickpeas"), css_class='col-4 col-lg-4 h-50'), Div(Field("concern", placeholder="concern"), css_class='col-8 col-lg-8 '), css_class="row", ), ) widgets.py from django.forms.widgets import NumberInput class RangeInput(NumberInput): input_type = 'range' html <div class='row mt-4' > <h6>Side Effects</h6> </div> <table id="sideeffects_table" border="0" cellpadding="0" cellspacing="5" width='100%'> <tbody> {% for form in sideeffect_formset %} <tr> <td> {% for fld in form.hidden_fields %}{{ fld }}{% endfor %} {% if form.instance.pk %}{{ form.DELETE … -
Django - Creating Keys that include calculated fields that are not saved to the database
I have a series of linked tables creating a django website. The user table has a calculated field which classifies people according to their age. This classification changes as the person gets older so I do not want to save this value to the database (unless it can be automatically updated as the age boundaries are reached). This age code needs to be used as part of a key to link to fields in another table. The classification table takes Value 1 and Value 2 from the Score table and the age code from the calculation in the User table which itself gets the code from the Age table. These provide a unique code that the classification table uses to provide a value back to the Score table.[Schematic image of tables here][1] I have been able to get the values for the score table, themselves links to other tables, it is just getting the calculated value back from the User table that is proving to be the problem. I don't really want to save the age code back to the User table unless this can be automatically updated when the age boundary is crossed. Any help would be greatly appreciated … -
Delete Django ImageField and FileField records whose files are not found on the server
I've recently lost some files in my media folder, and I want to delete the image field/FileField objects whose files have been removed. -
Terminal/Virtualenv may not be synchronized with github page
So I'm using a $5 droplet from digital oceans to host a django website and whenever I tried using python manage.py runserver 134.6.4.2:8000 it tells me to add 134.6.4.2 to ALLOWED_HOSTS even though I added it and pushed it into the master branch a while ago, also I added a new file into the folder and whenever I try to ls into the folder the file seems to be missing even though it can be seen on the github page through my profile. How do I solve this? I've been following this tutorial and this guide -
Custom alert not showing - React
I am currently following a tutorial for a Django+React project. When a user tries to login with the wrong credentials, an alert "error" should popup, and when the user manages to login a "success" alert should appear as well. The login logic works fine, but I don't get any alert (they are custom alerts btw). Here is the login part of the code : axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" axios.defaults.xsrfCookieName = "csrftoken" export const login = (email, password) => async dispatch => { const config = { headers: { 'Content-Type': 'application/json' } }; const body = JSON.stringify({ email, password }); try { const res = await axios.post('http://localhost:8000/api/token/', body, config); dispatch({ type: LOGIN_SUCCESS, payload: res.data }); dispatch(setAlert('Authenticated successfully', 'success')); } catch(err) { dispatch({ type: LOGIN_FAIL }); dispatch(setAlert('Error Authenticating', 'error')); } }; and here is the alert part : import { v4 as uuid } from 'uuid'; import { SET_ALERT, REMOVE_ALERT } from './types'; export const setAlert = (msg, alertType, timeout = 5000) => dispatch => { const id = uuid(); dispatch({ type: SET_ALERT, payload: { msg, alertType, id } }); setTimeout(() => dispatch({ type: REMOVE_ALERT, payload: id }), timeout); } I have checked import and variables names, and I can't find an answer … -
How to set select all data up to data_upload_max_number_fields (example 500) in django admin listing page
First of all sorry if is there any question already please let me know that because I am fresh in this community And thanks in advance for your valuable responses In the below screenshot in Django admin, How can I override the select all 1005 with some custom number like select up to 500. As you know data_upload_max_number_fields has only a 1000 limit but I don't want to increase the limit every time. Because it might be possible I have 100000 data then how much will increase the data_upload_max_number_fields in django settings. So is there any way that I can override this select all thing to less than the upload max field for example select all up to first 500 data I don't want like the default one shown in the 2nd image -
Removing circular data in a dictionary of dictionaries
I've hit a challenge with my personal accounting app I can't even imagine how to approach. The script is generating some JSON for a Sankey diagram which shows cash moving through the ledgers: The issue is that the Sankey goes wrong if the cash moves in a circle, eg from Ledger A to Ledger B to C and back to A. I'm trying to write some code that will evaluate the data and if there's a circular movement then it should break that circle by removing one of the links. The code starts with a dictionary of dictionaries which contains the amount of cash that's moving between each possible pair of ledgers. The top dictionary contains the ledgers as keys and another dictionary of ledgers as the values. The inner dictionary contains the ledgers as keys and amount of cash moving as the value. Below is a print(str(dict)) of the dictionary. Zeros mean there's no cash moving between the two ledgers. Have had to truncate due to Stack Overflow charactor limit. Would you suggest how to even approach this? {<Ledger: Basic food>: {<Ledger: Basic food>: 0, <Ledger: Benefits>: 0, <Ledger: Books>: 0, <Ledger: Clothing>: 0, <Ledger: Coffee & Snacks>: 0, … -
python django challenge app and while passing url which contains numeric produce below error
views.py from http.client import HTTPResponse from django.shortcuts import render from django.http import HttpResponse,HttpResponseNotFound # Create your views here. def index(request,week): return HTTPResponse(week) def allweek(request,week): text=None if week=='sunday': text='Sunday is funday and also utilize well' elif week=='monday': text='start of week and after break' elif week=='tuesday': text='very long meetings' elif week=='wednesday': text='finished half of week' elif week=='thursday': text='preparing for weekend party day' elif week=='friday': text='weekend arrived' elif week=='saturday': text='wait is over enjoy tour day!' else: return HttpResponseNotFound('Entered wrong week of the day') return HttpResponse(text) urls.py from django.urls import path from . import views urlpatterns = [ path('<int:week>',views.index), path('<str:week>',views.allweek), ] Getting below error while executing the above code As i tried to use int and str values in the urls to map the respective views but while mapping the int values below error is encountered. AttributeError at /challenges/1 'int' object has no attribute 'makefile' while runni -
DRF - Auto generation code Field doesnot show in admin
I want to make autogeneration field in my model. I have create when i give request to post man it will create next code automatically. But, I want to show code autogeneration field when user add the data inttable. models.py class GeneralDocumentType(models.Model): code = models.CharField(max_length=10, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name In serializer I have written code for autogeneration only in code field(DOC001,DOC002,..) serializers.py def get_code(model, prefix): content = model.objects.all().last() last = None code_prefix = prefix if content: a_string = content.code split_strings = [] n = len(prefix) for index in range(0, len(a_string), n): split_strings.append(a_string[index: index + n]) last = int(split_strings[1]) if last is not None: suggested = last + 1 else: suggested = 1 return "{}{:03d}".format(code_prefix, suggested) class GeneralDocumentTypeSerializer(serializers.ModelSerializer): class Meta: model = GeneralDocumentType fields = ["id", "code", "name", "description"] read_only_fields = ['code'] def create(self, validated_data): validated_data["code"] = get_code(GeneralDocumentType, "DOC") return GeneralDocumentType.objects.create(**validated_data) what i did wrong, How can I show code field should be (DOC003) increased when user add the data. How can i acieve that??? -
Field 'id' expected a number but got '{user.id}'
what should be the reason ...why am i getting this error if request.user.is_authenticated: user=request.user user_id=request.GET.get('user') payment_request_id=request.GET.get('payment_request_id') payment_id=request.GET.get('payment_id') print(payment_id,payment_request_id) response = API.payment_request_payment_status(payment_request_id, payment_id) # Purpose of Payment Request status=response.get('payment_request').get('payment').get('status') user=User.objects.get(id=user_id) -
settings.DATABASES is improperly configured. Heroku
Trying to do some testing on my Heroku Local Server (http://0.0.0.0:8000/) - the index.html loads correctly but when I navigate away (for example to admin) from that page I get the following error: Traceback (most recent call last): File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/admin/sites.py", line 417, in login return LoginView.as_view(**defaults)(request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/auth/views.py", line 64, in dispatch return super().dispatch(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/views/generic/edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/auth/views.py", line 101, in get_context_data current_site = get_current_site(self.request) File "/Users/x/Desktop/Programming/projects/anybody/venv/lib/python3.9/site-packages/django/contrib/sites/shortcuts.py", line 13, in get_current_site return Site.objects.get_current(request) … -
update view inside detail view
Right now I have one class based detail view and one class based update view. They are completely separate and both are working fine. I wonder if it is possible to combine these two? So that the user can update their data directly from the detail view, just to make it easier for the user. This is my models.py file class geography(models.Model): student = models.ForeignKey(User, on_delete=models.CASCADE, null=False) title = models.ForeignKey(Title, on_delete=models.CASCADE, null=False, max_length=120) rep1 = models.DateField(blank=True, null=True) rep2 = models.DateField(blank=True, null=True) rep3 = models.DateField(blank=True, null=True) rep4 = models.DateField(blank=True, null=True) rep5 = models.DateField(blank=True, null=True) def __int__(self): return self.pk def get_absolute_url(self): return reverse('geography') This is my forms.py file class GeographyForm(forms.ModelForm): class Meta: model = Geography fields = ('title', 'rep1', 'rep2', 'rep3', 'rep4', 'rep5') This is my detailview class GeographyDetailView(LoginRequiredMixin, UserPassesTestMixin, DetailView): model = Geography def test_func(self): Geography = self.get_object() if self.request.user == Geography.elev: return True return False This is my updateview class GeographyUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Geography form_class = GeographyForm def form_valid(self, form): form.instance.student = self.request.user return super().form_valid(form) def test_func(self): Geography = self.get_object() if self.request.user == Geography.student: return True return False I tried "FormMixins" in the detail view, but I could not get it to work. -
How can I customise different views to the normal users and admin using django?
I tried out the below view function. But the normal user's page 'studenthpage' is never getting rendered, while the superuser is able to login. instead of 'elif user.is_active:' I even tried just else condition, still not successful. can anyone help def login(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 not None : auth_login(request,user) if user.is_superuser: return redirect('adminhpage') elif user.is_active: return redirect('studenthpage') else: messages.info(request, 'Username OR password is incorrect') context = {} return render(request, 'login.html', context) -
how can i convert html to pdf in django, cyrilic font
I am trying to convert html to pdf in django using xhtml2pdf, and successfully converted html to pdf in english alphabet and numbers but in russian alphabet(cyrilic) it is giving me black square box, enter image description here Here is what I tried: views.py def download(request): user = request.user template_path = 'faktura.html' context = {'user': user} response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="contract.pdf"' template = get_template(template_path) html = template.render(context) # create a pdf pisa_status = pisa.CreatePDF( html, dest=response) # if error then show some funy view if pisa_status.err: return HttpResponse('We had some errors <pre>' + html + '</pre>') return response And html file: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> {# <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"#} {# integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">#} <title>Document</title> </head> <body> <div class="container"> <div class="row"> <div class="col-12"> <h5 class="text-center py-5">ДОГОВОР № 0000, от 00.00.0000 г</h5> <div class="d-flex justify-content-between px-5"> <h6>г.Наманган</h6> <h6>«00» месяц 0000 г</h6> </div> <p> Общество с ограниченной ответственностью <b>Ўзбекистон бўйлаб бепул етказиб берамиз!</b>, г.Наманган, Республика Узбекистан, именуемое в дальнейшем «Продавец», в лице директора Юсупова М.М., действующее на основании Устава, с одной стороны, ООО «_____________________________________________», именуемое в дальнейшем «Покупатель», в лице_____________________________________ , действующего на основании_______________, с другой …