Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to query a char field with regular expression?
I have a charField called 'blood_pressure' and it has values like 120/80, 110/70 and so on. I need to query the values by only the denominator value and regardless of the Numerator. I tried: Muserments.objects.filter(blood_pressure=r'/d+\/20') My goal I need to get the object with a denominator greater than \d+>=80 Muserments.objects.filter(blood_pressure=r'\d+\/\d+>=80') -
How to correctly display multi level data
I have a model MyModel which contains data with various levels. The goal is to display the data in a treegrid /treetable. Model: class MyModel(models.Model): title = models.CharField(max_length=100) level = models.IntegerField() price = models.FloatField(null=True, blank=True) parent = models.ForeignKey("self", on_delete=models.PROTECT, blank=True, null=True) Serializer: class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ('title', 'level', 'price', 'parent') depth = 5 Viewset: class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer The data: [ { "title": "First A", "level": 0, "price": 111.1, "parent": null }, { "title": "Second A", "level": 1, "price": 222.2, "parent": 1 }, { "title": "Third A", "level": 2, "price": 333.42, "parent": 2 }, { "title": "Fourth A", "level": 3, "price": 444.1, "parent": 3 }, { "title": "Fifth A", "level": 4, "price": 33.442, "parent": 4 }, { "title": "First B", "level": 0, "price": 321.0, "parent": null }, { "title": "Second B", "level": 1, "price": 1234.0, "parent": 6 }, { "title": "Third B", "level": 2, "price": 4335.0, "parent": 7 } ] I have followed [this][1] post, but I don't received the data that I want. The following output is received after calling the current viewset: [ { "title": "First A", "level": 0, "price": 111.1, "parent": null }, { "title": "Second A", "level": … -
How to create tasks correctly in Celery with Django?
I ask for help with the task. There is a notification model. I want to create an asynchronous task for creating notifications. But I get an error Object of type MPTTModelBase is not JSON serializable. models.py class Comment(MPTTModel): """Модель комментариев""" content_type = models.ForeignKey(ContentType, verbose_name=_('Тип контента'), related_name='content_ct_%(class)s', on_delete=models.CASCADE) object_id = models.PositiveIntegerField(verbose_name=_('ID контента'), db_index=True) content_object = GenericForeignKey('content_type', 'object_id') """Род.коммент""" parent = TreeForeignKey('self', on_delete=models.CASCADE, verbose_name=_('Родительский комментарий'), blank=True, null=True, related_name='children') """Инфо, привязка, модерация""" content = models.TextField(verbose_name=_('Комментарий')) created_by = models.ForeignKey(AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='comment_created_by', verbose_name=_('Автор комментария')) is_published = models.BooleanField(verbose_name=_('Опубликовать'), default=True) time_create = models.DateTimeField(auto_now_add=True, verbose_name=_('Дата добавления')) """Generic FK""" rating = GenericRelation('Rating', related_query_name='%(class)s') notification = GenericRelation('Notification', related_query_name='%(class)s') def save(self, *args, **kwargs): send_create_notification.delay(self, 3) super().save(*args, **kwargs) services.py def create_notification(instance, type): """Notification create""" from modules.core.models import Notification model_object = instance obj = model_object.content_object try: text = model_object.content[0:120] except: text = None try: to_user = obj.created_by except: to_user = obj from_user = model_object.created_by now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) similar_actions = Notification.objects.filter(from_user=from_user, to_user=from_user, type=type, time_create__gte=last_minute) if obj: from django.contrib.contenttypes.models import ContentType content_type = ContentType.objects.get_for_model(obj) similar_actions = similar_actions.filter(content_type=content_type, object_id=obj.id) if not similar_actions: if text: notification = Notification(from_user=from_user, to_user=to_user, type=type, content_object=obj, text=text) else: notification = Notification(from_user=from_user, to_user=to_user, type=type, content_object=obj) notification.save() return True return False tasks.py @shared_task() def send_create_notification(self, type): return create_notification(self, type) -
why changing my language is not working on django
I'm trying to change my language from french (the default langauge of my web navigator and my app) to the english language. LANGUAGES= [ ('fr', 'French'), ('en', 'English'), ] Here is my form to change the language, I found it on the documentation <form action="{% url 'set_language' %}" method ="post"> {% csrf_token %} <input type="hidden" name="next" value ="{{ redirect_to }}"> <select name="language" id=""> {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages%} <option value="{{ langauge.code }}" {% if language.code == LANGUAGE_CODE %} selected {% endif %}> {{language.name_local}} ({{language.code}}) </option> {% endfor %} </select> <input type = "submit" value="Go"> </form> Here is my urls pattern urlpatterns = [ path('i18n/', include('django.conf.urls.i18n')), path('mission/',include('mission.urls')), path('admin/', admin.site.urls), path('accounts/', include('django.contrib.auth.urls')), url(r'^favicon\.ico$', RedirectView.as_view(url='/static/images/favicon.ico')) ] at my views.py code I add this def index(request): from django.utils import translation #user_language = 'en' #translation.activate(user_language) #request.session[translation.LANGUAGE_SESSION_KEY] = user_language if translation.LANGUAGE_SESSION_KEY in request.session: del request.session[translation.LANGUAGE_SESSION_KEY] return render(request, 'mission/index.html', {}) But whene I try this in my views.py code to change the language manually it works user_language = 'en' translation.activate(user_language) request.session[translation.LANGUAGE_SESSION_KEY] = user_language I think the problem is on the fucntion set_langauge It is predifned on a file named i18n.py but i'm not sure -
Pass values from views.py for-loop to template in Django
I have a "Meeting room booking" system in my project,and here is my html: Here is the "views.py" I have written: def meeting(request): today = datetime.now().date() today2 = today + timedelta(days=1) today3 = today + timedelta(days=2) today4 = today + timedelta(days=3) today5 = today + timedelta(days=4) today6 = today + timedelta(days=5) today7 = today + timedelta(days=6) date_dict = {str(today): "today", str(today2): "today2", str(today3): "today3", str(today4): "today4", str(today5): "today5", str(today6): "today6", str(today7): "today7"} book_list = Booking.objects.filter(booking_date__gte=today).filter(is_deleted='0') booking = [] htmls = "" for day in date_dict: htmls += '<tr><td><a id="{}"></a></td>'.format(date_dict[day]) for time_choice in ["10:00~12:00", "12:00~14:00", "14:00~16:00", "16:00~18:00", "18:00~20:00", "20:00~22:00"]: book = None flag = False for book in book_list: if book.time_id == time_choice and book.booking_date == day: flag = True break if flag: if book.user == request.user.username: htmls += '<td><button type="button" class="btn btn-warning" data-toggle="modal" data-target="#modal-warning" onclick="RunAlg(this)" user-id="{}" theme-id="{}">You Booked</button></td>'.format(book.user, book.theme) booking.append(book.theme) print(booking) else: htmls += "<td bgcolor='#0088ff' class='info item'>Booker:{}<br>Meeting theme:{}</td>".format(book.user, book.theme) else: htmls += '<td><button type="button" class="btn btn-success" data-toggle="modal" data-target="#booking-success" onclick="RunAlg(this)">Bookable</button></td>' htmls += "</tr>" return render_to_response('meeting.html', {'htmls': htmls, 'booking': booking}) And here is my template part about modal: <div class="modal fade" id="modal-warning"> <div class="modal-dialog"> <div class="modal-content bg-warning"> <div class="modal-header"> <h4 class="modal-title">You booked this meeting room</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span … -
how to sort sentence according only first letter [duplicate]
If two words are starting with the same character then the same order of the words should be maintained from the original sentence. It is follow only first character or word This is my code st='this is an impossible task' sts=st.split() sts.sort() print(sts) Output ['an', 'impossible', 'is', 'task', 'this'] I want to this output how to get this output an is impossible this task -
Django not setting csrftoken cookie
I am writing a Django app that uses Django-hosts for the subdomains. I have the main app running (currently on localhost) and I have set CSRF_COOKIE_DOMAIN = ".localhost". However when I run localhost:8000/admin/, there is no csrftoken cookie set, same as when I run api.localhost:8000/<slug>. When I remove the setting, both subdomain endpoints get a different csrftoken which doesn't work when I make an AJAX request using the localhost endpoint to api.localhost endpoint. Is there a setting I am missing? I have tried removing the setting, and using *.localhost to no avail -
Django forms data retrieving and updating problem
I've four fields in my models.py file. class Item(models.Model): product_name = models.CharField(max_length=100) quantity = models.IntegerField() size_choice = ( ('S', 'Short'), ('M','Medium'), ('L','Long') ) size = models.CharField(max_length=30, choices=size_choice) date = models.DateField() And this is my forms.py file: class ItemForm(ModelForm): class Meta: model = Item widgets = {'date':DateInput()} fields = ['product_name','quantity'] As I'm taking two fields only so it will display only two fields in my additem.html file: <form action="" method="post"> {% csrf_token %} {{ form }} <button type="submit">Add</button> </form> </div> In my itemlist.html file I can retrieve 'product_name' and 'quantity' from database as it is being saved from additem.html file. But in this itemlist.html file I've created two more inputs for 'size' and 'date'. So from here i want to update data into database(all four coulmns). Updating two fileds is fine but how will i update 'size' and 'field' from itemlist.html file. {% for neww in all %} <tr> <td>{{ neww.product_name }}</td> <td>{{ neww.quantity }}</td> <td><input type="text" value="{{ neww.size }}"</td> /* This */ <td><input type="text" value="{{ neww.date }}"</td> /* and this i want to update from here */ <td><a href="{% url 'update_item' neww.id %}">Edit</a> My update.html file: <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Update"> </form> My … -
Use Django Admin Widgets on any given page
This is not a duplicate! Alle the older questions either do not work, or are simply outdated. According to the Django documentation https://docs.djangoproject.com/en/3.2/topics/forms/media/ The Django Admin application defines a number of customized widgets for calendars, filtered selections, and so on. These widgets define asset requirements, and the Django Admin uses the custom widgets in place of the Django defaults. The Admin templates will only include those files that are required to render the widgets on any given page. If you like the widgets that the Django Admin application uses, feel free to use them in your own application! They’re all stored in django.contrib.admin.widgets. Here is my forms.py: from django import forms from django.contrib.admin.widgets import AdminDateWidget, AdminTimeWidget from .models import Category, Event class AntragForm(forms.Form): user = forms.CharField() day = forms.DateField(widget=AdminDateWidget(), label="Datum", required=True) category = forms.ModelChoiceField( queryset=Category.objects.all() ) start_time = forms.TimeField(widget=AdminTimeWidget(), label="Start", required=False) end_time = forms.TimeField(widget=AdminTimeWidget(), label="Ende", required=False) whole_day = forms.BooleanField(label="Ganztag", required=False) private = forms.BooleanField(label="Privat", required=False) whole_week = forms.BooleanField(label="Ganze Woche", required=False) summary = forms.CharField(label="Grund", required=False) description = forms.CharField(widget=forms.Textarea, label="Beschreibung", required=False) and here's the part of the template: <div class="row"> <div class="col"> {{ form.day|as_crispy_field}} </div> </div> I also tried without crispy-fields, but it doesn't render either, so that's not the problem. It simply … -
Customizing Django login template
I'm new to Django and I want to use my custom login page instead of the ugly looking django login template. How could I make it work? I think I need to edit the urls.py file and override the login template but I don't know how to do it. Thanks -
Django Inline formsets always invalid
I am struck with inline formsets in Django. Each time I submit the formset it is considered invalid and hence the data doesn't get saved. I am a newbie in full-stack development and am learning Django. I am following Dennis Ivy's playlist on youtube and coding along with him. It is kind of an E-commerce portal where people can order stuff. Here is a link to the video where he implements inline formsets Video. It was working fine when I accepted orders through normal form i.e. one order at a time. I have done exactly as he did in his video. I also tried consulting my friends who are learning with me and also asked my mentor about it but no one could figure out what is wrong here. I browsed through the documentation but that too didn't help. Please help me out in fixing this. Github Repo link views.py from django.forms import inlineformset_factory def createOrder(request, pkCrteOrder): OrderFormSet = inlineformset_factory(customer, order, fields=('product','status'), extra=7) CustomerOrderOwner = customer.objects.get(id=pkCrteOrder) formSet = OrderFormSet(queryset = order.objects.none(), instance=CustomerOrderOwner) if(request.method == 'POST'): print("post request detected") formSet = OrderFormSet(request.POST, instance=CustomerOrderOwner) if formSet.is_valid(): formSet.save() return(redirect('/')) else: print("formset was invalid") context = {'formSet': formSet} return(render(request, 'accounts/orderForm.html', context)) Brief explaination: From … -
Edited form not getting saved in django
I've fixed almost everything, the form opens and I can make the edits but as soon as I make the edits and click on save, this shows up: I don't understand what's wrong. I did the same thing for my edit profile page and it worked perfectly there so I don't understand why it's not working here. views.py: class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template_name = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) What seems to be wrong? I think I need to change something in my views because everything else seems to work well so I'm not including anything else. But i don't understand what needs to be changed -
How to add a custom download path to downloaded files in django admin?
I have written some snippet to download datas from a model from default django admin. It works and csv file with name "some.csv" is downloaded to root project foler in my local machine. But what i want is customise the dir to new specific folder for eg ( C:\downloads). Also I am hosting it to heroku and I want the clients to see the downloads in their download folder. How to do that in both production and my local?? My model: class Booking(models.Model): name = models.CharField(max_length=100,blank=True) email = models.EmailField(blank=True) phone = models.CharField(max_length=50, blank=True) model = models.CharField(max_length=100, choices=Model,blank=True) # message = RichTextField(blank=True, null=True) location = models.CharField(max_length=50, blank=True) sent_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ('sent_at',) My admin.py: def download_csv(modeladmin, request, queryset): f = open('some.csv', 'w') abc = csv.writer(f) abc.writerow(["name", "email", "phone", "model"]) for s in queryset: abc.writerow([s.name, s.email, s.phone, s.model]) class BookingAdmin(admin.ModelAdmin): def delete(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/delete/">Delete</a>', obj.id) def edit(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/edit/">Change</a>', obj.id) list_display = ('name', 'email', 'phone', 'model','edit','delete') list_display_links = ('name',) icon_name = 'folder_open' actions = [download_csv] admin.site.register(Booking,BookingAdmin) -
how to implement test case for logout in Django?
I am trying to test the logout bypassing the username and password, but it is getting failed. Can anyone help from django.contrib.auth import logout from django.test import TestCase class BasicTest(Testcase): def test_logout(self): request = { 'data' : { 'username': 'admin', 'password': 'admin' } } logout(request) Error: request.session.flush() AttributeError: 'Session' object has no attribute 'flush' Thanks! -
View is getting rendered in the Network Preview tab Django
I have created the logon form in Django which working properly. However in the Network tab I am able to view the Form and for other views like GET request the form is getting rendered with prepopulated data. Am I missing something or doing something wrong. Below is the screenshot and login form code. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section col-md-6"> <form method="POST" autocomplete="off"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="Submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> </small> </div> </div> {% endblock content %} logon_form_in_network_tab -
What is the best and stable ODM for mongodb and django?
I want to connect django to mongodb but what is the best ODM for this issue? Djongo or mongoengine ? -
CSS is only applying on few html files and not rest
So i am building a personal website and am using Materialize for web designing. At first it was good and my pages look good, but then I added some new pages and i found that the css is not applied in these new pages, can anybody help me in solving this. Actually both are same pages(categories.html) but the path are different. header.html (main html file, have not changed the name yet) <<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="static/main/materialize.css" media="screen,projection"/> </head> <body> {% load static %} {% include "main/includes/navbar.html" %} {% include "main/includes/messages.html" %} <main> <div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')"> <div class = "container"> <br> {% block content %} {% endblock %} </div> </div> </main> {% include "main/includes/footer.html" %} <script type="text/javascript" src="static/main/materialize.js"></script> </body> </html> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item, ItemSeries, ItemCategory from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def single_slug(request, single_slug): categories = [c.category_slug for c in ItemCategory.objects.all()] if single_slug in categories: matching_series = ItemSeries.objects.filter(item_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Item.objects.filter(item_series__item_series=m.item_series).earliest("item_update") series_urls[m] = part_one.item_slug return render(request, "main/category.html", … -
Saving HTML form data all at once
I want to save HTML data using request.POST method all at once instead of column by column. But it is giving me error because of crsf token. I am using templates so I can't use Django Forms views.py @require_http_methods(["POST"]) def save_add_user(request): error="" message="" data=request.POST first_name=data.get('first_name') last_name=data.get('last_name') username=data.get('username') email=data.get('email') password=data.get('password') phone=data.get('phone') address=data.get('address') user_type=data.get('usertype') try: user=CustomUser.objects.create_user(username=username, email=email,password=password,user_type=user_type) #user=CustomUser.objects.create(**data) #gives me error unexpected argument 'csrfmiddlewaretoken' #user=CustomUser.objects.create_user(**data) #gives me error username not defined user.save() CustomUserDetails.objects.create(user=user, phone=phone,address=address,first_name=first_name,last_name=last_name) message='User Added Succesfully' except: error='Failed to add user' return render(request,'internal/add_user.html',{'messages':message,'error':error,}) -
Forum button only works when I am authenticated but returns NoReverseMatch at /forum/ Reverse for '' not found. '' when i'm not logged in
I'm having a lot of trouble with this. I don't understand why the same "Forum" button works when I'm logged in and redirects me to the forum page. However, it returns this when I'm not authenticated: NoReverseMatch at /forum/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/forum/ Django Version: 3.1.11 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Here is my layout.html which home.html extends from: <body> <nav class="nav d-flex flex-row justify-content-between nav-fill navbar-expand-lg navbar-dark bg-dark sticky-top container-fluid" style=""> <div class="first"> <a class="navbar-brand mr-4 ml-4" href="#"><b>My Site</b></a> <a class="nav-item nav-link text-light" href="{% url 'home' %}">Home</a> <a class="nav-item nav-link text-light" href="{% url 'forum:index' %}">Forum</a> {% if user.is_authenticated %} <a class="nav-item nav-link text-light" href="{% url 'users_list' %}">Find New Buddies</a> </div> {% block searchform %}{% endblock searchform %} <div class="second"> <a class="nav-item nav-link text-light" href="{% url 'post-create' %}">Create Post</a> <a class="nav-item nav-link text-light" href="{% url 'my_profile' %}">Profile</a> <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Messaging</a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'postman:inbox' %}">Inbox{% if unread_count %} <strong>({{ unread_count }})</strong> {% endif %}</a> <a class="dropdown-item" href="{% … -
Is there any module in python for web development?
I want to do web development in python and in a very simple language. Kindly suggest me some modules for web development in python. -
django 404 when loading admin but not local pages when deployed to heroku
I have just deployed my Django application to Heroku, All my locally saved apps load fine but not the django admin page # mysite/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', include('home.urls')), path('api/', include('api.urls')), path('admin/', admin.site.urls), # ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I go to the home page it loads and the same for all other URLs, except for the admin page at https://myapp.herokuapp.com/admin and you get the following error. -
Django query to fetch top performers for each month
I need to fetch the top performer for each month, here is the below MySql query which gives me the correct output. select id,Name,totalPoints, createdDateTime from userdetail where app=4 and totalPoints in ( select max(totalPoints) FROM userdetail where app=4 group by month(createdDateTime), year(createdDateTime)) order by totalPoints desc I am new to Django ORM. I am not able to write an equivalent Django query which does the task. I have been struggling with this logic for 2 days. Any help would be highly appreciated. -
Can't seem to understand where I'm going wrong
I am working on a django project that accepts complains from users: models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do … -
In my Django Models How can I create an Auto field which stores an id with format 'AAA BBB CCCC' (I also want to make this field as primary key)
In my Django Models, I want to create a custom field called 'facility_id' which will be storing in my database table column a unique facility_id for every registered facility using a format 'AAA BBB CCCC', where AAA,BBB, and CCCC are just mere random numbers. I intend to format this field because it will be used by people in a form, so I want it to look better and formatted, otherwise I would have simply used the default AutoField shown below. (Am too new in django & python, so pardon my simple question) Below is my autofield which I want to format, kindly help: class Facilities(models.Model): ... facility_id = models.AutoField(primary_key=True) # I want store this in form 'AAA BBB CCCC' ... -
What seems to be wrong with my code in django?
urls.py: urlpatterns = [ .... path('My-History/', accounts.views.History, name='MyHistory'), path('Complaint/<int:id>/edit', accounts.views.EditComplaint.as_view(), name='Complaint') ] views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('info', 'reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor …