Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I can't see my elasticbeanstalk application in the browser
I have followed AWS's instructions for deploying a django application using the ebcli. It is important to note, I think, that after running eb init I am prompted to select a reigon, enter my credentials, and set my instance. Afterwhich I receive feedback that my application has been created. I checked the AWS console on the browser and I see nothing. Yes, I checked all regions. I found out that after doing eb list and eb status that the environment wasn't actually created in the eb init step so I referenced this answer: AWS Elastic Beanstalk : the command eb list shows no environments Running eb create --single allowed the application to upload and I could access via the link provided. However, this for some reason is not attached to the instances in my user and cannot see it in the browser. Why is it that I cannot see my application in the AWS console despite it existing and running currently? Here is the output of eb status Environment details for: **** Application name: ***** Region: ***** Deployed Version: app-2ecd-200609_120851 Environment ID: e-wbqx6***** Platform: arn:aws:elasticbeanstalk:ap-northeast-1::platform/Python 3.7 running on 64bit Amazon Linux 2/3.0.2 Tier: WebServer-Standard-1.0 CNAME: *****.elasticbeanstalk.com Updated: 2020-**-** 03:18:12.491000+00:00 Status: … -
How to consume REST api running on the same network with android app built with Ionic?
Hi everyone I built an API with django and I can consume this with my Ionic app using my browser but when I try to connect using my real device which is an android I get "Unknown Error" message with every request to the api. In order to run my django project on another devices inside the same network I am using python manage.py runserver 0.0.0.0:8000 command settings.py (django project) ALLOWED_HOSTS = ['I got the ip with ipconfig'] CORS_ORIGIN_ALLOW_ALL=True On Ionic I send the next headers setHeaders: { 'Authorization': `Bearer ${token}` } config.xml on Ionic <?xml version='1.0' encoding='utf-8'?> <widget id="io.ionic.starter" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0"> <name>MyApp</name> <description>An awesome Ionic/Cordova app.</description> <author email="hi@ionicframework.com" href="http://ionicframework.com/">Ionic Framework Team</author> <content src="index.html" /> <access origin="*" /> <allow-intent href="http://*/*" /> <allow-intent href="https://*/*" /> <allow-intent href="tel:*" /> <allow-intent href="sms:*" /> <allow-intent href="mailto:*" /> <allow-intent href="geo:*" /> <preference name="ScrollEnabled" value="false" /> <preference name="android-minSdkVersion" value="19" /> <preference name="BackupWebStorage" value="none" /> <preference name="SplashMaintainAspectRatio" value="true" /> <preference name="FadeSplashScreenDuration" value="300" /> <preference name="SplashShowOnlyFirstTime" value="false" /> <preference name="SplashScreen" value="screen" /> <preference name="SplashScreenDelay" value="3000" /> <platform name="android"> <edit-config file="app/src/main/AndroidManifest.xml" mode="merge" target="/manifest/application" xmlns:android="http://schemas.android.com/apk/res/android"> <application android:networkSecurityConfig="@xml/network_security_config" /> </edit-config> <resource-file src="resources/android/xml/network_security_config.xml" target="app/src/main/res/xml/network_security_config.xml" /> <allow-intent href="market:*" /> <icon density="ldpi" src="resources/android/icon/drawable-ldpi-icon.png" /> <icon density="mdpi" src="resources/android/icon/drawable-mdpi-icon.png" /> <icon density="hdpi" src="resources/android/icon/drawable-hdpi-icon.png" /> <icon … -
Store django validation errors (without throwing) in model clean() method, retrieve them during model object creation?
I created a custom validation code inside a model class' clean method where validation errors are coded to be stored in error attributes instead of being thrown. Then, during object creation elsewhere in another function, it's desired the errors be either thrown and caught in try/exception block or programmatically retrieved and handled. The code snippets in those two locations are like the following. Therefore, please help in giving corrections or tips on who to go about achieving the result. Thanks! Code in models.py clean() method for validating two fields. def clean(self, *args, **kwargs): super().clean(*args, **kwargs) # Entry_ID Validation: Non negative integer – should not repeat in single file try: cast_value = int(self.watch_entry_id) if cast_value < 1: self.add_error({'watch_entry_id': ValidationError(_("Invalid Entry_ID: Non-positive integer."), code='invalid')}) except TypeError: self.add_error({'watch_entry_id': ValidationError( _("Invalid Entry_ID: Not a number."), code='invalid')}) # Customer_ID Validation: Non negative integer try: cast_value = int(self.cust_id) if self.cust_id < 1: self.add_error({'cust_id': ValidationError(_("Invalid Customer_ID: Non-positive integer"), code='invalid')}) except TypeError: self.add_error({'cust_id': ValidationError(_("Invalid Customer_ID: Not a number."), code='invalid')}) # Code in a function where model objects are created and processed. try: cwt = Cust_Watch_Time.objects.create( watch_entry_id=list_of_data_list[i][0], cust_id=list_of_data_list[i][1], # ... ) cwt.clean() field_errors.append(cwt.fields['watch_entry_id'].message_dict['invalid']) field_errors.append(cwt.fields['cust_id'].message_dict['invalid']) # ... if field_errors: raise ValidationError(field_errors) except ValidationError as e: data_with_error_msg = str(list_of_data_list[i]) + " … -
How to Change Django Default Page to your Design?
I uploaded my site to the live server, but still, I am seeing Django default page, I updated my urls.py file, but still, it's not working. and it's showing me this output. Please let me know where I am Mistaking. I am trying to access this mydomain.com/dashboard Using the URLconf defined in yoursite.urls, Django tried these URL patterns, in this order: admin/ The current path, dashboard, didn't match any of these. here is my urls.py file... urlpatterns = [ path('admin/', admin.site.urls), url(r'^dashboard/', include('dashboard.urls')), url(r'^accounts/', include('accounts.urls')), url('', include('frontpanel.urls')), path('', views.index, name='index'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) And here is my views.py file... def index(request): category = Category.objects.all().order_by('created_at') return render(request, "base.html", {'category':category}) -
How To Get Notification Count From Django-Notifications
Im using django-notifications and know I can get a count of the users unread notifications like this {% notifications_unread as unread_count %} {% if unread_count == 0 %} [..cont..] However, I cannot find out how to get a count of all a users notifications (read and unread). Thank you. -
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; …