Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.operationalerror:2002 through host -cloudcluster
Tried connecting my django application to my server its giving error- Exception has occoured: OperationalError (2002,"can't connect to MYSQL Server on'mysql-1111-0.cloudclusters.net'(10060)") my database in settings.py is import django.contrib.gis.db.backends.mysql import django.db.backends.mysql import django.db.backends.mysql.client DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME':'database1', 'USER':'user', 'PASSWORD':'******', 'HOST':'mysql-11111-0.cloudclusters.net', 'Port':'11111', } } on migrating getting the above Error.Kindly help. -
Allow partial update in serializer_class in Django REST
I am trying to partially update my ProfileSerializer when i am making PATCH request. However i am not able to make it beacuse by default Serializer doesn't allow partial changes to be made. I am using Django Rest Framwork UpdateModelMixin to handle my patch request. Where can i set partial=True in my case? View: class ProfileViewPartialUpdate(GenericAPIView, UpdateModelMixin): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' def patch(self, request, *args, **kwargs): return self.partial_update(request, *args, **kwargs) Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'bio', 'name', 'email', 'sport', 'location', 'image') -
Which Framework is best to learn for future...ASP.NET core(C#) or Django (python) [closed]
i am new to development i want to pursue my career in this field...which framework is best to learn for future ASP.NET (c#) or Django (python) . NEED experts advice to this.. thanks -
The annotate with Sum seems doesn't work Django
There's a db (mysql) table like below: class AccountsInsightsHourly(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) date = models.IntegerField(blank=True, null=True) hour = models.IntegerField(blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) class Meta: managed = False db_table = 'accounts_insights_hourly' unique_together = (('account_id', 'date', 'hour'),) ordering = ["account_id", "hour"] Some datas saved in db are like : id account_id spend date hour created_time 1 1222 200 20200820 12 .... 1 1222 300 20200820 14 .... And I tried with to get the max spend for each account at the specified date. base_queryset_yesterday = AccountsInsightsHourly.objects.filter(date=date_yesterday). \ annotate(yesterday_spend=Max("spend", output_field=FloatField())). \ values("account_id", "yesterday_spend") # I got results like below <QuerySet [{'account_id': '1222', 'yesterday_spend': 200}, {'account_id': '1222', 'yesterday_s pend': 300}]> # expected result is <QuerySet [{'account_id': '1222', 'yesterday_spend': 300}> How can I make annotate work as expected? -
Django Model Form not displaying information stored in session
My views.py file class multi_form(View): model=Customer template_name='index.html' def get(self, request): form=RegForm() if request.session.has_key('pan_card_number'): first_name=request.session['first_name'] last_name=request.session['last_name'] personal_email=request.session['personal_email'] official_email=request.session['official_email'] permanent_address=request.session['current_address'] current_address=request.session['permanent_address'] pan_card_number=request.session['pan_card_number'] aadhar_card_number=request.session['aadhar_card_number'] loan_amount=request.session['loan_amount'] context = {'form': form} return render(request, 'customer/index.html', context) def post(self, request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): request.session['first_name']=form.cleaned_data['first_name'] request.session['last_name']=form.cleaned_data['last_name'] request.session['personal_email']=form.cleaned_data['personal_email'] request.session['official_email']=form.cleaned_data['official_email'] request.session['current_address']=form.cleaned_data['current_address'] request.session['permanent_address']=form.cleaned_data['permanent_address'] request.session['pan_card_number']=form.cleaned_data['pan_card_number'] request.session['aadhar_card_number']=form.cleaned_data['aadhar_card_number'] request.session['loan_amount']=form.cleaned_data['loan_amount'] form.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') context = {'form': form} return render(request, 'customer/index.html', context) What I want is the form to auto populate the fields filled earlier with those I have saved in django session variables. So, when the user has a GET request on visiting the page again he is shown the data he filled out earlier. How will I implement this thing? My template file <fieldset> <h2 class="fs-title">Registeration Form</h2> <h3 class="fs-subtitle">Please fill the details below</h3> {{form.first_name}} {{form.last_name}} {{form.personal_email}} {{form.official_email}} {{form.permanent_address}} {{form.current_address}} {{form.pan_card_number}} {{form.aadhar_card_number}} {{form.loan_amount}} <input type="button" name="next" class="next action-button" value="Next" /> </fieldset> Will my template file remain the same or do I need to change it as well? -
Problems installing django channels and twisted on windows 10 with python 3.8
I am trying to install django channels on windows 10, I have python 3.8.3 and django 3.0.5 already installed. When I enter the command, pip install channels in the cmd of the virtual environment of my project, I run into a huge error when my system attempts 'Building wheel for twisted (setup.py)', and upon failing to build this, another giant error occurs when 'Running setup.py install for twisted'. I have tried downloading the appropriate version of twisted from https://www.lfd.uci.edu/~gohlke/pythonlibs/#twisted, however when I then open the file using a code editor and try to run it I receive this message: WARNING: Requirement 'Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl' looks like a filename, but the file does not exist ERROR: Twisted‑20.3.0‑cp38‑cp38‑win_amd64.whl is not a valid wheel filename. This issue has been plaguing me for days now and I cannot find the solution anywhere online. Please can someone help me to understand how to resolve this? -
is there anyway to set horizon session timeout more than 3600 seconds
i can't make horizon session age longer than one hour, i had setted SESSION_TIMEOUT to 7200 in settings.py,but it was not worked, session age is still one hour, if i set SESSION_TIMEOUT to a value less than 3600 , it will work. please help me,thank you very much. -
Unable to redirect on other other page giving MultiValueDictKeyError Django
I am working on one simple student management system in which i am providing different options like add student, display student, display all students etc. so first i tired to render all those functions with simple text html it works perfectly. views.py from django.shortcuts import render from django.http import HttpResponse def home(request): return render(request, 'csvcrud/home.html') def add(request): return render(request, 'csvcrud/add.html') def display(request): return render(request, 'csvcrud/display.html') def displayall(request): return render(request, 'csvcrud/displayall.html') base.html <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap 4 Website Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script> </head> <body> <div class="container" style="margin-top:30px"> <div class="row"> <div class="col-sm-4"> <h2 class="text-center">Options</h2> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-add' %}">Add Student</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-display' %}">Display Student</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-displayall' %}">Display All</a> <a role="button" class="btn btn-primary btn-block" href="{% url 'csvcrud-add' %}">Download CSV</a> </div> <div class="col-sm-8 border border-secondary rounded"> {% block content %}{% endblock %} </div> </div> </div> <br> <div class="jumbotron text-center" style="margin-bottom:0"> <p>Footer</p> </div> </body> </html> add.html {% extends "csvcrud/base.html" %} {% block content %} <h2 class="text-center">Add Students</h2> <form action="/add" method="get" name="myForm" enctype="multipart/form-data"> <div class="form-group"> <label for="sid">Student ID</label> <input type="text" class="form-control" id="sid" placeholder="Enter Student ID" name="sid"> … -
Django update an object using models.Field object
I have dozens of fields in a Django model. class Question(models.Model): op1 = models.CharField(verbose_name="Option 1",max_length=500,null=True,blank=True) op2 = models.CharField(verbose_name="Option 2",max_length=500,null=True,blank=True) op3 = models.CharField(verbose_name="Option 3",max_length=500,null=True,blank=True) .... I want to write a function def update_ith_option_of_question( q, i, val): op = d._meta.get_field('op'+str(i)) # I want to save val in field op of object q How do I write the above function? -
template cant recognize url name django
I have a search field in my website header, and it doesnt reconize the url search_result html file: <form action="{% url 'search_results' %}" method="get"> <input name="q" type="text" placeholder="Search..."> </form> urls.py: path('search/', SearchResultsView.as_view(), name='search_results'), views.py: class SearchResultsView(ListView): model = post template_name = 'main/search_results.html' def get_queryset(self): # new return post.objects.filter( Q(title__icontains=q) | Q(writer__icontains=q) ) I get the error: Reverse for 'search_results' not found. 'search_results' is not a valid view function or pattern name. -
Why should put django project outside /root/
When I read document of django, I see this: [![Screenshots of document][1]][1] p [1]: https://i.stack.imgur.com/WmiNd.png And I want to know why should put django outside of /root/ In fact, i have done it(forgive me), and i want to figure out why I shouldn't did it. -
django filter get filter field value inside the view
I have my filter like this class SummaryFilter(django_filters.FilterSet): start = django_filters.DateFilter( field_name="date_modified", lookup_expr="gte", ) end = django_filters.DateFilter( field_name="date_modified", lookup_expr="lte", ) and in my view i am doing like this class GetRiskyUsersSummary(generics.ListAPIView): model = Summary queryset = Summary.objects.all() serializer_class = serializers.ModelSerializer filter_backends = (filters.DjangoFilterBackend,) filterset_class = SummaryFilter def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) response = {} ********doing some stuff here and return in response******* **** for doing these i need the cleaned start and end date as date objects like below but couldnt figure out the option for this in the library**** self.filter.cleaned_data.get('start') self.filter.cleaned_data.get('end') return Response({"response": response}) How can I get this data in the view ? -
How to connect another object (or user) to Django views (add_to_cart)
I am trying to develop an e-comm site. Where parents buy stuff for kids. Parent add children to his/her profile: class Kid(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) first_name = models.CharField(max_length=120) slug = slug = models.SlugField(unique=True) last_name = models.CharField(max_length=120) province = models.CharField(choices=PROVINCE_CHOICES, max_length=2, default='AB') city = models.CharField(max_length=120) school = models.CharField(max_length=120) grade = models.CharField(max_length=120) teacher = models.CharField(max_length=120) Also, I have OrderItem and Order classes, taken from a tutorial and it works. I have added kid object to OrderItem, maybe I need to add it to Order too. class OrderItem(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) kid = models.ForeignKey(Kid, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) item = models.ForeignKey(MenuItem, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f'{self.quantity} of {self.item.title}' class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) items = models.ManyToManyField(OrderItem) order_date = models.DateTimeField(auto_now_add=True) event_date = models.DateTimeField() ordered = models.BooleanField(default=False) In views, I have a define add_to_cart: def add_to_cart(request, slug): item = get_object_or_404(MenuItem, slug=slug) order_item, created = OrderItem.objects.get_or_create( item=item, user=request.user, ordered=False ) order_qs = Order.objects.filter( user=request.user, ordered=False ) if order_qs.exists(): order = order_qs[0] if order.items.filter(item__slug=item.slug).exists(): order_item.quantity +=1 order_item.save() messages.info(request, "Quantity of " + item.title + " was updated.") return redirect('/menu/') else: order.items.add(order_item) messages.info(request, item.title +" was added to your cart.") return redirect('/menu/') else: event_date = timezone.now() order = Order.objects.create( user=request.user, event_date=event_date ) … -
How to fix an error on django admin interface
Hi i am using Django admin to work on some task. i have created a model and added project name. so whenever i am creating a project say 'project5' and adding details and if again i am creating another project with same name and same details it is being created. What i want is i do not want the project name created to be with same details. it should give error. Please let me know how to fix this. Here below i have created a model with a class name and some fields. -
Django FilterSet Using multiple Models
I am having some trouble on applying a filter to a table in django, when I apply the filter (i.e. click on "Search") nothing happens. No error. No crash. Nada. The table stays the same as if nothing had happened eventhough the url does change adding the search fields that I applied. I'll rename the original names of variables, models and everything in general for sake of simplicity. models.py from other_app.models import CustomUser from another_app.models import OtherModel class SomeThings(models.Model): # default User was replaced with an AbstractUser model user = models.OneToOneField(CustomUser, on_delete=models.PROTECT) id = models.CharField(max_length=10,primary_key=True) thing_1= models.PositiveIntegerField(blank=False) thing_2= models.PositiveIntegerField(blank=False) image= models.ImageField(null=True, blank=True) class SomeStuff(models.Model): id = models.OneToOneField(SomeThings, on_delete=models.PROTECT) stuff_1 = models.CharField(max_length=255, blank=False) stuff_2 = models.CharField(max_length=255, blank=False) stuff_3 = models.ForeignKey(OtherModel, on_delete=models.PROTECT, null=True) class OtherInfo(models.Model): id = models.OneToOneField(SomeThings, on_delete=models.PROTECT) character_1 = models.CharField(max_length=255, blank=False) character_2 = models.CharField(max_length=255, blank=False) filters.py import django_filters from .models import * class myFilter(django_filters.FilterSet): class Meta: model = SomeStuff fields = '__all__' exclude = ['stuff_2','stuff_3'] views.py from .filters import myFilter def search(request): products = SomeStuff.objects.all() filter= myFilter(request.GET,queryset=products) product= filter.qs context = {'products':products,'filter':filter,} return render(request, 'search.html', context) search.html {% load static %} ... some html stuff ... <form method="get"> {{ filter.form }} <button class="btn btn-primary" type="submit"> Search </button> </form> <table> <thead> … -
i'm just getting started with django and followed a tutorial. imitated every step but keep getting this error
t = ToDoList(name="tim") t.save() Traceback (most recent call last): File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main_todolist The above exception was the direct cause of the following exception: Traceback (most recent call last): File "", line 1, in File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 750, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 787, in save_base updated = self._save_table( File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 892, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\base.py", line 930, in _do_insert return manager._insert( File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\query.py", line 1249, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\sql\compiler.py", line 1395, in execute_sql cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\utils.py", line 90, in exit raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\Saman\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: main_todolist -
django.db.models ImageField save Image as Base64
I'm actually new to Django. Let's say I have this model as a class class UserAccount(AbstractBaseUser, PermissionsMixin): ... profile_photo = models.ImageField( upload_to='photos/profile-picture', blank=True) objects = UserAccountManager() def __str__(self): return self.email I want to save the profile_photo attribute as a base64 file (instead of file path). How do I do that? Context : In my client side (front-end), I can't render the image by getting its file path. So I want to save the image as base64 string in the DB instead of actual image path so that it will be easier to render in the front end -
i have a issue in view job button in Django Project
I am new in Django and I am trying to do my project and I have an issue in that project. in my project, I have a view job button and whenever I click on any job or view job then it will redirect to another page and on that page, I want to show a full description of that job so please help me. thank you. this is my views.py def BrowseJob(request): all_job = jobs.objects.all() myFilter = jobsFilter(request.GET, queryset = all_job) all_job = myFilter.qs return render(request,'jobs.html',{'all_job':all_job,'myFilter':myFilter}) this is urls.py from django.urls import path from . import views urlpatterns = [path('',views.index,name='index'), path('Browse_Job',views.BrowseJob,name='Browse_Job'), path('contact',views.contact,name='contact'), path('job_details',views.jobdetails,name="job_details")] this is my job.html {% for job in all_job %} <div class="job_lists"> <div class="row"> <div class="col-lg-12 col-md-12"> <div class="single_jobs white-bg d-flex justify-content-between"> <div class="jobs_left d-flex align-items-center"> <div class="thumb"> <img src="{{job.job_img.url}}" alt=""> </div> <div class="jobs_conetent"> <a href="job_details"><h4>{{job.job_name}}</h4></a> <div class="links_locat d-flex align-items-center"> <div class="location"> <p> <i></i>{{job.job_Category}}</p> </div> <div class="location"> <p> <i></i>{{job.job_Experience}}</p> </div> </div> </div> </div> <div class="jobs_right"> <div class="apply_now"> <a href="job_details" class="boxed-btn3">View Job</a> </div> <div class="date"> <p>Last Date for Apply: {{job.last_date}}</p> </div> </div> </div> </div> </div> </div> {% endfor %} this is my jobdetails.html {% for job in all_job %} <img src="{{job.job_details.url}}" alt=""> {% endfor %} please help … -
FullCalendar Some Events (not all) on Wrong Dates
I am listing dates on FullCalendar and as you can see in the image, some dates show up correctly and some don't. I cannot find any reason that this is the case. The only thing the incorrect events have in common is that they have a start time of 8pm or later. I selected the August 17th, which has two events. Only one shows correctly on the calendar. Here is my event code: events: [ {% for event in connected_events %} { title: "{{event.event_title}}", start: "{{event.start_time|date:'c'}}", end: "{{event.end_time|date:'c'}}", url: "{% url 'events:event-detail' event.unique_id %}", details: "test", {%if event.budget_amount > 0 and event.lfg_state == 'LFGM' %}color : "#ff8f07"{%elif event.budget_amount <= 0 and event.lfg_state == 'LFGM' %}color : "#d943c5"{%elif event.budget_amount > 0 and event.lfg_state == 'LFP'%}color : "#1ad914"{%else%}color:"#38b3ff"{%endif%}, }, {% endfor %} -
Django ValueError: Unable to configure handler 'file'
I'm having a hard time because my django project. I have a hard time because I'm a django beginner. Please share your wisdom in solving this problem. python3 manage.py runserver Problems arise when a project is executed. Change settings.py import os from dotenv import load_dotenv load_dotenv() ... SECRET_KEY = os.getenv('SECRET_KEY') DEBUG=os.getenv('DEBUG') DATABASES = { 'default': { 'ENGINE': os.getenv('DB_ENGINE'), 'NAME': os.getenv('DB_NAME'), 'USER': os.getenv('DB_USER'), 'PASSWORD': os.getenv('DB_PASSWORD'), 'HOST': os.getenv('DB_HOST'), 'PORT': os.getenv('DB_PORT'), } } ... and then I met this error message. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 562, in configure handler = self.configure_handler(handlers[name]) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/config.py", line 735, in configure_handler result = factory(**kwargs) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 148, in __init__ BaseRotatingHandler.__init__(self, filename, mode, encoding, delay) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/handlers.py", line 55, in __init__ logging.FileHandler.__init__(self, filename, mode, encoding, delay) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1087, in __init__ StreamHandler.__init__(self, self._open()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/logging/__init__.py", line 1116, in _open return open(self.baseFilename, self.mode, encoding=self.encoding) FileNotFoundError: [Errno 2] No such file or directory: '/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/logs/logfile' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 926, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/Users/haemil/Desktop/Back-end workspace/Django_workspace/asone/venv/lib/python3.7/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, … -
Image Not Found Using HTML/Django
Django cant find jpg. It is in the same folder as my html. Tried everything i could, I have no idea why this is happening. I am using index.html. Tried different files, different file paths, different file types...etc. File isnt corrupted, program works fine for everything else. File Locations <div> <img src="portBack.jpg" alt=""> </div> -
Django postgresql ArrayField with default of callable raises error while running tests
Looks like when I when I use the callable as recommended, I get this error when trying to run tests on my project. I do not have this issue if I us [] as the default or if I have done that or pass "--keepdb". django.db.utils.ProgrammingError: type "citext[]" does not exist LINE 1: ...RIMARY KEY, "role" varchar(16) NOT NULL, "emails" citext[] N... I am not sure what is happening here. I think my version of postgresql is >11. -
TypeError: Post() got an unexpected keyword argument 'body' in command line while working on query set
I am working on creating a blog app in Django and while I was making the Query set in cmd I got the following error, CODE IN CMD: from django.contrib.auth.models import User >>> from blog.models import Post >>> user = User.objects.get(username='mratyunjay') >>> post = Post(title='Another post', ... slug='another-post', ... body='Post body.', ... author=user) ERROR : Traceback (most recent call last): File "<console>", line 4, in <module> File "C:\Users\Computer\Desktop\project\my_env\lib\site-packages\django\db\models\base.py", line 501, in __init__ raise TypeError("%s() got an unexpected keyword argument '%s'" % (cls.__name__, kwarg)) TypeError: Post() got an unexpected keyword argument 'body' admin.py :- from django.contrib import admin # Register your models here. from .models import Post @admin.register(Post) class PostAdmin(admin.ModelAdmin): list_display = ( 'title', 'slug', 'author', 'publish', 'status') list_filter = ( 'status', 'created', 'publish', 'author') search_fields = ( 'title', 'body' ) prepopulated_fields = {'slug': ('title',)} raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ( 'status', 'publish' ) models.py:- from django.db import models # Create your models here. from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = … -
How to make a same field as Dropdown or Char Field in Django
I am having a Django custom form in this its having one field that need to be dropdown / Char Field Thease are my forms class VehicleDetails(forms.ModelForm): vehicle_type = forms.ModelChoiceField( queryset=List.objects.all(), required=True, widget=forms.Select(attrs={'data-init-plugin': 'select2', 'data-item': 'true'})) class VehicleForm(forms.Form): vehicle = forms.ModelChoiceField(queryset=None, required=True, widget=forms.Select( attrs={'data-init-plugin': 'select2', 'request': 'true', 'data-item': 'true'})) def __init__(self, project=None,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['vehicle'].queryset = Vehicles.objects.all() if vehicle: self.fields['vehicle'].initial = vehicle My issue is if I am selecting vehicle_type as car/bike it need to be shows a dropdown ...... But if I select other it need to be a char field in the form So users can enter the details...... -
Django: too many values to unpack (excpected 2) error (.objects.filter)
I am trying to remake the project alone that I've already finished with my team. What i want to do is to make the project almost the same with the one we've done. We worked with 3 apps-User, Product, Order-so this time again, I'll go with those 3 apps. And I decided to do it with the DB(going to call it 'old DB') that we've already built because whole environment of this project setting is just the same with the previous one. After connecting the old DB on settings.py, I wrote User app's views.py to try SignUp and SignIn API, and it didn't work. I realised that I didn't write other apps' models.py to make old DB work fine(because the old DB consists of info from all the apps we made-all three apps' models.py are connected to each other with foreign keys). So, I wrote every piece of models.py of all the apps(User, Product, Order) to figure out this issue. However, the same error occurs. Traceback (most recent call last): File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/soomialexhwang/miniconda3/envs/superfluid/lib/python3.8/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) …