Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djangorestframwork api on production patch method not more and return rest
I am create in an api using django as backend and react as front-end using docker. in local docker all things right done ! i have tree container -django and gunicorn -pstgres -nginx django == 3.1.1 python 3.8.1 but in in vps production environment PATCH method return this error PATCH http://x.x.x.x/api/v1/product_service/product/ewrewr HTTP/1.0 400 Bad Request Date: Wed, 23 Sep 2020 10:23:41 GMT Content-Type: text/html Content-Length: 5 X-Cache: MISS from jet_appliance X-Loop-Control: 255.255.255.255 B1267694C1EE70D52467A8BA99A4D50F Connection: close reset -
Using Django "sites" framework to handle subdomains?
I am developing a language-based web application using Django. I would like to separate content using language subdomains (similar to Wikipedia, Quora, and other multilingual websites). For instance, if my website were example.com, I would like to have en.example.com for the English version of my website, es.example.com for the Spanish version of my website, and so on and so forth. I came across different Django third-party libraries that could help with subdomains but I was considering using the "sites" framework from Django itself. However, its documentation is not very explicit about subdomains but rather just talks about "websites" and it's not clear whether the framework would be suitable for my purpose. So, my question is: is the Django "sites" framework a good option for handling subdomain in a fashion similar to the one described above? -
Django FileField to upload html and send it via Email
I have a problem, I got a model with a FileField to upload an HTML template. I upload it to the MEDIA folder. I'm trying to get that template in python and send an email with it. But I have a lot of problems with the encode.  , € ... These are some of the characters i'm getting. I tried a lot of things, my actual code: template2 = default_storage.open(grupo.email.correo.path, 'r') template = template2.read() template = unidecode(template) template = Template(template) html = template.render(Context({})) email = EmailMessage( subject, html, to=[to_email] ) email.content_subtype = 'HTML' email.send(fail_silently=False) The variable grupo.email.correo is the FileField. The result: As you see, in the right of each number should be €. I tried a lot of combinations, and I get a lot of other characters, but I can't get a good decoded string, anyone knows more about this? -
Django app does not work when DEBUG_VALUE=False and using django_heroku
I tried deploying my Django website using heroku and used a library called Django-Heroku. When setting my settings.py for deployment, it returns Server Error (500) when setting DEBUG_VALUE = False, importing import django_heroku and writing django_heroku.settings(locals()) at the last line of my settings.py file. How can I check the settings set by django_heroku that disables disables my django website for production? -
modelformset not working when applying style, How to show image inside formset
I'm trying to define a modelformset_factory on the model"Offer" When I'm form fields are not wrapped inside a div they are working fine (create and delete forms). As soon as I wrap them inside a div the functionality dosen't work. I also want to display the image inside modelformset_factory Here is my view function and html def offers(request): OfferFormSet = modelformset_factory(Offer, fields=('name', 'url', 'image', 'active'), can_delete=True) formset = OfferFormSet() if request.method == 'POST': formset = OfferFormSet(request.POST, request.FILES) if formset.is_valid(): instances = formset.save(commit=False) for instance in instances: instance.save() for instance in formset.deleted_objects: instance.delete() return redirect('.') formset = OfferFormSet() context = {'formset': formset} return render(request, 'offers.html', context) The Html is here: {% extends 'base.html' %} {% block content %} <style media="screen"> .form_div { padding: 20px 40px; margin: 20px; display: flex; flex-direction:row; flex-grow: 1; align-items: center; justify-content: space-between; background: #eee; border-radius: 2%; box-shadow: 0 0 10px 10px rgba(0, 0, 0, 0.1); } .form_grp{ display: flex; flex-direction: column; } </style> <div class="container"> <div class="formset"> <form method="post" enctype="multipart/form-data" class="forms"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="form_div"> <div class="form_grp"> <label for="">{{ form.name.label_tag }}</label> {{ form.name }} </div> <div class="form_grp"> <label for="">{{ form.url.label_tag }}</label> {{ form.url }} </div> <div class="form_grp"> … -
Add new subclass to CharField
I want to add extra subclass to my CharField. It would look like: first_row = models.CharField('General', extra_subclass="data", help_text='q122', max_length=30, blank=True, null=False) The code I tried and failed: class extra_subclass(models.CharField): def __init__(self, *args, **kwargs): self.kwargs['extra_subclass'] super(extra_subclass, self).__init__(*args, **kwargs) -
How can I add a magnifying glass to my website?
I'm a junior developer in charge of developing a website for elderly people using Django. My idea was to add a button that when you click it it generates a magnifying glass that biggens the words. Unfortunately I couldn't find any clear code related to this. Could anyone give me some clues about how to do this? It would be very much appreciated. -
Unable to update model data by using html based form
I am trying to update my pre existing model(ShiftChange) and in model based form i have used CHOICES and for update i thought to use html based form because i wanted to display content to end user(Is there any way to do by using django model based form?).When I am moving the cursor over the update button I can see it is showing the correct url but when clicking for submit after changing a few fields from dropdown option it is not redirecting. 1.model.py from django.db import models SHIFT_CHOICES = ( ('9.00-6.00','9.0-6.0'), ('6.30-3.30', '6.30-3.30'), ('12.30-3.30','12.30-3.30'), VENDOR_CHOICES = ( ('genesys','Genesys'), ('rmsi', 'RMSI'), ('tcs','TCS'), ('Cognizant', 'Cognizant'), ('CTS', 'CTS.') ) class ShiftChange(models.Model): ldap_id = models.CharField(max_length=64) Vendor_Company = models.CharField(max_length=64,choices=VENDOR_CHOICES,default='genesys') EmailID = models.EmailField(max_length=64,unique=True) Shift_timing = models.CharField(max_length=64,choices=SHIFT_CHOICES,default='General_Shift') Reason = models.TextField(max_length=256) # updated_time = models.DateTimeField(auto_now=True) 2.update.html <p>User information Update Form</p> <!-- <h5><span3>Note:</span3> For timing please use this format e.g 1.Morning Shift = <span2>6.30-3.30</span2> <br>2.Second Shift= <span1>3.30-12.30</span1><br>3.general Shift =<span4>9.00-6.00</span4></h5>--> <form method="post" class="post-form"> <!-- {{form.as_p}} #i'm not passing any form from view--> {%csrf_token%} <!-- #Now writing html form here instead of model based form because we want to show content also:)--> <!-- here name should be same variable as per the model we have defined.--> Ldap ID: <input type="text" … -
Django Filter taking list of foreign key model
I have this two model Route and Project and a relation models: class ProjectRoute(models.Model): #Fk project = models.ForeignKey(Project, null = False, on_delete = CASCADE) route = models.ForeignKey(Route, null = False, on_delete = CASCADE) Having project ID I want to retrieve a list of routes. relations = ProjectRoute.objects.filter(project__id = project_id) With this filter, I have a list of ProjectRoute. What I whant is the queryset of only route. Something like this (that doesn't work): routes = ProjectRoute.objects.filter(project__id = project_id).value_list(route) Is it possible? -
Is there is any way to use jinja inside the django flatpage?
{% load social_tags %} {% social_icon as social %} {% for i in social %} {{ i.title }} {% endfor %} my flatpage content which I write from django-admin the same code is working fine in simple django templete render page -
Passing data from django model into a list
I'm trying to pass data from a db record into a list. Here's my code: (it's inside my view) dates_queryset = Profile.objects.all().filter(user=request.user) dates = [] weights = [] num = 1 for qr in dates_queryset: dates.append(qr.date) weights.append(qr.weight) num += 1 -
Hey guys please i am getting SMTP error after running my code
I am trying to send an email to my second email account using gmails SMTP but i have been seeing errors. This is the error i keep getting SMTPConnectError at /register/ (451, b'Request action aborted on MFE proxy, SMTP server is not available.') This is in my settings.py file EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'my-gmail@gmail.com' EMAIL_HOST_PASSWORD = '*****' EMAIL_PORT = 587 EMAIL_USE_TLS = True This is my views.py file email = EmailMessage("Subject Here", "Testing hello world", "", ["therealemaluser96@gmail.com"] ) -
Django log configuration ignored despite config
I am trying to set up logging in my Django app. My logging configuration is defined in the settings.py: LOGGING_CONFIG = None LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'test': { 'format': '%(asctime)s %(levelname)-8s %(message)s' } }, 'handlers': { 'console': { 'class': 'logging.StreamHandler', 'formatter': 'test' } }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG' } } } import logging.config logging.config.dictConfig(LOGGING) Then in my code: import logging ... logger = logging.getLogger(__name__) logger.info("info") logger.debug("debug") logger.warn("warn") logger.critical("critical") logger.error("error") But I only get: warn critical error The log level and the formatter dont work. Why is my configuration not taken into account ? -
How much should a site cost? [closed]
I have to write a site as a dating site, a backend I'm going to write on django, and a frontend on bootstrap and jss. Among the functionality of the site should be the ability for users to chat with simultaneous translation. So how much can it cost to develop such a site, and how much time can it take? -
how to pass CSRF token in Django Ajax?
I am trying to update my popup form, but it's giving me csrf token issue, please let me know how I can solve this issue. Here is my Ajax code... function exampleModal(id){ $.ajax({ url: $(this).attr("data-url") type: 'POST', dataType: "HTML" success: function(res) { $('.exampleModal').html(res); $("#exampleModal").modal("show"); } }); } here is my form data... <form method="POST" action=""/> {% csrf_token %} <div class="modal-body"> <tr> <td>{{datas.name}}</td> <td>{{datas.price}}</td> <td>{{datas.category}}</td> </tr> </div> </form> I just want to know how i can pass CSRF Token in ajax using POST method... -
Common m2m field name for diffrent models
I'm working on Django(DRF) project and there are two models: Users and Roles. They have m2m relashionship through UserRole model. import uuid from django.contrib.auth.base_user import AbstractBaseUser from django.contrib.auth.models import UserManager from django.db import models class User(AbstractBaseUser): '''Custom user model''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) username = models.CharField(max_length=150,unique=True, blank=False, null=False) roles = models.ManyToManyField('Role', through='UserRole', related_name='users') created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) deleted_at = models.DateTimeField(null=True, blank=False) USERNAME_FIELD = 'username' objects = UserManager() class Meta: db_table = "Users" def __str__(self): '''String representation of User object''' return self.username class Role(models.Model): '''User role model''' id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=128, unique=True, null=False, blank=False) created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) deleted_at = models.DateTimeField(null=True, blank=False) class Meta: db_table = "Roles" def __str__(self): '''String representation of Role object''' return self.name class UserRole(models.Model): '''Model for many-to-many relationship between User and Role ''' user = models.ForeignKey(User, on_delete=models.CASCADE, db_column='user_id') role = models.ForeignKey(Role, on_delete=models.CASCADE, db_column='role_id') created_at = models.DateTimeField(auto_now_add=True, null=False, blank=False) updated_at = models.DateTimeField(auto_now=True, null=True, blank=False) class Meta: db_table = "Users_Roles" The task is not to delete really but only mark an object when a user deleles it(this applies to User and Roles models). Also, when the user deletes the object all object … -
Django Clear Field does not go even after changing widget
I am trying to create a edit_profile page for the CustomUser I created. I am using the UserChangeForm. But I notice that even when I change the widget (as specified here in this question) in the Meta class, the clear field is still displayed. forms.py class UserChangeForm(forms.ModelForm): profile_picture = forms.FileInput() class Meta: model = User fields = ('email', 'password', 'first_name', 'last_name', 'display_name', 'profile_picture', 'is_active', 'is_staff', 'is_superuser') widgets = { 'profile_picture': forms.FileInput(), } views.py class EditProfileView(UpdateView): model = User template_name = 'edit_profile.html' fields = ('email', 'first_name', 'last_name', 'display_name', 'profile_picture') edit_profile.html <form method="post" enctype="multipart/form-data" id="formUpload"> {% csrf_token %} {% for field in form %} {{ field|add_class:"form-control-sm"|as_crispy_field }} {% endfor %} <button class="btn btn-sm btn-primary" type="submit">Update Profile</button> </form> How do I remove the clear field? -
react, I want to put the data I created in the select options
console.log(test) image click The picture shows django's data by using console.log(test) in react. my code <Select placeholder="Select a player" style={{ width:'150px' }}> <Option>{test.name}/Option> </Select> What I want is to put the name of the test data in the select option. How can I get what I want? -
Cannot use ImageField because Pillow is not installed
CommandError: System check identified some issues: ERRORS: estore.Header.img: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "python -m pip install pillow". products.Product.img: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.python.org/pypi/Pillow or run command "python -m pip install pillow". I have latest version of Pillow installed (7.2.0) requirement already satisfied pillow in c:\users\admin\appdata\local\programs\python\python38\lib\site-packages (7.2.0) I m using python version 3.8.5, visual studio version v16.7.0 and Django 3.1 Please help me! -
Django, deploy to heroku with uvicorn
I have a Django app that is deployed to Heroku with daphne. I would like to replace daphne with uvicorn, so I changed my Procfile to the following: web: bin/start-pgbouncer uvicorn rivendell.asgi:application --limit-max-requests=1200 --port $PORT worker: python manage.py runworker channel_layer -v2 But the server started and crashed almost immediately with the following error: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch -
Django form: Update model values based on user input in one field
I am writing a form to let a user enter a purchase from the template. A couple things need to happen: the purchase goes to populate a row in the replenishment table some fields of the replenishment table get updated based on what the user has input here is what my model look like: class replenishment(models.Model): Id = models.CharField(max_length=100, primary_key=True, verbose_name= 'references') Name = models.CharField(max_length=200) Quantity = models.FloatField(default=0) NetAmount = models.FloatField(default=0) SupplierID = models.CharField(max_length=200) Supplier = models.CharField(max_length=200) SellPrice = models.FloatField(default=0) StockOnOrder = models.FloatField(default=0) StockOnHand = models.FloatField(default=0) def __str__(self): return self.reference and the form: class ProcurementOperationRecord(forms.Form) Id = forms.CharField(required=True) Quantity = forms.FloatField(required=True) NetAmount = forms.FloatField(required=True) Supplier = forms.CharField(required=True) SellPrice = forms.FloatField(required=True) I have no clue how to let the user input the values in form and automatically add Quantity to StockOnOrder as well as automatically recognize the SupplierID based on Supplier. At this point I don't know where to start really. At least, is it possible to achieve what I try to do? -
elements of the django selectfield also generate empty lines
I'm trying to build an html select field with the django tags. Django provides me with a select field and I try to create the individual elements myself. the code looks like this: {% for field in fields %} {% if field.field.widget.input_type == "select" %} <select style="width: 100%; hight: 20%;" size="8"> {% for e in field %} <option>{{ e }}</option> {% endfor %} </select> {% else %} {{ field }} {% endif %} {% endfor %} For example, the code creates a select field that looks like this in the html: <select style="width: 100%; hight: 20%;" size="8"> <option value="1"> bla </option> <option></option> <option value="2"> blub </option> <option></option> <option value="3"> blib </option> <option></option> <option value="4"> bleb </option> <option></option> </select> The question is where the <option></option> come from? I've already tried to intercept this with {% if %}, unfortunately without success. I know that {{field}} creates a select field for me, unfortunately this is not an option because I want to style the select field even more ... -
How to upload local images using django-tinymce4-lite?
I am using django-tinymce4-lite to add content and images in my blog, but I have problem adding local images from my computer. Can anyone help? Thank you -
Migrate from DateField to DateTimeField in Django
I have a model with field date = models.DateField() Now I want to migrate this field to DateTimeField, so it should look like this: date = models.DateTimeField() I know that I should run the commands below to make migrations. python manage.py makemigrations python manage.py migrate I tried to use this command python manage.py schemamigration --auto appname but it's not help me But I want to migrate all of this field with saving the date and only add the time 00:00:00:000000. Could you help me to explain how can I do it? -
AttributeError: 'QuerySet' object has no attribute 'requestedDate'
I just want to filter the CustomerPurchaseOrder(inputdate) to CustomerPurchaseOrderDetail(requestedDate). How do i do that? This is my current views.py record = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) date = CustomerPurchaseOrder.objects.filter(profile__in=client.values_list('id')) status = CustomerPurchaseOrderDetail.objects.filter(profile__in=client.values_list('id')) \ .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=date.requestedDate) class CustomerPurchaseOrder(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") customerdeliveryaddress = models.ForeignKey(CustomerDeliveryAddress, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Delivery Address") process = models.ForeignKey('Process', on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Process") requestedDate = models.DateField(auto_now_add=True) class CustomerPurchaseOrderDetail(models.Model): profile = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Client Account") products = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="Product") customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerPurchaseOrder") inputdate = models.DateField(auto_now_add=True) This is my full traceback Traceback: File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\decorators.py" in wrapper_func 42. return view_func(request, *args, **kwargs) File "C:\Users\User\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\contrib\auth\decorators.py" in _wrapped_view 21. return view_func(request, *args, **kwargs) File "C:\Users\User\Desktop\LastProject\OnlinePalengke\customAdmin\views.py" in client 116. .filter(customer_Purchase_Order__in=record.values_list('id')).filter(inputdate=records.requestedDate) Exception Type: AttributeError at /client/ Exception Value: 'QuerySet' object has no attribute 'requestedDate'