Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Update model field ( SearchVector ) using signals.py
I am trying to update search vector field using post_save signal. Through "Admin.py", It is working perfectly, but through "Form page" , the searchVector field or any other field is not getting updated. In form page, I have many to many field - "Tag" that I save through "form.save_m2m" method Please review my code and suggest .. https://dpaste.org/ujPi Thanks in advance #models.py class JobPostManager(models.Manager): def search(self, search_text): search_vectors = ( SearchVector( 'job_title', weight='A', config='english' ) ) search_query = SearchQuery( search_text, config='english' ) search_rank = SearchRank(search_vectors, search_query) trigram_similarity = TrigramSimilarity( 'job_title', search_text ) qs = ( self.get_queryset() .filter(search_vector=search_query) .annotate(rank=search_rank + trigram_similarity) .order_by('-rank') ) return qs class JobPost(models.Model): job_title = models.CharField(max_length=100, db_index=True) job_description = models.TextField() tags = TaggableManager() author = models.ForeignKey(User, on_delete=models.CASCADE, db_index=True) company_name = models.CharField(max_length=100,blank=True,null=True, db_index=True) objects = JobPostManager() def __str__(self): return self.job_title def get_absolute_url(self): return reverse('job_post_detail', kwargs={'slug': self.slug, 'pk':self.pk}) #################################################################################### #################################################################################### # views.py class JobPostCreateView(LoginRequiredMixin, CreateView): model = JobPost fields = ['job_title','job_description','tags'] widgets = { 'tags' : forms.TextInput(attrs={'data-role':'tagsinput'}), } def get_form(self): form = super().get_form() form.fields['tags'].widget = forms.TextInput(attrs={'value': 'all'}) return form def form_valid(self, form): print("views - form valid - run ") newpost = form.save(commit=False) form.instance.author = self.request.user form.instance.company_name = self.request.user.company_name print("form---------------------------") print(form.instance.author) print(form.instance.job_title) print(form.instance.company_name) print("form end---------------------------") newpost.save() print('newpost') print('--------------------------------',newpost) print('newpost',newpost.author) print('newpost',newpost.job_title) … -
How to create InMemoryUploadedFile objects proper in django
I,m using a python function to resize user uploaded images in django.I use BytesIO() and InMemoryUploadedFile() classes to convert pillow object to django UplodedFile and save it in the model. here how I instanciate InMemoryUploaded file object from PIL import Image import io import PIL import sys from django.core.files.uploadedfile import InMemoryUploadedFile def image_resize(image,basewidth): img_io = io.BytesIO() #code to resize image percent = (basewidth / float(img.size[0])) hsize = int(float(img.size[0]) * percent) img = img.resize((basewidth, hsize),PIL.Image.ANTIALIAS) img.save(img_io, format="JPEG") new_pic= InMemoryUploadedFile(img_io, 'ImageField', 'profile_pic', 'JPEG', sys.getsizeof(img_io), None) return new_pic but this resize the image and it does not save the file as jpeg it saves the file with type of File but when replace the filename with profile_pic.jpg it saves with the type of jpeg. why this happens -
Retreive last order of each customer
I am creating an API for the shop. There I should return the last order of each customer. Here is the code for my Customer and Order models. class Customer(models.Model): name = models.CharField(max_length=14, null=True) country = models.CharField(max_length=3, null=True) address = models.TextField() phone = models.CharField(max_length=50) class Order(models.Model): date = models.DateField(null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) This is serializers.py class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = ['id', 'name', 'country', 'address', 'phone'] class OrderSerializer(serializers.ModelSerializer): customer = CustomerSerializer() class Meta: model = Order fields = ['id', 'date', 'customer'] I am getting the last order of each customer using Django ORM in the following way @api_view(('GET',)) def customers_last_orders(request): orders = models.Order.objects.all().order_by('customer', '-date').distinct() serializer = serializers.OrderSerializer(orders, many=True) return Response(serializer.data) But I am getting from this view all the orders in descinding order. -
modelformset repeated my fields and fetching value from my db
I am using django 3 and modelformset, But I found a wired thing, that the modelformset is repeating my fields and autofilling the value: models.py `class DemoForm(forms.ModelForm): class Meta: model = Demo fields = ['title','content','type'] #def get_absolute_url(self): # return reversed('index') widgets ={ 'title': forms.TextInput(attrs={'class':'form-control','style':'width:500px;'}), 'content': forms.Textarea(attrs={'class':'form-control'}), 'type': forms.Select(attrs={'class':'form-control','style':'width:300px;'}), } #labels = {'title': 'Demo Name',"content":"Demo details","type":"Demo type"} class HostForm(forms.ModelForm): class Meta: model = Host fields = ['name','ip','os','method'] widgets ={ 'name': forms.TextInput(attrs={'class':'form-control'}), 'ip': forms.TextInput(attrs={'class':'form-control'}), 'os': forms.TextInput(attrs={'class':'form-control'}), 'method': forms.Select(attrs={'class': 'form-control','style':'width:300px;'}) } class CredForm(forms.ModelForm): class Meta: model = Credentials fields = ['login_user','keys','port'] widgets ={ 'login_user': forms.TextInput(attrs={'class':'form-control'}), 'keys': forms.TextInput(attrs={'class':'form-control'}), 'port': forms.TextInput(attrs={'class':'form-c ontrol'}) }` views.py `def cicd(request): u_session = request.session['user'] user = SystemUser.objects.get(username=u_session['name']) form1 = DemoForm() HostFormSet = modelformset_factory( model=Host, form=HostForm, extra=1 ) hostFormSet = HostFormSet() CredFormSet=modelformset_factory( model=Credentials, form=CredForm, extra=1 ) credFormSet=CredFormSet() demo = Demo.objects.all() for form in hostFormSet.forms: print(form) return render(request, "cicd.html", {'user': user,'form1':form1,'hostFormSet':hostFormSet,'credFormSet':credFormSet,'demo':demo})` template ` {% csrf_token %} {{form1.media}} {{form1.as_p}} {{ hostFormSet.as_p }} {{ credFormSet.as_p }}` But the form is rendered like this: Which is not horning the extra value and more strange it is autofilling the fileds value fetched from db automatically: Please help out, it is very strange! Thanks in advance. -
Can't get django-db-geventpool working in Heroku
I'm trying to set up my Django app in Heroku to use DB pooling, but I get an error when deploying the application to Heroku. I was following the guide for installing django-db-geventpool here: https://github.com/jneight/django-db-geventpool but that is not working. My guess is that for some reason Heroku is not loading my gunicorn_config.py file when launching gunicorn, but not sure why? My Procfile: release: python manage.py migrate web: gunicorn app.wsgi -k gevent --worker-connections 100 --timeout 600 --config gunicorn_config.py My gunicorn_config.py: from psycogreen.gevent import patch_psycopg # use this if you use gevent workers def post_fork(server, worker): patch_psycopg() worker.log.info("Made Psycopg2 Green") My settings.py: DATABASES = { 'default': dj_database_url.config(conn_max_age=500) } DATABASES['default'].update( ATOMIC_REQUESTS=False, OPTIONS={ 'MAX_CONNS': 4 } ) Here is the stack trace when deploying to Heroku: remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django_db_geventpool/backends/postgresql_psycopg2/base.py", line 13, in <module> remote: from gevent.lock import Semaphore remote: ModuleNotFoundError: No module named 'gevent' remote: During handling of the above exception, another exception occurred: remote: Traceback (most recent call last): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/db/utils.py", line 115, in load_backend remote: return import_module('%s.base' % backend_name) remote: File "/app/.heroku/python/lib/python3.6/importlib/__init__.py", line 126, in import_module remote: return _bootstrap._gcd_import(name[level:], package, level) remote: File "<frozen importlib._bootstrap>", line 994, … -
Django Rest Framework - Add Data and return it
I am new to Django Rest Framework and trying to create add data upon request and return the data after creating. My URL is path('quiz/<str:classId>/<str:subject>/<str:chapter>', CreateQuiz.as_view()), I want to add a row to Quiz Model using the parameters in the URL and return it. How should I approach this ? I tried adding it in get_queryset method and it runs twice. Any guide to this specific problem ? Please help. -
how to make Qrcode scanner in django
how i can make qrcode scanner in django like this web so i can see the result in text not in image video i already make the views.py like this def camera_feed(request): stream = CameraStream() frames = stream.get_frames() return StreamingHttpResponse(frames, content_type='multipart/x-mixed-replace; boundary=frame') def detect(request): stream = CameraStream() success, frame = stream.camera.read() if success: status = True else: status = False return render(request, 'detect_barcodes/detect.html', context={'cam_status': status}) my camera_stream.py class CameraStream(str): def __init__(self): self.camera = cv2.VideoCapture(0) def get_frames(self): while True: # Capture frame-by-frame success, frame = self.camera.read() if not success: break else: ret, buffer = cv2.imencode('.jpg', frame) color_image = np.asanyarray(frame) if decode(color_image): for barcode in decode(color_image): barcode_data = (barcode.data).decode('utf-8') else: frame = buffer.tobytes() #hasil2 = b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + barcode_frame + b'\r\n\r\n' yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n') this is my urls.py path('camera_feed', views.camera_feed, name='camera_feed'), path('detect_barcodes', views.detect, name='detect_barcodes'), and i use the html like this <img src="{% url 'qrcode' request.path %}" width="120px" height="120px;"> how i can pass the result in html? -
Django razorpay: How to get the order id after payment is complete
As per my understanding. Step1) create Order_id order_amount = 50000 order_currency = 'INR' order_receipt = 'order_rcptid_11' notes = {'Shipping address': 'Bommanahalli, Bangalore'} # OPTIONAL obj = client.order.create(amount=order_amount, currency=order_currency, receipt=order_receipt, notes=notes) then save order in databas order_id = obj['id'] Orders( id=order_id, status="pending", user=user, razorpay_payment_id="", razorpay_order_id="", razorpay_signature="").save() Step2 - Pass the order_id to the checkout page <form action="https://www.example.com/payment/success/" method="POST"> <script src="https://checkout.razorpay.com/v1/checkout.js" data-key="YOUR_KEY_ID" // Enter the Test API Key ID generated from Dashboard → Settings → API Keys data-amount="29935" // Amount is in currency subunits. Hence, 29935 refers to 29935 paise or ₹299.35. data-currency="INR"//You can accept international payments by changing the currency code. Contact our Support Team to enable International for your account data-order_id="order_CgmcjRh9ti2lP7"//Replace with the order_id generated by you in the backend. data-buttontext="Pay with Razorpay" data-name="Acme Corp" data-description="A Wild Sheep Chase is the third novel by Japanese author Haruki Murakami" data-image="https://example.com/your_logo.jpg" data-prefill.name="Gaurav Kumar" data-prefill.email="gaurav.kumar@example.com" data-theme.color="#F37254" ></script> <input type="hidden" custom="Hidden Element" name="hidden"> </form> Step3: Get the reponse on payment completed { "razorpay_payment_id": "pay_29QQoUBi66xm2f", "razorpay_order_id": "order_9A33XWu170gUtm", "razorpay_signature": "9ef4dffbfd84f1318f6739a3ce19f9d85851857ae648f114332d8401e0949a3d" } Now We have to verify this. But here we dont know this response is for which order_id as per this image. Because i have seen someone using the below to retrieve the order Orders.objects.get(order_id = … -
Decrease default checkbox size in django
I am developing a blood bank in django, and when updating the details of receiver in webpage, I have a checkbox called 'show details in receiver list' when rendering that checkbox from {{form.showDetails}} the size of the checkbox is huge and I cannot resize the size of that checkbox. If you have any idea to resize that box please share it. It would help me a lot. I have tried to decrease the size of that division but it did not help. And the code when rendering the checkbox data from the database is below. <div class="col-md-6"> <label for="inputAllergies" class="form-label">Show details in receiver list:</label> <div class="form-input" style="background-color:red; height: 20px;"> {{ form.showDetails}} </div> </div> -
Django sessions updated at django channel consumers
I am trying to update a certain Django request session value in my Django channel consumer. from my understanding from channels documentation, it’s the same session object and my session is updated correctly when I change its value in the consumer. however, when I reset my session value on the view side the value remains unchanged at the consumer session object. I could be missing something very simple. or my understanding of how this works is faulty. here is the snippet where I update at the consumers.py: self.scope['session']['unr_msg'] = f"{int(self.scope['session']['unr_msg']) + 1}" self.scope['session'].save() and at views.py : request.session['unr_msg'] = 0; request.session.modified = True I appreciate any help on this Best, -
NPM packages with Django CookieCutter
I am trying to setup my packages with NPM (instead of using Bower) with Django Cookiecutter. it is a fresh install of Cookiecutter. I can not get the packages to work. there is noting in my staticfiles. I am using gulp and it works fine. no issues when i run 'npm run dev' the packages show up as dependencies in the package.json. so how can i get the NPM packages to work as static files like: <script src="{% static 'jquery/dist/jquery.js' %}"></script> Thank you. from package.json "dependencies": { "foundation-sites": "^6.6.3", "jquery": "^3.6.0", "motion-ui": "^2.0.3", "what-input": "^5.2.10", "zingchart": "^2.9.3" }, "devDependencies": { "autoprefixer": "^9.4.7", "browser-sync": "^2.14.0", "cssnano": "^4.1.10", "gulp": "^4.0.0", "gulp-imagemin": "^5.0.3", "gulp-plumber": "^1.2.1", "gulp-postcss": "^8.0.0", "gulp-rename": "^1.2.2", "gulp-sass": "^4.0.2", "gulp-uglify-es": "^1.0.4", "pixrem": "^5.0.0" }, here is how cookiecutter sets up the gulpfile.js which is working fine when i run 'npm run dev. //////////////////////////////// // Setup //////////////////////////////// // Gulp and package const { src, dest, parallel, series, watch } = require('gulp') const pjson = require('./package.json') // Plugins const autoprefixer = require('autoprefixer') const browserSync = require('browser-sync').create() const cssnano = require ('cssnano') const imagemin = require('gulp-imagemin') const pixrem = require('pixrem') const plumber = require('gulp-plumber') const postcss = require('gulp-postcss') const reload = browserSync.reload const rename … -
<QuerySet Tags passing Through
So currently learning Danjo and have a problem I can't seem to get my head around. I have a model called eventlists which holds events (future and past), there is a separate table that holds event prices (because events have variable prices based on when you book). I have managed to join this data and pull it though to my template, all the fields from the eventslist table render correctly but the price field still comes through as: <QuerySet [Decimal('50.00')]>, the data itself is correct. Below is the view that is being executed, but I can for the life of me see this issue: def events_list_view(request): future_events = eventslist.objects.filter(eventStart__gt=datetime.now()).order_by('eventStart').prefetch_related("eventProductsList") past_events = eventslist.objects.filter(eventStart__lt=datetime.now()).order_by('eventStart').prefetch_related("eventProductsList") for future_event in future_events: currentEventActiveProduct = eventProducts.objects.filter(parentEvent=future_event.id, isActive=True) future_event.currentPrice = currentEventActiveProduct.values_list("productPrice", flat=True) return render(request, "events/eventlist.html",{'future_events':future_events, 'past_events':past_events,}) I'm sure its something super obvious that's just my lack of knowledge. -
Django Summernote Shows Blank on pythonanywhere but works fine locally
from django_summernote.widgets import SummernoteWidget # creating a form class PostForm(forms.ModelForm): content = forms.CharField(widget=SummernoteWidget()) # create meta class class Meta: # specify model to be used model = Post # specify fields to be used fields = [ "title", "slug", "content", "status", "youtubeVideo", "category", "image", ] create_post Template: {% load crispy_forms_tags %} <!-- Security token --> {% csrf_token %} <!-- Using the formset --> {{ form | crispy}} <input type="submit" value="Submit" class="btn btn-danger"> <a href="/posts/posts_manager" class="btn btn-info">Cancel </a> </form> works fine locally but not on server. -
Django - Two Factor Authentication Custom Login
After a quick search and reading documentation I implemented Django - Two Factor Authentication in one of my Django project [Reference Link]. It works great I am using Google Authenticator for token based login. The problem arises when I want to extend login methodology of the library. I want to enforce my every user to use 2-Factor-Auth as compulsion. I am not using any signup measures so there has to be a check at the time of Login for a user. The problem is to design a custom login mechanism but I am unable to incorporate this library with the custom login. PS: I have a custom user model and currently I am using default Login that came with Django Two Factor Authentication. I did not though the code was necessary so I did not posted it but I can share it if needed. -
Strategy for handling recursive template display in Django
I'm rewriting a family tree app in Django that I previously wrote in Laravel. There's an 'outline view' page where I start with the 'original families' at the top of the tree, and show an outline of their children, their children's families/kids, those kids' families/kids, etc. First I've generated a big nested list with all the info (in the controller for laravel, and in views.py in my Django rewrite). Then I give that list to a couple of views to display the lists for each original family. (Code included below) Testing the logic a couple levels at a time it works, but when I let it call recursively and load my outline page, it gives me a recursion error: maximum recursion depth exceeded while calling a Python object. Reading around, it sounds like python has a known limitation that it doesn't handle tail recursion, and I saw some posts saying that showing recursive views isn't good practice in Django. Do I need to do something very different (maybe generate the html in advance so I can pull it up statically, and just update when I add new records)? Or is there a better way to approach this recursive problem in … -
How to create your own interactive map from any image?
I want to create an interactive process flowchart for my company. This process flowchart lives on the browser and will have pins and markers on top of the products, where users can hover to reveal more information, similar to how this Zelda video game map was overlayed with pins and markers : https://zeldamaps.com/?game=BotW However, I have no clue where to even start. I think i need to convert my image to zoomable tiles. Can someone guide me what are the general steps required to achieve this interactive map? -
How to create form with context processor in Django?
I want to create a form in my navigation bar. I am using a context processor for that. I created themeChoice field in my UserProfile model. What I want to is when user click submit button, form will be save. I tried something but it did not work, my view prints nothing. How can I do that? Note: my context processor is working. views.py def approval_context_processor(request): ... if request.method == 'POST': form_theme = UserThemeChoiceform(request.POST) if form_theme.is_valid(): user_who = request.POST.get('user_who', None) user = UserProfile.objects.get(id=user_who) print(user_who) form_theme.save() return redirect('home') context= { ... 'form': form_theme, } return context navigation.html <form method="POST" id="theme" action="#"> {% csrf_token %} <input type="hidden" name="user_who" value="{{ request.user }}" > <button type="submit" class="btn btn-success">Send</button> </form> -
How do you format numbers called from an API in Django?
I have some values called from an API in a course I'm doing which I would like to format improve visibility. What is the best way to code this? Thanks. Example code is below: ${{list_item.marketCap}} {{list_item.ytdChange}}% Where, the first one I would like to add a comma for thousands and 2dp, and the second times by 100? -
How to work with Django ajax "GET method"
I want to do an ajax GET and POST method in django. MY post method is working well, but the GET method isn't. see my codes below; Urls path("getupdates/",views.getupdates,name="getupdates") views def getupdates(request): if request.user.is_authenticated: if request.method == "GET": user_instance = User.objects.filter(username=request.user.username)[0] info = userinfo.objects.filter(username=user_instance.username) game = spinwheel.objects.filter(user=info[0]) get_value= request.body data = {"info":info} print(data) return render(request,'spin.html',{"info":info}) Js-ajax $.ajax({ url: 'getupdates/', //datatype: 'json', data : data, type: 'GET', sucess: function(data) { console.log("refreshed!") } }); I wish to have the ajax GET method update some parts of my HTML. -
why email sent by normal users but not sent by superusers?
I need to use forgot password link to reset the password to a new one, the function works perfectly with me the problem is that: when I send the new request if that email was a superuser the request won't send, although, a normal user can send the request except the superuser so, anyone can help me in that? def password_reset_request(request): if request.method == "POST": password_reset_form = PasswordResetForm(request.POST) if password_reset_form.is_valid(): data = password_reset_form.cleaned_data['email'] associated_users = User.objects.filter(email=data) try: usr = User.objects.get(email=data) except User.DoesNotExist: messages.error(request, "%s Does not exists" % data, extra_tags='user_error') return redirect('accounts:reset_password') if associated_users.exists(): for user in associated_users: subject = "Password Reset Requested" plaintext = template.loader.get_template('accounts/password_reset_subject.txt') htmltemp = template.loader.get_template('accounts/password_reset_email.html') c = { "email": user.email, 'domain': '127.0.0.1:8000', 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': default_token_generator.make_token(user), 'protocol': 'http', } text_content = plaintext.render(c) html_content = htmltemp.render(c) try: msg = EmailMultiAlternatives(subject, text_content, settings.EMAIL_HOST_USER, [user.email], headers={'Reply-To': 'admin@example.com'}) msg.attach_alternative(html_content, "text/html") msg.send() except BadHeaderError: return HttpResponse('Invalid header found.') messages.info(request, "Password reset instructions have been sent to the email address entered.") return redirect("accounts:password_reset_done") password_reset_form = PasswordResetForm(None) return render(request=request, template_name="accounts/password_reset_form.html", context={"form": password_reset_form}) -
Export react app to static and separate html files, for use in django
I have a Github repo (https://github.com/cupliz/medical-calculators) with some components (calculators) that I want to integrate into my Django app, without having to do a SPA; I want to take advantage of Django's templating system. Integrating the React app as a Django app did not succeed (I tried a dozen tutorials based on Webpack and babel). I figured out the easiest way may be exporting the react app to static HTML files. I have tried the following: npm run build command (but this didn't work presumably because of the routing). react-snap module react-snapshot module react-static module (this requires the app to be built with react static from the start). What is the easiest way to export an existing react app, with routing, to static HTML files that can be served without any node.js on the hosting server? -
How does cookiecutter django create database in docker container/image
How does running docker-compose -f local.yml up create the postgres database in the postgres container with configurations in .envs/.local/.postgres. I have looked through the Dockerfiles and cannot seem to find a command such as createdb except in the maintenance/restore file. Cookiecutter-django: https://github.com/pydanny/cookiecutter-django -
Python django, How can I retrieve location by using the geolocation search API
I am doing a project which one of the function should be searching the location by using the location search, but how can I do that? How can I retrieve the location by using the searching APi which is https://geodata.gov.hk/gs/api/%5Bversion%5D/locationSearch?q=%5Bvalue%5D Hope that I can get some ideas from you guys. -
django returning 'AnonymousUser' object has no attribute '_meta' error
I am developing a feature, when a user registers it automatically logs the user in but i get 'AnonymousUser' object has no attribute '_meta' error. but when i use the same code to login the user it works fine. my forms.py: from django.contrib.auth.forms import UserCreationForm from django import forms from django.core.exceptions import ObjectDoesNotExist from django.contrib.auth.models import User from .models import * class RegisterForm(forms.Form): fname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"fname entry", "placeholder":"First Name"}), required=True) lname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"lname entry", "placeholder":"Last Name"}), required=True) phone = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"phone entry", "placeholder":"Phone Number"}), required=True) password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Password", "autocomplete":"off"}), required=True) password2 = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Confirm Password", "autocomplete":"off"}), required=True) def clean(self, *args, **kwargs): fname = self.cleaned_data.get("fname") lname = self.cleaned_data.get("lname") phone = self.cleaned_data.get("phone") password = self.cleaned_data.get("password") password2 = self.cleaned_data.get("password2") if phone and password and fname and lname and password2: try: user = User.objects.get(phone=PhoneNumber.objects.get(number=phone)) if user: raise forms.ValidationError("user exists login instead") except ObjectDoesNotExist: pass if password!=password2: raise forms.ValidationError("passwords didn't match") else: if len(password)<8: raise forms.ValidationError("short password! password should be longer than 8") in my forms i have a registration form which does not inherit from django's user creation form. my views.py: def registerView(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): fname = form.cleaned_data.get("fname") lname = form.cleaned_data.get("lname") username … -
How to add a model instance through another model
Guys I was looking at how I can add a model instance that can be added through another model. like how tags are done. If a model instance doesn't exist add it. if It does exist, don't add, just use the existing one. I wanted to do that with a Category model where if the category exists use the existing one and vice versa. #Models class Category(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Company(models.Model): name = models.CharField(max_length=120, help_text='Name of your company', ) slug = models.SlugField(unique=True, blank=True, null=True) categories = models.ManytoManyField(Category, related_name="company", blank=True, null=True, on_delete=models.PROTECT) #Views class CompanyCreate(CreateView): model = Company form_class = CompanyForm template_name = 'company/form.html' So when one adds a company can add many categories but use the one that already exists. Thanks in Advance