Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 3.2 Project with DB2 (IBM_DB driver)
Currently, I am working in developing a web application with Python 3.8.10, Django 3.2 and IBM_DB_DJANGO 1.5.0.0. When I am trying the first step to move from sqlite3 to DB2, I type the command: python manage.py migrate Unfortunately, I got the error as below django.db.utils.ProgrammingError: Statement Execute Failed: [IBM][CLI Driver][DB2/AIX64] SQL0401N The data types of the operands for the operation "IN" are not compatible or comparable. SQLSTATE=42818\r SQLCODE=-401 There are tables being created and including: AUTH_GROUP, AUTH_GROUP_PERMISSIONS, AUTH_PERMISSION, DJANGO_MIGRATIONS. There is one records added in the Django_migration only. I would like to know how I could confirm whether it is good to use. Thanks in advance. -
Failed - network error when downloading a file
I have configured the apache webserver for my Django application for https redirection and its working fine. When i was testing my application I found out that it sometimes shows Failed -Network error when trying to download a XLSX file .Downloading a tarfile does not give any error.. Tried in different browser but got the same result.. But when I download it via Free download manager it works fine.. Not sure what is wrong Ubuntu - 20.04 python - 3.6.9 Please Help. Thanks -
Django Model Design Difference: link multiple simple models
I am designing Django models and would like some feedback on differences between different design schemas. Also, currently I am working only with Django Admin so my confusion might be coming from there. Let's suppose I have model Industry, which has multiple Locations. Banking -> US Banking -> UK Banking -> Japan ... Also, I have another model where industry and location is selected by user (on the website). So, if Banking is selected I want to show only locations that are available for banking. Here's the basic design I have already implemented (for demo purpose): class Industry(models.Model): """ Model representing industries. """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID for this industry and location') name = models.CharField(blank=False,null=True,max_length=100,verbose_name="Industry") location = models.CharField(blank=False,null=True,max_length=100,verbose_name="Location") def __str__(self): field_values = get_val(self) #this functions works return ' '.join(field_values) class Meta: db_table = 'Industry' class Select(models.Model): """ Model Select """ id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text='Unique ID Select') industry = models.ForeignKey('Industry',on_delete=models.SET_NULL,related_name='+',blank=False,null=True,max_length=100,verbose_name="Industry") location = models.CharField(blank=False,null=True,max_length=100,verbose_name="Location") def __str__(self): field_values = get_val(self) return ' '.join(field_values) class Meta: db_table = 'Select' As a superadmin, let's suppose in Industry model I create Banking->USA, Banking->UK and in Select model I want to choose Banking, and for the location I want to select from available locations … -
How to translate django model field's help_text with variable
models.py: from django.conf import settings from django.db import models from django.utils.translation import ugettext_lazy as _ class MyModel(models.Model): name = models.CharFiled(help_text=_("Name cannot contain %s") % settings.SPECIAL_CHARS) django.po: msgid "Name cannot contain %s" msgstr "xxxxx" Not working. -
validated_data is returning empty OrderedDict for nested fields with Django Rest Framework
Can someone help me figure out why some fields are not parsed correctly using nested serialziers with Django and Django-rest-framework? I've researched the issue on SO, and the only cause for this happening I've found is that the request is sent as Form-data and not Json, but I've checked that response.content_type equals application/json - so this shouldn't be the issue here. This is what my validated_data looks like (note that 3 of the fields only contain an empty OrderedDict): {'author': OrderedDict(), 'disclosed_at': datetime.datetime(2021, 10, 19, 12, 0, tzinfo=<DstTzInfo 'Europe/Stockholm' CEST+2:00:00 DST>), 'event_date': datetime.date(2021, 10, 20), 'event_type': OrderedDict(), 'subject_companies': [OrderedDict()]} This is what request.data looks like (where you can see that all fields are there, and having the fields specified in each serializer): {'event_type': {'pk': 1}, 'author': {'pk': 1}, 'event_date': '2021-10-20', 'disclosed_at': '2021-10-19 12:00:00', 'subject_companies': [{'pk': 1}]} This is where I'm sending the request from (test.py): def test_authenticated_creating_event_for_own_organisation(self): view = NewsEventList.as_view() url = reverse('news_event_list', kwargs={'pk': self.organisation.pk}) request = self.client.post(url, data=json.dumps(self.payload_event), content_type='application/json') force_authenticate(request, user=self.user) response = view(request, pk=self.organisation.pk) json_data = json.dumps(response.data, indent=4) json_ = (json.loads(json_data)) self.assertEqual(response.status_code, 201, 'Should return 201 - Created') return response I have the following serializers class OrganisationNameSerializer(ModelSerializer): class Meta: model = Organisation fields = ['pk'] class EventTypeSerializer(ModelSerializer): class … -
if/else to change password for app user and social user
I am trying to build a functionality to change passwords, there are two users: registered through my app registered via social authentication. For the first case old password will be asked and then a new password to change the password for the second case since they don't have a password for the app when they want to change the password for the first time only the new password will be asked, and after that old password will also be asked. Below is what I have tried so far, the first test case passes but the second also requires old and new passwords! What is causing that? Is this the right way to approach the problem? views.py class ChangePassword(APIView): serializer_class=ChangePasswordSerializer serializer_class2=ChangePasswordSerializer2 model = User permission_classes = [IsAuthenticated] def get_object(self, queryset=None): obj = self.request.user return obj def put(self,request, *args, **kwargs): self.object = self.get_object() if self.object.auth_provider != "email": serializer = self.serializer_class2(data=request.data) if serializer.is_valid(): self.object.set_password(serializer.data.get("new_password")) self.object.auth_provider == "email" self.object.save() response={ 'status':'success', 'code':status.HTTP_200_OK, 'message':"Password changed Successfully", } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: #check old password serializer = self.serializer_class(data=request.data) if serializer.is_valid(): if not self.object.check_password(serializer.data.get("old_password")): return Response({'error':["Wrong_password"]}, status=status.HTTP_400_BAD_REQUEST) self.object.set_password(serializer.data.get("new_password")) self.object.save() response={ 'status':'success', 'code':status.HTTP_200_OK, 'message':"Password changed Successfully", } return Response(response) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class ChangePasswordSerializer(serializers.Serializer): model … -
Foreign key model values return same value
I have looked at all answer and nothing quite helps me. I have a model Group class Group(models.Model): group_num = models.CharField(max_length=100) group_name = models.CharField(max_length=200) type = models.CharField(max_length=200) def __str__(self): return self.group_name and a model Subgroup group class Subgroup(models.Model): sub_group_num = models.CharField(max_length=100) sub_group_name = models.CharField(max_length=200) group_number = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_numbers', verbose_name="Group Number") group_in_name = models.ForeignKey(Group, on_delete=models.CASCADE, related_name='group_names', verbose_name="Group Name") def __str__(self): return self.sub_group_name when I reference the group_number and group_in_name from subgroup they give the same value in the template -
How to combine 2 arrays in python & django?
I currently have 1 array called ageSelect that looks like so : ageSelect = [] for row in xAgeSelect: rdict = {} rdict["Account"] = row[0] rdict["Name"] = row[1] rdict["Balance"] = row[2] rdict["E-mail"] = row[3] ageSelect.append(rdict) and another array that has the called thirtyDay that looks like to : for row in thirtyDay: rdict = {} rdict["30day"] = row[0] XthirtyDay.append(rdict) The problem is that both arrays are appended through different date arguments and I need to combine them to look something like this array3 = ["Account" , "Name" , "Balance" , "E-mail" , "30day"] So that when I call it in a for loop (that writes to .xlxs) it can look like this: for x in arr3: data4 = ( x["Account"], '*', ' ','','','',x["30day"],x["Balance"]-x["30day"],x["Balance"],'',x["Name"],x["E-mail"] ) I have tried using numpy for this : like so arr3 = np.dstack(ageSelect, XthirtyDay) -
Override serializer fields by pattern in Django
So I have a Django project with Django REST Framework with large number of models. For frontend to be user friendly I should display not only related object's id but also name. My idea for the solution was to replace all the PrimaryKeyRelated fields with StringRelatedFields in serializers on response. As the number of models is large I decided to make a single abstract serializer/mixin and intercept field creation replacing the field if is of correct type. This is how far I got up to now: class AbstractSerializer(serializers.ModelSerializer): class Meta: model: AbstractModel = AbstractModel read_only_fields: list = [ 'created_at', 'created_by', 'modified_at', 'modified_by', 'is_deleted', 'deleted_at', 'deleted_by' ] + ['is_active'] if 'is_active' in [field.attname for field in model._meta.fields] else [] abstract: bool = True def to_representation(self, instance): serializer = AbstractRequestResponseSerializer(instance) return serializer.data class AbstractRequestResponseSerializer(AbstractSerializer): class Meta(AbstractSerializer.Meta): pass @classmethod def _get_declared_fields(cls, bases, attrs): fields = [(field_name, attrs.pop(field_name)) for field_name, obj in list(attrs.items()) if isinstance(obj, Field)] fields.sort(key=lambda x: x[1]._creation_counter) new_fields = [] for field in fields: if isinstance(field, PrimaryKeyRelatedField): field = StringRelatedField(source=field.source, required=False) new_fields.append(field) fields = new_fields known = set(attrs) def visit(name): known.add(name) return name base_fields = [ (visit(name), f) for base in bases if hasattr(base, '_declared_fields') for name, f in base._declared_fields.items() if name … -
Using Django with db.sqlite3 with persistent volume in a Kubernetes pod outputs - django.db.utils.OperationalError: unable to open database file
I'm trying to deploy a small Django app, that creates its own db.sqlite3 database, in a Kubernetes pod. When doing so without a persistent volume to save the db.sqlite3, it works fine but when trying to save it in a persistent volume, the pod outputs django.db.utils.OperationalError: unable to open database file The first problem I had is when these commands: python ./manage.py migrate sh -c "envdir ${ENVDIR} python manage.py collectstatic" were run in the Dockerfile. After mounting the volume, none of my files would be visible. I learned that K8s volumes behaved differently from docker volumes and my solution was to put the commands in a shell script and execute it in the CMD or ENTYPOINT. This created the files after mounting and were visible but still doesn't help with the current problem. I tried using a persistent volume, tried using a hostPath defined volume and even tried using an initContainer that has the same image as the app, only it first sets the permissions to 777 for db.sqlite3 and executes the two commands above, but it can't even start for some reason. Here's the deployment.yaml: apiVersion: apps/v1 kind: Deployment metadata: name: myapp labels: app: myapp namespace: app-prod spec: replicas: … -
Restrict multiple login for a user in Django Rest Framework
I am attempting to restrict multiple login from a single user in my webapp and for the same I am following this tutorial: https://dev.to/fleepgeek/prevent-multiple-sessions-for-a-user-in-your-django-application-13oo I followed this step by step and when I am logging in using postman(or anything): http://localhost:8000/api/token/ I am unable to see any session that has been created in the ORM. Is it because I am using JWTAuthentication ? apps.py class AccountsConfig(AppConfig): name = 'users' def ready(self): import users.signals signals.py @receiver(user_logged_in) def on_user_logged_in(sender, request, **kwargs): LoggedInUser.objects.get_or_create(user=kwargs.get('user')) @receiver(user_logged_out) def on_user_logged_out(sender, **kwargs): LoggedInUser.objects.filter(user=kwargs.get('user')).delete() Models.py class User(AbstractUser): is_company = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_client = models.BooleanField(default=False) @property def full_name(self): return self.first_name + " " + self.last_name class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete=models.CASCADE) # Session keys are 32 characters long session_key = models.CharField(max_length=32, null=True, blank=True) def __str__(self): return self.user.username When I try runserver with this configuration it shows the following error: django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: users settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', 'users', 'users.apps.AccountsConfig', Where users is the application name -
Image is not shown in django template,
I have a django template where i send an image actually its for an email.It only works when i keep the whole url like abc.com/images/a.png . i have sent he image like this: { 'picture':picture.url } This is the code for template that i am using for email template: <img src="{{picture}}" alt="image" width="200" height="200" > Am i missing something? as it only works when i keep the whole url? -
Is there any way to disable Update (UpdateView) and Delete (DeleteView) functionality after an elapsed time period?
What I wish to achieve is to "disable" the possibility for a user to update or delete a record after a set period of time. In my application, a user creates a delivery booking slot, as part of which they specify a delivery date delivery_date. Requirement: A user should not be able to update/delete a booking slot within 7 days of the delivery_date How would I go about this? models.py from django.db import models from django.utils import timezone from django.urls import reverse from django.contrib.auth.models import User class Customer(models.Model): username = models.ForeignKey(User,on_delete=models.CASCADE) name = models.CharField(max_length=20,null=True) def __str__(self): return self.name # Create your models here. class Booking(models.Model): customer_name = models.ForeignKey(Customer,on_delete=models.CASCADE,null=True) username = models.ForeignKey(User,on_delete=models.CASCADE) qty_plts = models.PositiveSmallIntegerField(default=1) cbm = models.PositiveSmallIntegerField(default=1) created_date = models.DateTimeField(default=timezone.now()) delivery_date = models.DateField(null=True) delivery_time = models.TimeField(null=True) booking_number = models.CharField(max_length=50,unique=True) def __str__(self): return self.booking_number def save(self, **kwargs): if not self.booking_number: self.booking_number = f"{self.delivery_date:%Y%m%d}{self.delivery_time:%H%M}" super().save(**kwargs) def get_absolute_url(self): return reverse('bookmyslot:detail',kwargs={'pk':self.pk}) views.py from django.shortcuts import render # Create your views here. from .models import Booking,Customer from .forms import BookingForm from django.urls import reverse,reverse_lazy from django.contrib import messages from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import (ListView,DetailView,CreateView,UpdateView,DeleteView,TemplateView) class AboutView(TemplateView): template_name = 'about.html' class HomeView(TemplateView): template_name = 'index.html' class BookingCreate(LoginRequiredMixin,CreateView): login_url = '/login' redirect_field_name = 'bookmyslot/booking_detail.html' model … -
KeyError in Safari, but it works in Firefox
Please help solve the problem! I am writing an online store in Django, it was necessary to split it into retail/wholesale with keeping one base. At one point safari started giving me KeyError, but in Firefox everything continues to work according to the logic. What could be the reason? Error looks like: "KeyError at /cart/retail/ 'price' Request Method: GET Request URL: http://127.0.0.1:8000/cart/retail/ Django Version: 3.2.7 Exception Type: KeyError Exception Value: 'price' Exception Location: /Users/vitbashy/Desktop/Projects/dekor-keramika/dekor_keramika/cart/**cart.py**, line 69, in __iter__ Python Executable: /Users/vitbashy/Desktop/Projects/dekor-keramika/venv/bin/python Python Version: 3.9.6" cart.py: def add_retail(self, product, quantity=1, update_quantity=False): # Add a product to cart or update its quantity product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = { 'quantity': 0, 'price': str(product.price_retail) } if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): # Updating the cart session self.session[settings.CART_SESSION_ID] = self.cart # Mark the session as "modified" to make sure it is saved self.session.modified = True def remove(self, product): # Removing an item from the cart product_id = str(product.id) if product_id in self.cart: del self.cart[product_id] self.save() def __iter__(self): """ Search for items in the shopping cart and retrieve products from the database. """ product_ids = self.cart.keys() # Receive product items and add them to cart … -
Limit forms foreign key to a choices in related model
I am working on creating a form but stuck at this issue. I have several businesses in the Business Model. Each Business has its own Service in Services Model. The User is tied to only one Business. Both Business, Service have a relationship. My Challenge I have a Service Request Form. When I present this Service Request Model Form, I want to show only services for One Business, that the customer/user belongs to. Please help me how this is possible. I thought it would be like "Instance = Business". I understood its not that simple. For example: Business1 has "Cars" and "Motor Bikes" as Services and Business2 has "nails" and "Hair Spa" as services. If a user from Business1 logged in and opened Service Request Form, She/He should see only "Cars" and "Motor Bikes" in service selection drop down. ''' # class Service(models.Model): class Business(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=100) active = models.BooleanField(default=True) class BusinessUser(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business') class Services(models.Model): business = models.ForeignKey(Business, on_delete=models.CASCADE, related_name='business_services') name = models.CharField(max_length=15) active = models.BooleanField(default=True) class ServiceRequest(models.Model): business = models.ForeignKey(Business, on_delete=models.DO_NOTHING) service = models.ForeignKey(Service, on_delete=models.DO_NOTHING, blank=True) requester_name = models.CharField(max_length=15) class ServiceRequestForm(forms.ModelForm): class Meta: model = ServiceRequest fields … -
Local variable 'cid' referenced before assignment
Im trying to add a payment method. I also add Getway and Get Success Message. Now I want to show success message with cid and name in my template page. When I want to get context data, I got This Error. ** Local variable 'cid' referenced before assignment. ** My code: class CheckoutSuccessView(View): model = Transaction template_name = 'success.html' def get(self, request, *args, **kwargs): # return render(request, self.template_name,{'transaction':transaction}) return HttpResponse('nothing to see') def post(self, request, *args, **kwargs): data = self.request.POST try: Transaction.objects.create( name = data['value_a'], cid = data['value_b'], tran_id=data['tran_id'], val_id=data['val_id'], amount=data['amount'], card_type=data['card_type'], card_no=data['card_no'], ... ... ) messages.success(request,'Payment Successfull') name = data['value_a'], cid = data['value_b'], except: messages.success(request,'Something Went Wrong') context = { 'cid': cid, 'name' : name } return render(request, 'success.html', context) -
How to display all celery tasks in django template
I have a django web application that uses celery to run tasks. I want to display all the tasks that are in queue and tasks that are currently running in a django template. I looked at this link. But I am not sure how to get this into the django views. This is my views.py file def views_tasks(request): # get the list of tasks here and send it to the context context = {} return render(request, 'tasks.html',context=context) How do I go about doing this? Thanks -
keyerror in drf serializer
I have a serializer like this : class LocationSerializer(serializers.Serializer): lat = serializers.DecimalField(max_digits=9, decimal_places=6), lng = serializers.DecimalField(max_digits=9, decimal_places=6), term = serializers.CharField(max_length=100) in views.py : @api_view(['POST']) def get_prefer_locations(request): serilizer = LocationSerializer(data=request.data) if serilizer.is_valid(): print(request.data) location_obj=Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term']) address = location_obj.convert_latandlong_to_address() and this is the Location class that i have defined : class Location: def __init__(self, latitude,longitude,term): self.lat = latitude, self.lng=longitude, self.term=term def convert_latandlong_to_address(self): geolocator = Nominatim(user_agent="geoapiExercises") location = geolocator.reverse(self.latitude+","+self.longitude) address = location.raw['address'] return address when i printed request.data in terminal i got this : {'lat': '29.623411959216355', 'lng': '52.49860312690429', 'term': 'cafe'} but i got this error : File "/home/admin1/mizbanproject/location/preferlocation/api/views.py", line 15, in get_prefer_locations location_obj = Location(serilizer.data['lat'],serilizer.data['lng'],serilizer.data['term']) KeyError: 'lat' and this is the json i am sending via postman: { "lat":"29.623411959216355", "lng":"52.49860312690429", "term":"cafe" } -
Testing HTML Templates/Paths to make sure they load properly
I'm currently using this code that I found on a separate post from Stack Overflow, but when I run it, it throws the error that pattern has no child regex. class UrlsTest(test.SimpleTestCase): def test_responses(self, allowed_http_codes=[200, 302, 405], credentials={}, logout_url="logout", default_kwargs={}, quiet=False): """ Test all pattern in root urlconf and included ones. Do GET requests only. A pattern is skipped if any of the conditions applies: - pattern has no name in urlconf - pattern expects any positinal parameters - pattern expects keyword parameters that are not specified in @default_kwargs If response code is not in @allowed_http_codes, fail the test. if @credentials dict is specified (e.g. username and password), login before run tests. If @logout_url is specified, then check if we accidentally logged out the client while testing, and login again Specify @default_kwargs to be used for patterns that expect keyword parameters, e.g. if you specify default_kwargs={'username': 'testuser'}, then for pattern url(r'^accounts/(?P<username>[\.\w-]+)/$' the url /accounts/testuser/ will be tested. If @quiet=False, print all the urls checked. If status code of the response is not 200, print the status code. """ module = importlib.import_module(settings.ROOT_URLCONF) if credentials: self.client.login(**credentials) def check_urls(urlpatterns, prefix=''): for pattern in urlpatterns: if hasattr(pattern, 'url_patterns'): # this is an included urlconf … -
Django CreateView form can't submit
My views: class AddSuiteView(CreateView): model = TestSuite form_class = TestSuiteForm def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) my_TestCase = TestCase.objects.all() context['my_testcase'] = my_TestCase return context def get_success_url(self): return reverse("integratedTest:testSuite") My form.py: class TestSuiteForm(forms.ModelForm): class Meta: model = TestSuite fields = ( 'name', 'test_case_list', 'created_by' ) My model is: class TestSuite(models.Model): name = models.CharField(max_length=200) test_case_list = models.CharField(max_length=200, validators=[validate_comma_separated_integer_list], default = "1") created_by = models.CharField(max_length=200, default = "anyone") create_datetime = models.DateTimeField("TestSuite created on", auto_now = True) My html is a bit complex: <form method="post"> {% csrf_token %} <script src="https://code.jquery.com/jquery-3.5.0.min.js"></script> <h1 class="addsuite">Create Test Suite:</h1> <p> <label for="id_name">Name:</label> <input type="text" id="id_name" name="name" required><br><br> </p> <p> <label for="id_test_case_list_select_l">test_case_list(double click to add):</label><br><br> <select size=10 name="test_case_list_select_l" id="id_test_case_list_select_l" class="multiselect" multiple="multiple" > {%for case in my_testcase %} <option value="{{case.name}}" >{{case.name}}</option> {%endfor %} </select> <br><br> <label for="id_test_case_list_select_r" >test case selected(double click to remove):</label><br> <select size=10 name="test_case_list_select_r" id="id_test_case_list_select_r" class="multiselect" multiple="multiple" > </select> <input type="hidden" id="id_test_case_list" name="test_case_list" value=""> <p>&#8679; <input type="button" id="addTestcaseByOne" value="++" onclick="addTestcaseByOne"> </p> <p>&#8681; <input type="button" id="decreaseTestcaseByOne" value="--" onclick="decreaseTestcaseByOne"> </p> <br><br> </p> <p> <label for="id_created_by">created_by:</label> <input type="text" id="id_created_by" name="created_by" "><br><br> </p> <input type="submit" value="Save"> </form> <script> $(document).ready(function() { $("#id_test_case_list_select_l").dblclick(function() { var selectedItem = $('#id_test_case_list_select_l').find(":selected").text() $('#id_test_case_list_select_r').append ('<option value= ' + selectedItem + '"*1">'+selectedItem+'*1</option>') var old_val = $('#id_test_case_list').val() //alert("old_val" + old_val) var new_val … -
Is there a function that updates var value in django views.py?
Good day, I am very new to django and programming in general. Is there a function that updates variable values based on user input? I would like to write a function that displays output to html using HttpResponse and waits for user input... on my views.py, I have the following: def getResponse(request): userMessage = request.GET.get('userMessage'); return HttpResponse("Good to see you. May I know your name?") name=input(userMessage) return HttpResponse("Good to know you", name, ". I can tell you your age if you tell me which year you were born") year=input(userMessage) age = ((datetime.date.today().year) - year) return HttpResponse("You are", age "old") My Html is looking like this: <div id="userInput"> <form id="user_Input" method="post"> {% csrf_token %} <input type="text" name="userMessage" id="textInput" placeholder="Type your message..."> <input type="submit" id="buttonInput" name="" value="Send"> </form> </div> </div> <script type="text/javascript"> function getUserResponse(){ var userText =$('#textInput').val(); var userHTML = "<p class='userText'>User: <span>"+userText+"</span></p>"; $('#textInput').val(""); $('#pal').append(userHTML); $.get('/qpal/getResponse',{userMessage:userText}).done(function(data){ var returnedMessage = "<p class='botText'> Pal: <span>"+ data +"</span></p>"; $('#pal').append(returnedMessage); }) } $('#buttonInput').click(function(e){ e.preventDefault(); getUserResponse(); }) </script> The html works, however it is only displaying the first HttpResponse value everytime like shown in the picturescreenshot. In pure python environment the code will work perfectly using only print and input and I am trying to make it … -
is it possible to customize django 3 nav_sidebar menu as a custom group?
I'd like to customize the left sidebar with my own caption and models list. The default nav_sidebar is: myapp A - model A.1 - model A.2 myapp B - model B.1 - model B.2 Is it possible to have this following instead? Custom name - model A.1 - model B.1 I'd appreciate any feedback -
UnboundLocalError at /register/ local variable 'form_value' referenced before assignment
I'm trying to get into it the register page but i cant views.py def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') context = {'form_key':form_value} return render(request, 'accounts/register.html', context) Traceback File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 26, in registerPage context = {'form_key':form_value} UnboundLocalError: local variable 'form_value' referenced before assignment Maybe have problem with indentation, please help me -
How to change queryset to dataframe in an environment where pandas is not installed or how to run code without pandas
I'm running the code in an environment where pandas cannot be installed. What do I need to fix to make the code below work in an environment without pandas ? (This is the code that ran successfully when tested in the environment where pandas is installed.) def download_supporting(request): locale.setlocale(locale.LC_ALL, 'ko_KR.UTF-8') supportings = Supporting.objects.filter(is_deleted='0').order_by('register_date') \ .annotate(register_date_str=Cast('register_date', CharField())) \ .values_list(register_date_str', 'name', 'sex', 'age', 'memo') #supportings = pd.DataFrame.from_records(supportings) #supportings = supportings.rename(columns={0: 'register_date_str', # 1: 'name', # 2: 'sex', # 3: 'age', # 4: 'memo'}) ----> Commented out to run without pandas. output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() merge_format = workbook.add_format({'bold': True, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True}) for supporting in supportings[0].unique(): ----> 'tuple' object has no attribute 'unique' u = supportings.loc[supportings[0] == supporting].index.values + 1 if len(u) < 2: pass # do not merge cells if there is only one supporting day else: worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Day'], merge_format) workbook.close() output.seek(0) supportings.set_index(supportings.columns[:-1].tolist()).to_excel('supporting.xlsx') -
How can I successful POST a Choice that is linked to a Question in a Poll's API in Django?
I am creating a survey / voting api, I can successfully POST question but I am getting the following error Choice() got an unexpected keyword argument 'question' when I try to create a choice that is linked to a question, I can't figure it out. These are the models from django.db import models import datetime from django.utils import timezone # Модели для опоросов class Question(models.Model): poll_question = models.CharField(max_length=255, blank=False) title = models.CharField(max_length=255, blank=True) start_date = models.DateTimeField('date published', blank=False) def __str__(self): return self.poll_question def published_not_longage(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.start_date <= now #Модель для Выбора class Choice(models.Model): poll_question = models.ForeignKey(Question, on_delete=models.CASCADE) poll_question_choice = models.CharField(max_length=255) votes = models.IntegerField(default=0) The choices serializer class ChoiceSerializer(serializers.Serializer): poll_question_choice = serializers.CharField(max_length=255) def create(self, validated_data): return Choice.objects.create(**validated_data) #The choices view - The error is arising when I pass in the question instance in the serializer.save() method. @api_view(['POST']) def choice_details(request, pk): question = Question.objects.get(pk=pk) # question = get_object_or_404(Question, pk=pk) serializer = ChoiceSerializer(data=request.data) if serializer.is_valid(): poll_question_choice = serializer.save(question=question) return Response(ChoiceSerializer(poll_question_choice).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)