Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Manually Adding Formsets Django
I'm so stuck on this problem. I have a use case where I have a formset which can be populated from existing objects on click of a button. For this, I have written a script which deletes the existing forms in the formset and replaces the HTML elements. Essentially, manifest-table25 gets deleted and the empty form gets appended to that div. {{ form2.management_form }} {% for form2 in form2.forms %} <div id="form_set"> <table id = 'manifest-table25' class="manifest-table2" width=100%> {% csrf_token %} <tbody width=100%> <tr class="manifest-row"> <td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form2.ProductCode}}</td> <td width = 32.5% class="description">{{form2.DescriptionOfGoods}}</td> <td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form2.UnitQty}}</td> <td width = 12.5% class="unitType">{{form2.Type}}</td> <td width = 12.5% class="price" oninput="calculate(this)">{{form2.Price}}</td> <td width = 12.5% class="amount2">{{form2.Amount}}</td> {{form2.id}} </tr> </tbody> </table> </div> {% endfor %} <div id="empty_form" style="display:none"> <table id="manifest-table200" class='manifest-table2' width=100%> {% csrf_token %} <tr class="manifest-row1"> <td width = 17.5% class="productCode" onchange="populateProduct(this)">{{form2.empty_form.ProductCode}}</td> <td width = 32.5% class="description">{{form2.empty_form.DescriptionOfGoods}}</td> <td width = 12.5% class="quantity" oninput="calculateUnit(this)">{{form2.empty_form.UnitQty}}</td> <td width = 12.5% class="unitType">{{form2.empty_form.Type}}</td> <td width = 12.5% class ="price" oninput="calculate(this)">{{form2.empty_form.Price}}</td> <td width = 12.5% class="amount2">{{form2.empty_form.Amount}}</td> {{form2.id}} </tr> </table> </div> The issue is that the form id does not get added. So I get a MultiValue Dict Key error. I understand that when submitting … -
Set year us a default value Django
I have the field in model which will be default is the current. So i use the default parameter and editable is false, but i getting this error name 'Year' is not defined My model def Get_Year(): year = datetime.date.today().year return year class DisposalHeader(models.Model): DisposalSecondaryKey = models.UUIDField(unique=True, default=uuid.uuid4, editable=False) Year = models.IntegerField(editable=False, default=Get_Year) Sequence = models.IntegerField(editable=False, default=Sequence_SysGen) CostCenter = models.ForeignKey(CostCenter, on_delete=models.CASCADE) Requestor = models.ForeignKey(User, on_delete=models.CASCADE) SiteLocation = models.ForeignKey(SiteLocation, on_delete=models.CASCADE) ItemType = models.ForeignKey(ItemType, on_delete=models.CASCADE) Remarks = models.CharField(max_length=100, null=True) -
django can't show a template - how to fix
I just made the app users to validate user that is already registered in database. Included url inside project directory(urls.py), executed the login page in urls.py from app directory, made the template and a link refer in base.html. It all works, however when click Login link return this error: TemplateDoesNotExist at users/login/ I tried to rename the path according tree navigation but always return this same error. Any idea what is happening? Sorry my english tree navigation in my project like this: my_project urls.py(project): from django.contrib import admin from django.urls import include, path app_name = ['app_web_gym', 'users'] urlpatterns = [ path('admin/', admin.site.urls), path('users/', include('users.urls', namespace='users')), path('', include('app_web_gym.urls', namespace='app_web_gym')), ] urls.py(app) from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'users' urlpatterns= [ path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] base.html: <p> <a href="{% url 'app_web_gym:index' %}">Web Gym</a>- <a href="{% url 'app_web_gym:clientes' %}">Clientes</a>- <a href="{% url 'app_web_gym:treinos' %}">Treinos</a>- <a href="{% url 'app_web_gym:instrutores' %}">Instrutores</a>- {% if user.is_authenticated %} <p>Hello, {{user.username}}.<p/> {% else %} <a href="{% url 'users:login' %}">Login</a> {% endif %} </p> {% block content %} {% endblock content %} login.html: {% extends 'app_web_gym/base.html' %} {% block content %} {% if form.errors %} <p>Wrong username/password. Try again.</p> {% … -
My CSS files are not responding for my Django Project. How am I suppose to make it work?
base.html file {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{% block title %}{% endblock %}</title> <link href="https://fonts.googleapis.com/css family=Tangerine:bold,bolditalic|Inconsolata:italic|Droid+Sans" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <link rel="stylesheet" href="{% static'css/blog.css'%}"> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous"> <link href=" https://fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet"> <link rel="stylesheet" href="{% static'css/zenburn.css' %}"> </head> Setting.py # STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, '/static/') STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] I have looked at all the solutions on the stack overflow. But none of them able to solve the issue I have added {% load static %} on the base.html and also add the code on setting.py. I do not know what else I can do? -
How to troubleshoot xhr eventListener
I have a modal window called on an AJAX request which suddenly stopped working. I have narrowed it down to the XMLHttpRequest object: $.ajax({ xhr: function() { var xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { console.log('Event listener') if (e.lengthComputable) { console.log('Length computable') showPleaseWaitWindow(); console.log('Percentage uploaded: ' + (e.loaded / e.total)) var percent = Math.round(e.loaded / e.total * 100); $('#progress-bar').attr('aria-valuenow', percent).css('width', percent + '%'); } else { showPleaseWaitWindow(); console.log(e.lengthComputable); } }); return xhr; }, None of these console.log();s print a statement. Inside my view I am able to print success to show it is in-fact an AJAX request. And the response is showing success: success: function(data){ if (data.success) { console.log("success"); window.location.href = data.url; } Why is the eventListener for the 'progress' not working? Or better yet, how do I troubleshoot this further? -
Django Count and Sum Results Too High
I have the following models (simplified): class Post(...): user = ... class Comment(...): post = Post(...) class Vote(...): vote = Either -1 or 1 post = Post(...) I want to know, for a given Post, how many comments it has + what the vote total is. I've written out a ton of queries, but I end up getting 3-4x the actual value. I don't want to settle and use distinct; the join is broken. I've read about using a Subquery, but no results. -
Django - Change date format for filtering a queryset
I've got a datatable on a website, using server-side processing (I'm using django-datatables-view for that). My problem is on the search field. It works fine if I pass a date as expected: %Y-%m-%d. However, I want to return values when passing values like %d/%m/%Y. Here's a sample of my code: def filter_queryset(self, qs): search = self.request.GET.get('search[value]', None) if search: qs = qs.filter( Q(pk__contains=search) | Q(client__first_name__unaccent__icontains=search) | Q(client__fantasy_name__unaccent__icontains=search) | Q(created_at__date__contains=search) | Q(proposal__pk__contains=search) | Q(total_value__contains=search) | Q(engeneering_value__contains=search) ) return qs I've tried strptime(), but if the user passes a value that isn't exactly a full date, the request returns a 500 response. -
How to write a POST method to an a tag in Django
I am trying to write a POST method an "a" tag href but it is not working I was successful writing it in another page to select from an option but I am trying to implement it in an a href but it is not working <form method="POST" action="{{ item.get_add_to_cart_url }}"> {% csrf_token %} <a href="{% url 'core:add-to-cart' order_item.item.slug %}"><i class="fas fa-plus ml-2"></a></i> </form> This is the HTML that I am trying to implement the same logic for which is working perfectly {% csrf_token %} <input class="btn btn-primary btn-md my-2 p" type="submit" value="Add to cart"> {% if object.variation_set.all %} {% if object.variation_set.sizes %} <select class="form-control" name="size"> {% for items in object.variation_set.sizes %} <option value="{{ items.title|lower }}">{{ items.title|capfirst }}</option> {% endfor %} </select> {% endif %} {% endif %} This is the views: @login_required def add_to_cart(request, slug): item = get_object_or_404(Item, slug=slug) order_item_qs = OrderItem.objects.filter( item=item, user=request.user, ordered=False ) print(item) print(order_item_qs) item_var = [] # item variation if request.method == 'POST': for items in request.POST: key = items val = request.POST[key] try: v = Variation.objects.get( item=item, category__iexact=key, title__iexact=val ) item_var.append(v) except: pass if len(item_var) > 0: for items in item_var: order_item_qs = order_item_qs.filter( variation__exact=items, ) if order_item_qs.exists(): order_item = order_item_qs.first() order_item.quantity += … -
Showing dict of lists with Jinja2 in HML Table
I have some data DF_HEAD = {'number1': [445999557, 442000687, 442000835, 442000843, 442001002], 'number2': [445999557.0, 442000687.0, 442000835.0, 442000843.0, 442001002.0]} And I'm trying to show this data as html table in Jinja2 like this {% if DF_HEAD %} <table> <thead> <tr> {% for key, value in DF_HEAD.items %} <th>{{ key }}</th> {% endfor %} </tr> </thead> <tbody> {% for key, value in item %} <tr> {% for column in value %} <td>{{ column }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> {% endif %} I would like to have dict key as Table header (number1, number2) and values as cells within approtiate row for that header. But this code prints only the headers, what I'm doing wrong? -
Displaying Maps in a Form
The back end is now working correctly. Now I want to create a form for the front end. models.py from django.contrib.gis.db import models from django.contrib.auth.models import User NO_OF_HRS = (('1', 'Office'),('2', 'Home')) class Home(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE) Location = models.PointField() City = models.CharField(max_length=50) Street = models.CharField(max_length=60, default="") PostCode = models.CharField(max_length=60, default="") Residential = models.CharField(choices=NO_OF_HRS, max_length=60, default='1') form.py from houses.models import Home from django import forms from django.contrib.gis import forms as geoforms from django.forms import TextInput User and Residential rendered correctly. But with Location there is a white square where a map should ideally be. class ContactForm(forms.ModelForm): class Meta: model = Home fields = ('User', 'Residential', 'Location') I then googled the problem and saw people talking about widgets. These are succesful experiments I did with widgets to try and get a better understanding of them. #description = forms.CharField(widget = forms.CheckboxInput) #title = forms.CharField(widget = forms.Textarea) #description = forms.CharField(widget = forms.CheckboxInput) #views = forms.IntegerField(widget = forms.TextInput) #name = forms.CharField( widget=forms.Textarea(attrs={'rows': 25, 'cols': 100})) #name = forms.CharField( widget=forms.Textarea(attrs={'rows': 40})) #address_2 = forms.CharField( # widget=forms.TextInput(attrs={'placeholder': 'Apartment, studio, or floor'}) #) #check_me_out = forms.BooleanField(required=False) #zip_code = forms.CharField(label='Zippy iii') #password = forms.CharField(widget=forms.PasswordInput()) #address_1 = forms.CharField( # label='Address test', # widget=forms.TextInput(attrs={'placeholder': '1234 Main St'}) #) These … -
Is Django .values() nontrivially more effecient than ORM?
In this Django documentation it states: "When you only want a dict or list of values, and don’t need ORM model objects, make appropriate usage of values()" I have a Table with about 100 columns, some of which are Foreign Keys to other models. I would like to know if using .values() with the following queries would be more performant: Queries that only make use of 20 columns Queries that make use of all 100 columns Please let me know if there is more information I can provide, I'll add it promptly :) -
Django model stoped working when adding more models
I have a view in which the user can edit their profile everything worked fine and everything was being updated (biography, first_name, username, email and profile-picture) but now that I added a new app that contains three views in which the user can upload, delete and like posts, the user update sistem stoped working for some reason just the (update, email, first_name)still worked. The update view calls 2 models, User that lets you edit(name, username and email) and Profile that lets you edit(bio and change the profile pictures) it looks like when I added the upload, delete and like functions mentioned before, the whole Profile model "disapeared" even tho is there. The error I am getting is RelatedObjectDoesNotExist User has no profile. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) profile_pic = models.ImageField(upload_to='profile_pics', null=True, blank=True, default='default.png') bio = models.CharField(max_length=400, default=1, null=True) def __str__(self): return f'{self.user.username} Profile' class Post(models.Model): text = models.CharField(max_length=200) video = models.FileField(upload_to='clips', null=True, blank=True) user = models.ForeignKey(User, related_name='imageuser', on_delete=models.CASCADE, default='username') liked = models.ManyToManyField(User, default=None, blank=True, related_name='liked') updated = models.DateTimeField(auto_now=True) created =models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.text) LIKE_CHOICES = ( ('Like', 'Like'), ('Unlike', 'Unlike'), ) class Like(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) value = models.CharField(choices=LIKE_CHOICES, default='Like', max_length=10) def … -
when create row in table take value from another table in django
I have two Tables i want when create a new invoice tacke field "emp_code" from "HrEmployee" where user=user and insert "emp_code" in fielde "sup_emp_code" in "Invoice" class Invoice(models.Model): user= models.ForeignKey(User,db_column='user', related_name="user_name", on_delete=models.CASCADE, blank=True, null=True) id_invoice = models.AutoField(db_column='Id_Invoice', primary_key=True) # Field name made lowercase. code_invoice = models.CharField(db_column='Code_Invoice', max_length=50, blank=True, null=True) # Field name made lowercase. code_auto_invoice = models.IntegerField(db_column='Code_Auto_Invoice', blank=True, null=True) # Field name made lowercase. invoicedate = models.DateTimeField(db_column='InvoiceDate', blank=True, null=True) # Field name made lowercase. id_store = models.IntegerField(db_column='Id_Store', blank=True, null=True) # Field name made lowercase. sup_emp_code = models.IntegerField(db_column='Sup_Emp_Code', blank=True, null=True) # Field name made lowercase. class HrEmployee(models.Model): emp_code = models.AutoField(db_column='Emp_Code', primary_key=True) # Field name made lowercase. hr_employeegroupid = models.IntegerField(db_column='Hr_EmployeeGroupId', blank=True, null=True) # Field name made lowercase. full_name = models.CharField(db_column='Full_Name', max_length=350, blank=True, null=True) # Field name made lowercase. firstname = models.CharField(db_column='FirstName', max_length=100, blank=True, null=True) # Field name made lowercase. lastname = models.CharField(db_column='LastName', max_length=100, blank=True, null=True) # Field name made lowercase. birthdate = models.DateTimeField(db_column='Birthdate', blank=True, null=True) # Field name made lowercase. pic = models.BinaryField(db_column='Pic', blank=True, null=True) # Field name made lowercase. active = models.IntegerField(db_column='Active', blank=True, null=True) # Field name made lowercase. user_id = models.IntegerField(blank=True, null=True) signal def createdesktopuser(sender,**kwargs): created = kwargs['created'] instance = kwargs['instance'] name= instance.username online_id = instance.id gro= instance.is_staff if created: … -
AWS Elastic Beanstalk can not find static files for Django App
I am having a little trouble setting up the static folders on elastic beanstalk for a django app I created. I manged to get the app to run without any of the css/js/etc. My file structure is: |.ebextensions | --django.config |.elasticbeanstalk | --config.yml |django_app | --core | --blog | --other apps.. |config | --settings | --base.py | --local.py | --production.py | --asgi.py | --urls.py | --wsgi.py |static | --blog | --css/js/etc | --other apps |manage.py |requirements.txt |secrets.json in my django.config I have it set up like so: option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: config.settings.production aws:elasticbeanstalk:container:python: WSGIPath: config.wsgi:application NumProcesses: 3 NumThreads: 20 and for my static settings in base.py (production/local.py do import base.py): # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' STATIC_ROOT = "static" I had a similar problem with flask but it didn't give me this much trouble. I have tried to follow some of the solutions that are on here but nothing has worked just yet or I am misinterpreting something. Any help is appreciated! -
boundfield.py -- render() got an unexpected keyword argument 'renderer'
i see this error many times here and it seems to be different each time. I'm working on a geodjango app with leaflet. and i'm getting this error since i installed leaflet. I rode this in an other post: Support for Widget.render() methods without the renderer argument is removed. Is there any way i can fix this without having to go back to version - 2.0.8 ?? Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/travel/location/15493/change/ Django Version: 3.0.4 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'pages.apps.PagesConfig', 'travel.apps.TravelConfig', 'django_extensions', 'leaflet'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template /Users/marcusbey/.local/share/virtualenvs/rb-website-fKSjEdfu/lib/python3.8/site-packages/django/contrib/admin/templates/admin/includes/fieldset.html, error at line 19 render() got an unexpected keyword argument 'renderer' 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} … -
How update foreign key for several instances in Django formset
I just need to show the list of all Child instances without a parent, when a new Parent is created, so a user can set a checkbox in front of those he would like to add to this parent How to deal with this? I need to let people assign Foreign key to a number of Child instances in django formset. I can't figure out how to do this: models.py: class Parent(models.Model): pass class Child(models.Model): owner = models.ForeignKey(to=Parent, null=True) forms.py: class PartFormset(forms.BaseInlineFormSet): model = Child def get_queryset(self): return self.model.objects.filter(owner__isnull=True) MyFormSet = inlineformset_factory(parent_model=Parent, model=Child, formset=PartFormset, extra=0, can_delete=False, ) this one obviously doesn't work because inlineformset_factory misses fields argument. But of course if I provide the 'owner' as a field, that doesn't work either. -
Stop overriding the default template loader in django project
i am new to django and i am stuck at this problem TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'OPTIONS': { 'loaders' : [ ('admin_tools.template_loaders.Loader', 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', 'project.settings.fileloder.Loader', ) ], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] i have created a template loader which works fine, but the problem is it overrides the default admin templates. whenever i go to admin page it starts using the created template loader.if i remove the created template from the code then admin interface works fine. can anyone help me with this, i am really stuck here -
How do I receive a key back from rest-auth?
I can't seem to receive a key when I log in to rest-auth. Postman just gives me a 404 error. Page not found at /rest-auth/login. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'core', 'rest_auth', ] urls.py from django.contrib import admin from django.urls import path,include from core.views import TestView from rest_framework.authtoken.views import obtain_auth_token urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls')), path('', TestView.as_view(),name='test'), path('api/token', obtain_auth_token,name='obtain_token'), path('rest-auth/login', include('rest_auth.urls')), ] -
Why can't this method in a server be found?
I am working on a new Django project that we uploaded to a server. The problem is that there is a method that is supposed to be called by an API we made. That API is used in another project, and that project works fine. I think it's a matter of my urls or some configuration that I can't think of, since it doesn't say there's an error, it just gives a "Not Found" page when the method url is typed, and the logs on the server say 2020-06-08 17:43:43.337 WARNING log - log_response: Not Found: /whatsapp/get_response/ The project's urls are: from reportes.views import Home from django.conf import settings from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.contrib.auth.views import LogoutView urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('allauth.urls')), path('', Home.as_view(), name='home'), path('orders/',include('orders.urls', namespace='orders')), path('whatsapp/',include('whatsapp.urls', namespace='whatsapp')), path("logout/", LogoutView.as_view(), name="logout"), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And the app which has the method (whatsapp) has these urls: from django.contrib import admin from django.urls import path, include from django.views.generic import TemplateView from whatsapp.conversation import get_response_dialog from .views import webhook_pedidos app_name = 'whatsapp' urlpatterns = [ path('get_response/', get_response_dialog, name='get_response'), path('webhook_pedidos/', webhook_pedidos, name='webhook_pedidos'), ] The method exists and is there, ctrl+click … -
Django POSTing stripe element view reads empty formData
I am trying to read the element I sent using XHR request, but even though the data is there, I cannot access it the usual way: Here is the JS code: $( function() { var customerEmail = document.querySelector("[data-email]").getAttribute('data-email'); var submissionURL = document.querySelector("[data-redirect]").getAttribute('data-redirect'); var stripeSubscriptionForm = document.getElementById('subscriptionId'); var cardElement = elements.create("card", { style: style }); // Mounting the card element in the template cardElement.mount("#card-element"); stripeSubscriptionForm.addEventListener('submit', function(event){ event.preventDefault(); // Before submitting, we need to send the data to our database too theForm = event.target; // getting the form; same as using getElementById, but using the event only theFormData = new FormData(theForm); stripe.createPaymentMethod( { type : 'card', // this is what's sent to stripe card : cardElement, billing_details : { email : customerEmail, } }, ) .then( (result) => { // Once stripe returns the result // Building the data theFormData.append('card', cardElement); theFormData.append('billing_details', customerEmail); theFormData.append('payement_method', result.paymentMethod.id); // Setting up the request const xhr = new XMLHttpRequest() // Creating an XHR request object xhr.open(method, url); // Creating a POST request // Setting up the header xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest"); xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("X-CSRF-TOKEN", "{{ csrf_token }}"); xhr.onload = function() { // After server sends response data back console.log('Got something back from server ') const response = xhr.response; … -
the css and jquery stylesheet are not referencing on my django project, i have tried switching the location
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Trave</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css" rel="stylesheet" type="text/css' %"> the SRC plugins refused to reference even after using the jason format and loaded the static files first <link rel="stylesheet" type="text/css" src="{% static 'plugins/OwlCarousel2-2.2.1/owl.carousel.' %"> <link rel="stylesheet" type="text/css" src="{% static 'plugins/OwlCarousel2-2.2.1/owl.theme.default.css' %"> this plugins has refused to reference <link rel="stylesheet" type="text/css" src="{% static 'plugins/OwlCarousel2-2.2.1/animate.css' %}"> <link rel= type="text/css" src="{% static 'styles/main_styles.css' %}" > this CSS file ha failed to reference <link rel= type="text/css" src="{% static 'styles/responsive.css' %}"> </head> <body> -
how can I fix this error: no module named 'PIL' on Heroku cloud?
I did create a project in Django and I installed everything Django needs to into the virtual environment now I upload the project on the Heroku cloud and when I try to upload any image I get message error: No module named 'PIL' so, I thought maybe I didn't install Pillow when I check on pip3 freeze I get a Pillow and the project locally works properly. so what is the real problem here and How can I fix this issue? -
Django: how to add custom fields to data on form save?
I want to insert some custom variable eg Status into the model when the user submits the form. I want the field status to be updated to Pending when a new record is inserted. This should be done automatically when the user inserts a new form. I know how to insert the form with values set by the user how can i insert my own values instead. My current form that inserts all data into db and it looks like this def createProcess(request): form = ProcessForm() if request.method =='POST': #print('Printing POST request : ', request.POST) form = ProcessForm(request.POST) if form.is_valid(): form.save() # above this i think i can add something to set the status return redirect('process_list') context = {'form' : form} return render(request, 'process/create_process.html', context) How can I customize the value of for eg the status field? I want the status field to automatically be updated without the user submitting any information. -
Running into problems with some java Script
Ive been following a tutorial on YouTube ( Django Ecommerce Website | Add to Cart Functionality | Part 3) and at (20:56 - 23:00) i keep getting this error. Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I followed every thing he did i even spent a few days backtracking through my code and i still cant get this error to go away, Ive only been coding for a few weeks so i probably need more knowledge on java script.But for the time being i wanna see if i can get some help from you guys,Thanks in advance!! -
after submit the views functions do nothing
hello this my html formulaire <div id="Admin" class="tabcontent"> <form method="POST" action=""> {% csrf_token %} <h2> Vous ètes un Admin ?</h2> <div class="container" action > <input type="hidden" name="user_type" value="1"> <label for ="id_email"><b>Votre Email</b></label> <input id="id_email" type="text" placeholder="Entrer Votre Email" name="email" required> <label for ="id_password" ><b>Mot de Passe</b></label> <input id="id_password" type="password" placeholder="Entrer Votre Mot de passe" name="password" required> <button type="submit" >Login</button> <label> <input type="checkbox" checked="checked" name="remember"> souviens de moi </label> </div> and this the views function called login def login(request): context = {} user = request.user if user.is_authenticated: return render(request, "login.html") if request.POST: form = LoginForm(request.POST) if form.is_valid(): email = form.cleaned_data.POST['email'] password = form.cleaned_data.POST['password'] user = authenticate(request, email=email, password=password) if user: login(request, user) if user.user_type == '1': return render(request, "administrateur.html") elif user.user_type == '2': return render(request, "entrepreneur.html") else: print("errors") form = AuthenticationForm() context['login_form'] = form return render(request, "entrepreneur", context) and i create in form files this class class LoginForm(forms.ModelForm): email = forms.EmailField() password = forms.PasswordInput() this my 3 user class in model: class CustomUser(AbstractUser): user_type=((1,"admin"),(2,"entrepreneur")) user_type=models.IntegerField(default=1,choices=user_type) email=models.EmailField(unique=True,blank=True) objects = UserManager() def __str__(self): return self.first_name #admin----------------------------------------------------------------------- class Admin(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE,primary_key=True) date_naissance = models.DateField(default=timezone.now) adresse = models.CharField(max_length=20, blank=True) def __str__(self): return self.user.first_name # Entrepreneur---------------------------------------------------------------- class Entrepreneur(models.Model): user= models.OneToOneField(CustomUser,on_delete=models.CASCADE,primary_key=True) date_naissance=models.DateField() adresse_entr=models.CharField(max_length=20,blank=True) telephone=models.IntegerField() occupation=models.CharField(max_length=50) …