Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can not import pandas in django though it is installed
I have installed pandas version 1.0.3 with Django. whenever I try to import pandas it gives me an error like AttributeError: type object 'datetime.datetime' has no attribute 'fromisocalendar' django . how can i fix this? my python version is 3.8. -
Alter form data of a CreateView class in django
I have three models -> User from Django contrib Profile (has a filefield default_resume) Company (has a filefield resume) Profile and Company are in two different apps users and blog respectively. While creating a new profile a user has to add a default resume and then on creating a new company user has to add a new resume or leave the input empty for using the default one. models.py in app users: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default = 'default.jpg', upload_to='profile_pics') default_resume = models.FileField(upload_to='resume_default', blank=True) def __str__(self): return self.user.username models.py for app blog: class Company(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) resume = models.FileField(upload_to='resume_company', blank=True) For the addition of a new Company, I used a class-based view : class CompanyCreateView(CreateView): model = Company fields = ['resume'] def form_valid(self, form): form.instance.user = self.request.user if form.instance.resume == '': form.instance.resume = self.request.user.profile.default_resume return super().form_valid(form) So this code copies the address of default_resume file and stores it in the company database. I need it to copy the file and save it in 'resume_company' and store its location in the database since default resume can be changed by the user where the original file gets deleted since I used django_cleanup. Any help is appreciated. … -
Initials from Postgres character field in Django 2.2
I am trying to write a Django annotation to add initials generated from words in a single CharField in a Django model. For example: The ABC Company would become TAC A Company Making Everything would become ACME I'm using PostgreSQL 12.2. I found the following SQL from https://stackoverflow.com/a/33312435/3443946: select full_name, string_agg(substr(initials, 1,1)||'.', ' ') initials from ( select full_name, unnest(string_to_array(full_name,' ')) initials from my_table ) sub group by 1; This SQL works (more or less), and now I'm trying to adapt it to Django. Unnest was pretty easy as the following: class Unnest(Func): function = 'unnest' The difficulty arises in that two of the Postgres functions used aren't implemented by django.contrib.postgres or in any 3rd-party packages I've found. I figured I'd try to do it myself, but I'm not 100% sure how to tackle the string_to_array function... or even how to use it properly once implemented. I found the following function from https://brownbears.tistory.com/496 (adapted slightly to remove an internal variable reference and a possible translation error): class StringToArray(Func): function = 'string_to_array' output_field = ArrayField(CharField(max_length=1)) arity = 1 template = "%(function)s(%(expressions)s,'%(delimiter)s','%(null)s')" def __init__(self, expression, delimiter=',', null=''): super().__init__(expression, delimiter=delimiter, null=null) I'm trying to use the above like this: Account.objects.annotate( temp=Subquery( Account.objects.all().annotate( initials=Unnest( … -
Django Checkbox with multiple options to choose from
I am trying to make a field in my Django Admin Model to have a checkbox. But instead of one box (True/False) I would like to have 3 different options. Label: [] Option1 [] Option2 [] Option3 Not a multi select. As I should only be able to select one of these. EDIT: models.py This is what I have in my model. required = models.BooleanField(default=False) But this only gives me one checkbox. I would like to have 3 different options to choose from. -
Threading event wait in django application
I have DRF API consumed by a front-end application. I need to handle a special feature: the user clicks a button, he's being asked to scan a RFID card on an external device (he has 30 seconds to do so, he must not be able to do anything else during this time), then after the scan or timeout he gets the focus back. So far I've been able to deal with the scanning part, but troubles comes with the timeout. Here's my setup: The endpoint /rfid/create/ is called by the front when the user clicks the button. It waits for a threading.Event to be set and returns some data, or an error if it timed out. Post method of the view: def post(self, request): scanned = RFID_ASSIGN_EVENT.wait(timeout=RFID_ASSIGN_TIMEOUT) if scanned: RFID_ASSIGN_EVENT.clear() return Response({ 'some': data, }) return Response( {'code': 'timeout', 'message': 'no RFID card was scanned'}, status=status.HTTP_408_REQUEST_TIMEOUT ) On the other hand, the endpoint /rfid/assign/ is called by the external device (a raspberry but doesnt really matter) attached to the RFID reader when a card is scanned, and set the event. Post method of the view: def post(self, request): RFID_ASSIGN_EVENT.set() return Response({ 'some': data }) In reality there's some database calls … -
Query to get data in an own format in django
I want to get all expenses in the format given below.so when I hit the URL api/expenses I get the result in the following manner and also when I call api/expenses/<id> it shows all expense with that expense id. My Model: class Category(models.Model): name = models.CharField(max_length=40) class Expense(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="category_name") description = models.CharField(max_length=200) total_amount = models.IntegerField() class Expense_Details(models.Model): expense = models.ForeignKey(Expense, on_delete=models.CASCADE, related_name="expense") user = models.IntegerField() amount = models.IntegerField() type = models.CharField(max_length=100) ---->type is owe or lend When I request /api/expenses/: Expected Output { “total_expenses”: 10, “Expenses”: [{ “id”: 1, “category”: 1, “created_by”: 1, ------> expense id “description”: “lunch”, “total_amount”: “105”, “owe”: [{ “user_id”: 1, “amount”: 10 }, { “user_id”: 2, “amount”: 95 }], “lend”: [{ “user_id”: 3, “amount”: 10 }, { “user_id”: 4, “amount”: 95 }], }, ... ] } What Query should I use to get Output in the above format? How will my view look like? -
I want list items to be hidden based on string input in Javascript
So I have these list items in the div below: <div class="container"> <h2>Dissapearing Game</h2> <div> <li class="list-group-item go" id="item">Door#1</li> <li class="list-group-item go" id="item">Door#2</li> <li class="list-group-item go" id="item">Door#3</li> <li class="list-group-item go" id="item">Door#4</li> <li class="list-group-item go" id="item">Door#5</li> </div> My Goal is to make them dissapear upon typing the string "None" into it. The JavaScript goes as so: <script type="text/javascript"> var TextInsideLi0 = document.querySelectorAll('li')[0].innerHTML; // Retrieving text line 1 var TextInsideLi1 = document.querySelectorAll('li')[1].innerHTML; // Retrieving text line 2 var TextInsideLi2 = document.querySelectorAll('li')[2].innerHTML; // Retrieving text line 3 var TextInsideLi3 = document.querySelectorAll('li')[3].innerHTML; // Retrieving text line 4 var TextInsideLi4 = document.querySelectorAll('li')[4].innerHTML; // Retrieving text line 5 var MenuItems = document.querySelectorAll('.go'); // Retrieves the Menu Item by Class 'go' //BELOW executes the CSS to hide the list item when "None" string is entered: if (TextInsideLi0 == "None") { MenuItems[0].classList.add('hidden') } else if (TextInsideLi1 == "None") { MenuItems[1].classList.add('hidden') } else if (TextInsideLi2 == "None") { MenuItems[2].classList.add('hidden') } else if (TextInsideLi3 == "None") { MenuItems[3].classList.add('hidden') } else if (TextInsideLi4 == "None") { MenuItems[4].classList.add('hidden') } </script> ABOVE works for the 5 list items.. I just want clues in adding a for loop for it which will allow me to enter infinite list items with the same functionality. -
Is there a way to automatically fill in ForeignKey from model?
I am pretty new to programming but I've run into a bit of a problem and I can't find an answer anywhere; probably because I don't know how to describe the problem very well. I've made some models: user, customer and contract. Code: models.py: class CustomerInfo(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) customer_name = models.CharField(max_length=30, blank=False, null=False) def __str__(self): return self.customer_name class ContractInfo(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) customer = models.ForeignKey(CustomerInfo, null=True, on_delete=models.SET_NULL) contract_nr = models.CharField(max_length=20, blank=False, null=False) contract_active = models.BooleanField(default=True) contract_start = models.DateField(blank=False, null=False) contract_end = models.DateField(blank=False, null=False) def __str__(self): return self.contract_nr views.py: def addcontract(request): addcontract = AddContractForm() if request.method == "POST": form = AddContractForm(request.POST) if form.is_valid(): contr = form.save(commit=False) contr.user = request.user contr.save() return HttpResponseRedirect(reverse('Manager:contracts')) else: form = AddContractForm() else: form = AddContractForm() return render(request,'manager/addcontract.html',{'addcontract':addcontract}) forms.py: class AddContractForm(forms.ModelForm): class Meta(): model = ContractInfo exclude = ('user', 'customer',) fields = ('contract_nr', 'contract_active', 'contract_start', 'contract_end',) Now I've set it up that people can register and log in. When they register they create a company where they work for (customer). After they're logged in they can add contracts. They only see the contracts they make, trough filtering the contracts for user id by doing: contr.user = request.user. However, if they add the … -
how to make environment variable in "/etc/supervisord.conf" work in shell or python?
I would like to add an environment variable in the file “/etc/supervisord.conf”, but it doesn’t work. Can anyone please help? What I did is as below: in the file /etc/supervisord.conf, I added below line: environment=LOY_ENVIRONMENT="dev" then in Unix prompt, I run below and got error. > python -c "import os; print(os.environ['LOY_ENVIRONMENT'])" Error: Traceback (most recent call last): File "<string>", line 1, in <module> File "/usr/lib64/python2.7/UserDict.py", line 40, in __getitem__ raise KeyError(key) KeyError: 'LOY_ENVIRONMENT' Below doesn't work either. I tried reboot the server as well. echo $LOY_ENVIRONMENT -
Django 3.0 missing positional argument in db converter
Setting up a website using Django 3.0.6, django-cms 3.7.2, djangocms-blog 1.1.1, PostgreSQL 12, Apache 2.4.29, Ubuntu 18.04. All was going well until I attempted to create my first blog post. The attempt apparently succeeded (and there is a row in djangocms_blog_post,) but from the point I hit the 'save' button onward, every operation that hits the blog (or, oddly, my main menu) results in a TypeError: "from_db_value() missing 1 required positional argument: 'context'." Per the error page, the culprit is /lib/python3.6/site-packages/django/db/models/sql/compiler.py in function apply_converters, line 1095: value = converter(value, expression, connection) Google and SO turned up a couple of posts implying that the code isn't ported to django 3.0...but the code IS django 3.0, so deep in django that it's kinda odd that this glitch took so long to show itself. Settings and apache config checks OK. Database appears OK. I'm stuck. Any/all ideas greatly appreciated. -
Dynamically disable row in ModelFormSet?
I'm rendering a "timesheet" grid displaying input fields for day 1 through day 7 (mon-sun) (Screenshot for the curious: https://imgur.com/UIngiNZ) My Model looks like this: class Timesheet(Model): year = PositiveIntegerField(validators=[MaxValueValidator(2500), MinValueValidator(1900)]) week = PositiveIntegerField() project = ForeignKey("projects.Project", on_delete=CASCADE) user = ForeignKey("accounts.User", on_delete=CASCADE) day_1 = DecimalField("monday", blank=True, null=True, max_digits=3, decimal_places=1) day_2 = DecimalField("tuesday", blank=True, null=True, max_digits=3, decimal_places=1) day_3 = DecimalField("wednesday", blank=True, null=True, max_digits=3, decimal_places=1) day_4 = DecimalField("thursday", blank=True, null=True, max_digits=3, decimal_places=1) day_5 = DecimalField("friday", blank=True, null=True, max_digits=3, decimal_places=1) day_6 = DecimalField("saturday", blank=True, null=True, max_digits=3, decimal_places=1) day_7 = DecimalField("sunday", blank=True, null=True, max_digits=3, decimal_places=1) status = CharField(max_length=15, choices=STATUS_CHOICES, blank=True, default='open') And then in my forms.py I've created a TimesheetModelFormSet as such: TimesheetModelFormSet = modelformset_factory(Timesheet, exclude=("year", "week", "project", "user"), extra=0) And rendering the formset to my template after instantiating it from my view (timesheet_formset = self.form_class(queryset=timesheet)) template.html ... <tbody> {{ timesheet_formset.management_form }} {% for row in timesheet_formset %} <tr class="tracker"> <th scope="row">{{ row.instance.project }} {{ row.id }}</th> <td>{{ row.day_1 }}</td> <td>{{ row.day_2 }}</td> <td>{{ row.day_3 }}</td> <td>{{ row.day_4 }}</td> <td>{{ row.day_5 }}</td> <td>{{ row.day_6 }}</td> <td>{{ row.day_7 }}</td> <td class="align-middle">{{ row.instance.total_duration }}</td> </tr> {% endfor %} </tbody> ... How can I dynamically add self.fields[<formset_field>].disabled = True for each "row"? E.g class TimesheetModelForm(ModelForm): def __init__(self, … -
Deployment of django app - Scaling, Static Files, Servers
I am working my way to deploy my django app on a Linux Server. Encountered with various problems and want someone to clarify that for me. I searched for days but the answer I found are either too broad or faded away from topic. 1) According to django docs, it is inefficient to serve static files locally. Does that means that all the static files including html,css,js files should be hosted on another server? 2) I have an AWS S3 bucket hosting all my media files, can I use that same bucket (or create a new bucket) to host my static files if above answer is yes. If so, is that efficient? 3) According to search, in order for django to scale horizontally, it should be a stateless app, does it means that I also have to host my database on a different location than my own Linux server ? -
Problem with send_email function using a third package in django
I am using a third package for manage login in my django project and i do not find where is the problem. I filled my settings.py with the mail config.. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myuser@gmail.com' DEFAULT_FROM_EMAIL = 'myuser@gmail.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_PORT = 465 EMAIL_USE_TLS = True EMAIL_USE_SSL = True I am using the page "resend/activation-code/' to resend activation as written in urls.py urlpatterns = [ path('log-in/', LogInView.as_view(), name='log_in'), path('log-out/', LogOutView.as_view(), name='log_out'), path('resend/activation-code/', ResendActivationCodeView.as_view(), name='resend_activation_code'), path('sign-up/', SignUpView.as_view(), name='sign_up'), path('activate/<code>/', ActivateView.as_view(), name='activate'), This page (resend activation) uses the class ResendActivationCodeView in views.py: class ResendActivationCodeView(GuestOnlyView, FormView): template_name = 'accounts/resend_activation_code.html' @staticmethod def get_form_class(**kwargs): if settings.DISABLE_USERNAME: return ResendActivationCodeViaEmailForm return ResendActivationCodeForm def form_valid(self, form): user = form.user_cache activation = user.activation_set.first() activation.delete() code = get_random_string(20) act = Activation() act.code = code act.user = user act.save() send_activation_email(self.request, user.email, code) messages.success(self.request, _('Um novo código de ativação foi enviado para o seu email.')) return redirect('accounts:resend_activation_code') The function send_activation_email is utils.py is: def send_activation_email(request, email, code): context = { 'subject': _('Ativar Conta'), 'uri': request.build_absolute_uri(reverse('accounts:activate', kwargs={'code': code})), } send_mail(email, 'activate_profile', context) I inserted a print(email) and print(context) before the end of the function send_mail() and it contains the correct data. I tried also other emails servers to … -
How to get client true machine name in a web application
My question is independant of platform , suppose we use a web application ( using Php , Jee , Django , Js or any other one .. etc ) it is easy to know some informations about the client who visit the web application like the browser , operating system , public ip address , but till now i didnt find a way to know the machine name When i try to do this for example with Php ( $_SERVER['REMOTE_ADDR'] ) and i host the website on internet , i get the hostname of the router that gives the public ip address to the client and not the client's machine hostname I dont know if this possible in a language that i didnt mention or that i dont know about yet , in that case i'll be glad to know about it Is there a way to get the true client's machine name ? Thanks for you answer -
Customised allauth sign in form. Receiving error: AttributeError: 'NoneType' object has no attribute 'is_active'
I am using Django with allauth for my users registration. I want to add a "Name" field to this. I used a guide and added the following code to override the default allauth sign up form: from django import forms from allauth.account.forms import SignupForm class MyCustomSignupForm(SignupForm): def __init__(self, *args, **kwargs): super(MyCustomSignupForm, self).__init__(*args, **kwargs) self.fields['name'] = forms.CharField(required=True) def save(self, request): name = self.cleaned_data.pop('name') ... user = super(MyCustomSignupForm, self).save(request) I have added this to my settings.py: ACCOUNT_FORMS = {'signup': 'users.forms.MyCustomSignupForm'} The good news it that 'Name' is now appearing on the registration page! The bad news is that when I click 'Register' I receive the following error: AttributeError AttributeError: 'NoneType' object has no attribute 'is_active' Traceback (most recent call last) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/contrib/staticfiles/handlers.py", line 65, in __call__ return self.application(environ, start_response) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 141, in __call__ response = self.get_response(request) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 75, in get_response response = self._middleware_chain(request) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 36, in inner response = response_for_exception(request, exc) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 90, in response_for_exception response = handle_uncaught_exception(request, get_resolver(get_urlconf()), sys.exc_info()) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 125, in handle_uncaught_exception return debug.technical_500_response(request, *exc_info) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django_extensions/management/technical_response.py", line 37, in null_technical_500_response six.reraise(exc_type, exc_value, tb) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/six.py", line 702, in reraise raise value.with_traceback(tb) File "/Users/default/Documents/dev/covid19/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = … -
Delete multiple objects in HTML table using Django template tags
I have a table of manufacturers and am trying to implement the ability to select multiple manufacturers at once to be deleted. I am using a for loop to list all of the manufacturers within the table which are stored in the database. Within that loop are the input checkboxes that I would like to use to selectively delete these manufacturers. I'm not sure how can I pass in an unknown number of arguments to a Django template tag or if that is even the proper way to implement something like this. Any help or guidance in the right direction is appreciated! manufacturers.html: {% extends 'base.html' %} {% block content %} <div id="content-wrapper"> <!-- [ manufacturer list ] start --> <div class="col-xl-12 col-md-12"> <div class="card User-Activity"> <div class="card-header"> <h5>Manufacturers</h5> <div class="card-header-right"> <div class="btn-group card-option"> <div class="dropdown"> <button class="btn btn-warning" id="delete-button" type="button"> Delete </button> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Edit </button> <a href="" id="cancel-button"> <i class="fas fa-times"></i> </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" href="#" data-toggle="modal" data-target="#add-manufacturer">Add Manufacturer</a> <a class="dropdown-item" href="#" onclick="showBoxes()">Remove Manufacturer</a> </div> </div> ... </div> </div> </div> <div class="card-block pb-0"> <div class="table-responsive"> <table class="table table-hover"> <thead> <tr> <th>Manufacturer</th> <th>Manufacturer Part Number Prefix</th> <th>Priority</th> <th>Status</th> <th class="text-right"></th> … -
Where I can find google ads refresh token
I would like call google ads API with django application and I am unable to find refresh_token I am using below code credentials = { 'developer_token': 'q4QiPbt111aV4ZqcLRJ58Q', 'refresh_token': '', 'client_id': '266173227311-92222etht268a6921jv4i8tvjpl3rds1.apps.googleusercontent.com', 'client_secret': 'aHJUqc0DqSH1234_OqU6U91O'} adwords_client = GoogleAdsClient.load_from_dict(credentials) And getting below code in django ('invalid_request: Missing required parameter: refresh_token', '{\n "error": "invalid_request",\n "error_description": "Missing required parameter: refresh_token"\n}') -
How to override POST method for bulk adding - Django Rest Framework
I'm writing a REST API using Django Rest Framework and I would like that one of my routes accepts bulk adding on POST method, to create multiple objects. Others methods (GET, PUT, PATCH, DELETE) will still remain the same, accepting only one at a time. What I have so far is below and it's currently working just fine for posting one at a time. In my urls.py: path('book', books.BookViewSet.as_view()), books.py: class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() permission_classes = (IsAuthenticated, ) serializer.py: class BookSerializer(serializers.ModelSerializer): def create(self, validated_data): # I assume this is the method to be overridden to get this class Meta: model = Book fields = ('id', 'name', 'author_id', 'page_number', 'active') -
DRF Upload Image Unittest with Debian Buster Docker
I keep getting this response: AssertionError: Response {'file': [ErrorDetail(string='Upload a valid image. The file you uploaded was either not an image or a corrupted image.', code='invalid_image')]} E assert 400 == 201 when running pytest. My test case: def test_upload_picture(self, user, arf, generate_local_images, settings): settings.DEBUG = True view = UserProfilePictureView.as_view() from django.core.files import File from rest_framework.reverse import reverse from django.core.files.uploadedfile import SimpleUploadedFile file = File(new_image_paths[0].open('rb')) file.seek(0) uploaded_file = SimpleUploadedFile('hi.jpg', file.read(), content_type="image/jpeg") client = APIClient() client.force_authenticate(user=user) data = {"file": uploaded_file} response = client.post(reverse("picture"), data=data, format='multipart', **{"HTTP_CONTENT_DISPOSITION": "inline; filename=hi.jpg"}) assert response.status_code == 201, f"Response {response.data}" # with open(str(new_image_paths[0]), "rb") as fp: # request = arf.post( # "/api/v1/picture/", # data={"file": uploaded_file}, # format="multipart" # ) # request.user = user # request.META["HTTP_CONTENT_DISPOSITION"] = "attachment; filename=hi.jpg" # response = view(request) # assert response.status_code == 201, f"Response {response.data}" # No response data if successful Of which I tried using APIClient and APIRequestFactory. Neither of which work. Both give the same response. My view is an APIView that uses a serializer with serializer.ImageField(). It works when I test with my mobile iOS client, but not on this test. I'm using Docker with slim-buster Python image on 3.7. I checked Pillow's GH issues, and one of them mentions that … -
How to solve "'datetime.datetime' has no attribute 'fromisocalendar'" in django with python
I have made a Measurements model which has foreign key relation with custom user model. And also I have a form using this Measurements model where user submit data and stores in the db. In views analyze function stores the data of database to pandas dataframe. I have not used any datetime function. whenever i runserver it causes an error like in the title. how should i fix this? for your information Measurements model has a DateTimeField. here is my model: class Measurements(models.Model): d_value=models.IntegerField() created=models.DateTimeField(auto_now_add=True) patient=models.ForeignKey(UserSignupModel,on_delete=models.CASCADE) def __str__(self): return str(self.patient) here is the views: def analyze(request): qs=Measurements.objects.all().values() data=pd.DataFrame(qs) return render(request,'diabetes/analyze.html',{'df':data.to_html()}) -
Not able to perform Update Operation on Django
I am making todo application and i am having problem doing the update operation views.py def update(request, task_id): task = Task.objects.get(pk=task_id) if request.method == 'POST': form = TaskForm(request.POST or None, instance=task) if form.is_valid(): form.save() return redirect('/') return render(request, 'update.html', {'task': task}) forms.py class TaskForm(forms.ModelForm): class Meta: model = Task fields = '__all__' urls.py path('update/<int:task_id>', views.update, name='update'), update.html {% extends 'base.html' %} {% block content %} {% if task %} <form class="form-inline my-2 my-lg-0" method="POST" > {% csrf_token %} <input type="search" class="form-control mr-sm-2" name="task" value="{{task.text}}"> <input type="hidden" name="completed" value="{{task.completed}}"> <button type="submit" class="btn btn-outline-secondary my-2 ">Edit Task</button> </form> {% endif %} {% endblock %} I am able to get the Value of the selected item in textbox but when i edit it and press Edit Task Nothing happens . -
Issue with Django Login Form
i am learning to customize django login forms. But here i am facing some weired issues. Like when i am trying to login but shows an error "Enter a valid email address" enter image description here Can anyone tell me which one actually causing this problem? Forms.py from django.contrib.auth.forms import AuthenticationForm from django import forms class UserLoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super(UserLoginForm, self).__init__(*args, **kwargs) username = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Username', 'id': 'hello'})) password = forms.CharField(widget=forms.PasswordInput( attrs={ 'class': 'form-control', 'placeholder': 'Enter your Password', } )) Urls.py from django.urls import path from django.contrib.auth.views import LoginView, LogoutView from . import views from .forms import UserLoginForm urlpatterns = [ path('', views.HomeView, name='index'), path('login/', LoginView.as_view(template_name="registration/login.html", authentication_form=UserLoginForm), name='login'), path('about/', views.AboutView.as_view(), name='about'), path('authuser/', views.userView, name='authuser'), path('logout/', LogoutView.as_view(next_page='/'), name='logout') ] login.html <!DOCTYPE html> <html> <head> <title></title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> <h3>This is login page</h3> <form method="POST"> <div class="form-group"> {% csrf_token %} <p>{{ form.username }}</p> <p>{{ form.password }}</p> <p>{{ form.username.errors }}</p> <p>{{ form.password.errors }}</p> <input type="submit" class="btn btn-primary" name="Log in"> </div> </form> </body> </html> views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.decorators import login_required from django.views.generic import ListView, DetailView, CreateView from django.contrib.auth.mixins import … -
How send more than 1 image from my views.py function to my template?
In my views.py, i create 2 subplot and send the plot(of these 2 subplot) to my template in order to display it. I would like to send my 2 subgraphs separately to my template in order to display them in different places in my templates, but I can't do it. here my views.py: def Cdr3Results(request): t1 = np.arange(0.0, 5.0, 0.1) t2 = np.arange(0.0, 5.0, 0.02) plt.subplot(211) plt.plot(t1, np.exp(-t1) * np.cos(2 * np.pi * t1), "bo") plt.plot(t2, np.exp(-t2) * np.cos(2 * np.pi * t2), "k") plt.subplot(212) plt.plot(t2, np.cos(2 * np.pi * t2), "r--") fig = plt.gcf() buf = io.BytesIO() fig.savefig(buf, format='PNG', bbox_inches='tight') buf.seek(0) string = base64.b64encode(buf.read()) uri = parse.quote(string) return render(request, 'data/cdr3Results.html', {'data': uri}) All that i need is to send these 2 plot in 2 differents object of my dictionnary that i send to my template. Could someone please help me please, i have been trying for several days. -
Django: OperationalError while trying to inherit models
Got one model that i want inherit into the other. But getting OperationalError at /admin/permits/general/ (no such column: permits_general.id) instead. models.py looks like that: class Permit(models.Model): contractor = models.CharField(max_length=100) class Meta: abstract = True class General(Permit): safety_precautions = models.TextField(max_length=200) Models are registered in admin correctly. Tried to flush the database, but still get same error. Also tried to add id with uuid, but nothing happened. Any suggestions are very welcome. Thank You! -
How to handle special chars in the field name of a JSON payload
I need to handle a payload with special chars in field names like { "name" : "bob", "address(location)": "somewhere" } using Django rest framework I can have serializer like: class ContactSerializer(serializers.Serializer): name = serializers.CharField() address = serializers.CharField() but Djrf fails to map "address(location)" to "address", how can I do this ? I cannot change the payload structure and the serializer complains "address" is missing.