Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: duplicate column name: Email
I want to create a Django app that supports two different kinds of users. For that I have first extended my User by inheriting AbstractUser. Some fields are common to both the types of Users that I want my Django app to support and hence I add those fields in the extended User model. My User model is as follows. class User(AbstractUser): is_a = models.BooleanField(default=False) # a boolean flag to determine if this user is of type a is_b = models.BooleanField(default=False) # a boolean flag to determine if this user is of type b Name = models.CharField(max_length=128) Email = models.EmailField() MobileNumber = PhoneNumberField(null=False, blank=False, unique=True) Age = models.PositiveIntegerField() Gender = models.CharField(max_length=1, choices=GenderChoices) Organisation = models.CharField(max_length=128) Designation = models.CharField(max_length=128) def __str__(self): return self.Name I then make migrations. This is my first ever migration in this project. My migrations file is as follows: # 0001_initial.py # Generated by Django 2.0.1 on 2020-10-01 17:30 from django.conf import settings import django.contrib.auth.models import django.contrib.auth.validators from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import phonenumber_field.modelfields class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0009_alter_user_last_name_max_length'), ] operations = [ migrations.CreateModel( name='User', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('password', models.CharField(max_length=128, verbose_name='password')), ('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')), … -
Duplicating and then extending Django admin template
I want to copy and extend the admin's change_list.html for my app's model. I override the Django admin index.html to provide a link to a template, link works fine, sends to admin/links which has the following: VIEW def links(request): context = dict( #common variables for rendering the admin template admin.site.each_context(request), ) return render(request, 'links.html', context) I then copied the change_list.html template verbatim because I want to work off this as a starting point because I would like it to look and function similar, with a few modifications. This is where I run into errors: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/links/ Django Version: 3.0.8 Python Version: 3.7.7 Installed Applications: ['grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'useraudit', 'encrypted_fields', 'easyaudit', 'multiselectfield', 'algorx'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'sesame.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'useraudit.middleware.RequestToThreadLocalMiddleware', 'easyaudit.middleware.easyaudit.EasyAuditMiddleware'] Template error: In template C:\Bitnami\djangostack-3.0.8-0\python\lib\site-packages\grappelli\templates\admin\base.html, error at line 118 Reverse for 'app_list' with keyword arguments '{'app_label': ''}' not found. 1 pattern(s) tried: ['admin/(?P<app_label>auth|useraudit|easyaudit|algorx)/$'] 108 : <!-- Switch --> 109 : {% switch_user_dropdown %} 110 : </ul> 111 : </li> 112 : <!-- Site URL --> 113 : {% if site_url %} 114 : <li><a href="{{ site_url }}">{% trans 'View site' %}</a></li> 115 : {% endif %} 116 … -
How can i get radio button values from html to django view.py?
This is my html code : <input type="radio" name="male" value="0"> <input type="radio" name="female" value="1"> and I am getting error for this line in views.py in django: male= request.POST['male'] -
django onetoonefield errors foreing key
i'm making a django project. I have 2 models AccountUser and Club, where club have a onetoone relationship with AccountUser. The problem is: while im logged in with the AccountUser "club1" and try to create a club record in the table Club(so a club record with the user field set to club1), django put admin in the field user and I don't know why models file class AccountUser(AbstractUser): # email = models.EmailField(_('email address'), unique=True) AbstractUser._meta.get_field('email')._unique = True first_name = models.CharField(max_length=50) middle_name = models.CharField(max_length=50, null=True, blank=True) last_name = models.CharField(max_length=50) terms_of_service_acceptance = models.BooleanField(default=False) terms_of_service_acceptance_datetime = models.DateTimeField(auto_now_add=True) is_club = models.BooleanField(default=False) REQUIRED_FIELDS = ['email'] USERNAME_FIELD = 'username' class Meta: verbose_name = _('Account') verbose_name_plural = _('Accounts') @property def has_profile(self): try: assert self.profile return True except ObjectDoesNotExist: return False def clean(self): if not self.terms_of_service_acceptance: raise ValidationError(_("You must accept the terms of service")) class Club(models.Model): club_name = models.CharField(max_length=50, unique=True) street = models.CharField(max_length=150) civic_number = models.CharField(max_length=5, null=False, blank=False) city = models.CharField(max_length=50) zip_code = models.CharField(max_length=5) user = models.OneToOneField( AccountUser, on_delete=models.CASCADE, related_name='club', primary_key=True ) class Meta: verbose_name_plural = 'Clubs' ordering = ['-club_name', 'city'] unique_together = ('street', 'civic_number', 'city') def clean(self): if len(self.zip_code) != 5 or not self.zip_code.isdigit(): raise ValidationError(_("Il CAP inserito non è valido")) if not self.civic_number.isdigit(): raise ValidationError(_("Numero civico … -
Invalid CSRF Verification with Django
I have a HTMl form i created and i am trying to get Django to process. Here is my main.html (shortened): <form action="/polls/thanks/" method="post" name = 'tag_name'> {% csrf_token %} <div class="w-3/4 py-10 px-8"> <table class="table-auto"> <thead> <tr> <th class="py-10 h-4"> <div class="mr-64"> <input type="checkbox" class="form-checkbox h-8 w-8"> <label class="ml-4">test</label> </div> </th> </tr> and here is the views.py: from django.http import HttpResponseRedirect from django.shortcuts import render def get_name(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = request.POST.get('tag_name') print(form) if form.is_valid(): return HttpResponseRedirect('/polls/thanks/') return render(request, 'main.html', {'form': 'mainform'}) def thanks(request): form = request.POST.get('tag_name') print(form) if form.is_valid(): print(form.cleaned_data) return render(request, 'thanks.html') yet it still returns a Invalid CSRF Verification if I try and submit the form Does anyone know how to fix this? Thanks -
How to display value from the database in input tag in django?
I am having an HTML template for displaying my form data to allow users to view as well as edit their data:- <div id="div_id_first_name" class="form-group"> <label for="id_first_name" class="requiredField"> First name<span class="asteriskField">*</span> </label> <div class=""> <input type="text" name="first_name" value="{{p_form.first_name}}" maxlength="20" class="textinput textInput form-control" required id="id_first_name" /> </div> </div> <div id="div_id_last_name" class="form-group"> <label for="id_last_name" class="requiredField"> Last name<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="last_name" value="{{p_form.last_name}}" maxlength="20" class="textinput textInput form-control" required id="id_last_name" /></div> </div> <div id="div_id_id_no" class="form-group"> <label for="id_id_no" class="requiredField"> ID No.<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="id_no" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_id_no" /></div> </div> <div id="div_id_phone_no" class="form-group"> <label for="id_phone_no" class="requiredField"> Phone No.<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="phone_no" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_phone_no" /></div> </div> <div id="div_id_cgpa" class="form-group"> <label for="id_cgpa" class="requiredField"> CGPA<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="cgpa" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_cgpa" /></div> </div> <div id="div_id_degree" class="form-group"> <label for="id_degree" class="requiredField"> Degree<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="degree" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_degree" /></div> </div> <div id="div_id_stream" class="form-group"> <label for="id_stream" class="requiredField"> Stream<span class="asteriskField">*</span> </label> <div class=""><input type="text" name="stream" value="{{p_form.}}" maxlength="20" class="textinput textInput form-control" required id="id_stream" /></div> </div> I am rendering this page with the view funstion:- def profile(request): if request.method == 'POST': u_form = UserUpdateForm(request.POST, … -
How to properly configure route while using sockets?
I am learning django channels as well as djangochannelsrestframework and I am very new to it. I am following the tutorial. routing.py from django.conf.urls import url from channels.routing import ProtocolTypeRouter,URLRouter from channels.auth import AuthMiddlewareStack from djangochannelsrestframework.consumers import view_as_consumer from api.consumers import LiveContentListView, LiveContentDetailView application = ProtocolTypeRouter({ "websocket" : AuthMiddlewareStack( URLRouter([ url(r'api-live/',view_as_consumer(LiveContentListView)), url(r'api-live/(?P<pk>\w+)/$',view_as_consumer(LiveContentDetailView)), ]) ) }) The server is running fine and channels are also running fine. But when I browse localhost:8000/api-live/, it only searches for urls.py path. Please help me to properly configure the route here -
in python venv vscode: ModuleNotFoundError: No module named 'tastypie'
I have already tried searching your questions. This site won't allow me to paste in the command prompt message. -
Join 2 class in one query with common Foreign key
My model: class Doc(models.Model): numdoc = models.CharField(max_length=14) class DocQT(models.Model): doc = models.ForeignKey(Doc, models.DO_NOTHING, related_name='doc_qt') quantity = models.DecimalField(max_length=14) class DocDate(models.Model): doc = models.ForeignKey(Doc, models.DO_NOTHING, related_name='doc_date') date_cons = models.DateTimeField(defalt=date.today()) Now, i need to order by date_cons and get quantity using che common foreign key to join the classes. Something like: myquery= [...] for member in myquery: i need to render: member.quantity and member.date_cons -
Edit specific user in Django using UserChangeForm
I'm trying to edit an specific User in Django, but I couldn't create my own form, since Django doesn't let you edit it after it's been created. So, I'm using 'UserChangeForm', but I can't get the information from the specific user, only the one that is logged in. How can I fix it? forms.py class EditarUsuarioForm(UserChangeForm): class Meta: model = User fields = ( 'first_name', 'last_name', 'email', ) first_name = forms.CharField(label='Nome', max_length=20, widget=forms.TextInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: José", 'name': 'nome' } )) last_name = forms.CharField(label='Sobrenome', max_length=150, widget=forms.TextInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: da Silva", 'name': 'sobrenome' } )) email = forms.EmailField(label='Email', max_length=200, widget=forms.EmailInput( attrs={ 'class': 'form-control', 'maxlength': '200', 'placeholder': "Ex.: jose@unemat.br", 'name': 'email' } )) views.py def editar(request, username): if request.method == 'GET': usuario = User(username=username) form = EditarUsuarioForm(instance=usuario) context = { 'form': form, 'user': usuario, } return render(request, 'usuarios/editar.html', context) if request.method == 'POST': usuario = User(username=username) form = EditarUsuarioForm(request.POST, instance=usuario) if form.is_valid(): form.save() return redirect('lista') else: print(form.errors) context = { 'form': form, } return render(request, 'usuarios/editar.html', context) edit.html <main role="main"> <div class="container mt-4"> <form action="" class="form-group" method="POST">{% csrf_token %} <div class="form-group"> {{form.first_name.label_tag}} {{form.first_name}} </div> <div class="form-group"> {{form.last_name.label_tag}} {{form.last_name}} </div> <div class="form-group"> {{ form.email.label_tag … -
NoReverseMatch at / Reverse for 'view_profile_with_pk' with keyword arguments
this error is killing me please help I sat on in like for 3 hours and I couldn't even know why is the error happening I will give all the information needed, btw I am new to Django so please explain if you can Thank You, Error: NoReverseMatch at / Reverse for 'view_profile_with_pk' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['account\/profile\/\(P(?P[^/]+)\\d\+\)\/$'] My URLs .py from django.urls import path, include from . import views from django.contrib.auth.views import (PasswordResetView , PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView) app_name= 'accounts' urlpatterns = [ path('signup/', views.register, name='signup'), path('login/', views.login, name='login'), path('logout', views.logout, name='logout'), path('profile/', views.view_profile, name='view_profile'), path('profile/(P<pk>\d+)/', views.view_profile, name='view_profile_with_pk'), path('profile/edit/', views.edit_profile, name='edit_profile'), path('change-password/', views.change_password, name='change_password'), path('password_reset/', PasswordResetView.as_view(), name='password_reset'), path('password_reset/done/', PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/',PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] My views.py from django.shortcuts import render, redirect from django.contrib.auth.models import User from django.contrib import auth from django.contrib.auth.decorators import login_required from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.urls import reverse from accounts.forms import ( RegistrationForm, EditProfileForm, UserProfileForm ) from django.contrib.auth.models import User from django.contrib.auth.forms import UserChangeForm, PasswordChangeForm from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required def register(request): if request.method =='POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('accounts:home') else: form = RegistrationForm() args = {'form': form} … -
Django rest framework limit the number of image uploads
I would like to restrict the number of images a user can upload in Django Rest Framework when he creates a product. Let's say I want to restrict him to upload only 5 images per product. What is the best way to do this? models.py class Product(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=100) image = models.ForeignKey(Image, on_delete=models.CASCADE) class Image(models.Model): image = models.ImageField(upload_to='product_images') serializers.py class ProductSerializer(serializers.ModelSerializer): class Meta: model = models.Product fields = ('__all__') -
AttributeError: 'postComments' object has no attribute 'model
I have made a new model postComments for my blogging website and now I am facing the above issue: models.py: from django.db import models from django.contrib.auth.models import User from django.utils.timezone import now # Create your models here. class post(models.Model): SrNo = models.AutoField(primary_key=True) title = models.CharField(max_length=50) content = models.TextField() author = models.CharField(max_length=50) slug = models.SlugField(max_length=200) timeStamp = models.DateTimeField(blank=True) def __str__(self): return self.title + " by " + self.author class postComments(models.Model): sno = models.AutoField(primary_key=True) comment = models.TextField() user = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(post, on_delete=models.CASCADE) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(default=now) after writing the above '''postComments``` model the log window is showing me this error: error log Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = checks.run_checks( File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\checks.py", line 54, in check_admin_app errors.extend(site.check(app_configs)) File "C:\Users\jayant nigam\projects\practise\lib\site-packages\django\contrib\admin\sites.py", line 84, in check if modeladmin.model._meta.app_config in app_configs: AttributeError: 'postComments' object has no attribute 'model' before adding this new model, … -
Removing collected static files
I ran collectstatic a few weeks back and I would like to remove most (99.5%) of the collected files so that I do not have to store them when deploying to production. I tried collectstatic --clear but this removed them and then placed the deleted files back afterwards (not sure what the practical point of the command is). Is there a way to erase the collected files? I've been using this page of the Django docs to try and find a solution but haven't had any luck. -
Django sum on an external attribut
I have an issue with database and sum in Django. I have 3 tables: customer, order and orderLine. For a report, I would like to calculate the sum of all line price for every order of a customer. class Customer(models.Model): firstName = models.CharField(max_length=200) lastName = models.CharField(max_length=200) mail = models.EmailField(max_length=100) etc... def get_count_of_orders(self): return self.orders.count() def get_sum_line_prince_of_all_orders(self): ??????????? return (sum_of_all_line_prince_all_orders) class Order(models.Model): orderNum = models.CharField(max_length=200) customer = models.ForeignKey(Customer, related_name="orders") globalAmount = models.DecimalField(max_digits=20, decimal_places=4) ... class OrderLine(models.Model): item = models.ForeignKey(Item, related_name="ordersLine") linePrice = models.DecimalField(max_digits=20, decimal_places=4) ... I don't know what to set in get_sum_of_orders to get the right result. I've trayed different things like annotate or aggregate. But without success at the moment. I didn't understand this process at the moment. Could you help me? -
Django Query month wise with last 6 month
I am trying to query and the group is the Order of the last 6 months. and this is my models: class Order(models.Model): created_on = models.DateTimeField(_("Created On"), auto_now_add=True) and this is my method to parse month: from django.db.models import Func class Month(Func): """ Method to extract month """ function = 'EXTRACT' template = '%(function)s(MONTH from %(expressions)s)' output_field = models.IntegerField() And this is my query: current_date = date.today() months_ago = 6 six_month_previous_date = current_date - timedelta(days=(months_ago * 365 / 12)) order = Order.objects.filter( created_on__gte=six_month_previous_date, ).annotate( month=Month('created_on') ).values( 'month' ).annotate( count=Count('id') ).values( 'month', 'count' ).order_by( 'month' ) In my database order table, there is only on entry: So it is returning [{'month': 10, 'count': 1}] But i dont want like this, i want like these of last 6 month, if in one month, there is no sales, it should return the count: 0 Like thise bellow: [ {'month': 10, 'count': 1}, {'month': 9, 'count': 0} {'month': 8, 'count': 0} {'month': 7, 'count': 0} {'month': 6, 'count': 0} {'month': 5, 'count': 0} ] -
I cannot create category and sub-categories list in home page,django
I can create a category page with sub-categories in a new template but i cannot list all my sub-categories in home page. All i need is a logic to work in home page. Here is my models.py class Category(MPTTModel): name = models.CharField(max_length=100,unique=True) parent = TreeForeignKey('self',null=True,blank=True,related_name='children',db_index=True,on_delete = models.CASCADE) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name def get_absolute_url(self): return reverse('product:product-category',args=[self.slug]) class Product(models.Model): category = TreeForeignKey(Category,null=True,blank=True,on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = models.SlugField(max_length=200,unique=True) def get_absolute_url(self): return reverse('product:product-detail',kwargs={ 'slug':self.slug, }) here is my views.py def product_list(request,category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category,slug=category_slug) products = products.filter(category=category) return render( request,'product/home.html',{ 'category':category, 'categories':categories, 'products':products } ) def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') parent = None root = Category.objects.all() for slug in category_slug[:-1]: parent = root.get(parent=parent, slug = slug) try: instance = Category.objects.get(parent=parent,slug=category_slug[-1]) except: instance = get_object_or_404(Product, slug = category_slug[-1]) return render(request, 'product/product.html', {'instance':instance}) else: return render(request, 'product/categories.html', {'instance':instance}) I used this logic in my template but it doesn't work. So any help to display the categories … -
Is there a way I could specify server timezone in Django database settings
Hello I would like to know if someone could help me. I have a problem with Django's TIMEZONE configuration in the settings.py file. The problem is the following. The timezone is set to TIME_ZONE = 'America/New_York' USE_TZ = True I have an online MySQL database set-up, which the details to are here database settings and when I try to run run the server, the following error appears django.db.utils.OperationalError: (2026, 'SSL connection error: unknown error number') Now, I have downloaded the plugin database browser AND MySQL Workbench after entering the details of the connection was able to get connected to the database in both cases. In the Data Sources and Drivers I could connect because it allowed me to edit serverTimezone as seen here: serverTimezone So now I'm having troubles and I don't know what to do. Sorry I just have no idea how to load this, I've also run the SELECT @@system_time_zone; inside the MySQL Workbench and the timezone I get is EDT. I have put TIME_ZONE parameter inside of the database settings in settings.py to TIME_ZONE = 'America/New_York', after which the front page can be loaded IF USE_TZ = False, but if I try to access any other sites, … -
Django parent creation with children collection
I'm having an issue passing several children OrderItem, a collection, when creating an Order parent instance. Although there a one to many relationship between Order and OrderItem models, I can't pass a list of children to the parent. What am I missing or doing wrong? Thanks for your responses! Here is an example of the request I try to make on this endpoint /api/orders/: { "bar_id": 2, "order_items":[ { "ref_id": 3 }, { "ref_id": 2 }, { "ref_id": 1 } ] } The error is as: { "order_items": { "non_field_errors": [ "Invalid data. Expected a dictionary, but got list." ] } } Here is my parent OrderModel: from django.db import models from .model_bar import * class Order(models.Model): bar_id = models.ForeignKey(Bar, null=True, on_delete=models.CASCADE, related_name='orders') Here is my child OrderItemModel: from django.db import models from .model_order import * from .model_reference import * class OrderItem(models.Model): order_id = models.ForeignKey(Order, null=True, on_delete=models.CASCADE, related_name='order_items') ref_id = models.ForeignKey(Reference, null=True, on_delete=models.CASCADE, related_name='order_items') -
Django The API results do not link to the post
I'm a beginner and I'm trying to understand why when I receive the results of my API, that I add to my aliments field (linked by the ManyToManyField to the ListAliments model), are not directly linked to my post. The API works and the response too: data { concepts { name: "salad" ... } ... I use as agreed create and add if the result of the API is not already created in the ListAliments model. If one of the results is already created I just want to add it (link it to the post). The problem is that it doesn't work. My first step was to start with: self.aliments.create(name=concept.name) class ListAliments(models.Model): name = models.CharField(max_length=40, unique=True) slug = models.SlugField(editable=False) status = models.IntegerField(choices=STATUS, default=1) def save(self, *args,**kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.name)) super(ListAliments, self).save(*args, **kwargs) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length=190) url_image = models.URLField(max_length=200, default=None) aliments = models.ManyToManyField('ListAliments',blank=True, related_name='listaliments_post') ... def save(self, *args, **kwargs): if not self.slug: self.slug = unique_slugify(self, slugify(self.title)) ... if self.url_image: request = ... response = ... if response: names = [] for concept in response.outputs[0].data.concepts: current_aliments = ListAliments.objects.filter(name=concept.name) if current_aliments.count()<1: create_aliments = self.aliments.create(name=concept.name) self.aliments.add(create_aliments) else: existed_aliments = ListAliments.objects.get(name=concept.name) self.aliments.add(existed_aliments) super().save(*args, **kwargs) -
Two different on.change() events in JQuery and one ajax call
I have two built-in python dropdown and I am trying to link them together using Ajax calls. You can see the relevant code in the html: <script> $("#id_city").change(function () { // event on the city dropdown change. var cityId = $(this).val(); $.ajax({ // initialize an AJAX request url: '{% url "city_autocomplete" %}', // set the url of the request (= localhost:5000/app/ajax/city-autocomplete/) data: { 'cityId': cityId // add the city id to the GET parameters }, // dataType: 'json', success: function (data) { $('#preview').html(data); // replace the html response with the <div> content } }); event.preventDefault(); }); </script> <script> $("#id_tag").change(function () { var tagId = $(this).val(); $.ajax({ url: '{% url "city_autocomplete" %}', 'tag': tagId }, success: function (data) { $('#preview').html(data); } }); event.preventDefault(); }); </script> Once I select city, cityId takes the value but tagId returns none and vice-versa. I want to know what is the solution in jQuery, to listen to both dorpdown changes at the same time, or let's say how to merge two on.change() together? -
How to register a user with Email instead of username in Django Rest Framework
I've read tons of stack overflow posts about how to register a user with email instead of username but none of them seem to work, so I'm resetting to my defaults. I tried this and this but I still get 'username is required' back from the API when I try to register user. I think the problem might be that I couldn't find a post that's explicit to Django 3 and uses Django Rest Framework. Below are my models, serializers and views. # models class User(AbstractUser): ROLES = ( ('d', 'Doctor'), ('s', 'Secretary'), ('p', 'Patient'), ) role = models.CharField( max_length=1, choices=ROLES, blank=True, default='p', help_text='Role') class Doctor(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) clinic = models.ManyToManyField( Clinic, related_name="doctors", blank=True) appointment_duration = models.IntegerField(default=20, blank=True) # serializer User = get_user_model() class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password', 'role', 'first_name', 'last_name', 'email', 'phone') extra_kwargs = {'password': {'write_only': True, 'required': True} # viewset class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer permission_classes = (AllowAny,) So, how could I register with email instead of username? -
how can i access django with apache? apache showing default page on django
i am getting the default page of apache2 when i try to access the django on my lan ip address via apache server. i am also running django python manage.py runsever command and try to access with 192.168.10.11. but it still showing the default page of apache. how can i access django with apache? <VirtualHost *:80> ServerName localhost DocumentRoot /home/five/NewsDesk/server WSGIScriptAlias /NewsDesk /home/five/NewsDesk/server/server/wsgi.py # adjust the following line to match your Python path WSGIDaemonProcess 192.168.10.11 processes=2 threads=15 display-name=%{GROUP} python-home=/home/five/NewsDesk/env/lib/python3.8 WSGIProcessGroup 192.168.10.11 <directory /home/five/NewsDesk/server> <Files wsgi.py> Allow from all Require all granted </Files> AllowOverride all Require all granted Options FollowSymlinks </directory> Alias /static/ /home/five/NewsDesk/server/staticfiles/ <Directory /home/five/NewsDesk/server/staticfiles> Require all granted </Directory> </VirtualHost> apache2ctl -S $apache2ctl -S VirtualHost configuration: *:80 is a NameVirtualHost default server localhost (/etc/apache2/sites-enabled/000-default.conf:1) port 80 namevhost localhost (/etc/apache2/sites-enabled/000-default.conf:1) port 80 namevhost localhost (/etc/apache2/sites-enabled/newsdesk.conf:1) ServerRoot: "/etc/apache2" Main DocumentRoot: "/var/www/html" Main ErrorLog: "/var/log/apache2/error.log" Mutex default: dir="/var/run/apache2/" mechanism=default Mutex watchdog-callback: using_defaults PidFile: "/var/run/apache2/apache2.pid" Define: DUMP_VHOSTS Define: DUMP_RUN_CFG User: name="www-data" id=33 not_used Group: name="www-data" id=33 not_used -
django image not loading in many-to-many relationship
I have one model for the date and another model for images and a third many-to-many model that connects images to dates but in the template, I made a for loop but no image is showing up and in the developer console, I see <img class="img-fluid img-thumbnail" src="" alt=""> my models.py class MyDate(models.Model): english_date = models.DateField(auto_now=False) hebrew_date = models.CharField(max_length=20,unique=True) def get_absolute_url(self ): return reverse('date_detail',kwargs={'pk':self.pk}) def __str__(self): return self.hebrew_date # images class Images(models.Model): image = models.ImageField(unique=False,upload_to='images/') def get_absolute_url(self): return reverse("image_detail",kwargs={'pk':self.pk}) #connect days and images together class DayImage(models.Model): date = models.ForeignKey('luach.MyDate',related_name='day',on_delete=models.CASCADE) image = models.ManyToManyField('luach.images',related_name='images') def __str__(self): return self.pk my views.py def my_date_detail(request,pk): mydate = MyDate.objects.get(pk=pk) dayimage = DayImage.objects.filter(date=mydate) context = {'mydate':mydate,'dayimage':dayimage} return render(request, 'luach/mydate_detail.html',context) my urls.py urlpatterns = [ path('admin/', admin.site.urls), path('date/<int:pk>',views.MyDateDetailView.as_view(),name='date_detail'), path('date/<int:pk>/add_image/',views.create_day_image_view,name='add_image') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and I do have a media URL setup MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my mydate_detail.html <div class="jumbotron"> <h2>Images</h2> {% for p in dayimage %} <div class="col-lg-3 col-md-4 col-6"> <div class="d-block mb-4 h-100"> <img class="img-fluid img-thumbnail" src="{{ p.image.url }}" alt="hi"> </div> </div> {% empty %} <h3>There is no images linked to this day</h3> {% endfor %} <a class="btn btn-outline-warning btn-sm" href="{% url 'add_image' pk=mydate.pk %}">add image</a> </div> -
How to speed up backend in electron framework?
I am creating a small project and I used electron for the front end and python for back end. The python is taking voice input and responding accordingly at back end but its too slow when integrated with electron. Is there any way to speed up the process by using Django or flask?