Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Adding a different app to my already existing project
I have a project in django with several apps, now I asked somebody to create another app, I was sent the code via email but i want to add this new app to the already existing projects i have. Please how do i go about it as i was sent all the files including requirements and Im trying to get it done on my local computer. -
how to pass optional parameter in views.py [ Django ]
urls.py: def shopgrid(request, proname=None): products = Product.objects.all() categories = Categories.objects.all() recent_products = Product.objects.order_by('-date')[0:3] if proname != None: products = Product.objects.filter(categorie__title=proname) if request.method == "GET": recent = request.GET.get('val') amount = request.GET.get('amount') print('This is amount--->',amount) if recent == 'name': products = Product.objects.order_by('name') if recent == 'price': products = Product.objects.order_by('-price') if 'val' in request.GET: check_values = request.GET.getlist('val') first_element=check_values[0] last_element=check_values[-1] fe = first_element[0:4] le = last_element[-4:] min_price = int(fe) max_price = int(le) products = Product.objects.filter(price__range=(min_price, max_price)) print(products) context={'p':products, 'rp':recent_products, 'cat':categories} return render(request, 'cart/shop-grid.html', context) urls.py: urlpatterns = [ path('', views.index, name="index"), path('shopgrid/', views.shopgrid, name="shopgrids"), path('shopgrid/<str:proname>/', views.shopgrid, name="shopgrid"), path('cat_sort/<str:proname>/', views.cat_sort, name="cat_sort"), ] ERROR: **Reverse for 'shopgrid' with no arguments not found. 1 pattern(s) tried: ['shopgrid/(?P<proname>[^/]+)/$']** <form id="priceform" action="**{% url 'shopgrid' %}**" method="GET"> {% csrf_token %} <input type="text" id="amount" name="amount" placeholder="Add Your Price"> </form> def shopgrid(request, proname=None): proname is an optional parameter.Question is how to write optional parameter in Jinja template. i already write a proname=None but I am facing error only HTML -
Problem extracting value from Django object serialized as JSON
I have serialised a Django object using data = serializers.serialize("json", vchemicals) and passed it into my template, where it can be printed as: [{"model": "vbench.vchemical", "pk": 1, "fields": {"shortname": "NaCl", "longname": "Sodium Chloride", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 2, "fields": {"shortname": "NH4SO4", "longname": "Ammonium Sulphate", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 3, "fields": {"shortname": "Glucose", "longname": "D-Glucose", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 4, "fields": {"shortname": "NaPO4", "longname": "Sodium Phosphate", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 5, "fields": {"shortname": "Glycerol", "longname": "Glycerol", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 6, "fields": {"shortname": "KCl", "longname": "Potassium Chloride", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 7, "fields": {"shortname": null, "longname": "Tryptone", "catno": null, "batchno": 1, "owner": 1}}, {"model": "vbench.vchemical", "pk": 8, "fields": {"shortname": "Test", "longname": "Name that is clearly too long for the table", "catno": null, "batchno": 1, "owner": 1}}] I set this as a JS variable within a script using var chemlist = "{{ data }}"; It is now printed as [{&quot;model&quot;: &quot;vbench.vchemical&quot;, &quot;pk&quot;: 1, &quot;fields&quot;: {&quot;shortname&quot;: &quot;NaCl&quot;, &quot;longname&quot;: &quot;Sodium Chloride&quot;, &quot;catno&quot;: null, &quot;batchno&quot;: 1, &quot;owner&quot;: 1}}, {&quot;model&quot;: &quot;vbench.vchemical&quot;, &quot;pk&quot;: 2, &quot;fields&quot;: {&quot;shortname&quot;: &quot;NH4SO4&quot;, … -
Best approach to auto create profile object upon user creation in django
I was wondering what would be the best way to auto create and assign a related Profile object to a user upon creation in django. Any Ideas or Links to check out? -
Django REST ViewSet create
I have a viewset for employees where I want to add a create definition, such that I can set employer=request.user.pk and add the employee (user). I've tried making a create definition (see code below) but the serializer is always invalid so it returns status 400. I don't know if it's me but there seems to be a lack of documentation on the create function so I can't figure out how to do it correctly. Any ideas? class EmployeeViewSet(viewsets.ModelViewSet): queryset = CustomUser.objects.all() serializer_class = CustomUserSerializer def list(self, request): queryset = self.queryset.filter(employer=request.user.pk) serializer = CustomUserSerializer(queryset, many=True) return Response(serializer.data) def create(self, request): serializer = self.serializer_class(data=request.data) if serializer.is_valid(): CustomUser.objects.create_user(**serializer.validated_data) return Response(serializer.validated_data, status=status.HTTP_201_CREATED) return Response({'status': 'Bad Request', 'message': serializer.is_valid()}, status=status.HTTP_400_BAD_REQUEST) -
TemplateDoesNotFound Error after deploying django app in heroku
I have deployed my Django app successfully on Heroku. But it is not running at all. The problem showing here is TemplateDoesNotExist error which tells it could not find the base.html file which I extended at every other template. But I have all the templates up and running on the local environment. Here is a log of the errors- TemplateDoesNotExist at / base.html Request Method: GET Request URL: https://barikoi.herokuapp.com/ Django Version: 2.2 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: /app/.heroku/python/lib/python3.6/site-packages/django/template/backends/django.py in reraise, line 84 Python Executable: /app/.heroku/python/bin/python Python Version: 3.6.11 Python Path: ['/app/.heroku/python/bin', '/app', '/app/.heroku/python/lib/python36.zip', '/app/.heroku/python/lib/python3.6', '/app/.heroku/python/lib/python3.6/lib-dynload', '/app/.heroku/python/lib/python3.6/site-packages'] Server time: Sun, 12 Jul 2020 13:26:22 +0000 Template loader ostmortem shows the following issues- Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /app/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /app/.heroku/python/lib/python3.6/site-packages/django/contrib/auth/templates/base.html (Source does not exist) I tried the solution from this answer but it did not work in my case. I checked everything on the local environment, everything seemed ok. -
How to iterate a queryset and append to a string
I have the following function in my view to generate notifications whenever a user has been removed from a project : for user in project.userProfile.all(): Notifications.objects.create( target=user.user, extra='Users', object_url='', title='The following users have been removed : ' + str(removed_users) , ) Of which removed_users is a queryset containing my UserProfile model. What i wish to accomplish is to be able to iterate through the queryset removed_users , access the username field which belongs to the default django auth model , and append it to the string in title Is there a clean easy way to accomplish this? -
mark as read django-notifications-hq
I pretty much have django-notifications-hq working except I can't figure out how to mark unread notifications as read after seeing the notifications. I followed along this StackOverflow answer to get the notifications to appear in a dropdown list in the navbar: django-notifications-hq: cannot show notifications But I can't seem to mark them as read. The docs say you can use an API call mark_as_read but it doesn't seem to work. I added mark_as_read to the callback section of the script call here: <script src="{% static 'notifications/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list,fill_notification_badge,mark_as_read' %} Here's the rest of the navbar code where I have the notifications: {% load notifications_tags %} {% if user.notifications %} <script src="{% static 'notifications/notify.js' %}" type="text/javascript"></script> {% register_notify_callbacks callbacks='fill_notification_list,fill_notification_badge' %} <li class="nav-item"> <div class="dropdown"> <a aria-expanded="false" aria-haspopup="true" class="dropdown-toggle nav-link nav-item arrow-bottom" data-toggle="dropdown-grid" href="#" role="button"><span class="badge badge-light">{% live_notify_badge %}</span></a> <div class="row dropdown-menu"> <div class="col-auto" data-dropdown-content> <ul class="dropdown-grid-menu" id="notice-link"> <a href="{% url 'messages' %}"> {% live_notify_list %} </a> </ul> </div> </div> </div> </li> {% endif %} -
MultiValueDictKeyError at /EditPage - Django , Python , Html
I have this Error from the task of the Web Programing course: The function objective is to write or update the text that comes with the page in a textarea , save in the same file oppened and redirect to other page. Django Error: MultiValueDictKeyError at /EditPage 'NewContent' Request Method:POST -Request URL:http://127.0.0.1:8000/EditPage -Django Version:3.0.8v -Exception Type:MultiValueDictKeyError -Exception Value:'NewContent' -Exception Location:C:\Python38\lib\site-packages\django\utils\datastructures.py in getitem, line 78 -Python Executable: C:\Python38\python.exe -Python Version: 3.8.3 Exception Type: MultiValueDictKeyError at /EditPage Exception Value: 'NewContent' My HTML: <h2>{{title}}</h2> <br> <form action="{% url 'encyclopedia:EditPage' %}" method="post" width=90% > {% csrf_token %} <label for="NewContent"><h4>Change Encyclopedia Item :</h4></label> <textarea type="text" wrap="hard" onclick="showNewcontent()" name="NewContent" id="NewContent"> {{content}} </textarea> <br> <form class="form-inline" style="position:relative ; top:15px" > <p><button type="submit" class="btn btn-success">Save New Content</button> <button type="button" class="btn btn-danger"> <a href="{% url 'encyclopedia:index' %}">Cancel</button> </p> </form> </form> My JS <script> function showNewcontent() { var x = ""; var depois = ""; var x = document.getElementById("content").value; document.getElementById("NewContent").innerHTML = x; var depois = document.getElementById("NewContent").value; alert(x); } </script> My Python : def EditPage(request): if request.method == "POST": entry = str(request.POST["entry"]) title = str( request.POST["title"]) print("Reading:" , "Título:",title, "Entry:", entry) content =util.get_entry(title) print(content) NewContent= request.POST["NewContent"] print("Will Save:", NewContent) if len( NewContent) >0: pagename = "Wiki/"+title.capitalize() filename = f"entries/{title}.md" print(pagename, filename) … -
I accidentally deleted my website in django admin/sites page
I was having an issue with the django generated sitemap.xml showing example.com instead of my domain name. I have read that I should change the name of my website in django admin, going to " sites" menu. But instead of modifying it, I deleted it and created a new one with the right domain name. Now, I can still access my website but not my sitemap.xml anymore. When I try to do so, I have the following message error: Site matching query does not exist. Does anyone know how I can solve this? -
why the page doesn't return me to the correct user profile page?
I have a strange problem, I did create a user and user profile then I create the function that leads to saving the user as an instance in user profile as you can see the code below now I need when someone clicks the user who creates the post will return back to the profile page of this user but that not happen. what happens is when I click on the user suppose I use username called Abdin and I need to click on John the page will return me back to my profile page, at this moment is (Abdin), also if I want to change the user to login with the John user and when I need to click on Abdin will return me back to John profile, not Abdin profile, however, when I do inspect in the page to sure of the URL of the user I see that URL be correct but it doesn't take me to the correct page so, what is the mistake I made here? #account app models.py from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.template.defaultfilters import slugify CHOICE = [('male', 'male'), ('female', 'female')] class UserProfile(models.Model): user = … -
Combine multiple modelform in one create view in django
I have a multiple modelforms form multiple model. I want one single form for submitting all the values. It means I want one single createview for posting all modelforms data. I dont know how to that. forms.py: class EmployeeAddModelForm(forms.ModelForm): """ Creates a form for employee invitations """ class Meta: model = Employee fields = [ 'e_id', 'first_name', 'last_name', 'gender', 'religion', ] class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] class EducationForm(forms.ModelForm): """ Creates a form for saving educational info of an employee """ class Meta: model = Education fields = [ 'institution_name', 'degree', 'passing_year', 'result',] I have three model forms from three models in form.py. I want that my createview inherits all this modelforms and create a single form for posting data. views.py: class EmployeeAddView(LoginRequiredMixin,CreateView): """ Creates new employee """ login_url = '/authentication/login/' template_name = 'employee/employee_add_form.html' form_class = EmployeeAddModelForm work_form_class = WorkExperienceForm queryset = Employee.objects.all() def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) work_form = self.work_form_class(request.POST, prefix='work_form') print(form.errors) if form.is_valid() and work_form.is_valid(): form.save(commit=True) work_form.save(commit=True) return redirect('employee:employee-list') return render(request, self.template_name, {'form': form, 'work_form': work_form}) def get_success_url(self): return … -
Accessing database table FileField showing module error combined with configuration error django
My database table is of type FileFields(). I uploaded a csv file to it via django admin. I want to access the file from my DB table and run pandas on the file, to crunch some numbers. I have created a main.py file where i will run my pandas code. Main.py import pandas as pd import matplotlib.pyplot as plt from .models import UploadedFile df = pd.read_csv(UploadedFile.the_file.name('hello.csv'), index_col='Date', parse_dates=True) 2 errors are coming up when i run main.py. one in the terminal and one in the run window: Terminal error ModuleNotFoundError: No module named 'chartsjs' Run window error ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. See I can run the file no problem locally using: df = pd.read_csv('hello.csv', index_col='Date', parse_dates=True) But when i try to access it from the database table 2 errors are thown. even though my layout seem correct. -
How to calculate total of defs using django?
I would like to calculate the total balance of clients, i did this class with def but it calculate for one client only, i would like to create one def to calculate the total of balance_client of all clients i have class ClientsBalance(models.Model): client = models.OneToOneField(Client, on_delete=models.CASCADE,related_name='Client') def sales(self): invoices = self.client.invoice_set.all() sales_amount = 0 for invoice in invoices: sales_amount += invoice.amountDuettc() return sales_amount def clientpayment(self): invoices = self.client.invoice_set.all() clientpayment = 0 for invoice in invoices: clientpayment += invoice.amount_paid() return clientpayment def client_balance(self): items = self.client.invoice_set.all() invoice_balance = 0 for item in items: invoice_balance = (self.sales()) - (self.clientpayment()) + (item.client.initialBalance) return invoice_balance -
django.core.exceptions.ImproperlyConfigured error
I want to add a path to my url and get this error: django.core.exceptions.ImproperlyConfigured: The included URLconf 'cineam.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. here is my url.py from django.contrib import admin from django.urls import path from cineam.ticketing.views import cinema_list urlpatterns = [ path('admin/', admin.site.urls), path('ticketing/cinema', cinema_list), ] what is the problem? -
How to define two Django fields unique in certain conditions
I want to make Django Model fields unique with two fields(values) in some conditions. there's two fields: 'team', 'type'. And I want to make team manager unique For Example: team=1, type='manager' team=1, type='manager' -> Not available team=1, type='manager' team=1, type='member' team=1, type='member' team=2, type='manager' -> Available I think unique_together('team', 'type') won't work properly with this situation. How can I make this with Django Model? -
How to get the context of a view to another in Django without accessing the database again?
I have a view that lists the items in the cart of a user, to show the user the invoice for their purchase. The code for that view is def invoice_view(request): cart = Cart.objects.get(user=request.user) cart_items = ItemInCart.objects.filter(cart=cart) total_cost = 0 for item in cart_items: total_cost += item.cost return render(request, 'app1/checkout.html', {'cart_items': cart_items, 'total_cost': total_cost}) Now say I need the 'cart_items' list in another view of the same app - to checkout the user. How do I do it without having to access the database again? The methods I found on SO and other forums were storing the information in session data or sending the data as parameters to an HTTP request. Is there an alternative to this? Thanks. -
django if in queryset is always false
class Product(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path,null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) class OrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE ) quantity = models.IntegerField(default=1) item_cart = models.CharField(max_length=20, null=True, blank=True) active = models.BooleanField(default=True) class Cart(models.Model): user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE) products = models.ManyToManyField(OrderItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) """ """ def product_list_view(request): queryset = Product.objects.all() item = OrderItem.objects.all() cart_obj, new_obj = Cart.objects.new_or_get(request) print(item) context = { 'product_list': queryset, 'cart' : cart_obj, 'orderitem' : item } return render(request, "products/list.html", context) """hmtl page list.hmtl {% if obj in orderitem %} doesnt print else print allways """ {% for obj in product_list %} <div class='col my-3'> {{obj.title}} {{obj.price}} {{orderitem}} {% if obj in item %} <h1>in cart</h1> {% else %} <h5>delete</h5> {% endif %} </div> {% endor %} orderitem = <QuerySet [<OrderItem: iphone 6s>, <OrderItem: hi>]>, obj = hi , in list.hmtl if obj in orderitem always shows error and also tried obj.title in orderitem But always else statement is printed without any error trying to check the product is in ordereditem... -
Django Model Relation entries
I have data and I want to organize it as: I create three tables, on for MonthsM, Wellinfo and TestPRODM: class MonthsM(models.Model): MonthsM = models.DateTimeField(unique=True) class Wellinfo (models.Model): WellID = models.CharField(max_length=15,unique=True) class TestPRODM(models.Model): WellID = models.ForeignKey(Wellinfo ,to_field='WellID', on_delete=models.CASCADE) TestMonth = models.ForeignKey(TestMonthM, on_delete=models.CASCADE) TestOIL = models.DecimalField(max_digits=10, decimal_places=3,null=True, blank=True) #conditions In my real data I have one WellID that can be tested only once in month. so how to set a condition that do that? so in the table (TestPRODM) it can have many entry with same WellID but with different months and so it can have many entry with same TestMonth but with different WellID. NB. NO entry in (TestPRODM) table that have the same WellID and TestMonth in the same time. -
sort product without reload page in django
views.py def shopgrid(request): products = Product.objects.all() categories = Categories.objects.all() recent_products = Product.objects.order_by('-date')[0:3] if request.method == "GET": recent = request.GET.get('val') if recent == 'name': products = Product.objects.order_by('name') if recent == 'price': products = Product.objects.order_by('-price') context={'p':products, 'rp':recent_products, 'cat':categories} return render(request, 'cart/shop-grid.html', context) HTML File <form id="forms" action="{% url 'shopgrid' %}" method="GET"> {% csrf_token %} <label>Sort By :</label> <select name="val" id="val"> option selected="selected" value="name">Name</option> <option value="price">Price</option> </select> </form> javascript File: I try first Ajax but problem not solve $('#val').change(function(){ $.ajax({ type: "GET", url: "{% url 'shopgrid' %}", success: function() { $('#forms').submit() } }); }); then I try this stuff $('#val').change(function(){ $('#forms').submit() $( "#forms").submit(function( event ) { event.preventDefault(); }); }); basically I try sort product without reloading the page using dropdown menu please also see the HTML file I'm new in web developing thankyou -
Running pandas on database table in django
My database table is of type FileFields(). I uploaded a csv file to it via django admin. I want to access the file from my DB table and run pandas on it to crunch some numbers. I am running into the error: Traceback (most recent call last): File "/Users/petergaffney/PycharmProjects/chartsjs/chartsapp/main.py", line 3, in <module> from .models import UploadedFile ImportError: attempted relative import with no known parent package I am trying to access the file called hello.csv from my object called the_file. in my main.py i am setting a pandas dataframe to the file as follows: import pandas as pd import matplotlib.pyplot as plt from .models import UploadedFile df = pd.read_csv(UploadedFile.the_file.name('hello.csv'), index_col='Date', parse_dates=True) -
background_task_completedtask doesn't exist
while running background task in python django it is showing me this error. why background_task_completedtask is not created by brackgroud_task in models . /Users/getmyparking/Documents/workspace/env_new/bin/python /Users/getmyparking/Documents/workspace/enable_backend/enable_backend/manage.py process_tasks Rescheduling backendV2.tasks.operator_login_api Traceback (most recent call last): File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/backends/mysql/base.py", line 101, in execute return self.cursor.execute(query, args) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.ProgrammingError: (1146, "Table 'hybrid-staging.background_task_completedtask' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/background_task/tasks.py", line 48, in bg_runner completed = task.create_completed_task() File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/background_task/models.py", line 278, in create_completed_task completed_task.save() File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/base.py", line 808, in save force_update=force_update, update_fields=update_fields) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/base.py", line 838, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/base.py", line 924, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/base.py", line 963, in _do_insert using=using, raw=raw) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/query.py", line 1079, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/models/sql/compiler.py", line 1112, in execute_sql cursor.execute(sql, params) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) File "/Users/getmyparking/Documents/workspace/env_new/lib/python3.7/site-packages/django/db/utils.py", line 94, in __exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) … -
The page was refreshed even we use AJAX
$('#val').change(function(event){ var id = document.getElementById('val') event.preventDefault(); $.ajax({ type: "GET", url: "{% url 'shopgrid' %}", success: function( ) { $('#forms').submit() } }); }); using preventDefault() even so the page was refreshing -
31/5000 how to insert a new user?
I am trying to create a new personalized user and when I click on the register button it does not register anything for me, below I show my code to help me solve this problem in advance thank you very much This is the forms.py class FormularioUsuario(forms.ModelForm): password1=forms.CharField(label='Contraseña', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder':'Ingrese su Contraseña...', 'id': 'password1', 'required':'required', } )) password2=forms.CharField(label='Contraseña de Confirmacion', widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder':'Ingrese nuevamente su Contraseña...', 'id': 'password2', 'required':'required', } )) class Meta: model=Usuario fields=('email', 'username', 'nombres', 'apellidos') widgets ={ 'email': forms.EmailInput( attrs={ 'class': 'form-control', 'placeholder': 'Correo Electronico', } ), 'nombres': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Ingrese su nombre', } ), 'apellidos': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Ingrese su Apellido', } ), 'username': forms.TextInput( attrs={ 'class': 'form-control', 'placeholder': 'Ingrese su Nombre de Usuario', } ) } def clean_password2(self): print(self.cleaned_data) password1=self.cleaned_data.get('password1') password2=self.cleaned_data.get('password2') if password1 != password2: raise forms.ValidationError('Contraseñas no coinciden') return password2 def save(self, commit=True): user=super().save(commit=False) user.set_password(self.cleaned_data['password1']) if commit: user.save() return user This is the views.py class RegistrarUsuario(CreateView): model=Usuario form_class=FormularioUsuario template_name='usuario/crear_usuario.html' success_url = reverse_lazy('usuario:listar_usuarios') This is the models.py class Usuario(AbstractBaseUser): username = models.CharField('Nombre de usuario',unique = True, max_length=100) email = models.EmailField('Correo Electrónico', max_length=254,unique = True) nombres = models.CharField('Nombres', max_length=200, blank = True, null = True) apellidos … -
Setting Up a Language-Switching Button in Django
I'm new to Django and would like some advice on how to set up a single language switching button to switch between two languages (English and Japanese in this case), and specifically how to set up this functionality in a view and access it from a template. In the template, I've arrived at the following which works but it includes repeated code for the form and the button, which obviously isn't great. {% get_current_language as LANGUAGE_CODE %} {% ifequal LANGUAGE_CODE 'en' %} <form action="{% url 'set_language' %}" method="post" id="form_{{ 'ja' }}" > {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ 'ja' }}" /> </form> <button class="btn btn-sm btn-outline-primary" type="submit" form="form_{{ 'ja' }}" value="Submit">日本語</button> {% else %} <form action="{% url 'set_language' %}" method="post" id="form_{{ 'en' }}" > {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}" /> <input name="language" type="hidden" value="{{ 'en' }}" /> </form> <button class="btn btn-sm btn-outline-primary" type="submit" form="form_{{ 'en' }}" value="Submit">English</button> {% endifequal %} My apologies for the beginner question but I'd really appreciate some advice as to how to put the above logic into a view and access it from the template. Thanks in advance.