Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
migration issue, django.core.exceptions.FieldDoesNotExist: lightspeed.inventoryimagehistory has no field named 'imageID'
I'm having issues with this Django project, when I try to run migrations got the following message: base dir path C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop Traceback (most recent call last): File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\manage.py", line 20, in <module> execute_from_command_line(sys.argv) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\core\management\commands\makemigrations.py", line 141, in handle loader.project_state(), File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\loader.py", line 324, in project_state return self.graph.make_state(nodes=nodes, at_end=at_end, real_apps=list(self.unmigrated_apps)) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\graph.py", line 315, in make_state project_state = self.nodes[node].mutate_state(project_state, preserve=False) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\migration.py", line 87, in mutate_state operation.state_forwards(self.app_label, new_state) File "C:\Users\itres\OneDrive\Desktop\medaDoc\dsco_api-develop\venv\lib\site-packages\django\db\migrations\operations\fields.py", line 326, in state_forwards raise FieldDoesNotExist( django.core.exceptions.FieldDoesNotExist: lightspeed.inventoryimagehistory has no field named 'imageID' this is the class for InventoryImageHistory class InventoryImageHistory(models.Model): ImageID = models.IntegerField(db_index=True, unique=True, null=False, primary_key=True) history = ListField(DictField()) objects = models.DjongoManager() these are the migration files: Any help with this will be really appreciated, best regards -
why am I getting status code error while registering user through django rest framework
I am developing an authentication system for User registration through Django restframework. I have followed youtube link to configure serialzers. Since the Tutor is not using class based views, So, I didn't follow that part. I have written own class based view for ListCreateAPIView. serializers.py from rest_framework import serializers from .models import NewEmployeeProfile class RegistrationSerializers(serializers.ModelSerializer): ''' We need to add the password2, as its not the part of the NewEmployeeProfile model. So, we need to make it manually. ''' password2 = serializers.CharField(style={'input_type: password'}, write_only=True) class Meta: model = NewEmployeeProfile fields = ('email', 'first_name', 'last_name', 'employee_code', 'contact', 'dob', 'password', 'password2') extra_kwargs = { 'password': {'write_only': True} } def save(self, **kwargs): """ before we save the new user, we need to make sure that the password1, and password2 matches. In order to do that, we need to override the save() method. """ account = NewEmployeeProfile( email=self.validated_data['email'], first_name=self.validated_data['first name'], last_name=self.validated_data['last name'], employee_code=self.validated_data['employee code'], contact=self.validated_data['contact'], dob=self.validated_data['dob'], ) password = self.validated_data['password'] password2 = self.validated_data['password2'] if password != password2: raise serializers.ValidationError({'password': f'password must match..'}) account.set_password(password) account.save() return account views.py class UserRegisterView(ListCreateAPIView): create_queryset = NewEmployeeProfile.objects.all() serializer_class = RegistrationSerializers(create_queryset, many=True) permission_classes = [AllowAny] def post(self, request, *args, **kwargs): serializer = RegistrationSerializers(data=request.data) if serializer.is_valid(): newUser = serializer.save() serializer = … -
How to save predict model's results to database? Django
I made a predict model in my django project. Now I want to save the ptrdicted results to the UserResults table. But I don't know how to do. I'd be appreciated if you could give me some advices. Here is my models.py: from django.db import models from django.contrib.auth.models import User class UserResults(models.Model): results = models.IntegerField(blank=True) expect = models.IntegerField(blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.owner below is the views.py: from django.shortcuts import render from django.http import HttpResponse import pandas as pd import joblib def home(request): return render(request, "DeployModel/predict_home.html") def result(request): predict_modal = joblib.load('DeployModel/loan_model.pkl') temp = {} temp['ApplicantIncome'] = request.GET['ApplicantIncome'] temp['CoapplicantIncome'] = request.GET['CoapplicantIncome'] temp['LoanAmount'] = request.GET['LoanAmount'] temp['Loan_Amount_Term'] = request.GET['Loan_Amount_Term'] temp['Credit_History'] = request.GET['Credit_History'] temp['Married_Section'] = request.GET['Married_Section'] temp['Gender_Section'] = request.GET['Gender_Section'] temp['Edu_Section'] = request.GET['Edu_Section'] temp['Employed_Section'] = request.GET['Employed_Section'] temp['Property_Section'] = request.GET['Property_Section'] td = pd.DataFrame({'x':temp}).transpose() # print(temp) ans = predict_modal.predict(td)[0] return render(request, "DeployModel/predict_result.html", {'ans':ans}) Let me know if you need any more details. Thank you! -
Django template - for loop and then if statement
I have this loop: <div class="product-gallery-preview order-sm-2"> {% for images in Artikel.productimages_set.all %} {% if images.Position == 1 %} <div class="product-gallery-preview-item active" id="gallery{{ images.Position }}"> {% else %} <div class="product-gallery-preview-item" id="gallery{{ images.Position }}"> the problem is that all div classes are active I think because it's true for the first picture which is found. Is it possible to go in the loop check all pictures if it is in Position 1 and just output the div box I tried to print? -
How to post a delete request to django?
I am try ing to make a blog using django and reactjs. I am having a problem that when i send a delete request to server it responses me a text: You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to localhost:16/Blog/1/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. Can anyone help me ? Thank You ! this is my project source code https://github.com/KhanhGamer1601/React-Frontend-Blog https://github.com/KhanhGamer1601/Django-Backend-Blog -
How to make alert message disappear in Django
This is in my base html. How do i make the alert message only show for 5 seconds and automatically close? {% if messages %} {% for message in messages %} <div class = "alert alert-{{ message.tags }}"> {{ message }} </div> {% endfor %} {% endif %} -
How to fix error "'ManyRelatedManager' object has no attribute 'field_name'"
I am trying to extract some the student_ID and student_name from a model which has a manytomanyfield relations. unfortunately, i don't know how to go about that. The method i tried resulted into the attribute error i got. models.py class add_courses(models.Model): Course_Name = models.CharField(max_length=200, blank=True) Manager_Name = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE, blank=True) description = models.TextField(default='', blank=True) syllabus = models.TextField(default='', blank=True) classroom = models.CharField(choices=choices, default='in person', max_length=12, blank=True) course_code = models.CharField(max_length=14, default='', blank=True) student = models.ManyToManyField(add_students_by_manager, blank=True) def __str__(self): return self.Course_Name class add_students_by_manager(models.Model): manager_ID = models.ForeignKey(Manager_login_information, on_delete=models.CASCADE) student_ID = models.CharField(max_length=200) student_name = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address = models.CharField(max_length=200) dob = models.CharField(max_length=200) major = models.CharField(max_length=200) password = models.CharField(max_length=200) def __str__(self): return self.student_name @staticmethod def matching_loging_stu(userID): try: return add_students_by_manager.objects.get(student_ID=userID) except: return False views.py def assignment_page(request): if request.method == "POST": get_course_name = request.POST.get('get_course_name') add_courses_get = add_courses.objects.get(Course_Name=get_course_name) stu_course_all_stu = add_courses.objects.filter(Course_Name=add_courses_get) print(stu_course_all_stu) for m in stu_course_all_stu: print(m.student.student_ID) print(m.student.student_name) context = {"stu_course_all_stu":stu_course_all_stu, "get_course_name":get_course_name} return render(request, 'assignment_page.html', context3) -
Is it possible to pass a specific value to a django formset?
So I've been playing with Django formsets for about a week and I'm about ready to throw out Django altogether. Just kidding. Kinda. :). I have the standard inline formset implementation working finally as I documented here. How do I properly implement Django formsets with a CreateView ( Class Based View )? Hope it helps someone. Now I'm trying to leverage this code by trying to pass a specific queryset to it as shown below. class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(team_pk=20) As shown above, if I hard code a value, no worries it works to populate my formset. Although hardcoding this value is of little value to the implementation. I have researched form_kwargs, played around with numerous implementations as shown throughout SO, about passing a value but nothing I try works other than the code above for one team obviously and I can't for the life of me figure out how to do something like: class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(self.object.team_pk) Or... class PlayerFormSet(PlayerFormSet,BaseInlineFormSet): def __init__(self, *args, **kwargs): super(PlayerFormSet, self).__init__(*args, **kwargs) self.queryset = Player.objects.filter(self.instance.team_pk) I know the pk, it can clearly be passed here in a hardcoded fashion...And … -
Unable to save scrapped images to models or database using beautifulsoup and django
The following images were scrapped with beautiful soup https://people.net/wp-content/uploads/2021/03/ad1-746x375.jpg https://people.net/wp-content/uploads/2020/08/caroon-1-600x375.jpg something like this brought the images images = [i['data-src'] for i in soup.find_all('img', {'class','attachment-jnews-750x375 size-jnews-750x375 lazyload wp-post-image'})] but am unable to save the images scrapped above like this because it will bring an error Post.objects.create( title=title, content_1=paragraphs, image=images, sources=lnk, ) this will bring an error when i try saving to models class Post(models.Model): title = models.CharField(max_length=250, blank = True, help_text='Maximum 160 Title characters.') image = models.FileField(upload_to='images', blank=True, null=True, help_text='You must upload original image before continuing.') if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' and I try using for loop but the same error exist too for image in images: / Post.objects.create(title=title, content_1=paragraphs, image=images, sources=lnk, ) and I got this error also if file and not file._committed: AttributeError: 'list' object has no attribute '_committed' i think i need help immediately and i know this great people here will help me out. -
can you help me to know this error (Django Rest API )I am just learning now and new at REST API
import requests URL= "http://127.0.0.1:8000/stuinfo/2" r = requests.get(url = URL) data = r.json() print(data) python myapp.py Traceback (most recent call last): File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 170, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\util\connection.py", line 96, in create_connection raise err File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\util\connection.py", line 86, in create_connection sock.connect(sa) ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connectionpool.py", line 706, in urlopen chunked=chunked, File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1229, in request self._send_request(method, url, body, headers, encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1275, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1224, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 1016, in _send_output self.send(msg) File "c:\users\sunny\appdata\local\programs\python\python37\lib\http\client.py", line 956, in send self.connect() File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 200, in connect conn = self._new_conn() File "C:\Users\sunny\Desktop\Carry_Wire\Django_REST\ENV\lib\site-packages\urllib3\connection.py", line 182, in _new_conn self, "Failed to establish a new connection: %s" % e urllib3.exceptions.NewConnectionError: <urllib3.connection.HTTPConnection object at 0x0000015898D193C8>: Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it During handling of the above exception, another exception … -
Django UserCreationForm turning popup validation errors into in-line errors
I have created a user registration form using Django's inbuilt registration/validation, and I can't figure out how to modify the display of the popup style validation errors. I've noticed that validation errors are displayed in two forms: If any required field is not filled, or if the email field doesn't contain an '@' symbol, the validation error will be displayed in a popup message (screenshot 1). If an error is not raised due to any of the reasons in (1), but for some other reason (i.e. passwords are too short or don't match; username is already taken), errors will be displayed in the form of an unordered list with class name 'errorlist' (screenshot 2, errors in dark red). I don't really like the look of the popup style errors, and I would like to display them in the same way as the in-line errors. How should I go about doing this? Form code: from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username','email','password1','password2'] HTML: {% extends 'base/main.html' %} {% load static %} {% block css %} <link rel="stylesheet" type="text/css" href="{% static 'css/register.css' %}"> {% endblock css %} {% block content %} <div … -
Form wont appear in admin side of website and confused as to why and wondering if someone else could see why
models.py class Contact(models.Model): BookID = models.CharField(max_length=30) BookTitle = models.CharField(max_length=30) Author = models.CharField(max_length=35) UploadImage = models.ImageField(upload_to='ContactImg') def __str__(self): return self.BookId forms.py class ContactForm(forms.Form): BookID=forms.CharField(max_length=30,required=True) BookTitle=forms.CharField(max_length=30,required=True) Author=forms.CharField(max_length=35,required=True) UploadImage=forms.ImageField() class Meta: model = Contact fields = ('BookID', 'BookTitle', 'Author','UploadImage') Views.py def ContactUs(request): context_dict = {} if request.user.is_authenticated: context_dict['logged_in'] = True else: context_dict['logged_in'] = False user_form=ContactForm() if request.method == 'POST': user_form = ContactForm(request.POST) if user_form.is_valid(): # we load our profile instance Contact.BookId = user_form.get('BookId') Contact.BookTitle = user_form.get('BookTitle') Contact.Author= user_form.get('Author') Contact.UploadImage= user_form.get('UploadImage') Contact.save() return redirect('readingTime:home') else: # Invalid form # messages.error(request, 'Form contains errors. Double check') print(user_form.errors) messages.error(request, 'Form contains errors. Double check') # user_form = user_form.errors # user_form = RegisterForm() else: # Blank form since we do not have an HTTP POST user_form = ContactForm() return render(request,"readingTime Html {% extends 'readingTime/base.html' %} {% load staticfiles %} {% block style_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/ContactUs.css' %}" xmlns="http://www.w3.org/1999/html"/> {% endblock %} {% block navigation_bar %} <div class="navigation-bar"> <a href="/readingTime/">home</a> {% if logged_in %} <a href="/readingTime/logOut/" class="right">Sign Out</a> <a href="/readingTime/signIn/" class="right">My account</a> <a href="/polls/" class="right">User Polls</a> {% else %} <a href="/readingTime/register/" class="right">Register</a> <a href="/readingTime/signIn/" class="right">Sign In</a> <a href="/readingTime/signIn/" class="right">Poll Results</a> {% endif %} </div> {% endblock %} {% block body_block %} <div class="main" > <h1>Contact … -
How to work with docker containers created by cookiecutter-django?
I started a project using cookiecutter-django. I use docker. I also use wsl 2 (ubuntu 20.04) on windows 10. I edit using vscode started from wsl shell. When I create a new file using a remote docker command, e.g. when I issue docker-compose -f local.yml --rm django python manage.py startapp appname , the new files have the user and group root, and then I need to fix owner and group to my user to edit the files created this way. The questions are: Is this the way I am supposed to work? Should I edit directly in the container created, so that things like mypy linting and code completion would work better hopefully. Can you give steps to do that for a docker noob? -
Passing value from one html template to another in Django
I am making a web project using Django and relatively new to Django. I am stuck at the following part I want to get user input from one html search box and display it on another html page. This is my first page <html> <head> <title>Title</title> <style type="text/css"> #title{margin-top:150px;font-size:40px; font-family:"roboto"; text-align:center; color:grey} #info_text{margin-top:10px;font-size:15px; font-family:"roboto"; text-align:center; color:grey} #search_bar{height:40px;margin-top:20px;margin-bottom:9px;width:50%; margin-left: 24%} #search_button{height:50px;margin-top:20px;width:20%;margin-left: 40%;background-color:grey; font-size:40px; font-family:"roboto"; text-align:center; color: white} </style> </head> <body id="body"> <div> <h1 id="title">Enter Value</h1> <form action="result" method="POST"> {% csrf_token %} <input id="search_bar" type="text" name="search_box" onfocus="this.value=''"> <input type="submit" value="Search" id="search_button"> </form> </div> </body> </html> This is my view.py file from django.shortcuts import render # Create your views here. def home(request): return render(request, 'templates/home.html') def result(request): raw_details = None if request.method == 'GET': raw_deatils = request.POST.get('search_box', None) print(raw_details) return render(request, 'templates/result.html', raw_details) Please help Thankyou -
normalize different date formats
I am trying to work with an XML data that has different kinds of (string) date values, like: 'Sun, 04 Apr 2021 13:32:26 +0200' 'Sun, 04 Apr 2021 11:52:29 GMT' I want to save these in a Django object that has a datetime field. The script that I have written to convert a str datetime is as below: def normalise(val): val = datetime.strptime(val, '%a, %d %b %Y %H:%M:%S %z') return val Although, this does not work for every datetime value I scrape. For example for above 2 examples, the script works for the first one but crashes for the second. What would be an ideal way of normalising all the datetime values ? -
can't makemigrations in wagtail
I'm trying to migrate this model, and I get this error message. You are trying to add a non-nullable field 'id' to secondsection without a default; I'm using wagtail 2.11.3 and python 3.6 I want to generate the following: in CMS to add a title for the page description and three sections the first section will have : 1- text 2- image 3- title the second section will have: 1- a title 2- three blocks with title subtitle and text the third section will have : 1- title 2-text 3-image I've seen this solution, it didn't work from django.db import models from wagtail.core.fields import * from wagtail.admin.edit_handlers import * from wagtail.images.edit_handlers import * from modelcluster.fields import ParentalKey from wagtail.core.models import Orderable class AboutUs(Page): """About us Model""" templates = 'aboutus/about_us.html' description = models.TextField(blank=True, null=True) banner_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) first_section_title = models.CharField(max_length=100, blank=True, null=True) first_section_text = models.TextField(max_length=100, blank=True, null=True) first_section_image = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) second_section_title = models.CharField(max_length=100, blank=True, null=True) third_section_title = models.CharField(max_length=100, blank=True, null=True) third_section_Text = models.TextField(blank=True, null=True) third_section_image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) content_panels = Page.content_panels + [ MultiFieldPanel( [ FieldPanel('description'), ImageChooserPanel('banner_image') ], heading='Banner Section' ), MultiFieldPanel([ FieldPanel('first_section_title'), FieldPanel('first_section_text'), … -
Django forms select from choices or enter new data
I have a Django form in which for some fields I pull choices from my database, shown below. I have another field in which the user has to manually type in the data. Is it possible to give that field choices that are present from the database and an option to enter the data if the choice isn't there? Example: The field name is player and I would like to have all the players already in database as options to choose from and if it is a new player, the option to enter it. Is that what a TypedChoiceField is? I have been trying to find examples but no luck. thanks! forms def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) team_names = TeamName.objects.filter(league__name='MLB').order_by('name') teams = [(team.id, team.name)for team in team_names] self.fields['team'].choices = teams -
What is the best choice of models for a multiple choice quiz app created with Django?
I know there's a similar questions to this one here. My question builds on that answer. I am building a web app that will allow a user to create quizzes for educational purposes. This implies that there will be hundreds of questions created. In the quoted answer the method suggested is to use a ForeignKey relationship as such: class Question(models.Model): prompt = models.TextField (max_length=300) answer = models.CharField (max_length=50) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice = models.CharField (max_length=300, blank=True) However, the problem with this method is that if I have 300 questions, that will create 1200-1800 or choice entries. As there are more and more questions created, that number will grow by 10. As an educator, I plan to use this for my work (I have several thousand questions) and share the app with other teachers who will all be adding and sharing their own questions. I am concerned that on a larger scale this will create performance issues with the database. What has been suggested to me is to use this approach instead: class Question(models.Model): prompt = models.TextField (max_length=300) answer = models.CharField (max_length=50) class ChoiceList(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice1 = models.CharField (max_length=300, blank=True) choice2 = models.CharField (max_length=300, blank=True) … -
Create path with pk in router. Django
I need to create one more endpoint in my urls. Now i have this: router = DefaultRouter() router.register('collection', CollectionViewSet, basename='collection') urlpatterns = router.urls urlpatterns += [ path('collection/<int:pk>/video/', CollectionVideoViewSet.as_view({'get': 'list'}), name='collection-videos') ] But i need to set this 'collection/<int:pk>/video/' path to router because i want to have pk after it. Like this - 'collection/<int:pk>/video/<int:pk>'. But if create router.register('collection/<int:pk>/video', CollectionViewSet, basename='video') and go to http://0.0.0.0:8000/api/collections/v1/collection/1/video/ got an error Page not found (404) and see that django have api/collections/ v1/ ^collection/<int:pk>/video/$ [name='collection-list'] path in urls but don't go to it. What i have to do? -
changing Arrow Color for users
iam a Django BackEnd Developer and i have created a Blog i just want to know how to color slected Arrow after user Vote for specific Post and save it this is Arrow Html: <a href="{% url 'home:post-vote-up' id=posts.id %}"><i class="fas fa-arrow-up"></i></a> <p class="lead">{{posts.votes}}</p> <a href="{% url 'home:post-vote-down' id=posts.id %}"><i class="fas fa-arrow-down"></i> </a> -
How to get only month name and total in Django
I am trying to get only month name and count number from Data = QuerySet [{'month': datetime.datetime(2021, 3, 1, 0, 0, tzinfo=<DstTzInfo 'Asia/Dhaka' +06+6:00:00 STD>), 'count': 2 }] If I use Data[0]['month'] result is showing like (2021, 3, 1,0,0, ...) but I need to see only as March How can I view the month? Thanks in advance. -
Pip freeze > requirements doesn't work well with anaconda
I am trying to create a virtual environment based on another, for this, I want to extract the information from the libraries for a Django environment with pip freeze> requirements.txt But the output is asgiref @ file:///tmp/build/80754af9/asgiref_1605055780383/work certifi==2020.12.5 cffi==1.14.5 chardet==4.0.0 cryptography==3.4.7 cycler==0.10.0 Django @ file:///tmp/build/80754af9/django_1613762073373/work django-clear-cache==0.3 djangorestframework==3.12.4 idna==2.10 kiwisolver==1.3.1 matplotlib==3.4.1 numpy==1.20.2 Pillow==8.2.0 psycopg2 @ file:///C:/ci/psycopg2_1612298766762/work pycparser==2.20 PyMySQL==1.0.2 pyparsing==2.4.7 PyQt5==5.15.4 PyQt5-Qt5==5.15.2 PyQt5-sip==12.8.1 python-dateutil==2.8.1 pytz @ file:///tmp/build/80754af9/pytz_1612215392582/work requests==2.25.1 six==1.15.0 sqlparse @ file:///tmp/build/80754af9/sqlparse_1602184451250/work urllib3==1.26.4 wincertstore==0.2 When I try pip install -r requirements.txt doesn't work. Output Processing c:\tmp\build\80754af9\asgiref_1605055780383\work ERROR: Could not install packages due to an OSError: [Errno 2] No such file or directory: 'C:\\tmp\\build\\80754af9\\asgiref_1605055780383\\work' So I need a way to extract info with pip and install it with pip in another environment. -
Django | Why are my added fields to my CreateView not saved to the database/ or aren't rendered?
For a couple of days I'm stuck on a part of my Django project, where I want to add some extra fields for the user to fill in when they create a post. The problem is that the extra fields are not showing up on the page, or are saved in the database. I'm seeing these added fields on the create post template, so they are showing up and I can use them in the form (I'm using Cripsy forms), but after submitting, its not being saved (or something?) I'm using the CreateView and use a ModelForm to add those fields. I've followed all of the steps from the Django documentation but I can't solve it. I'm still a beginner, but I've looked everywhere for answers but nowhere I can find a specific solution to this problem. Please take a look at my code. I'm using the Django Post model: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(max_length=300) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) I've added a forms.py file where my ModelForm is located which holds the extra fields: class AddPostCreateForm(forms.ModelForm): # forms.ModelForm i.p.v. forms.Form omdat ik gebruik maak … -
When I open the model, one field value is replaced automatically
everyone! Have a stupid issue: When I open the employee model (in django admin), one field (employee_type) value is replaced automatically, idk why... Example: I create employee, define employee type as manager, save. In DB value is manager. After that, I open employee and see employee type as sewer and if I save, that value will saved in DB. I created text choices for this field, and In DB field is defined as enum. I tried to research the issue, value isn't used from DB, always first value from text choices is used. By the way, I created same fields (enum in DB and text choices in the model) in other model. And all works properly. How can I fix it??? Models.py with the issue: class Employee(models.Model): class EmployeeType(models.TextChoices): SEWER = 'SEWER', _('Sewer') MANAGER = 'MANAGER', _('Manager') UNDEFINED = 'UNDEFINED', _('Undefined') id = models.OneToOneField(User, models.CASCADE, db_column='id', verbose_name=_('User'), primary_key=True) employee_type = models.CharField(db_column='Employee type', verbose_name=_('Employee type'), max_length=9, choices=LabourIntensity.choices, default=LabourIntensity.MEDIUM) phone = models.CharField(db_column='Phone', verbose_name=_('Phone'), max_length=255) work_xp = models.IntegerField(db_column='Work XP', verbose_name=_('Work XP'), blank=True, null=True) Another one models.py. With same fields but without issues: class Order(models.Model): class OrderStatus(models.TextChoices): CREATED = 'Created', _('Created') CANCELLED = 'Cancelled', _('Cancelled') IN_PROGRESS = 'In progress', _('In progress') COMPLETED = 'Completed', … -
Framework, front-end, back-end, full stack? Or not to learn a framework?
I have several questions. I am a student and am training in web development. I have practically finished developing my first site which uses HTML, CSS, Javascript, PHP and MySQL. I want to acquire a certain ease in web development, but in theory this will not become my job, nor my daily life. I am about to start a bigger project (several months of development to be expected) because I am starting to be confident and have the capacities of my ambitions (not crazy either). Basically I'm more Python, not web development. So I would like to know if it is important to learn a framework? Especially since not wishing to be professionalized, therefore not specialized in front-end or back-end, I would prefer to solidify myself in full-stack knowledge for the moment. I have heard of Symfony (PHP), Node.js (JS), Bootstap (JS), etc ... But these are specialized front or back frameworks. If I have to learn a framework I would prefer it to be full-stack. And I ask myself the question if Django will not be what I need since it is a Python web framework. But is it good? Is it "full-stack" or just back-end? Isn't it a …