Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Username_field error while migrating to database
I was implementing django's custom user model but during migration it gives me a USERNAME_FILED error.Also the username field is clearly mentioned in the account class.I am extending django's custom user model for creating a blog like website. account/models.py from django.db import models from django.db import models from django.contrib.auth.models import BaseUserManager,AbstractBaseUser class MyAccountManager(BaseUserManager): def create_user(self, email, username, password = None): if not email: raise ValueError('Users must have an email') if not username: raise ValueError('Users must have a username') user = self.model(email=self.normalize_email(email),username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,username,password): user = self.create_user(email=self.normalize_email(email),password=password,username=username) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=60,unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) # firstname = models.CharField(max_length=30) USERNAME_FILED = 'email' REQUIRED_FIELDS = ['username',]#firstname objects = MyAccountManager() def __str__(self): return self.email def has_perm(self,perm, obj=None): return self.is_admin def has_module_perms(self,app_label): return True AttributeError: type object 'Account' has no attribute 'USERNAME_FIELD' -
Filtering Fields with Custom User Model -- Django
Very new to Django. I created a custom user model as below. I also created a page for the users to update their details. I want the two user 'groups' to use the same page 'account.html' to update their details. But if the user is an 'Employee' I want to display additional fields. Simply put, I'm trying to achieve the following logic: If users group = 'Client' then display fields A & B to update If users group = 'Employee' then display fields A, B, C & D update Any help much appreciated Models.py group_types = [('Client', 'Client'), ('Employee','Employee')] class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) groups = models.CharField(choices=group_types, default="client", max_length=60) company_name = models.CharField(verbose_name='company name', max_length=30) account.html <form class="form-signin" method="post">{% csrf_token %} <h1 class="h3 mb-3 font-weight-normal">Account Details</h1> <p> Email Address </p> <input type="email" name="email" id="inputEmail" class="form-control" placeholder="Email address" required autofocus value={{account_form.initial.email}}> <br> <p> Username </p> <input type="text" name="username" id="inputUsername" class="form-control" placeholder="Username" required autofocus value={{account_form.initial.username}}> <br> <p> Company Name </p> <input type="text" name="company_name" id="inputCompany_Name" class="form-control" placeholder="Company Name" required autofocus value={{account_form.initial.company_name}}> -
Email not being sent using Django send_mail()
settings.py: EMAIL_HOST = 'smtp.mail.yahoo.com' SMTP_PORT = 456 EMAIL_HOST_USER = 'my_email@yahoo.com' EMAIL_HOST_PASSWORD = 'pass' EMAIL_USE_SSL = True the method: def contact(*args,**kwargs): contactform = ContactForm(request.POST, prefix='contactform') send_mail( 'Contact from website by '+contactform.name, contactform.message, settings.EMAIL_HOST_USER, ['saxoya8501@emailhost99.com'], fail_silently=False, ) It does not send any email. In the logs I get: "GET /?contactform-name=myname&contactform-email=aaaa%40gnm.com&contactform-message=aaaaaaaaaaaaaa HTTP/1.1" 200 20808 The form that I am using is this: class ContactForm(forms.Form): prefix = 'contactform' name = forms.CharField(max_length=50) email = forms.EmailField() message = forms.CharField(widget=forms.Textarea(attrs={'class':'materialize-textarea'})) Any suggestions on how to get it to work? -
Creation WYSIWYG and upload images
I'm developing an application in Django, so I'm trying to develop a minimal wysiwyg. One of the main task of this editor is to upload images, so I was wondering how can I upload some images to the server? <form class="formTrepeat" enctype="multipart/form-data" method="POST"> {% csrf_token %} {{form.as_p}} <div class="toolbar"> <input type="button" name="" value="Bold" onclick="document.execCommand('bold', false, '');"> <input type="button" name="" value="Italic" onclick="document.execCommand('italic', false, '');"> <input class="tool-items fa fa-file-image-o uploaderImages" type="file" accept="image/*" id="file" style="display: none;" onchange="getImage()"> <label for="file" class="tool-items fa fa-file-image-o"></label> <input type="button" name="" value="Undo" onclick="document.execCommand('undo',false,'')"> <input type="button" name="" value="Redo" onclick="document.execCommand('redo', false, '');"> </div> <div class="center"> <div class="editorPostClass" contenteditable> </div> </div> <input type="button" name="" value="Invia" onclick="copyContent()"> <input type="submit" class="btn btn-lg btn-block" style="background: #FCC844 !important;" name="Create" value='{% trans "Create Post" %}'> </form> Now I'm testing it so I added a button that copy the text to a textarea, so when I add an image, the code is blob:....., how can I upload it? js code: var editorContent = document.querySelector(".editorPostClass"); function getImage() { var file = document.querySelector(".uploaderImages").files[0]; var reader = new FileReader(); var tmppath = URL.createObjectURL(event.target.files[0]); var img = new Image() img.src = tmppath img.onload = function() { editorContent.appendChild(img); // revoke the url when it's not needed anymore. //URL.revokeObjectURL(this.src) } img.onerror = function() { … -
ModuleNotFoundError on running makemigrations
here is the code of my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'libraryapp', ] for reference: https://imgur.com/a/cbjmrTx the Error stack: (venv) C:\Users\ZinonYT\PycharmProjects\CRUD\library>python manage.py makemigrations Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_from_command_ line utility.execute() File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\ZinonYT\PycharmProjects\CRUD\venv\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\ZinonYT\AppData\Local\Programs\Python\Python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 965, in _find_and_load_unlocked ModuleNotFoundError: No module named 'libraryapp' -
Fetch table data from database without a model related to it
Im looking for a way to fetch some data to display to the user.(Run a raw sql query like) select * from "DB-table" where Name like "%blabla%" and Year like "%2020%" My problem is that the "DB-table" lives in my database but its already populated with important data which is not related to some model in my django-app. Its a standalone table with a lot of data. How can i refer to that table from my views.py file? -
Can't add username to logging record using Middleware
I'm trying to log (by default) username and project (which can be decided from request object). I don't want to add context to every log manually. The problem is that I can't make Django to add request or straight username and project to the LogRecord. I tried tens of ways. This is my code: middlewares.py import threading local = threading.local() class LoggingRequestMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_request(self, request): setattr(local, 'request', request) def process_response(self, request, response): setattr(local, 'request', request) return response settings.py def add_username_to_log(record): record.username = '-' print(record.request) if hasattr(record, 'request') and record.request.user.is_authenticated: record.username = record.request.user.username return True LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': LOGGING_VERBOSE_FORMAT, 'style': '{', }, }, 'filters': { 'context_filter': { '()': 'django.utils.log.CallbackFilter', 'callback': add_username_to_log, }, }, 'handlers': { 'console': { 'level': DEFAULT_LOG_LEVEL, 'class': 'logging.StreamHandler', 'formatter': 'verbose', 'filters': ['context_filter'], }, 'file_main': { 'level': DEFAULT_LOG_LEVEL, 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(LOG_PATH, 'main.log'), 'maxBytes': DEFAULT_LOG_SIZE, 'formatter': 'verbose', 'filters': ['context_filter'], 'backupCount': 0, }, }, 'loggers': { '': { 'handlers': ['file_main'], 'level': DEFAULT_LOG_LEVEL, 'propagate': False, }, }, } But Django raises: AttributeError: 'LogRecord' object has no attribute 'request' And moreover, it raises: Traceback (most recent call last): File … -
Custom User Model Registration In Django Rest Framework
I'm new in django rest framework. I have User model that I created with (models.Model) and now I want to make API for register User in this model and I don't know what should I do in views.py and serializers.py? class Restaurant_User(models.Model): Restaurant_Owner_UserName = models.EmailField(unique=True, default='') # Email Of Restaurant Owner. Restaurant_Owner_Phone = models.IntegerField(unique=True, default='') # Phone Number Of Restaurant Owner. Restaurant_Password = models.CharField(max_length=32, default='') -
is_valid() function returning false based in the traceback from a IntergerField in forms
is_valid() function returning false based in the traceback from a IntergerField in forms. I am probably missing out on something in the is_valid() line of code. Any input is appreciated. template <form action="{% url 'playlist_add' P_id=p.id %}" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">Add Song</button> </form> traceback [26/Apr/2020 15:32:59] "GET / HTTP/1.1" 200 9195 coo voo [26/Apr/2020 15:33:23] "POST /playlist/add/6/ HTTP/1.1" 200 4373 forms.py class IdForm(forms.Form): id = forms.IntegerField() Views.py class PlaylistAddFormFunction(View): form_class = IdForm #determine fields template = 'homepage_list.html' def get(self, request): form = self.form_class(None) print('soo') return render(request, self.template, {'form':form}) @method_decorator(login_required) def post(self, request, P_id): print('coo') form = SongForm(request.POST, request.FILES) if form.is_valid(): print('xoo') id = form.cleaned_data['id'] song = Song.objects.get(id=id) playlist, created = Playlist.objects.get_or_create(id=P_id) playlist.song.add(song) return redirect('home') else: form = self.form_class(None) print('voo') return render(request, self.template, {'form':form}) -
Django REST upload multiple files with data
I'm trying to create an endpoint that accepts (key/value) data and multiple files. The user can send serial and multiple files along with his request. Uploaded files must be saved in FileModel and add a relation to the RequestModel. The problem is when I send the request the RequestSerializer can't resolve the files and I get an error about missing the files field. #tests.py def test_create_request_with_files(self): with tempfile.NamedTemporaryFile() as file: file.write(b"SomeFakeData") file.seek(0) request = { 'files': [file], 'serial': "SomeSerial", } res = self.client.post( '/CreateRequest/', request, format='multipart') print(res.data) self.assertEqual(res.status_code, status.HTTP_201_CREATED) #--------------------------------------------------------------------------- # models.py class FileModel(models.Model): file = models.FileField(upload_to='upload_files') class RequestModel(models.Model): serial = models.CharField(max_length=100) files = models.ManyToManyField('FileModel', blank=True) def __str__(self): return str(self.id) #--------------------------------------------------------------------------- # serializers.py class FileSerializer(serializers.ModelSerializer): class Meta: model = FileModel fields = '__all__' read_only_fields = ('id',) class RequestSerializer(serializers.ModelSerializer): files = FileSerializer(many=True) def create(self, validated_data): files = validated_data.pop('files') request_model = RequestModel.objects.create(**validated_data) for file in files: file_model = FileModel.objects.create(file=file) request_model.files.add(file_model) request_model.save() return request_model class Meta: model = RequestModel fields = '__all__' read_only_fields = ('id') #--------------------------------------------------------------------------- #views.py class RequestList(generics.ListCreateAPIView): queryset = RequestModel.objects.all() serializer_class = RequestSerializer parser_classes = (FormParser, MultiPartParser) def post(self, request, *args, **kwargs): serializer = RequestSerializer(data=request.data) if serializer.is_valid(): request_model = serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The output of test: {'files': … -
How to implement spelling insensitive search in django & ProstgreSQL?
What I wanted to achieve is, if user enters search for "laptp" then database should return results with actual word "Laptop". Similarly if user enters "ambroidery", then database should return results with both "embroidery" and "embroidred" words containing strings. Hope it clears!! So what I tried is, I went through whole django documentation and closest thing I found is "Trigram Similarity" search. I followed documentation and tried this: data = 'silk' data= Product.objects.annotate( similarity=TrigramSimilarity('description', data)).filter(similarity__gt=0.3).order_by('-similarity') In my database, I have Products whose description contains word "silky" but everytime I runs this qury I get empty query set. Even when I put data value "silky", again I got empty query set. So first of all suggest me that whether this is right approach for what I wanted to achieve and secondly if it is, then why it is returning empty query set? -
How to install tensor flow for Django Applications
I am trying to use tensorflow for my django web application. I installed tensor flow in anaconda using the following commands conda create -n tensorflow_env tensorflow conda activate tensorflow_env Now I am trying to impot tensor flow and executing the belwo script in django shell but I am getting an error ModuleNotFoundError: No module named 'tensorflow' I have read similar questions but they talk about the tensorflow environment is different from the conda environment. How do I make sure that the tensorflow imports work in my anaconda environment. I am pretty confused about these environments. Here is my code from django.db.models import Avg,Sum from django.db.models.functions import TruncDate import pandas as pd import tensorflow as tf import matplotlib as mpl import matplotlib.pyplot as plt # Create your views here. from myapp.models import Order orders = Order.objects.all().annotate(date = TruncDate('timestamp')).values('itemName','date').annotate(itemPrice = Avg('itemPrice'),quantity=Sum('quantity'),orderPrice = Sum('orderPrice')) df = pd.DataFrame(list(orders)) -
Passing Trait Value to SubFactory Django
I have two factories. class DispatchDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.DispatchData order = factory.SelfAttribute('order_data.order') sku = factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku) category = SKUCategory.SINGLE quantity = 50 class Params: combo_sku=False order_data = factory.SubFactory(OrderDataFactory, combo_sku=factory.SelfAttribute('combo_sku')) combo_sku = factory.Trait( sku=factory.LazyAttribute(lambda obj: '%d' % obj.order_data.sku), category=SKUCategory.COMBO, quantity=1 ) class OrderDataFactory(factory.django.DjangoModelFactory): class Meta: model = models.OrderData order = factory.SubFactory(OrderFactory) category = SKUCategory.SINGLE quantity = 75.6 price_per_kg = 10.5 sku = factory.SelfAttribute('crop_data.id') class Params: crop_data = factory.SubFactory(CropFactory) combo_data = factory.SubFactory(ComboSkuFactory) combo_sku = factory.Trait( sku=factory.SelfAttribute('combo_data.id'), category=SKUCategory.COMBO, quantity=1, price_per_kg=34.56 ) so if combo_sku is True then it must on combo_sku in OrderDataFactory. I am getting following error. Cyclic lazy attribute definition for 'combo_sku'; cycle found in ['category', 'combo_sku'] Is there any other way to pass trait value to SubFactory. -
'The view dashboard.views.index didn't return an HttpResponse object. It returned None instead.' when using POST request of specific variable
So I am trying to build a simple view which allows user to change their avatar using form submission. Rendering the view before the POST request works just fine however when a user submits a new image file through form submission I got the following error: Value Error at / The view dashboard.views.index didn't return an HttpResponse object. It returned None instead. The following is a snippet from my view.py @login_required(login_url='/accounts/login/') def index(request): if request.method == 'POST': if 'imagefile' in request.POST: form = forms.AvatarUpdate(request.POST, request.FILES) if form.is_valid(): image = request.FILES['image'] request.user.avatar = image request.user.save() return redirect('/') else: form = forms.AvatarUpdate() return render(request, 'dashboard/index.html', {"this_page": "home", "form": form}) While the forms.py is as follow: class AvatarUpdate(forms.Form): imagefile = forms.ImageField(widget=forms.FileInput(attrs={'name': "imagefile"}), label="Change user avatar") My intention here is that the model would only be saved only if the POST request contains the variable imagefile. How should I go about fixing the problem? -
Django delete in a transaction
In a Django view, if two requests enter an atomic block that gets a model instance (that exists) and deletes it with transaction.atomic(): MyModel.objects.get( id=1234 ).delete() what happens when they exit the block? Would an exception be raised on one of them? If so, what exception? (i.e. so I can catch it) -
Django Simplejwt: Return existing valid token on relogin
I am using djangorestframework-simplejwt for jwt based authentication in my DRF project. But every time i login a new token is getting generated. How can i make sure when a valid token exists for a user then same is returned on relogin. -
React/Material UI - Can I not use <form> tag anymore when creating forms?
I am working on a React/Django project and my form input elements are created using Material UI. In my backend, I am using Django Rest Framework for serializers and APIs. On my frontend, I use material-ui input components but I no longer wrap the input elements within the form tag because I am sending my requests via ajax and in the background I have Django to handle the serialization and validation of the request data. Is this a good approach or should I always wrap input elements inside form tag? What my react code looks is something like: const TestComponent = props => { const [state, setState] = useState({ input1: "" }) const testPost = (data,token) => new Promise((res,rej) => { let endpoint = '/test/add/' let options = { method: "POST", headers: { 'Content-Type': 'application/json', 'Authorization': `Token ${token}` }, body: JSON.stringify(data), credentials: 'include' } fetch(url,options) .then(res=>res.json) .then(data=>{res(data)}) .catch(err=>{rej(err}) }) const handleChange_input1 = e => { setState(prev => ({ ...prev, input1: e.target.value })) } return( <Grid container> <Grid item> <TextField label="Input 1" value={state.input1} onChange={handleChange_input1} /> <Button variant="text" onClick={e => { testPost({input1: state.input1},"token123") }} > Submit </Button> </Grid> </Grid> ) } export default TestComponent -
Get value from Django model
Can I access Django models using this methods ? views.py def participant_view(request): participant = get_object_or_404(Participant, user=request.user) seconds_left = participant.seconds_left model.py class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) seconds_left = models.FloatField(default=0) def __str__(self): return self.user.username if not, what the correct way to do so ? -
Ecommerce checkout: when and where to create intermediate and final order for items in cart in relational database
I am working on a ecommerce project(in Django) where users can place orders. Users can add items they are interested to buy in a shopping cart which is persistent. They go through the checkout process to place the order. I am not clear how to store and manage intermediate order stage before creating final order in order table. I am thinking of these options: using separate cart, order table: cart table will have items selected by the user. when they click checkout, create an order but with a flag which says it is in intermediate stage. when payment is initiated, it will be marked as a final order. using separate table for cart, checkout and order: cart table will have items selected by the user. when they click checkout, create a checkout entry. when payment is initiated, create an entry in the order table. here checkout needs to have replica of the order structure. this seems to duplicate lot functionality using cart+checkout(combined), order table: cart table will have items selected by the user. when they click checkout, checkout stages will be stored in same table. this is similar to the magento sales_flat_quote table. when payment is initiated, a final order … -
Rainfall Intensity Prediction using Machine Learning
I have a project that needs to predict Rainfall Intensity on upcoming days or weeks. I learned that I need to use machine learning but I'm new to this technology. I will explain my project below My project is a rainfall advisory system running on Django, which have a arduino(tipping bucket) connected to it to measure the rainfall's intensity, (e.g. 30mm/hr = heavy, 50mm/hr = torrential) on present time (live graph on chartjs). But I also have records of the data and I think I'm gonna need those for prediction. My question is How am I gonna do this? - Predict the intensity on upcoming days, weeks. (how much mm/hr) - What are the requirements to save my time, I have a deadline, can I complete this within 1 week? (surprise deadline lol) - dependencies, tools. - Display prediction on graph (chartjs) I also found that you need a CSV file for the model to read, how to read the data directly from my database without importing a CSV file? I think better idea for visualization is send prediction data to database and display it to my graph. Any suggestions/tips please? Thanks! -
Django ValueError: The view usermanager.views.group_perm didn't return an HttpResponse object. It returned None instead
I am creating a News Website. When I try to delete permission from a group the same error is showing. The codes above this function are almost same. But they are working fine.Please Help This is my view file def group_perm(request, name): if not request.user.is_authenticated: return redirect('my_login') perm = 0 for i in request.user.groups.all(): if i.name == "masteruser": perm = 1 if perm == 0: error = "Access Denied" return render(request, 'back/error.html',{'error': error}) permission = Permission.objects.all() for group in Group.objects.filter(name=name): gperm = group.permissions.all() return render(request, 'back/group_perm.html', {'gperm':gperm, 'name':name, 'permission': permission}) def group_permission_del(request, gname, name): if not request.user.is_authenticated: return redirect('my_login') perm = 0 #"request.user" means current logged User for i in request.user.groups.all(): if i.name == "masteruser": perm = 1 if perm == 0: error = "Access Denied" return render(request, 'back/error.html',{'error': error}) group = Group.objects.get(name=gname) gperm = Permission.objects.get(codename=name) group.permissions.remove(gperm) return redirect('manage_permission') -
How to submit a form to server using ajax?
I'm trying to send a button id to my server using ajax to submit a form because I don't want to load a new page everytime I click on a button. But it isn't working and I don't know why. It donesn't even change the button thexto 'x' anymore. I'm very new to ajax btw Here is my script: <script> var docFrag = document.createDocumentFragment(); for (var i=0; i < 3 ; i++){ var row = document.createElement("tr") for (var j=0; j < 3 ; j++){ var elem = document.createElement('BUTTON'); elem.type = 'button'; elem.id = 'r'+i+'s'+j; elem.value = 'r'+i+'s'+j; elem.onclick = function () { document.getElementById("klik").value = this.id; document.getElementById("ID").value = this.id; //document.getElementById("klik").submit(); $("#klik").submit(function(event){ event.preventDefault(); //prevent default action var post_url = $(this).attr("action"); //get form action url var request_method = $(this).attr("method"); //get form GET/POST method var form_data = new FormData(this); //Creates new FormData object $.ajax({ url : post_url, type: request_method, data : form_data, contentType: false, cache: false, processData:false }).done(function(response){ alert('Done'); }); }); var id = this.getAttribute('id'); var novi = document.createElement('BUTTON'); novi.type = 'button'; //alert("This object's ID attribute is set to \"" + id + "\".") novi.value = id; novi.innerHTML = 'x'; this.parentElement.replaceChild(novi,this); }; elem.innerHTML = elem.value; docFrag.appendChild(elem); } document.body.appendChild(docFrag); document.body.appendChild(row); } </script> -
Why EmailMessage.attach_file(file_path, type) attaches blank document in the mail, but the attachment shows a size?
I am using EmailMessage to send email. And need to attach a pdf. My code is below: msg = EmailMessage(email_subject, html_content, from_email, [email], reply_to=reply_to, attachments=attachment_list) msg.encoding = "utf-8" msg.attach_file('alert_pdf_files/846d5c04___alert_89072e99.pdf', mimetype="application/pdf") msg.content_subtype = "html" msg.send() In the mail, i find the attachment and it shows a convincing size too. But when i open it or download it, it looks blank. The SS is attached. Please help me fix this. It would be appreciated. -
Django messages: how can i change message text in html?
View: messages.add_message(request, messages.ERROR, 'Cells marked incorrectly.') HTML: {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> {{ message }} </li> {% endfor %} </ul> {% endif %} Problem: I need to remove marker which you can see on the related picture. I read so many documentation and forums and find nothing. Maby somebody faces this problem and can help me. -
It Is possible to use own django admin
hi i am new to Django and i want use my own admin site instead of default Django admin site due to my site requirement, Django admin is very power full but i want my own so i can program thing my way, it is very irritating find and use the admin objects even for small change, for that need research and it is time consuming task. please help me https://docs.djangoproject.com/en/3.0/ref/contrib/admin/