Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
postgresql is connected in django but not in pgadmin 4
I have installed postgresql in ubuntu, it is working well. I am running django in locally too. This is my settings.py file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'testdb', 'USER': 'postgres', 'PASSWORD': 'secret', 'HOST': '127.0.0.1', 'PORT': '5432' } } This is really working great with no objection, no complain, no error, no warning But i am experiencing a problem with connecting this testdb with pgadmin 4 My pgadmin 4 is running on docker. I am not getting why it is not connecting. pgadmin 4 saying: Unable to connect to server: could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? With the same information and credential, django sucessfully connected but why not on pgadmin 4? Can anyone help me to fix this issue? -
Why are Masonry (desandro) grid-items vertically overlapping? (Used with bootstrap 4 cards)
I have a hard time getting the DeSandro Masonry (https://masonry.desandro.com/) work together with bootstrap 4. What happens is that the bootstrap cards, which are children of the masonry grid-item, all overlap vertically on top of each other when the collapse button is clicked. Below can be seen the structure of the HTML file. I'm using python 3.8.2 together with django 3.0, as well as Bootstrap 4 and the latest version of Masonry. I've simplified the content for the sake of readability. <div class="container-fluid"> <div class="row justify-content-center"> <div class="col-2"> ...Some content here... <div class="col-9"> <!-- wrap all collapsible content --> <div id="entrycontent"> ...Some more content here... <div class="row"> <div class="col-12"> <div class="collapse multi-collapse" id="c{{entry.id}}" data-parent="#entrycontent"> ...Bootstrap Collapse Buttons here... <div class="grid"> <div class="grid-item"> <div class="collapse multi-collapse" id="onethinghere{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingelse{{entry.id}}"> <div class="card p-2"> ...Main card content here... <div class="grid-item"> <div class="collapse multi-collapse" id="somethingmore{{entry.id}}"> <div class="card p-2"> ...Main card content here... And so on... And initialized with jQuery at the bottom of the body tags.: <script> $('.grid').masonry({ // options itemSelector: '.grid-item', columnWidth: 200 }); </script> Also tried initializing with HTML as per the Masonry guide: <div class="grid" data-masonry='{ "itemSelector": ".grid-item", "columnWidth": 200 … -
Rendering Django template as an image [duplicate]
In my Django application, I have a model that I would like to render with a template (one image per object) and export the rendered output as an image with a given resolution. Is it possible? -
Django Python Forms - submitting complex view with multiple forms and formsets
Imagine this concept, I have a Taxi that can be ordered by a group for a full day multiple visits, and I should assign a group leader for each booking. now I have a Booking (PNR) that holds Clients traveling Routes, and a Group Leader (Operator) assigned for that booking. my view holds these: form for selecting the operator formset to add clients in this view I'm trying to make it easier for the user by giving the ability to save each form separately by ajax or save all data of forms by a button at the bottom of the view. I've been searching for a few days and I got the nearest approach on these two linkes 1 & 2 but still can't make my code run correctly and do what it's supposed to do. :( ANY SUPPORT WILL BE HIGHLY APPRECIATED! My models.py: class Operator (models.Model): name = models.CharField(max_length=50) # Other Fields def __str__(self): return self.code class PNR (models.Model): date_created = models.DateTimeField(auto_now_add=True) # Other Fields def __str__(self): return self.pk class Client (models.Model): related_pnr = models.ForeignKey(PNR, on_delete=models.CASCADE) name = models.CharField(max_length=200) # Other Fields def __str__(self): return self.related_pnr+" "+self.name My forms.py: class ChooseOperatorCode(forms.Form): operator = forms.ModelChoiceField(queryset=Operator.objects.all()) def clean(self, *args, **kwargs): … -
import datetime - Clarification
'''' from datetime import datetime now = datetime.now().time() print(now) o/p: 21:44:22.612870 '''' But, when i am trying: '''' import datetime now = datetime.now().time() print(now) '''' it give following error: Traceback (most recent call last): File "D:/3. WorkSpace/3. Django/datemodel/first.py", line 9, in now = datetime.now().time() # time object AttributeError: module 'datetime' has no attribute 'now' any one explain what is difference between both? -
Creating a Django form that allows "extra fields" on a "through" table to be edited
I have User, SocialNetwork, and UserSocialNetwork models in a Django 3.0.3 project. class User(AbstractUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) middle_name = models.CharField(blank=True, max_length=255, unique=False) bio = models.TextField(blank=True, default='') … socialnetworks = models.ManyToManyField(SocialNetwork, through='UserSocialNetwork') updated_at = models.DateTimeField(auto_now=True) class SocialNetwork(models.Model): name = models.CharField(blank=False, max_length=255) description = models.TextField(blank=True, default='') url = models.URLField(blank=False, max_length=255) format = models.CharField(blank=False, max_length=8, choices=[('handle', 'handle'), ('url', 'url')]) base_url = models.URLField(blank=True, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['name'] def __str__(self): return self.name class UserSocialNetwork(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) socialnetwork = models.ForeignKey(SocialNetwork, on_delete=models.CASCADE) identifier = models.CharField(blank=False, max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['socialnetwork', ] verbose_name = "User's Social Network" I'm using django-formtools to step through profile creation. One of the steps should be a page where the profile creator is presented with a list of SocialNetworks and given the opportunity to enter their identifier on those networks. I've been struggling with this. It was suggested I use formsets and I've got this class UserSocialNetworkForm(BaseModelForm): class Meta: model = UserSocialNetwork fields = [ 'socialnetwork', 'identifier', ] labels = { 'socialnetwork': _('Social Network'), } UserSocialNetworkFormSet = formset_factory(UserSocialNetworkForm, extra=SocialNetwork.objects.count()) which yields this but all I really want is one line per … -
How to get details of a nested object in a serializer in DRF
So I'm trying to create a serializer that would return a bunch of details of a 'Post' model in my project, but I want to get details of a nested object as well, the output of which I will show below: Post model: class Post(models.Model): # Base post attributes user = models.ForeignKey(UserOfApp, related_name="posts", on_delete=models.CASCADE) ... # Repost post attributes original_repost = models.ForeignKey( to="self", related_name="reposted_post", null=True, blank=True, on_delete=models.CASCADE, ) # Quote post attributes is_quote_post = models.BooleanField(default=False) quoted_post = models.ForeignKey( to="self", null=True, blank=True, on_delete=models.CASCADE ) ... My serializer, using 'depth': class HomeSerializer(serializers.ModelSerializer): id_str = serializers.ReadOnlyField() ... quoted_post_id_str = serializers.ReadOnlyField() class Meta: model = Post depth = 2 fields = "__all__" This yields me an output like, the problem being it returns all sensitive data from my user model as well, like 'password' etc: { "id": 16, ... "is_quote_post": false, "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, "username": "manas", "first_name": "Manas", "last_name": "Acharekar", "email": "manas.acharekar98@gmail.com", "is_staff": true, "is_active": true, "date_joined": "2020-03-01T18:42:11Z", "dob": "1998-11-11", "gender": "M", "bio": "i own this place", "location": "", "website": "", "verified": true, "followers": [], "friends": [], "groups": [], "user_permissions": [] }, "original_repost": { "id": 1, ... "user": { "id": 1, "password": "pbkdf2_sha256$180000$ni6drJvLjUU2$xoMt5tpJmz8TlmORfB/eTkYlGGpUGfriGz8rO7kVB8E=", "last_login": "2020-03-21T06:20:48Z", "is_superuser": true, … -
How to implement Django Chained Drop Down using clever select
I'm using doing a small django project and using django-clever-select to created chained drop down select. I followed the exact instruction given in their installation useage guide at https://pypi.org/project/django-clever-selects/. But once i run the app in pycharm the dropdown doesn't show any data to be selected. models.py <pre> class Category(models.Model): mname = models.CharField(max_length=100, blank=False,unique=True) mdescription = models.CharField(max_length=255, blank=True) def __str__(self): return self.mname class Meta: ordering = ('mname',) class SubCategory(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE,null=True, blank=True) scname = models.CharField (max_length=100, blank=False,unique=True) scdecription = models.CharField(max_length=255, blank=True) def __str__(self): return self.scname class Meta: ordering = ('scname',) class Deals(models.Model): vendor_deal = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) subcategory = models.ForeignKey(SubCategory, on_delete=models.SET_NULL, null= True) description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='documents/') uploaded_at = models.DateField(auto_now_add=True) expire_date = models.DateField(null=False) current_date = models.DateField(auto_now_add=True) def __str__(self): return self.description class Meta: ordering = ('description',) </pre> template file for the form ` {% extends 'base.html' %} {% load static %} {% block content %} </br></br></br></br> <div class="content"> <div class="row"> <div class="col-md-2"></div> <div class="col-md-6"> <form id="post_from" method="post"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} </div> <button type="submit" class="btn btn-primary">Upload</button> </form> </div> <div class="col-md-2"></div> </div> <div class="row"> </div> <div class="row"> </div> </div> {% endblock %} </pre></code> ` form.py file `<pre> … -
Create a subclass not to repeat matching fields
I created two class models in Django. Is there a way not to repeat the same matching fields storing them in a different class or variable? This is what i got: class Post(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post, self).save(*args, **kwargs) def __str__(self): return self.title class Post2(models.Model): title = models.CharField(max_length=50) content = RichTextField(blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE) posted_by = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(null=True, unique=True, editable=False) def __str__(self): return str(self.category) + self.slug + " " + str(self.id) def save(self, *args, **kwargs): self.slug = slugify(str(self.category)) + "/" + slugify(self.title+str(-self.id)) super(Post2, self).save(*args, **kwargs) def __str__(self): return self.title -
prefetch_related on existing django instance
I have a prefetch_related defined on my ObjectManager - is it possible to get the prefetch_related functionality on an instance that wasn't retrieved by this manager? This would apply to something like a newly-created instance. class Foo(models.Model): objects = FooManager() class FooManager(models.Manager): return (...).prefetch_related("bars") fooA = Foo.objects.get(...).bars # prefetched + cached for later fooB = Foo.objects.create() fooB.bars # not prefetched fooB.bars # queries each time because not included in prefetch cache -
GeoDjango IntegrityError when following the Tutorial
I am precisely following the GeoDjango Tutorial: https://docs.djangoproject.com/en/3.0/ref/contrib/gis/tutorial/ and decided to use SpatiaLite instead of PostGIS as my db-Backend. In order to do that, i edited my projects settings.py-file: DATABASES = { 'default': { 'ENGINE': 'django.contrib.gis.db.backends.spatialite', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } Following the Tutorial worked up to the Part "LayerMapping". When running $ python manage.py shell >>> from world import load >>> load.run() i get the following error: django.db.utils.IntegrityError: NOT NULL constraint failed: world_worldborder.fips What can I do to fix this Error? Thanks in Advance! -
ImportError: cannot import name 'forms' from 'basicapp'
form.py: from django import forms class FormName(forms.Form): name=forms.CharField() email=forms.EmailField() text=forms.CharField(widget=forms.Textarea) views.py: from django.shortcuts import render from .forms import forms def index(request): return render(request,'basicapp/index.html') def form_page(request): Form = forms.FormName() return render(request,'basicapp/form_page.html',{'form':Form}) I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp' -
Django form with only one select field is passing the input tag value instead of the selected one
Django beginner here. I have a form which asks the user to select an answer to be set as the correct one. Now my form is the following: class SelectCorrectAnswer(forms.Form): def __init__(self, choices, *args, **kwargs): super(SelectCorrectAnswer, self).__init__(*args, **kwargs) self.fields['correct_answer'].choices = choices correct_answer = forms.ChoiceField(choices=(), required=True) As you can see the choices are added dynamically, in fact, they are correctly displayed in the template, which is the following: <!--Select the correct answer--> <form action="{% url 'create-assessment' %}" method="post"> {% csrf_token %} {{ select_correct_form.as_p }} <input type="submit" value="Select" name="select-correct-answer" > </form> And retrieved in the view as shown below: # Initialize select correct answer form. problem_answers = Answer.objects.filter(creator=current_user, question=problem_to_be_answered) choices = [] for answer in problem_answers: choices.append((answer.answer, answer.answer),) select_correct_form = SelectCorrectAnswer(choices) print(choices) The view tries to handle the POST request as follows: # Set answer as correct. if request.method == 'POST' and 'select-correct-answer' in request.POST: print(f'CODE REACHED HERE {request.POST}') select_correct_form = SelectCorrectAnswer(request.POST) if select_correct_form.is_valid(): selected_answer = select_correct_form.cleaned_data['correct_answer'] correct_answer = Answer.objetcs.get(id=selected_answer.id) correct_answer.is_correct_answer = True correct_answer.save() print(f'THIS IS THE CORRECT ANSWER {correct_answer}') From the print statements, I can see that the correct request is being processed but the value I select is not passed. In fact, as you can see from the printed output, … -
Django blocked the raw socket connection
I build a socket server on the python and it worked. And when i call it as thread from django server the connection is refuse. This is my server code on thread: def add_device_to(self): socket_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_server.bind((host, 5555)) socket_server.listen() while True: socket_c , address = socket_server.accept() print("ok") self.register(socket_c, address) This is my client code: socket_client1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM) host = socket.gethostname() socket_client1.connect((host,5555)) The error on the client side is: socket_client2.connect((host, 5554)) ConnectionRefusedError: [Errno 111] Connection refused And when i tried that on windows it work fine. -
Use Django Queryset filter API on in-memory list of Model instances?
Is it possible to re-use the Django Queryset API when I've already retrieved a list of objects? i.e. foos = list(Foo.objects.filter(color="red")) large_foos = foos.filter(size="large") small_foos = foos.filter(size="small") I can of course iterate through my foos list, but it'd look cleaner to reuse the API. Use case is something like the color column being indexed but the result set small, and size isn't indexed (or size has high cardinality). -
render data with rest framework based on user input (Django)
I am struggling to modify this view so that a chart is generated based on user input. The underlying isssue is that I cannot find a way to make this with Django rest framework. Here is what I have been able to do so far: view.py: class forecast(APIView): def get(self, request, *args, **kwargs): query = request.GET.get('search_res', None) if query and request.method == 'GET': reference = Item.objects.filter(reference = query) forecast1 = Item.objects.filter(reference = query).values('demand_30_jours') forecast2 = Item.objects.filter(reference=query).values('Lt2') forecast3 = Item.objects.filter(reference=query).values('Lt3') data = {'reference': reference, 'forecastdata':[forecast1, forecast2, forecast3]} return Response(data) urls.py urlpatterns = [ path('', HomeView.as_view(), name='HomeView'), path('items.html', ItemPage.as_view()), path('charts',TemplateView.as_view()), path('admin/', admin.site.urls), path('api/chart/data',ChartData.as_view()), path('api/chart/forecast',forecast.as_view()) items.html <form id="searchform" method="get" action="" accept-charset="utf-8"> Search <input id="searchbox" name="search_res" type="text" placeholder="Search"> <input type="submit" value="OK"> </form> <div class="col-lg-6"> <div class="card mb-4"> <div class="card-header"><i class="fas fa-chart-bar mr-1"></i>90 DAYS FORWARD FORECAST</div> <div class="card-body"><canvas id="myChart" width="150" height="116"></canvas></div> <div class="card-footer small text-muted">References</div> </div> </div> <script> $(document).ready(function() { var endpoint = '/api/chart/forecast' var forecastdata= [] var reference = [] ; $.ajax({ method: "GET", url: endpoint, success: function (data) { reference = data.reference forecastdata = data.forecastdata setChart() }, error: function (error_data) { console.log(error_data) } } ) function setChart(){ var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'scatter', data: { labels: reference, … -
How to make automatic anser to mattermost channel
I have a problem with automatic generator of response via mattermost. To simplify a question- I have some dedicated channel on mattermost and if a message send by me is correct I want to have automatic answer "OK" + my_message. Right now I am checking a message and if is good making: result = {"channel" = "@username", "text" = "OK" + my_message} return HttpResponse(result, status=200) but it doesn't work. Ideas? -
Django not working after switching from sqllite3 to postgresql
I'm getting the following error after making switch of database when trying to make migrations: django.db.utils.OperationalError No explanation at all following it. I change the base sqlite3 code in settings to: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '', } } My models.py: from django.db import models # Create your models here. class Company(models.Model): KIND = ( (0, "Corporate"), (1, "Start Up"), ) name = models.CharField(verbose_name="full company", max_length=50) address = models.CharField(max_length=100) kind = models.IntegerField(default=0) class Job(models.Model): name = models.CharField(max_length=50) salary = models.DecimalField(max_digits=8, decimal_places=2, null=True) company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) Any idea what is going on? I did makemigrations when using sqlite3, but I already deleted the database. Full traceback error here: Traceback (most recent call last): File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 220, in ensure_connection self.connect() File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.connection = self.get_new_connection(conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\Admin\Anaconda3\lib\site-packages\django\db\backends\postgresql\base.py", line 185, in get_new_connection connection = Database.connect(**conn_params) File "C:\Users\Admin\Anaconda3\lib\site-packages\psycopg2\__init__.py", line 130, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line … -
how can i pass my context variables to javascript in Django?
views.py context = {'select_company': select_company,} return render(request, 'invest/chart.html', context) html <option value="{{o}}">{{select_company}}</option>----------{{select_company}} can show its value <script> company = {{select_company|safe}}; ---------------js tell me undefined </script> django 2.2 python 3.7 how to solve the weird problem -
TypeError at /stock/delete sequence item 0: expected str instance, int found
I'm deleting multiple objects using checkboxes but I'm facing this error TypeError at /stock/delete sequence item 0: expected str instance, int found views.py class DeleteProducts(SuccessMessageMixin, View): success_url = reverse_lazy('stock:stock') success_message = "Products {} are deleted successfully." def post(self, request, *args, **kwargs): products = self.request.POST.getlist('product') products_deleted = Product.objects.filter(pk__in=products).delete() msg = self.success_message.format(', '.join(products_deleted)) messages.success(self.request, msg, extra_tags='alert-danger') return HttpResponseRedirect(self.success_url) urls.py path('delete', login_required(DeleteProducts.as_view(), login_url='login'), name='deleteproducts'), -
Django & MongoDB has issue with default ID autoField on django models
I have Django 2 that the Rest Framework and Djongo is used in it. The Account can be created but when I try to see the list of created Accounts to updated or do any operation on them I can't actually I can't retrieve the list of Accounts and gives me error on ID field. I think this is an issue with MongoDB, so how I can fix this issue? Here is the error that I have that followed by my Account related codes MigrationError at /Accounts/account/ id Request Method: GET Request URL: http://localhost:8000/Accounts/account/ Django Version: 2.2.7 Exception Type: MigrationError Exception Value: id Exception Location: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib\site-packages\djongo\sql2mongo\query.py in _align_results, line 287 Python Executable: C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\python.exe Python Version: 3.8.0 Python Path: ['E:\Project\accountingPy', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\python38.zip', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\DLLs', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32\lib', 'C:\Users\PC 001\AppData\Local\Programs\Python\Python38-32', 'C:\Users\PC 001\AppData\Roaming\Python\Python38\site-packages', 'C:\Users\PC ' '001\AppData\Local\Programs\Python\Python38-32\lib\site-packages'] Server time: Mon, 6 Apr 2020 15:00:38 +0000 The record that stored in database // 1 { "_id": ObjectId("5e8b3a0c10fc9f40cdca44be"), "label": "Mapping", "owner": "Nasser", "balance_currency": "USD", "balance": "23.00", "desc": "This the Cash account that manage by cash payments", "status": true, "created_at": ISODate("2020-04-06T14:17:48.838Z"), "updated_at": ISODate("2020-04-06T14:17:48.838Z") } Account model class Account(models.Model): class Meta: db_table = 'account' def __str__(self): return self.label label = models.CharField(max_length=20,unique=True) owner = models.CharField(max_length=20) balance = … -
How to upgrade python version inside a virtual environment (in windows)
How to make my virtual environment use same version of python installed in my system. (see picture) -
How to create auto generate code in django
I have a company, department, and item list. in item list company and department are foreign keys. so when I add an item into the item list, item will generate a code for itself automatically like from company name's 3 alphabets, department name's 3 alphabets and 4 or 5 digits no. starting from 0001 and auto-increment. each company item will start from 0001. As an example: If a company is "ABCDE" and the department is "Finance" the code will be auto-generated like ABC-Fin-0001. is there any way to get these things done? Model_Class class Item(models.Model): item_name = models.CharField(max_length=255, blank =True) item_choice = ( ('IT','IT'), ('Electronics', 'Electronics'), ) item_type = models.CharField(max_length=255, blank =True, choices = item_choice ) code = models.CharField(unique=True, max_length=255) company = models.ForeignKey(Company, on_delete = models.SET_NULL, null =True,blank=True) department = models.ForeignKey(Department, on_delete = models.SET_NULL,null= True, blank=True) My_view def item_entry(request): title = 'Add Item' form = ItemForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, 'Successfully Saved') return redirect('/item_list') context = { "title": title, "form":form } return render(request,'item_entry.html', context) Form_View class ItemForm(forms.ModelForm): class Meta: model = Item fields = ("item_name","item_type", "code","company","department",) Template_view <table> <tr> <th>#</th> <th>Item Name</th> <th>Item Type</th> <th>Code</th> <th>Company</th> <th>Department</th> </tr> {% for instance in queryset %} <tr> <td>{{forloop.counter}}</td> <td><a href="{% … -
Django: How can i get multiple model class fields in one model with our without foregin key
Models.py I have a model like these. I'm trying to access 2 fields from all top 4 models into last model class(UserTimeZone) but im getting only one field from each models,anyone if anyone who can understand these problem,it will be a great help for me. class ControllerParameters(models.Model): ControllerName = models.CharField(max_length=50,null=True) ControllerID = models.IntegerField(null=True) . #multiple fields here.. def __str__(self): return self.ControllerName class DoorInfo(models.Model): DoorName = models.CharField(max_length=50, null=True) DoorSensor = models.CharField(max_length=10, choices=SensorChoice,default=True) . #multiple fields here.. In DoorInfo Table i have fixed 4 door records like,door1,door2,door3,door4 class Enrollment(models.Model): userid = models.CharField(max_length=15,blank=True,null=True) username =models.CharField(max_length=15,blank=True,null=True) . #multiple fields here.. class TimeZone(models.Model): timezoneid = models.CharField(max_length=50,choices=Timezone_Choices,blank=True, null=True) timezonename = models.CharField(max_length=100,db_column='TimeZone Name', blank=True, null=True) . #multiple fields here.. class UserTimezone(models.Model): employeeid = models.CharField(max_length=20, blank=True, null=True) employeename = models.ForeignKey(Enrollment, related_name="enrollment", on_delete=models.SET_NULL,null=True) controllerid = models.CharField(max_length=20, blank=True, null=True) controllername = models.ForeignKey(ControllerParameters, related_name="controlparameter", on_delete=models.SET_NULL,null=True) doornumber = models.IntegerField(blank=True, null=True) doorname = models.ForeignKey(DoorInfo,related_name="doorname", on_delete=models.SET_NULL,null=True) timezoneid = models.IntegerField(blank=True, null=True) timezonename = models.ForeignKey(TimeZone, related_name="timezone", on_delete=models.SET_NULL,null=True) views.py this code might be totally wrong as per my requirement so not understanding how can i do queryset, def usertimezone(request): timez = TimeZone.objects.all() text = DoorInfo.objects.all() enroll = Enrollment.objects.all() usertext = UserTimezone.objects.all() if request.method == "POST": userform = UserTimezoneForm(request.POST) if userform.is_valid(): userform.save() userform =UserTimezoneForm() context = {'userform':userform,'usertext':usertext, 'enroll':enroll,'text':text,'timez':timez, … -
How to redirect from one page to another in Django
I have created sign up Page and I want to redirect to login if the user is already registered. I am confused about how to do it in views I am also attaching views.py Thanks. def register(request): if request.method == 'POST': first_name = request.POST['Firstname'] last_name = request.POST['Lastname'] username = request.POST['Username'] password1 = request.POST['password'] password2 = request.POST['password1'] email = request.POST['email'] user = User.objects.create_user(username=username, password= password1, first_name=first_name, last_name=last_name, email=email) user.save() print('user Created') return redirect('/') else: return render(request, 'register.html')