Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to insert date time value into django model but getting invalid format error
I am trying to save my date time values from the datetimepicker into the Django model. I am getting a time format error. This is the error : time data '2020-09-17T10:05' does not match format "yyyy-mm-dd'T'HH:MM" My code: name = request.POST["name"] date1 = request.POST["start"] startdate = datetime.strptime(date1, "yyyy-mm-dd'T'HH:MM") start = startdate.isoformat() date2 = request.POST["end"] enddate = datetime.strptime(date2, "yyyy-mm-dd'T'HH:MM") end = enddate.isoformat() e = Events(name=name, start=start, end=end) e.save(); -
Static files not served in Django "dockerized" (dev environnement)
I try to "dockerize" a Django apps. All works fine except static files that are not served. I run docker exec -it coverage_africa_web_1 python manage.py collectstatic command and get the confirmation You have requested to collect static files at the destination location as specified in your settings: /usr/src/app/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Found another file with the destination path 'randomization/js/script.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. 140 static files copied to '/usr/src/app/static'. settings.base.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(BASE_DIR,'randomization_management/static'), os.path.join(BASE_DIR,'randomization_settings/static'), os.path.join(BASE_DIR,'randomization/static'), ) MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') .env.dev SECRET_KEY=************************************* DEBUG=1 DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] SQL_ENGINE=django.db.backends.postgresql SQL_DATABASE=db_dev SQL_USER=user SQL_PASSWORD=user SQL_HOST=db SQL_PORT=5432 DATABASE=postgres DJANGO_SETTINGS_MODULE=core.settings.dev docker-compose.yml version: '3.7' services: web: build: ./app restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/usr/src/app ports: - 8000:8000 env_file: - ./.env.dev depends_on: - db db: image: postgres:12.0-alpine restart: always volumes: - postgres_data:/var/lib/postgres/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=db_dev volumes: postgres_data: -
Django AbstractBaseUser - Unable login to the admin panel
I just wanted to create a custom user model but unfortunately, I can not log in to the admin panel successfuly. I don't know what is my mistake... models.py from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models here. class CustomUserManager(BaseUserManager): def create_user(self, email, username, first_name, last_name, password=None): if not email: return ValueError("User must have an email!") if not username: return ValueError("User must have an username!") if not first_name or not last_name: return ValueError("User must have a first name and last name!") user = self.model( email=self.normalize_email(email), username=username, first_name=first_name, last_name=last_name ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, first_name, last_name, password=None): user = self.create_user( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name ) user.is_active = True user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractBaseUser): email = models.EmailField(verbose_name="Email", max_length=60, unique=True) username = models.CharField(verbose_name="Username", max_length=40, unique=True) first_name = models.CharField(verbose_name="First Name", max_length=40) last_name = models.CharField(verbose_name="Last Name", max_length=40) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now=True) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email', 'first_name', 'last_name'] def has_perm(self, perm, obj=None): return self.is_admin # this methods are require to login super user from admin panel def has_module_perms(self, app_label): return True settings.py ... … -
Django views and templates and static html
I want to fabricate some HTML inside my view and then have it rendered in my template. What I see rendered is xyz and I just want to see xyz. What am I doing wrong? My template snippet: {{ normalized }} My view snippet: context["normalized"] = "<div>xyz</div>" template_name = "demo.html" return render(request, template_name, context) -
How can I filter django many to many models?
User Model class User(PermissionsMixin, AbstractBaseUser): name = models.CharField(max_length=511, null=True, blank=True) email = models.EmailField(unique=True) phone_number = PossiblePhoneNumberField(blank=True, null=True, default=None) addresses = models.ManyToManyField(Address, blank=True) is_staff = models.BooleanField(default=False) is_active = models.BooleanField(default=True) # is_featured = models.BooleanField(default=True) note = models.TextField(null=True, blank=True) date_joined = models.DateTimeField(default=timezone.now, editable=False) default_shipping_address = models.ForeignKey( Address, related_name='+', null=True, blank=True, on_delete=models.SET_NULL) default_billing_address = models.ForeignKey( Address, related_name='+', null=True, blank=True, on_delete=models.SET_NULL) reward_point = models.PositiveIntegerField(default=0, blank=True) last_login_user_ip = models.GenericIPAddressField(blank=True, null=True) last_login_user_country = CountryField(null=True, blank=True) USERNAME_FIELD = 'email' objects = UserManager() history = HistoricalRecords() Order Model class Order(models.Model): created = models.DateTimeField( default=now, editable=False) status = models.CharField( max_length=32, default=OrderStatus.UNFULFILLED, choices=OrderStatus.CHOICES) buyer_user = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, related_name='buyer_orders', on_delete=models.SET_NULL) vendor_users = models.ManyToManyField( settings.AUTH_USER_MODEL, blank=True, related_name='vendor_orders') order_updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='order_updated_user', on_delete=models.SET_NULL, blank=True, null=True) is_ready_for_aadibd = models.BooleanField(default=False) is_ready_for_shipment = models.BooleanField(default=False) is_delivered = models.BooleanField(default=False) language_code = models.CharField( max_length=35, default=settings.LANGUAGE_CODE) tracking_client_id = models.CharField( max_length=36, blank=True, editable=False) billing_address = models.ForeignKey( Address, related_name='+', editable=False, null=True, on_delete=models.SET_NULL) User and Order Model relationship is Many to Many Now I'm filtering User (seller) who has at least one order is is_delivered=True. And I Print on user list my HTML page. But Problem is I got user who has not order is_deliverd=True seller_list = User.objects.select_related('vendor_details').prefetch_related('vendor_orders').filter( groups__name="vendor", vendor_details__isnull=False, vendor_orders__is_delivered=True).order_by( 'vendor_details__company_name').distinct() Date filter: seller_list = seller_list.filter(vendor_orders__created__date__gte=default_last_month_start_days, vendor_orders__created__date__lte=default_last_month_last_days) Order Filter: if selected_orders: … -
Keeping record of foreign key fields selected in Python Django
For a project I have a two model Food and Profile. Each day one profile is created.When users adds forr the food_selected field is updated.Everytime I update the food_selected field in profile I want to keep a record of it. So that I can show all the food selected for a single day class Food(models.Model): name = models.CharField(max_length=200 ,null=False) def __str__(self): return self.name class Profile(models.Model): food_selected=models.ForeignKey(Food,on_delete=models.CASCADE,null=True,blank=True) How can i solve this problem. Thank You -
Create an invitation link using django rest framework?
am looking for some advice/Mentorship. wanted to create an invitation link for onboarding user to a company similarly slack does by sending company employees email so that they could directly join the company but using the Django rest framework is there any method that you can refer? see things that I have in my mind coming is that I can put company_id in hash inside a link and then when a user will come with that hash I can compare it and onboard the user. but in that case, there is no link_time_age I can compare! is there any method or any crypto algo in which is can convert company_UUID into some string and decode back into UUID and then compare it through icontains and similarly I can do with time and age of link? but first of all, is this the right approach? or how do people in a company like slack or telegram do? any kind of help will be really appreciated. See what am looking for certain guidance or any reference documentation. -
SearchRank on multiple SearchVectorFields
I'm trying to integrate full text search in my application. Referencing Django 3.1 documentation If I want to do weighted search across several fields I should do the following: from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector vector = SearchVector('body_text', weight='A') + SearchVector('blog__tagline', weight='B') query = SearchQuery('cheese') Entry.objects.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('rank') I decided to add SearchVectorField for the text columns I want to search later, but I think the documentation about how to work with those fields is not good enough and I can't find any reference on how to do the same as the query above, but using SearchVectorField Ideally I want something like the following objects = Post.objects.annotate( rank=SearchRank( F('title_text_vector', weight='A') + F('body_text_vector', weight='B'), SearchQuery('keyword1 keyword2 keyword3') ) ) objects.filter( < MORE QUERIES HERE > ) -
Django changing filters based on the selection made
I need some some help to find a good way to filter my Model. I want to display on a map just the objects which met the checked requirements. I passed my entire dictionary with all entries in my template and I want to create different select-boxes and dropdowns to filter it. For example I need a dropdown and after a value is selected I need to launch another forms with values from the result of the first dropdown selection. It's kind of what excel filters does for a table. I am thinking of using javascript but also I have read that Ajax could do this better. It's something like every E-commerce app does with the products, filtering a value changes the values of the other filters -
How can I render Django Form with vuetify?
In our regular Django form we can render the form with something like this {{form.username}} and we specify the widget within the constructor of the form class like name, class, id, label, etc. Now suppose that I have this form class class LoginForm(forms.Form): email = forms.EmailField(widget=forms.EmailInput()) password = forms.CharField(widget=forms.PasswordInput()) class Meta: fields = ['email', 'password'] def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.fields['email'].required = True self.fields['password'].required = True How can I render it with vuetify components in template? # example <v-text-field label="username"></v-text-field> <v-select></v-select> # something like that Thanks you -
How to calculate time duration between 2 time intervals in django rest framework
I am trying to display over time work duration of an employee ,i have standard shift hours and working time , i need to subtract shift hours from worked hours.Here is my code models class EmployeeShift(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) employee_attendance = models.ForeignKey(EmployeeAttendance, on_delete=models.CASCADE, blank=True, null=True) shift = models.ForeignKey(Shift, on_delete=models.CASCADE) start_date = models.DateField() end_date = models.DateField() class EmployeeAttendance(models.Model): employee = models.ForeignKey(Employee, related_name='employee_attendances', on_delete=models.CASCADE) check_in = models.TimeField() check_out = models.TimeField() def time_worked(self): check_in = datetime.datetime.combine(self.date, self.check_in) if self.check_out <= self.check_in: next_day = self.date+datetime.timedelta(days=1) else: next_day = self.date check_out = datetime.datetime.combine(next_day, self.check_out) time_worked = check_out-check_in return time_worked class Shift(ModelDateCommonInfo): name = models.CharField(max_length=150) start_time = models.TimeField() end_time = models.TimeField() def total_shift_hours(self): start_time = datetime.datetime.combine(self.created_at, self.start_time) if self.end_time <= self.start_time: next_day = self.created_at+datetime.timedelta(days=1) else: next_day = self.created_at end_time = datetime.datetime.combine(next_day, self.end_time) total_hours = end_time-start_time return total_hours views class EmployeeOverTime(generics.ListAPIView): authentication_classes = [authentication.TokenAuthentication] permission_classes = [permissions.IsAuthenticated] serializer_class = EmployeeOverTimeSerializer def get_queryset(self): start_date = self.request.query_params.get('start_date') end_date = self.request.query_params.get('end_date') employee_shift_map = EmployeeShift.objects.filter(employee__user=self.request.user,start_date__gte=start_date, start_date__lte=end_date).order_by('start_date') return employee_shift_map serializers class EmployeeOverTimeSerializer(serializers.ModelSerializer): employee_name = serializers.ReadOnlyField(source='employee_attendance.employee.user.first_name', read_only=True) time_worked = serializers.ReadOnlyField(source='employee_attendance.time_worked', read_only=False) total_shift_hours = serializers.ReadOnlyField(source='shift.total_shift_hours', read_only=False) class Meta: model = EmployeeShift fields = ['employee_name','time_worked','total_shift_hours'] Here i want to calculate over_time = time_worked - total_shift_hours , how can i achieve that, please help me … -
Django : using self.key where key is a variable in for loop
Good afternoon everyone. I have created a model in Django (code below) and I overwrite the save method to populate the fields. Inside the save methods I call a parser function which returns me a dict where the key is the name of the field in the model, and value, well is the value i'd like to write. The commented lines are working great (such as self.temp = parsedData['temp']) but I would like to refactor it. I thought of something like this but it's not working and I can't figure out why: for key, value in parsedData.items(): self.key = value Any ideas ? Thank you very much for your help :) class Data(models.Model): deviceId = models.ForeignKey('Device', to_field='deviceId', on_delete=models.CASCADE) rawData = models.CharField(max_length=24, blank=False, null=False) temp = models.DecimalField(max_digits=4, decimal_places=2, default=0) humidity = models.PositiveSmallIntegerField(default=0) pressure = models.DecimalField(max_digits=8, decimal_places=2, default=0) luminosity = models.PositiveSmallIntegerField(default=0) batteryLevel = models.PositiveSmallIntegerField(default=0) time = models.DateTimeField(null=False, default=now) def save(self, *args, **kwargs): """ Use the parser utility functions in utils to decode the payload """ firmware = Device.objects.get(deviceId=self.deviceId).firmware parsedData = parser(self.rawData, firmware) # Commented lignes below are working just fine # self.temp = parsedData['temp'] # self.humidity = parsedData['humidity'] # self.pressure = parsedData['pressure'] # self.luminosity = parsedData['luminosity'] # self.batteryLevel = parsedData['batteryLevel'] # How … -
Python - Django, Cannot install mysqlclient using pip
I'm new to Django and I'm facing some issues installing mysqlclient for my application running this command pip install mysqlclient I'm getting an error ModuleNotFoundError: No module named 'pip._internal.operations.build.wheel_legacy' Traceback (most recent call last): File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "E:\Python-projects\web_project\venv\Scripts\pip.exe\__main__.py", line 7, in <module> File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\cli\main.py", line 73, in main command = create_command(cmd_name, isolated=("--isolated" in cmd_args)) File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\commands\__init__.py", line 104, in create_command module = importlib.import_module(module_path) File "C:\Users\Ahmad\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\commands\install.py", line 37, in <module> from pip._internal.wheel_builder import build, should_build_for_install_command File "e:\python-projects\web_project\venv\lib\site-packages\pip\_internal\wheel_builder.py", line 11, in <module> from pip._internal.operations.build.wheel_legacy import build_wheel_legacy ModuleNotFoundError: No module named 'pip._internal.operations.build.wheel_legacy' I have Python 3.8.3 and pip 20.2.3 what is the cause of this error and how can I solve it? -
Django : Can a user affect/change the view of another user?
So I am trying to implement a wheel of fortune into my website, wich can be spun by clicking on a button. Now, if one user spins the wheel I want that the wheel also spins for all the other users. How can I achieve that one user can affect the view of another user (like spinning the wheel for another user)? -
Retrievel of data from Django Redis Cache is taking great amount of time
I'm trying to use Redis in caching my data so that DB calls are reduced. But the time taken for retrieval from cache is much large than the time which I'm getting when fetching the records without caching. I'm trying to store the django queryset object which consist of around 28k+ records and it's only going to increase as the data increases in the Database. I'm using Django - 3.0 DRF - 3.10.3 django-redis - 4.12 redis - 3.5.3 CodeWise: here is my settings.py for setting default cache CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': [ f'redis://{REDIS_HOST}:{REDIS_PORT}/1', f'redis://{REDIS_HOST}:{REDIS_PORT}/2' ], 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.ShardClient', 'CONNECTION_POOL_KWARGS': { 'max_connections': 100, 'retry_on_timeout': True }, 'PASSWORD': os.environ.get('REDIS_PASSWORD') } } views.py from rest_framework import viewsets from django.core.cache import cache from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT from rest_framework.response import Response CACHE_TTL = 60 * 1 class RecordsList(viewsets.ModelViewSet): __basic_fields = ('name', 'id') # queryset = Records.objects.all() serializer_class = RecordsNewSerializer http_method_names = ['get', 'post', 'put', 'delete'] filter_fields = __basic_fields search_fields = __basic_fields def get_queryset(self): if 'records' in cache: print('from cache') queryset = cache.get('records') else: print("Saving to Cache") queryset = Records.objects.all() # queryset = queryset[1:5] cache.set('records', queryset, timeout=CACHE_TTL) return queryset Here as you can see I'm saving … -
Best authentication way in django rest framework
I was using spring boot and my favorite way to authenticate users then was JWT, now i am learning django and there is a lot of ways to authenticate users and i am confused which one i should use, So what's the most common way to authenticate users in django? is it Basic authentication(Of course not), or built in auth token in django rest framework, or Djoser, or Oauth? I need to know the best way/the most popular way/the most way that used in real life applications? -
Private Chat Messaging django Such as facebook
I want to implement a private chat messaging app just like on linkedin or facebook as they have a chat bar on the bottom bar of the screen. I have created the chat application as a different app on the project as the user has to go the messages/ url in order to chat with the user, but in order to make chat boxes like that on facebook home page, do I have to make chat as a separate app or just make the chat app within my main app. I don't have any strategy to it. any help towards the approach would help alot. -
Django (DRF) Patch with composite key
I'm trying to update the model which has a composite key but I always run into a problem when the update itself is being run Here's the Model: class ProductOnClient(models.Model): productid = models.CharField(db_column='productId', max_length=255) clientid = models.ForeignKey(Host, models.DO_NOTHING, db_column='clientId') producttype = models.CharField(db_column='productType', max_length=16) targetconfiguration = models.CharField(db_column='targetConfiguration', max_length=16, blank=True, null=True) installationstatus = models.CharField(db_column='installationStatus', max_length=16, blank=True, null=True) actionrequest = models.CharField(db_column='actionRequest', max_length=16, blank=True, null=True) actionprogress = models.CharField(db_column='actionProgress', max_length=255, blank=True, null=True) actionresult = models.CharField(db_column='actionResult', max_length=16, blank=True, null=True) lastaction = models.CharField(db_column='lastAction', max_length=16, blank=True, null=True) productversion = models.CharField(db_column='productVersion', max_length=32, blank=True, null=True) packageversion = models.CharField(db_column='packageVersion', max_length=16, blank=True, null=True) modificationtime = models.DateTimeField(db_column='modificationTime') class Meta: db_table = 'PRODUCT_ON_CLIENT' unique_together = (('productid', 'clientid'),) The Serializer: class ProductOnClientSerializer(serializers.ModelSerializer): class Meta: model = ProductOnClient fields = "__all__" The View class ProductOnClientDetailView(generics.ListAPIView): queryset = ProductOnClient.objects.all() serializer_class = serializers.ProductOnClientSerializer def patch(self, request, clientid, productid): print("patch recevied") filter = { 'productid': productid, 'clientid': clientid } item = ProductOnClient.objects.filter(**filter)[0] ser = serializers.ProductOnClientSerializer(item, data=request.data, partial=True) if ser.is_valid(): ser.save() return JsonResponse(201, data=ser.data, safe=False) print(ser.errors) return JsonResponse(400, safe=False) When I send a request via patch with a json valid json body, I get a MySQL error that there's a duplicated error. django.db.utils.IntegrityError: (1062, "Duplicate entry '<productid>-<clientid>' for key 'PRIMARY'") Also the ProductID and ClientID is one string merge with … -
How to extend the Django auth.permissions model?
I have the following models. class Post(models.Model): content = models.TextField() class User(AbstractUser): pen_name = models.Charfield() I want to restrict a user to create a specific number of posts (let's say 10) and no more than that. Also, I want the permission to expire by a certain date. How can I extend the auth.permissions model to achieve this, for APIViews in DRF? -
Django RF 405 error for POST request on APIView without ending slash
I'm pretty new to Django Rest Framework and I've been investigating this issue but can't find any solution. I'm pretty sure it will be a small detail but I'm out of idea. I'm using DRF for a project. The team made the choice to not end URL paths with a ' / '. I have an endpoint linked to an APIView with a POST method. We want to do some stuff with a body sent in this POST. However calling it brings (Postman response): 405 Method Not allowed { "detail": "Method \"POST\" not allowed." } Putting a ' / ' at the end of the URL path works (Postman response for normal behavior): { "success": True, "message": "A message returned by the function in APIView" } urls.py from django.urls import path, include from runbook import views from rest_framework.routers import DefaultRouter router = DefaultRouter(trailing_slash=False) router.register(r'my_objects', views.ObjectViewset) urlpatterns = [ path('', include(router.urls)), path('my_objects/myFunction', views.MyFunctionView.as_view(), name="my-function") views.py class MyFunctionView(APIView): """ """ def post(self, request, format=None): try: MyObject.objects.get(slug=slugify(request.data['candidate_name'])) except MyObject.DoesNotExist: return Response(boolean_response(False)) else: return Response(boolean_response(True)) What I read and tried: Wrong type of view: 405 "Method POST is not allowed" in Django REST framework ; 405 “Method POST is not allowed” in Django REST … -
How to correctly setup Global Site Tag (gtag.js) for user_id tracking
I'm trying to implement user_id tracking on my website. I send emails to users with a user_id in their personal link which I need to track. As per the documentation I have added to gtag.js. gtag('config', 'MY_GA_MEASUREMENT_ID', { 'user_id': 'USER_ID' }); But when I go to my website with the following parameters ?user_id=1 I check my Tag Assistent to see which parameters are set and I see the following: uid = USER_ID And no mention at all of user_id or the value I supposedly gave to the parameter. I figured gtag would look for the value in the request but it looks like it accepts the value USER_ID as the string assigned in gtag.js. Does anyone have a clue about how to tackle this? -
Django REST Framework: Can you mix API views with template views?
I am developing a web application using Django and React, and using Django REST Framework to have them talk to each other. I am trying to create a Django view that could handle both AJAX requests from React code AND render Django HTML templates. To accomplish this, I am using the TemplateHTMLRenderer class from Django REST Framework that I found here. However, when I try to fetch() data from that view from React I do not receive any valid response. Here is my view: # URL: "/" class IndexView(APIView): renderer_classes = [TemplateHTMLRenderer] template_name = "dictionary/index.html" def get(self, request, format=None): definitions = Definition.objects.all() return Response({"definitions": definitions}) And here is how I am trying to fetch() datafrom React: componentDidMount() { fetch("/") .then(response => response.json()) .then(data => { this.setState({ definitions: data }); }, error => { this.setState({ alert('ERROR') }); }) } This code ends up displaying the alert "ERROR". Apparently, my view is not returning a valid JSON object. How can I change it to provide both rendering and API functionality? -
Django form of CreateView not accepting submission after setting default value
My django form made using CreateView is refusing to get submitted because of the inital value I prepopulated it with ( and which is correct ) This is my model : class Post(models.Model): #some code author = models.ForeignKey(User, on_delete=models.CASCADE) #some more code This is my view for the form : class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' def get_initial(self): initial = super(AddPostView, self).get_initial() #Setting the inital value of author in the form to the username of the logged in user initial['author'] = self.request.user.username return initial And this is the form being referred by the above view class PostForm(forms.ModelForm): class Meta: model = Post fields = ('x','y', 'author', 'z', 'm') widgets = { #some code 'author': forms.TextInput(attrs={'class': 'form-control','readonly':'readonly' }), #some more code } Now , When I am trying to submit the form , I am getting the error Select a valid choice. That choice is not one of the available choices. Why is this happening?d -
Error with Pillow library when dockerinzing Django app
I develop Django apps in Windows environnement and deploy my apps in production in Linux server. Python 3.8.3 I have a Django project that works (in dev and prod) and I try to "dockerize" it but I got an error when installing requirements.txt error seems to come from pillow library but even if I remove the Pillow==6.2.1 it doesn't change below the tracelog error requirements.twt Django==2.2.5 django-bootstrap4==1.0.1 django-crispy-forms==1.7.2 django-debug-toolbar==2.0 django-extensions==2.2.9 django-maintenance-mode==0.15.0 django-partial-date==1.2.2 django-safedelete==0.5.2 django-simple-history==2.7.3 django-widget-tweaks==1.4.5 Pillow==6.2.1 python-gettext==4.0 pytz==2019.2 reportlab==3.5.32 selenium==3.141.0 six==1.12.0 soupsieve==1.9.3 sqlparse==0.3.0 urllib3==1.25.6 xlwt==1.3.0 Creating network "coverage_africa_default" with the default driver Building web Step 1/10 : FROM python:3.8.3-alpine ---> 8ecf5a48c789 Step 2/10 : WORKDIR /usr/src/app ---> Using cache ---> 6e7b9e258aae Step 3/10 : ENV PYTHONDONTWRITEBYTECODE 1 ---> Using cache ---> 130a8576b1fa Step 4/10 : ENV PYTHONUNBUFFERED 1 ---> Using cache ---> 6e32ad96bd91 Step 5/10 : RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev ---> Using cache ---> c4010960001d Step 6/10 : COPY requirements/ requirements/ ---> 2591c3840465 Step 7/10 : RUN pip install --upgrade pip && pip install -r requirements/dev.txt ---> Running in defe0caa7725 Collecting pip Downloading pip-20.2.3-py2.py3-none-any.whl (1.5 MB) Installing collected packages: pip Attempting uninstall: pip Found existing installation: pip 20.1.1 Uninstalling pip-20.1.1: Successfully uninstalled pip-20.1.1 Successfully … -
I am rendering HTML template and sending context with it but in fetch response it is not reading that context and showing an error regarding JSON
I am sending context json object to template here in views.py all the things are working properly views.py def adminLogin(request): if request.method == 'GET': return render(request, 'admin/login.html') elif request.method == 'POST': data = request.POST username = data['username'] password = data['password'] user = authenticate(username=username, password=password) if user is not None and isAdmin(user.username): token, created = Token.objects.get_or_create(user=user) context = { "login" : "Done", "token" : token.key, "username" : user.username, "email" : user.email, } print("admin login done") context = dumps(context) return render(request, 'admin/login.html', {"context" : context}) else: print("login unseccesfull") return render(request, 'admin/not-login.html') the context i am catching in javascript and try to read context but i am failed to read that context even i am using JON.parse() and also JSON.stringify() both are not working Template HTML ` var loginForm = document.getElementById("adminLogin"); loginForm.addEventListener('submit', function(event) { event.preventDefault(); const formData = new FormData(this); const searchParams = new URLSearchParams(); for (var pair of formData) { searchParams.append(pair[0], pair[1]); } fetch('http://127.0.0.1:8000/my_admin/login/', { mode: 'cors', method: 'post', headers: { "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" }, body: searchParams, }) .then(res => { var context = JSON.stringify("{{context|escapejs") if (context.login === "Done"){ localStorage.clear(); localStorage.setItem("username", context.username); localStorage.setItem("token", context.token); localStorage.setItem("email", context.email); localStorage.setItem("login", "done"); window.location.href = "http://127.0.0.1:8000/my_admin/"; } }) .catch(function(error) { console.log(error) alert("Something went wrong"); }); }) </script>`