Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can i loop around a javascript code using Django for loops
Example of what i wanted to the javascript accomplish: torsos=document.querySelectorAll("#torsolavender, #torsogreen, #torsoblue, #torsoviolet"); how i tried to do the above: torsos=document.querySelectorAll("{% for color in colors %}#torso{{color.name}},{% endfor%}") -
django rest framework extra actions for routing to specific financial statement of data set
I have a viewset for stocks by ticker/company which corresponds to the urls. localhost:8000/stocks/AAPL works for example. what I want is an extra action to route to localhost:8000/stocks/AAPL/income_statement, but I cant figure out how to create the extra action using the detail_route decorator below. I've commented in the code base where I am having troubles views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer # !!! this is what I don't know what to do !!!! @detail_route(methods=["get"]) def get_is(self, request, statement): stock = self.get_object() serializer = IncomeStatementSerializer(data=request.data) if serializer.is_valid(): return Response(serializer.data) urls.py router = DefaultRouter() router.register(r"stocks", views.StockViewSet) urlpatterns = router.urls -
Creating additional tables to support custom Django model
I have 2 abstract models: class AdditionalModel(models.Model): x = models.CharField(max_length=20) class Meta: abstract = True class BaseModel(models.Model): y = models.CharField(max_length=20) class Meta: abstract = True Now I have my models.py: class MainModel(BaseModel): z = models.CharField(max_length=20) On migration, I need to create two tables, one for MainModel which extends the BaseModel and another for "mainmodel_additional_model" which gets additionally created for MainModel. I was trying to achieve this using save() method. Not quite getting there, also what are the standard ways to do this. -
Render django formset forms inside another loop (Other item loop) inside table)
I have a model formset for entering quantity field for sale invoice model. I pass the sale invoice items to django template and use a loop to render them in a table. What I want is to render the individual forms in a formset along with the items. My Template looks like this <tbody style="background-color: #ffffff;"> {{formset.management_form}} {% for item in line_item %} <tr> <td>{{item.line_number}}</td> <td>{{item.item.item_description}}</td> <td>{{item.item.item_uom}}</td> <td>{{item.sale_price}}</td> <td>{{item.order_quantity}}</td> <td>{{item.form.bill_quantity}}{{item.form.id_form}}</td> <td>"**Here I want to render a form field from the formset**"</td> <td><input disabled type="text" name="" value=""></td> <td>{{item.tax.tax_value}}</td> <td><input disabled type="text" name="" value=""></td> <td><input disabled type="text" name="" value=""></td> </tr> {% endfor %} </tbody> Is it possible to render forms in a formset inside another loop? One way of doing this is to append the individual form to the line_item list, but it seems to me a non-standard way of doing this, and I believe there must be some standard way of doing this. -
How to calculate the size of Django model object?
I explored and found sys.getsizeof() to get the size of an object, but it is giving the same size for below objects: import sys >>> obj = MyModel.objects.first() >>> sys.getsizeof(obj) 64 >>> obj.description = 'abcdefghi....xyz' # entered a very long string here >>> sys.getsizeof(obj) 64 No matter which model objects I use, the size is always 64, even if the object contains too many fields. What am I doing wrong, and how to get the actual size of an object in bytes? -
can we pass two args in url - django?
this is my models.py file for Category and Product ''' models.py from django.db import models # Create your models here. class Category(models.Model): objects = models.Manager() name = models.CharField(max_length=250, null=False) slug = models.CharField(max_length=250, null=False) desc = models.TextField(blank=True) class Meta: verbose_name = 'category' verbose_name_plural = 'categories' def __str__(self): return self.name class Product(models.Model): objects = models.Manager() name = models.CharField(max_length=250, null=False) slug = models.CharField(max_length=250, null=False) desc = models.TextField(blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) class Meta: verbose_name = 'product' verbose_name_plural = 'products' def __str__(self): return self.name ''' This is the url file where i am stucked urls.py from django.urls import path, include from website import views urlpatterns = [ path('', views.home, name='home'), path('categorys/<slug:category_slug>/', views.category_product, name='category_product'), path('category/<slug:category_slug>/<slug:product_slug>', views.product, name='product_slug'), ] ''' is it possible to pass to arguments in url from the html so that we can pass that to the product function. views.py from django.shortcuts import render, get_object_or_404 from website.models import Product, Category def home(request): allcategories = Category.objects.all() return render(request, 'website/home.html', {'allcategories':allcategories}) def product(request, category_slug, product_slug): product = Product.objects.get(category__slug=category_slug, slug=product_slug) return render(request, 'website/display_product.html', {'product':product}) def category_product(request, category_slug): current_category = get_object_or_404(Category, slug=category_slug) product = Product.objects.filter(category=current_category) return render(request, 'website/category_product.html',{'current_category':current_category, 'product':product}) ''' this is the html page from where i am trying to pass the two args to the … -
debug_toolbar module is not persisted after docker down / docker up
I started a new project using Django. This project is build using Docker with few containers and poetry to install all dependencies. When I first run docker-compose up -d, everything is installed correctly. Actually, this problem is not related with Docker I suppose. After I run that command, I'm running docker-compose exec python make -f automation/local/Makefile which has this content Makefile .PHONY: all all: install-deps run-migrations build-static-files create-superuser .PHONY: build-static-files build-static-files: python manage.py collectstatic --noinput .PHONY: create-superuser create-superuser: python manage.py createsuperuser --noinput --user=${DJANGO_SUPERUSER_USERNAME} --email=${DJANGO_SUPERUSER_USERNAME}@zitec.com .PHONY: install-deps install-deps: vendor vendor: pyproject.toml $(wildcard poetry.lock) poetry install --no-interaction --no-root .PHONY: run-migrations run-migrations: python manage.py migrate --noinput pyproject.toml [tool.poetry] name = "some-random-application-name" version = "0.1.0" description = "" authors = ["xxx <xxx@xxx.com>"] [tool.poetry.dependencies] python = ">=3.6" Django = "3.0.8" docusign-esign = "^3.4.0" [tool.poetry.dev-dependencies] pytest = "^3.4" django-debug-toolbar = "^2.2" Debug toolbar is installed by adding those entries under settings.py (MIDDLEWARE / INSTALLED_APP) and even DEBUG_TOOLBAR_CONFIG with next value: SHOW_TOOLBAR_CALLBACK. Let me confirm that EVERYTHING works after fresh docker-compose up -d. The problem occurs after I stop container and start it again using next commands: docker-compose down docker-compose up -d When I try to access the project it says that Module debug_toolbar does not exist!. … -
django.db.utils.IntegrityError: UNIQUE constraint failed: api_user.username
I'm implementing a custom user model in django. Implementing user model and matching username with unique property true resulted in the following error. django.db.utils.IntegrityError: UNIQUE constraint failed: api_user.username I wonder how we can solve this error without removing the unique property from usernames. What should I do? Here is my code. models.py from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin) from django.db import models from django.utils import timezone class UserManager (BaseUserManager) : def create_user (self, username, email, profile, password=None) : if username is None : raise TypeError('Users should have a username') if email is None : raise TypeError('Users should have a email') user = self.model( username=username, email=self.normalize_email(email), profile=profile, ) user.set_password(password) user.save() return user def create_superuser (self, username, email, profile, password=None) : if password is None : raise TypeError('Password should not be none') user = self.create_user( username=username, email=self.normalize_email(email), profile=profile, password=password ) user.is_admin = True user.is_superuser = True user.is_staff = True user.save() return user class User (AbstractBaseUser, PermissionsMixin) : username = models.CharField(max_length=255, unique=True, db_index=True) email = models.CharField(max_length=255, unique=True, db_index=True) profile = models.ImageField(default='media\default_image.jpeg') is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'profile'] objects = UserManager() def __str__ (self) : return self.email -
Email Verification Check
I want to have an email check in my email form field so that if the user's email doesn't end with '@aun.edu.ng' it will through an error message. forms.py class EmployeeRegistrationForm(forms.ModelForm): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') cv = forms.FileField(label='CV') skills_or_trainings = forms.SlugField(label='Skills or Trainings', required=False, widget=forms.Textarea) class Meta: model = Student fields = ['first_name', 'last_name', 'gender', 'level', 'school', 'major', 'cv', 'skills_or_trainings' ] class EmployerRegistrationForm(forms.ModelForm): company_name = forms.CharField(label="Company Name") company_address = forms.CharField(label="Company Address") website = forms.CharField() class Meta: model = Employer fields = ['company_name', 'company_address', 'website'] views.py def student_register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) student_form = EmployeeRegistrationForm(request.POST) if form.is_valid() and student_form.is_valid(): user = form.save(commit=False) user.is_student = True user.save() student = student_form.save(commit=False) student.user = user student.save() return redirect('login') else: form = UserRegistrationForm() student_form = EmployeeRegistrationForm() context = {'form': form, 'student_form': student_form} return render (request, 'accounts/employee/register.html', context) def employer_register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) employer_form = EmployerRegistrationForm(request.POST) if form.is_valid() and employer_form.is_valid(): user = form.save(commit=False) user.is_employer = True user.save() employer = employer_form.save(commit=False) employer.user = user employer.save() return redirect('login') else: form = UserRegistrationForm() employer_form = EmployerRegistrationForm() context = {'form': form, 'employer_form': employer_form} return render (request, 'accounts/employer/register.html', context) Please how do I go about it so that I will … -
How to increase the speed of django filter condition?
I have 2 million data in the database. I tried to filter the foreign data in database. Finally filter data around 30 records only. but it's taking time around 2 to 3 minutes. I need to reduce the time and filter data fastly. How to achieve this scenario. Models.py class Sample1(models.Model): name = models.CharField( max_length=64 ) class Sample2( models.Model): name2 = models.CharField( max_length=64 ) class Sample3(models.Model): name3 = models.CharField( max_length=64 ) class sample4(models.Model): sample1 = models.ForeignKey( Sample1,on_delete=models.CASCADE ) sample2 = models.ForeignKey( Sample2,on_delete=models.CASCADE ) sample3 = models.ForeignKey( Sample3,on_delete=models.CASCADE ) name4 = models.CharField( max_length=64 ) views.py def user(sample1,sample2,): rank = sample4.objects.filter( sample1=sample1, sample2=sample2, sample3=sample3).order_by( 'name' ) return rank user(sample1,sample2,sample3) This my case. In sample4 table i have 1 million data and tried to filter some records using this condition. I got the records. but It's taking show much time. I need to reduce the time and get the filter data fastly. Any one can give sample example code used this scenario -
Django atomic transaction handle unique constraint
I have model class Order(models.Model): order_id = models.CharField(max_length=30, default='', unique = True) amount = models.FloatField() And I have this cycle which saves objects to my database from json and validates for unique field order_id for json_obj in json_data: order = Order(symbol=json_obj['order_id'], amount= json_obj['amnount']) try: order.save() except IntegrityError as exception: if 'UNIQUE constraint failed' in exception.args[0]: print('duplicate order id => skip this') continue Everything works fine, but when I add @transaction.atomic decorator to my function everything breaks. And I get an error: "An error occurred in the current transaction. You can't " django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. What is recommended way of handling such case? -
stl.base.BaseMesh - WARNING by using numpy-stl package
I have a Django application which it's deployed to Amazon Elastic Beanstalk(Python 3.7 running on 64bit Amazon Linux 2/3.0.3). I have to use numpy-stl library for reading .stl files. My class; import stl class STLLoaderClass: def __init__(self, file_path): self.filePath = file_path def read_stl(self): stlMesh = stl.mesh.Mesh.from_file(self.filePath) volume, cog, inertia = stlMesh.get_mass_properties() user_mesh = stlMesh xMin = user_mesh.points[0][stl.Dimension.X] xMax = user_mesh.points[0][stl.Dimension.X] yMin = user_mesh.points[0][stl.Dimension.Y] yMax = user_mesh.points[0][stl.Dimension.Y] zMin = user_mesh.points[0][stl.Dimension.Z] zMax = user_mesh.points[0][stl.Dimension.Z] for p in user_mesh.points: # p contains (x, y, z) xMax = max(p[stl.Dimension.X], xMax) xMin = min(p[stl.Dimension.X], xMin) yMax = max(p[stl.Dimension.Y], yMax) yMin = min(p[stl.Dimension.Y], yMin) zMax = max(p[stl.Dimension.Z], zMax) zMin = min(p[stl.Dimension.Z], zMin) boundary_limits = [xMax - xMin, yMax - yMin, zMax - zMin] boundary_volume= boundary_limits[0] * boundary_limits[1] * boundary_limits[2] rectangleVolume = boundary_volume rectangleRemovedVolume = (((boundary_volume - volume) / boundary_volume)*100.0) return rectangleVolume, rectangleRemovedVolume my function that I called this class: def get_volume_info(uploadedVolume): s3 = boto3.resource('s3', region_name='eu-central-1') bucket = s3.Bucket('bucket') obj = bucket.Object(uploadedVolume) tmp = tempfile.NamedTemporaryFile() with open(tmp.name, 'wb') as f: obj.download_fileobj(f) stl_loader = STLLoaderClass(tmp.name) rectangleVolume, rectangleRemovedVolume = stl_loader.read_stl() return rectangleVolume, rectangleRemovedVolume and my view; def uploadFile(request): if request.method == 'POST': file = request.FILES.get('img') filename = file.name key = 'media/' + filename s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('bucket') … -
can't able to extends template django
i want to extend the template movie_detail.html to post_detail.html but it don't show the extended template in it i have {% block det %} which i want to extend movie_detail.html {% extends "blog/post_list.html" %} {% block det %} <div class="header"> <h2>Blog Name</h2> </div> <div class="row"> <div class="leftcolumn"> <div class="card"> <h2>TITLE HEADING</h2> <h5>Title description, Dec 7, 2017</h5> <div class="fakeimg" style="height:200px;">Image</div> <p>Some text..</p> <p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p> </div> <div class="card"> <h2>TITLE HEADING</h2> <h5>Title description, Sep 2, 2017</h5> <div class="fakeimg" style="height:200px;">Image</div> <p>Some text..</p> <p>Sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco.</p> </div> </div> <div class="rightcolumn"> <div class="card"> <h2>About Me</h2> <div class="fakeimg" style="height:100px;">Image</div> <p>Some text about me in culpa qui officia deserunt mollit anim..</p> </div> <div class="card"> <h3>Popular Post</h3> <div class="fakeimg">Image</div><br> <div class="fakeimg">Image</div><br> <div class="fakeimg">Image</div> </div> <div class="card"> <h3>Follow Me</h3> <p>Some text..</p> </div> </div> </div> {% endblock %} post_list.html i want to extend that {% block det %}in … -
How to set jwt token for functional testing, using factory_boy and django-webtest?
import factory from django_webtest import WebTest from rest_framework_jwt.utils import jwt_encode_handler from api.models import User, Organisation class OrganisationFactory(factory.Factory): class Meta: model = Organisation id = factory.sequence(lambda n: n) name = "test org ltd" status = "verified" billing_address = "united kingdom" industry = "cybersecurity" website = "https://factoryboy.com" class UserFactory(factory.Factory): class Meta: model = User id = factory.sequence(lambda n: n) full_name = "john smith" email = factory.LazyAttribute(lambda obj: "{}@example.com".format(''.join(obj.full_name.split(' ')))) password = "test@2020" org_website = "https://factoryboy.com" role = "ADMIN" org = factory.SubFactory(OrganisationFactory) class UserApiTest(WebTest): def setUp(self): self.user = UserFactory() def test_user_orgs(self): response = self.app.get('/api/v1/user/orgs/', user=self.user) self.assertEqual(response.status, '200 OK') This is my code. I am using rest_auth for authorisation, I want to write functional tests using factory_boy and django-webtest. I have created the user using factory boy and wrote a simple get test case which returns me webtest.app.AppError: Bad response: 401 Unauthorized (not 200 OK or 3xx redirect for http://testserver/api/v1/user/orgs/) b'{"detail":"Authentication credentials were not provided."}' I am unable to figure out how my token will be set for authorization. My settings have, Authentication class set for jsonwebtoken. Can someone please help here, have been looking for solution since long time, might be trivial but unable to figure out the fix. -
How to show code blocks for programming snippets in Django Summernote?
I am using Django Summernote on my website. This is how the editor looks. Below you can find the django settings for my Summernote editor. SUMMERNOTE_CONFIG = { # Or, you can set it as False to use SummernoteInplaceWidget by default - no iframe mode # In this case, you have to load Bootstrap/jQuery stuff by manually. # Use this when you're already using Bootstraip/jQuery based themes. 'iframe': False, # You can put custom Summernote settings 'summernote': { # As an example, using Summernote Air-mode 'airMode': False, # Change editor size 'width': '100%', 'height': '480', 'toolbar': [ ['style', ['style']], ['font', ['bold', 'underline', 'clear']], ['fontname', ['fontname']], ['color', ['color']], ['para', ['ul', 'ol', 'paragraph']], ['table', ['table']], ['insert', ['link', 'picture', 'video']], ['view', ['fullscreen', 'codeview', 'help']], ], 'codemirror': { 'mode': 'htmlmixed', 'lineNumbers': 'true', # You have to include theme file in 'css' or 'css_for_inplace' before using it. 'theme': 'monokai', }, } } But sadly, it doesn't have the option for a Code block to show programming snippets. What am I doing wrong here? -
Run django application on registered devices only [closed]
My django application uses facial detection so as to identify the user. I will use this application on some systems(RaspberryPi with camera/Tablet/Custom devices with screen etc.) I don't want anyone with the link to access the application, hence I need it to be only accessed by the devices I have the details about, or devices that can be authenticated by me while going on the link. Any help will be appreciated!!!! -
Django API call to endpoint
I'm trying to send an API call with order_id and tracking_code values In my model to an endpoint when the order status is updated to shipped. However I'm getting this error "HTTPConnectionPool(host='165.225.124.85', port=10605): Max retries exceeded with url:http://doxxxn.net/api/manufacturing/tracking-code-callback?order_id=TT12349 (Caused by ProxyError('Cannot connect to proxy.', RemoteDisconnected('Remote end closed connection without response')))" def update_order(request, pk): order = Order.objects.filter(id=pk).first() orm = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': if form.is_valid(): if order.status=='Shipped': URL = "http://domxxx.org/api/manufacturing/tracking-code-callback" order_id = order.order_id tracking_code = order.tracking_code PARAMS = {'order_id':order_id, 'tracking_code':tracking_code } r= requests.post(url=URL,params=PARAMS) data = r.json() form.save() return redirect('/orderlist/') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) -
How do I password protect all but one URL in Django without authentication?
Is there a tool that allows me to password protect all but one URL in Django without requiring authentication? -
Django multiple admin sites with different templates
In the Django docs there is a section detailing how to create multiple admin sites. https://docs.djangoproject.com/en/3.1/ref/contrib/admin/#multiple-admin-sites-in-the-same-urlconf Does anyone know if it is possible to have different templates for each site? So for example I would like to create a customer facing admin site with their branding and another admin site with the standard django templates. -
django RecursionError : maximum recursion depth exceeded while calling a Python object
I have implemented membership by building a custom user model in the django rest framework. By the way, the following error occurs when you code and run the server. RecursionError : maximum recursion depth exceeded while calling a Python object Here is full traceback Traceback (most recent call last): File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "D:\school\대회 및 프로젝트\CoCo\api\views.py", line 16, in post serializer.save() File "D:\school\대회 및 프로젝트\CoCo\venv\lib\site-packages\rest_framework\serializers.py", line 212, in save self.instance = self.create(validated_data) File "D:\school\대회 및 프로젝트\CoCo\api\serializers.py", line 61, in create return User.objects.create_user(**validate_data) File "D:\school\대회 및 프로젝트\CoCo\api\models.py", line 29, in create_user user = self.create_user( File "D:\school\대회 및 프로젝트\CoCo\api\models.py", line 29, in create_user … -
Get count of tags usages using django-taggit
I have following model structure class TrackingData(models.Model) item = models.ForeignKey(Item) class Item(models.Model) user = models.ForeignKey(User) name = models.CharField() tags = TaggableManager() I have the following objects inside the Item Item Name Tags ------------------------------------------- Item 1 static, item, anuj Item 2 static, anuj Item 3 item Item 4 dynamic I want to get the count of TrackingData based on the selected tag static, anuj q = TrackingData.objects.filter(item__user=request.user) Expected output [ ['static', 2], ['anuj', 2 ] I also want the list of all tags added by the user inside the Item so that it can be used to show in autocomplete suggestion. -
Email activated but still user.activated is False in views.py & email verification form (mail.html) is appearing everytime we fill for a new job?
I have registered a user and activated my profile now when I apply for a job in in job_detail.html it takes us to applytojob(request, pk), now the user is activated and not applied so it will go in elif part and request.user.activated is true so it should just send a mail. But in my case apply now, takes a activated user into else part of the elif statement and thus returns a form which again send a verification mail. Everytime user want to apply for a job he has to fill the verification form ???? views.py @login_required def applytojob(request, pk): """ Apply to a job. """ context = {} job = Job.objects.get(pk=pk) context['job'] = job user = request.user # If User is activate and has already applied redirect User to already applied page. if request.user in job.applied_by.all(): # return HttpResponse("You've applied already to Job: %s." % job) return render(request, "applicant_app/applicationdonealready.html",context) # If user is activate and has not applied for the job. elif request.user not in job.applied_by.all(): if request.user.activated: if request.method == 'GET': job.applied_by.add(request.user) n_applications = job.applied_by.count() send_mail("Successfully applied", "application done", "contact.profcess@gmail.com", [str(request.user.mail)], fail_silently=False) return HttpResponse("Successfullly applied") # If User has not applied # If User is not activate Pop … -
Django Admin Every page show all my models
I run my web application on pythonanywhere and main admin page works fine, but others show my models on left side, can't find reason for this. Any idea? -
Displaying contact details using Ajax
I am doing Paying Guest finder website. When I try to click the contact button on my website I am getting all the pg's contact details present in the home page. For example on my home page it has two pg details pg1 and pg2. When I click the pg1 contact button I am getting pg1 and pg2 contact details as alert one after the other. views.py def contact(request): phone= request.GET.get('phone') data={"phone" : "phone"} return JsonResponse(data) home.html <button class="btn btn-primary" id="request-btn">Contact</button> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("#request-btn").click(function(){ $.ajax({ url: "/listings/contact", type: "GET", dataType:"json", success: function(){ alert( task.phone ) } }); }); }); </script> -
How to add a user to group programatically in Django
I have a Django project where each user belongs to just one group, Doctor and Nurse but not both. I showed a form in my front-end to let Admin users add the user profiles, where each user profile is made with First name, Last name, Email, Groups etc. My challenge is when an admin user assigns a user profile to a group from the front-end that user is not added to the group when I check the Django admin i.e when I click on the on user on the Django admin I can't see the user being assigned to the group. The important part of my forms.py is this part from django.contrib.auth.models import Group groups = forms.ModelChoiceField(label='Role', queryset=Group.objects.all(), widget=forms.Select(attrs={'class':'form-control'})) The full form can be seen here from django.contrib.auth.forms import UserCreationForm from django_starter_app.models import User, Post from django.contrib.auth.models import Group class RegisterForm(UserCreationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Username'})) email = forms.CharField(widget=forms.EmailInput(attrs={'class':'form-control', 'placeholder':'Email'})) first_name = forms.CharField(label='Firstname', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Firstname'})) last_name = forms.CharField(label='Lastname', widget=forms.TextInput(attrs={'class':'form-control', 'placeholder':'Lastname'})) groups = forms.ModelChoiceField(label='Role', queryset=Group.objects.all(), widget=forms.Select(attrs={'class':'form-control'})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Password'})) password2 = forms.CharField(label='Confirm Password', widget=forms.PasswordInput(attrs={'class':'form-control', 'placeholder':'Confirm Password'})) class Meta(): model = User fields = ('username', 'email', 'first_name', 'last_name', 'groups', 'password1', 'password2') def save(self, commit=True): user = super().save(commit=False) user.username = self.cleaned_data['username'] …