Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Face error in install Django REST framework
When I write: pip install djangorestframework In CMD show me: Fatal error in launcher: Unable to create process using '"H:\Full Stack\Django\Django_All\project1\env\Scripts\python.exe" "H:\Full Stack\Django\Django_All\project1\studybud\env\Scripts\pip.exe" install djangorestframework': The system cannot find the file specified -
<slug> path converter not working, but literal <slug> in URL works
When I try to visit this URL: http://127.0.0.1:8000/slugtest/ I get 404 page. Here's the message that I get: Using the URLconf defined in scrap.urls, Django tried these URL patterns, in this order: admin/ api-auth/ getpage/ ^<slug>/$ [name='ArticleInfoViewSet-list'] ^<slug>/(?P<slug>[^/.]+)/$ [name='ArticleInfoViewSet-detail'] __debug__/ The current path, slugtest/, didn’t match any of these. However, if I use http://127.0.0.1:8000/<slug>/ the page loads perfectly, but that's not intended behavior. models.py class Article(models.Model): url = models.CharField(max_length=255,validators=[RegexValidator(regex=website_regex)]) slug = models.CharField(max_length=255, null=True) unique_id = models.CharField(max_length=255, unique=True, null=True) views.py class ArticleInfoViewSet(ModelViewSet): serializer_class = ArticleInfoSerializer lookup_url_kwarg = 'slug' lookup_field = 'slug' def get_queryset(self): queryset = Article.objects.prefetch_related('data') return queryset serializer.py class ArticleInfoSerializer(serializers.ModelSerializer): data = ArticleDataSerializer(many=True) class Meta: model = Article fields = ['url', 'data', 'slug'] lookup_field = ['slug'] read_only_fields = ['url', 'data', 'slug'] urls.py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('getpage/', include('getpage.urls')), path('', include('getpage.urls2')), path('__debug__/', include('debug_toolbar.urls')), ] urls2.py from . import views from rest_framework_nested import routers router = routers.SimpleRouter() router.register('<slug>', views.ArticleInfoViewSet, basename='ArticleInfoViewSet') urlpatterns = router.urls What am I doing wrong here? -
Nginx Gunicorn powered server unable to access media in a separate postgresql server
Long story short, my BE dev left midway through setting up my apps' BE server and I'm trying to pick up the pieces to find out what is left to do. I'm by no means any form of a developer, so I apologize in advance for asking silly questions and if I am lacking any details needed to better understand my problem. Will do my best updating this question and be as concise as I can as I go along. Problem The Django admin panel runs in https, but is unable to access the files stored in the database. Current configuration Virtual machine 1 - Docker, Nginx, Gunicorn, Django (admin panel) Virtual machine 2 - postgresql (database) Here are the following file configurations docker-compose.yml version: "3" services: theapp: image: theapp-be/python-3.10-full container_name: theapp-be build: ./ command: bash -c "./deploy.sh" volumes: - ./:/usr/app/ - ./ssl/:/etc/ssl/theapp-BE/ expose: - "80" restart: always nginx: image: theapp-be/nginx container_name: theapp-be-nginx build: ./nginx volumes: - ./:/var/www/theapp-BE/ - ./ssl/:/etc/ssl/theapp-BE/ - ./nginx/config/:/etc/nginx/conf.d/ - ./nginx/log/:/var/log/nginx/ ports: - "80:80" - "443:443" depends_on: - theapp restart: always default.conf (nginx) # Upstreams upstream wsgiserver { ip_hash; server theapp-be:80; } # Redirect to HTTPS server { listen 80; listen [::]:80; server_name theapp; access_log /var/log/nginx/theapp-access.log; error_log … -
Question about sorting by date inside a database using Django
I have a database, in which it's possible to find products by their name. The DB has ID, category, name, amount and date defined, and I was trying to create a separate search field that would let me search those items by the date they were added. The models.py looks like this: class Expense(models.Model): class Meta: ordering = ('-date', '-pk') category = models.ForeignKey(Category, models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8, decimal_places=2) date = models.DateField(default=datetime.date.today, db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' And views.py looks like this: class ExpenseListView(ListView): model = Expense paginate_by = 5 def get_context_data(self, *, object_list=None, **kwargs): queryset = object_list if object_list is not None else self.object_list form = ExpenseSearchForm(self.request.GET) if form.is_valid(): name = form.cleaned_data.get('name', '').strip() if name: queryset = queryset.filter(name__icontains=name) return super().get_context_data( form=form, object_list=queryset, summary_per_category=summary_per_category(queryset), **kwargs) I've added the "date" field under the "name", following it's structure, but I kept getting the 'datetime.date' object has no attribute 'strip' error. Is there a different format for defining the date? When I've also added it to the search field in forms.py, it was seen there as a string. I've also found a similar post from How to make date range filter in Django?, but it didn't explained … -
In Django, restrict user view using class based views
I have this url pattern: path("user/<int:pk>", MyAccountView.as_view(), name='my_account'), And this view: class MyAccountView(DetailView): model = CustomUser When the user is logged Django redirect to that URL. The problem is that any user can access other users. For example, if the logged user has pk 25, he can access the view of user with pk 26 by writing in the browser url box: localhost:8000/user/26 I want that each user can access to his user page only, so if user with pk 25 try to access the url with pk 26, the access should be denied. Can you point me in some direction of how this is done? The Django documentation is very confusing in this respect. Thanks. -
How to combine two methods for uploading file?
I have a Django application And I have a upload functionality. And I have two methods that shows the extracted text: def filter_verdi_total_number_fruit(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(\d*(?:\.\d+)*)\s*\W+(?:" + '|'.join(re.escape(word) for word in self.extractingText.list_fruit) + ')' return re.findall(regex, self.extractingText.text_factuur_verdi[0]) def filter_verdi_fruit_name(self, file_name): self.extractingText.extract_text_from_image(file_name) regex = r"(?:\d*(?:\.\d+)*)\s*\W+(" + '|'.join(re.escape(word) for word in self.extractingText.list_fruit) + ')' return re.findall(regex, self.extractingText.text_factuur_verdi[0]) But as you can see. There are some duplicate code. Like: file_name and: re.findall(regex, self.extractingText.text_factuur_verdi[0]) So I try to combine this two methods in one method: def combine_methods(self, file_name): self.filter_verdi_total_number_fruit(file_name) self.filter_verdi_fruit_name(file_name) and then I try to call the combined method in the views.py: if uploadfile.image.path.endswith('.pdf'): content ='\n'.join(filter_text.combine_methods(uploadfile.image.path)) But then I get this error: can only join an iterable Exception Location: C:\Users\engel\Documents\NVWA\software\blockchainfruit\main\views.py, line 50, in post Raised during: main.views.ReadingFile Question: how can I change this? -
Unable to do exception handling in Django forms
I have made a ModelForm in which the user is supposed to enter date and time. I want to make sure that the time is in the correct format so I wrote convert_to_time function so that it can raise a ValidationError when the format of time is wrong but it is not working. I seem that the Exception part is not working. I mean the control is never going inside the Exception part. Here is the ModelForm import datetime class BookingForm(forms.ModelForm): class Meta: model = Booking fields = ['check_in_date', 'check_in_time', 'check_out_time', 'person', 'no_of_rooms'] def clean(self): cleaned_data = super().clean() normal_check_in = cleaned_data.get("check_in_time") str_check_in = str(normal_check_in) format = '%H:%M:%S' try: print("vukwqa") #This gets printed in the terminal. datetime.datetime.strptime(str_check_in, format).time() except Exception: print("srhni") #This does not get printed in the terminal. raise ValidationError( _('%(value)s Wrong time format entered.'), code='Wrong time format entered.', params={'value': str_check_in}, ) Is it not possible to do exception handling in forms.py because if it were a normal python program the control does go inside the exception part. Is there a different way to do it? Can someone please help? -
Django filtering in the filtered relate model
I HAVE THESE MODELS: # Create your models here. import datetime from django.conf import settings from django.db import models from django.db.models import Q from django.utils import timezone from django.contrib.auth.models import User # Create your models here. from datetime import date class Docs(models.Model): doc_id = models.CharField ('ID документа', max_length=200,null=True, unique=True) doc_title = models.CharField ('Название документа', max_length=200,null=True) hyp_name = models.URLField('Ссылка на документ') update_date = models.DateField (auto_now=True,verbose_name='Дата обновления документа') date_per = models.IntegerField('Срок действия прохождения') def __str__(self): return self.doc_id class Meta: verbose_name = 'Документ' verbose_name_plural = 'Документы' class Curicls(models.Model): curic_id = models.CharField ('ID курикулы', max_length=100, null=True,unique=True) cur_title = models.CharField ('Название курикулы', max_length=100, null=True) doc_id = models.ManyToManyField(Docs) def __str__(self): return self.curic_id class Meta: verbose_name = 'Курикула' verbose_name_plural = 'Курикулы' class Rolesl(models.Model): LEARN = 'A' CHECK = 'B' RANG_DIF = [ (CHECK, "ОЗНАКОМИТЬСЯ"), (LEARN, "ИЗУЧИТЬ") ] role_name = models.CharField('Название роли', max_length=100, unique=True) cur_id = models.ManyToManyField (Curicls, max_length=200, verbose_name='ID курикулы') rang = models.CharField(max_length=1, choices=RANG_DIF, default='', verbose_name='Ранг') def __str__(self): return self.role_name class Meta: verbose_name = 'Роль' verbose_name_plural = 'Роли' class Emp(models.Model): emp_name = models.OneToOneField(User, on_delete= models.CASCADE) per_no = models.IntegerField('Pers.No.') last_name = models.CharField('Last Name', max_length=50) first_name = models.CharField('First Name', max_length=50) emp_mail = models.EmailField('Email', max_length=100) roles_name = models.ManyToManyField(Rolesl) def __str__(self): return str(self.emp_name) class Meta: verbose_name = 'Работник' verbose_name_plural = 'Работники' … -
Event loop is closed while runing Celery tasks
I got the following RuntimeError when I run Celery worker, I'm new to Celery and I don't understand the source of this bug and why the task exception is not retrieved. My Celery tasks run but if I click on any trigger, the error shows up frequently and I ended up with another opertationalError that said: django.db.utils.OperationalError: database is locked [2022-10-25 13:22:58,428: ERROR/ForkPoolWorker-2] Task exception was never retrieved future: <Task finished name='Task-77' coro=<Connection.disconnect() done, defined at /home/.../lib/python3.8/site-packages/redis/asyncio/connection.py:819> exception=RuntimeError('Event loop is closed')> Traceback (most recent call last): File "/home/.../lib/python3.8/site-packages/redis/asyncio/connection.py", line 828, in disconnect self._writer.close() # type: ignore[union-attr] File "/usr/lib/python3.8/asyncio/streams.py", line 353, in close return self._transport.close() File "/usr/lib/python3.8/asyncio/selector_events.py", line 692, in close self._loop.call_soon(self._call_connection_lost, None) File "/usr/lib/python3.8/asyncio/base_events.py", line 719, in call_soon self._check_closed() File "/usr/lib/python3.8/asyncio/base_events.py", line 508, in _check_closed raise RuntimeError('Event loop is closed') -
Create editable spreadsheet-like table in Django site
I am making a planning site that uses a spreadsheet-like table where every day is a row and every school subject is a column. The table rows are all the days of a year and the columns are all the school subjects. The table cells have to be editable and stylable, so you can add and remove and highlight homework. Basicallly just like google spreadsheets. You have to be able to instantly edit the cell upon clicking on it. These edits have to be saved to a database, so that other users can follow along with the edits. But how can I save everything onedit to the database? How can I create this spreadsheet functionality in a Django website? I already tried html tables with contenteditable. Or should I use input forms? Could anyone provide with an example for this? -
Problems with Django Templatetag `regroup`
When using the regroup templatetag I encountered a problem where a Queryset would produce an empty list ([]) as a result. A similar Queryset (e.g. a Set with the same columns and filters however one filtervalue differed) worked perfectly fine. My Query looks like this: GraZeichen.objects.filter(gtid__id=gtid).values("id", "findno").exclude(findno=None, formid=0).annotate(values_id=GroupConcat( "formid", separator=',')).annotate(values_en=GroupConcat("fombez_en", separator=',')) and my Template looks like this: {% regroup zeichen|dictsort:'values_de' by values_en as zeichen_by_val %} {% for valgroup in zeichen_by_val %} {{ valgroup.grouper }} ({{ valgroup.list|length }}) <div> {% for zeichen in valgroup.list %} <div> <a href="alink"> <img ...> </a> </div> {% endfor %} </div> {% endfor %} As I said it works perfectly fine for some gtids, but if I compare the printed Queryset of gtids where it worked with the ones where it did not I can see no difference. What are the cases, where regroup would return an empty list? -
djoser not requesting static files from build folder correctly for PASSWORD_RESET_CONFIRM_URL
I am using React frontend and django backend with DRF, djoser and JWT for authentication. I did npm run build in my frontend and pasted the build folder in the django project. When i did a password reset, it sends email and when i click on the link it is not rendering any page, instead it is a blank page. In python console it is printing the below api requests. [25/Oct/2022 19:26:05] "GET /password/reset/confirm/MQ/bdunk6-9b9ca4dea8ba7ff3f16f192165a380cb HTTP/1.1" 200 565 [25/Oct/2022 19:26:05] "GET /password/reset/confirm/MQ/static/js/main.2e1e85b9.js HTTP/1.1" 200 565 [25/Oct/2022 19:26:05] "GET /password/reset/confirm/MQ/static/css/main.738adac0.css HTTP/1.1" 200 565 it is adding the djoser url too for the reqeust "/password/reset/confirm/MQ/" Below is my djoser settings in my settings.py file DJOSER = { 'LOGIN_FILED': 'email', 'USER_CREATE_PASSWORD_RETYPE': True, 'USERNAME_CHANGED_EMAIL_CONFIRMATION': True, 'PASSWORD_CHANGED_EMAIL_CONFIRMATION': True, 'SEND_CONFIRMATION_EMAIL': True, 'SET_PASSWORD_RETYPE': True, 'PASSWORD_RESET_CONFIRM_URL': 'password/reset/confirm/{uid}/{token}', 'USERNAME_RESET_CONFIRM_URL': 'email/reset/confirm/{uid}/{token}', 'ACTIVATION_URL': 'activate/{uid}/{token}', 'SEND_ACTIVATION_EMAIL': True, 'PASSWORD_RESET_CONFIRM_RETYPE': True, 'SERIALIZERS': { 'user_create': 'accounts.serializers.UserCreateSerializer', 'user': 'accounts.serializers.UserCreateSerializer', 'user_delete': 'accounts.serializers.UserDeleteSerializer' }} Below is the post request i used in my frontend. export const reset_password_confirm = (uid, token, new_password, re_new_password) => async dispatch => { const config = { headers: { 'Content-Type': 'application/json' } }; const body = JSON.stringify({ uid, token, new_password, re_new_password }); try { await axios.post(`${process.env.REACT_APP_API_URL}/auth/users/reset_password_confirm/`, body, config); dispatch({ type: PASSWORD_RESET_CONFIRM_SUCCESS }); } catch (err) … -
How to show output from different methods?
I have a method that extracts the text from a file. And then I have seperate methods for filtering strings from the extracted text. But now I want to combine the seperated methods. So that I can show the filtering strings in a texfield. So this is the method that extracts the text from the file: class ExtractingTextFromFile: def extract_text_from_image(self, filename): self.text_factuur_verdi = [] pdf_file = wi(filename=filename, resolution=300) all_images = pdf_file.convert('jpeg') for image in all_images.sequence: image = wi(image=image) image = image.make_blob('jpeg') image = Image.open(io.BytesIO(image)) text = pytesseract.image_to_string(image, lang='eng') self.text_factuur_verdi.append(text) return self.text_factuur_verdi def __init__(self): # class variables: self.apples_royal_gala = 'Appels Royal Gala 13kg 60/65 Generica PL Klasse I' self.ananas_crownless = 'Ananas Crownless 14kg 10 Sweet CR Klasse I' self.peen_waspeen = 'Peen Waspeen 14x1lkg 200-400 Generica BE Klasse I' self.tex_factuur_verdi = [] self.list_fruit = ['Appels', 'Ananas', 'Peen Waspeen', 'Tomaten Cherry', 'Sinaasappels', 'Watermeloenen', 'Rettich', 'Peren', 'Peen', 'Mandarijnen', 'Meloenen', 'Grapefruit', 'Rettich'] and then I have the methods for extracting the subtext from the extracted text: class FilterText: extractingText = ExtractingTextFromFile() def __init__(self): pass self.extracting_text_from_pdf = ExtractingTextFromFile() def combine_filtered_text(self, file_name): self.filter_verdi_total_number_fruit(self, file_name) + ' ' + self.filter_verdi_fruit_name(self, file_name) #self.filter_verdi_total_fruit_cost(self, filename) def regex_fruit_cost(self, substr): return r"(?<=" + substr + r").*?(?P<number>[0-9,.]*)\n" def regex_verdi_total_number_fruit(self): return r"(\d*(?:\.\d+)*)\s*)" def filter_verdi_total_number_fruit(self, … -
Using a custom database engine with Django
I have a custom database engine for company's internal database. I have made required changes and same structure as built in sqlite. I added it inside my project at same level as settings.py and also manage.py but when I run command python manage.py makemigrations getting following error, how should I use my own database backend module ? django.core.exceptions.ImproperlyConfigured: 'testdb.django.db.backends.mydb' isn't an available database backend or couldn't be imported. https://github.com/django/django/tree/0dd29209091280ccf34e07c9468746c396b7778e/django/db/backends/sqlite3 -
Filter by property in Django Rest
I have a model with a class property, to calculate a field based on some foreign key of the model. class Company(models.Model): field_id = models.AutoField(db_column='_id', primary_key = True) ... @property def status(self): opportunities = list(self.opportunities.all()) #logic ... # return status I want to filter on that new field. I have read different points of view, and some of them says that is not possible directly in django ORM. I've found one solution but i don't know if exits one more efficient. My solution would be override the queryset in the viewset if the param is in the request. Filter by a list comprehension and getting de queryset again. My problem is that I need to get all objects, calculate the status field and iterate. def get_queryset(self): if 'status' in self.request.GET: status = self.request.GET['status'] queryset = models.Company.objects.all() objects=[obj.field_id for obj in queryset if obj.status == status] queryset = models.Company.objects.filter(field_id__in=objects) else: queryset = models.Company.objects.all() return queryset -
django forms dropdown list (ChoiceField) refresh event to update TextArea
I am new to django and using forms.form and I have a ChoiceField for which I want to write a changed/refresh event and based on specific choice I want to update a CharField How Can I achieve this? Is it mandatory to use jquery? GEEKS_CHOICES =( ("1", "Event"), ("2", "Transaction"), ("3", "Health"), ) logfile= forms.ChoiceField(choices=GEEKS_CHOICES, widget=forms.Select(attrs=. {"onChange":"myFunction();"} )) eventlogstr= "I am event" txnlogstr="I am transaction" healthlogstr="I am health" arguments= forms.CharField(widget=forms.Textarea(attrs={"rows":"5"}), initial=eventlogstr) -
Django Background Task: how to get result of the processed method?
The django background task works well, I can get the status of a completed task. But I would need to get the result of the method that has been processed via background task. The method is supposed to return a dictionary object and I don't know how to get it so I can pass it to View. Can you help me please? :) I have checked other questions here, but without success :( There is nothing helpful in Completed Tasks model.. -
Django/React: Fetching API endpoint works fine from within the application, but returns 404 when request comes from outside
So I made an React + Django app and decided to seperate it, so the backend would work just as a rest API, and frontend would send requests to it. The goal was to facilitate hosting it. As a single app it works fine. API requests are returned like so [25/Oct/2022 14:31:21] ←[m"GET /spotify/current-song HTTP/1.1" 200 236←[0m But then I seperated the frontend, installed cors headers in django to accept traffic from the react app and most of it works fine. However: the api call to fetch info from spotify API gets a response [25/Oct/2022 14:31:41] ←[33m"GET /spotify/current-song HTTP/1.1" 404 2←[0m Not Found: /spotify/current-song, even though this is the very same endpoint that worked when the call came from within the app. The API call from react app: const getCurrentSong = async () => { const song = await fetch(`${BASEURL}spotify/current-song`); if (!song.ok || song.status == 204) { return defaultSong; } const songJson = await song.json(); setSong(songJson); document.body.style.backgroundImage = `url('${songJson.image_url}')`; }; useEffect(() => { const interval = setInterval(() => { getCurrentSong(); }, 1000); setAppBackground(); getRoomDetails(); return () => clearInterval(interval); }, []); Django project urls.py: urlpatterns = [ # other, irrelevant path('spotify/', include('spotify.urls')), ] And django spotify app urls.py: urlpatterns = [ … -
Display Data in form of Table row by clicking single or multiple Checkboxes in Django
I am working on Django framework and stuck in a bad situation. I have my Data table that is fetched from database and displaying in a table form. At the end of the table there are multiple checkboxes which is used to customize the data and display the only data for which I have clicked on single or multiple checkboxes. After clicking on checkbox / checkboxes data have to display in table form. <head> <script> function getvalues() { let selected = new Array(); var chckbox = document.getElementById("tab1"); var selchk = chckbox.getElementsByTagName("input"); for(var i=0; i<selchk.length;i++) { if(selchk[i].checked) { selected.push(selchk[i].value); } } if(selected.length> 0) { document.getElementById("displayvalues").innerHTML= selected; } }; </script> </head> <body> <table border = "1"> <tr> <th> ID </th> <th> NAME </th> <th> EMAIL </th> <th> SALARY </th> <th> PHONE </th> </tr> {%for getdata in EmployeeDetails %} <tr> <td> {{getdata.id}}</td> <td> {{getdata.empname}}</td> <td> {{getdata.email}}</td> <td> {{getdata.salary}}</td> <td> {{getdata.phone}}</td> </tr> {% endfor %} </table> <table id = "tab1"> <tr> <td> {%for display in EmployeeDetails %} <input type="checkbox" value="{display.salary}}" /> {{display.salary}} {% endfor %} </td> </tr> </table> <input id="but1" type="button" value="display records" onclick="getvalues()"/> <b id="displayvalues"></b> </body> As you can see in image when I click on a checkbox and press a button it … -
Django distinct selection
i have this model: class Person: first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) sexe = models.TextChoices('M', 'F') arrival_date = models.DateField(max_length=30) reason = models.CharField(max_length=30) It turns out that the same person can be registered several times (only the arrival date and the reason change). I would like to make a query that lists distinctly persons. For example, if a person is registered many times, he will be selected only once. How can i do it ? Thanks. -
Django-viewflow query all assigned to user tasks
How to query django-viewflow for all tasks assigned to user? Probably viewflow.managers.TaskQuerySet inbox() is right place. But how to invoke it? Alternatively how to query users task from viewflow.models.Process object? -
Problem with starting a Django project in current directory?
I am trying to start a django project in my current directory. Online I found this command as a solution: django-admin startproject . ^(Also the command used by my lecturer in one of his videos) However when I enter this into my terminal I get: CommandError: '.' is not a valid project name. Please make sure the name is a valid identifier. Edit: The command works fine if I give it a valid project name and creates a new directory with the project. The '.' from my understanding is meant to signify that the project should be started in the current directory, so I don't understand why it is treating it as a name -
Django Integrity Error 1048 cannot be null
Under views.py def addcomments(request): comment_text = request.POST.get('comment') user_id = request.POST.get('user_id') name = request.POST.get('name') email = request.POST.get('email') comment = Comment.objects.create(user_id=user_id, body=comment_text, name=name, email=email) comment.save() return HttpResponseRedirect(reverse('users:detail', args=(user_id, ))) this one, from detail.html {% extends 'base.html' %} {% block title %} {{ user.user_fname }} {{ user.user_lname }} {% endblock %} {% block content %} {% if error_message %} <p class="alert alert-danger"> <strong>{{error_message}}</strong> </p> {% endif %} <div class="row"> <div class="col-lg-6"> <div class="mb-5"> <h1>{{ user.user_fname }} {{ user.user_lname }}</h1> <p class="text-muted">{{ user.user_email }}</p> <p>Position: {{ user.user_position }}</p> </div> <div class="img-responsive"> <img src="/users/media/{{user.user_image}}" alt="profile_user" class="img-rounded" width="300"> <!-- ito yung hinahanap ng search engine--> </div> <div class="btn-group mt-5"> <a href="{% url 'users:delete' user.id %}" class="btn btn-sm btn-danger">Delete</a> <a href="{% url 'users:edit' user.id %}" class="btn btn-sm btn-info">Edit</a> <a href="{% url 'users:index'%}" class="btn btn-sm btn-success">Back</a> </div> </div> <div class="col-lg-6"> <h2>Comment</h2> <p class="text-muted"> Number of comment : {{ comments_count }}</p> {% if comments_count > 0 %} {% for comment in comments %} {% if comment.active %} <p><strong>{{comment.name}}</strong> : {{comment.body}}</p> {% endif %} {% endfor %} {% endif %} <hr> <br><br><br><br><br><br> <form action="{%url 'users:addcomments'%}" method="post"> {% csrf_token %} <div class="form-group"> <label>Comment</label> <textarea name="comment" id="comment" cols="30" rows="5" class="form-control" required placeholder="Enter your comment here ..."></textarea> </div> <br> <input type="text" name="name" id="name" … -
'Posts_update' object is not iterable in django
i am just try to get data from db table and show on detail page but i am getting error -'Posts_update' object is not iterable. I have two tables posts and posts_update. in posts table i am doing CRUD operation and on each update i am adding information in posts_update table now i am trying to get information from posts_update table using mobile as a parameter but i am getting error -'Posts_update' object is not iterable. models.py from django.db import models class Posts(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) content = models.TextField() mobile = models.CharField(max_length=15,default='') class Posts_update(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(unique=True) content = models.TextField() mobile = models.CharField(max_length=15,default='') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create/', views.create, name='create'), path('detail/<int:post_mobile>', views.read, name='detail'), path('delete/<int:post_id>', views.delete, name='delete'), path('update/<int:post_id>', views.update, name='update') ] views.py from django.shortcuts import render, redirect from django.template.defaultfilters import slugify from django.http import HttpResponse from django.contrib import messages from .models import Posts from .models import Posts_update def index(request): posts = Posts.objects.all() return render(request, 'index.html', { 'posts': posts }) def create(request): if request.POST: req = request.POST post = Posts(title=req.get('title'), slug=slugify(req.get('title')), content=req.get('content'), mobile=req.get('mobile')) post.save() messages.success(request, 'The record was saved successfully') return redirect('/') else: return render(request, … -
Custom User Model, Custom Authentication not working
I am a beginner in Django and I am working on a project which requires Custom user model as I Don't require is_staff, is_superuser, is_admin. So, but searching and other ways I made my own Custom user model. But it is not working and I am stuck on it for days. It will be a huge help if someone can help me with the code. settings.py AUTH_USER_MODEL = 'accounts.Usermanagement' AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuthBackend', ] models.py (models + manager) #models.py class UsermanagementCustomUserManager(BaseUserManager): # create_user(username_field, password=None, **other_fields) def create_user(self,emailid,roleid,organizationid,firstname, password=None, passwordexpirydate="2022-12-12 12:00:00",createdby=0,modifiedby=0): """ Creates and saves a User with the given email, date of birth and password. """ if not emailid: raise ValueError('Users must have an email address') user = self.model( emailid=self.normalize_email(emailid), roleid = roleid, organizationid=organizationid, firstname = firstname, password=password, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,emailid,roleid,organizationid,firstname,passwordexpirydate,password=None,createdby=0,modifiedby=0): """ Creates and saves a superuser with the given email, date of birth and password. """ user = self.create_user( emailid=emailid, roleid = roleid, organizationid=organizationid, firstname = firstname, password=password, passwordexpirydate=passwordexpirydate, ) user.save(using=self._db) return user class Organization(models.Model): organizationid = models.AutoField(db_column='OrganizationID', primary_key=True,blank=True) organizationname = models.CharField(db_column='OrganizationName', max_length=45,blank=True) def __str__(self): return self.organizationname class Meta: managed = False db_table = 'Organization' class Role(models.Model): roleid = models.AutoField(db_column='RoleID', primary_key=True,blank=True) organizationid = models.ForeignKey(Organization, …