Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error: unindent does not match any outer indentation
my django code shows me this error unindent does not match any outer indentation, read that it's about tabs and spaces, but nothing works for me. I will appreciate if someone take a look into my code. views.py from django.shortcuts import render, redirect from django.http import HttpResponse # Create your views here. from .models import * from .forms import OrderForm from .filters import OrderFilter def home(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending } return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk_test): customer = Customer.objects.get(id=pk_test) orders = customer.order_set.all() order_count = orders.count() **myFilter = OrderFilter()** context = {'customer':customer, 'orders':orders, 'order_count':order_count, 'myFilter': myFilter} return render(request, 'accounts/customer.html',context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': #print('Printing POST:', request.POST) form = OrderForm(request.POST) #sending data into the form if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): #prefill forms after click update order = Order.objects.get(id=pk) form = OrderForm(instance=order) #save the changes if request.method == 'POST': form = OrderForm(request.POST, instance=order) #sending data into the form if form.is_valid(): form.save() … -
Render svg content Django
I have static svg file inside my images folder. I'd like to render actual svg content inside my anchor tag. I tried {% static "images/blog/facebook-icn.svg" %} and it just parse it as a string. what is the function to render actual content of svg file inside html? The code: {% load staticfiles %} <a href="http://www.facebook.com/sharer/sharer.php?u=my-site{{ request.get_full_path|urlencode }}" target="_blank" class="facebook"> {% static "images/blog/facebook-icn.svg" %} </a> -
How set Foreign key value as email not ID?
I have User Model and Favorite Product Model. I have link as ID to user in Favorite Product model. Can I change ID link to email? This is my User Model. class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) surname = models.CharField(max_length=255, default='Фамилия') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) favorite_product = models.ForeignKey( 'FavoriteProduct', related_name='favorite_products_for_user', on_delete=models.SET_NULL, null=True ) objects = UserManager() USERNAME_FIELD = 'email' This is my Favourite Product model class FavoriteProduct(models.Model): """Favorite product object""" created = models.DateTimeField(auto_now_add=True, null=True) product = models.ForeignKey( 'Product', related_name='favorite_products', on_delete=models.CASCADE, null=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) If you do not undersatnd me? I uploaded picture.png file.enter image description here -
Django: def save() in models.py
I'm trying to add the save-function inside my models.py, but it seems I'm doing something wrong. The user has to type the first- and last-name. Without him or her entering any more data, another field inside my models.py should be filled with a combination from these fields. models.py: class Coworker(models.Model): first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) full_name = models.CharField(max_length=100, null=False, blank=False) def save(self, *args, **kwargs): self.full_name = self.first_name + " " + self.last_name super().save(*args, **kwargs) Is this even possible? Thanks for all your help. Have a nice weekend! -
Django Video Encoding package not converting videos
hey guys I am trying to add the django-video-encoding package, but it doesn't seem to be working. I have followed exactly as per the documentation. Can someone help with checking the code I have if I missed anything? This is the link to the package: https://github.com/escaped/django-video-encoding Can anyone tell me where I went wrong? I couldn't see any tutorials or much info regarding this package but it seems like its the only one there. I have given the path to ffmpeg like this (am not sure whether its the right way). this is in settigs. VIDEO_ENCODING_FFMPEG_PATH = "c:\\ffmpeg\\bin\\ffmpeg.exe" in my signals.py I have this. @receiver(post_save, sender=VideoPost) def convert_video(sender, instance, **kwargs): enqueue(tasks.convert_all_videos, instance._meta.app_label, instance._meta.model_name, instance.pk) print('Done converting!') and this prints after I upload a video, but the conversion is not happening. -
Django initialize model formset with instances
I have following model: class ModelA(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) And it is used in modelformset: ModelAFormSet = generic_inlineformset_factory( ModelA, form=AddModelAForm, extra=2) where AddModelAForm looks like this: class AddModelAForm(forms.ModelForm): selected = forms.BooleanField(required=False) class Meta: model = ModelA fields = ['id'] and then initialized following way: formset = ModelAFormSet( queryset = ModelA.objects.none(), initial=[{'id':16, 'selected': True}, {'id': 32, 'selected': False}]) I would like to use in template instance, instead of actual model fields. Something like this: {{formset_form.id}} {% with formset_form.instance as modelA %} Name: {{modelA.name}} Description: {{modelA.description}} {{formset_form.selected}} {% endwith %} Which is working with such instantiation of ModelAFormSet: formset = ModelAFormSet(queryset=ModelA.objects.all()) I know I could use change Meta class of AddModelAForm to have fields = ['id', 'name', description'] and then initialize those values. But in this case I can no longer use instance, but regular fields values (e.g. {{formset_form.name.value}}). And because of that I need to have something like this in clean() method of my form: def clean(self): try: del self.errors['name'] del self.errors['description'] except KeyError: pass I'd like to ask if there is any better way to have such formset initialized and doesn't need to remove errors explicitly? -
Django 3.1: OperationalError - No Such Column/Table
I've been solving this problem for the entire day. My code in my models.py is the following: from django.db import models from django.contrib.auth.models import User from users.models import TeacherProfile, StudentProfile class Course(models.Model): name = models.CharField(max_length=100) desc = models.TextField() short_code = models.CharField(max_length=5) teacher = models.ForeignKey(TeacherProfile, null=True, on_delete=models.SET_NULL) students = models.ManyToManyField(StudentProfile) def __str__(self): return self.name class Partition(models.Model): name = models.CharField(max_length=20) chunk = models.FloatField() result = models.FloatField(blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.name class Activity(models.Model): title = models.CharField(max_length=100) content = models.TextField() file = models.FileField(blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) parent = models.ForeignKey(Partition, on_delete=models.CASCADE) def __str__(self): return self.title class Grade(models.Model): grade = models.FloatField() remarks = models.CharField(max_length=200, blank=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) I've ran the following commands: python manage.py makemigrations python manage.py migrate I even written the following command as per my research to other StackOverFlow questions related to this: python manage.py migrate --run-syncdb Only the Course table worked. The Activity and the Grade table received OperationalError - No Such Column and the Partition Table got an OperationalError - No Such Table. Activity OperationalError at /admin/course/activity/ no such column: course_activity.parent_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/course/activity/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such column: course_activity.parent_id Exception Location: … -
Bad request 400 while trying to do partial update with UpdateAPIView
I am using DRF UpdateAPIView to take in PATCH method and partially update my model. It should by default handel correctly partial update but i somehow get Bad request error. What could be issue here? View: class ProfileViewUpdate(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'bio', 'name', 'email', 'sport', 'location', 'image') -
How to get GDAL to work with Google GCLOUD
I am getting the below error trying to deploy my app to gcloud app engine. The whole problem is from trying to add the GDAL library to my app. File "/opt/python3.7/lib/python3.7/ctypes/init.py", line 377, in getattr func = self.getitem(name) File "/opt/python3.7/lib/python3.7/ctypes/init.py", line 382, in getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 I followed all the directions I could possibly find online. But nothing seems to work at all. Here is my app.yml files: runtime: custom entrypoint: gunicorn -b :8080 app.wsgi env: flex # any environment variables you want to pass to your application. # accessible through os.environ['VARIABLE_NAME'] env_variables: ... beta_settings: cloud_sql_instances: site:asia-northeast2:site-db handlers: - url: /.* script: auto secure: always manual_scaling: instances: 1 runtime_config: python_version: 3 And Dockerfile: FROM gcr.io/google-appengine/python #FROM python:3.7 #FROM python:3.8.0-slim-buster EXPOSE 8080 ENV PYTHONUNBUFFERED 1 # Install GDAL dependencies #RUN apt-get update && apt-get install --yes libgdal-dev RUN apt-get update && apt-get install --reinstall -y \ #libopenjp2-7 \ #libopenjp2-7-dev \ #libgdal-dev \ binutils \ gdal-bin \ python-gdal \ python3-gdal # Update C env vars so compiler can find gdal #ENV CPLUS_INCLUDE_PATH=/usr/include/gdal #ENV C_INCLUDE_PATH=/usr/include/gdal RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal # Create a virtualenv for dependencies. This isolates these packages from # system-level packages. # … -
Best way to implement background “timer” functionality in Python/Django
I am trying to implement a Django web application (on Python 3.8.5) which allows a user to create “activities” where they define an activity duration and then set the activity status to “In progress”. The POST action to the View writes the new status, the duration and the start time (end time, based on start time and duration is also possible to add here of course). The back-end should then keep track of the duration and automatically change the status to “Finished”. User actions can also change the status to “Finished” before the calculated end time (i.e. the timer no longer needs to be tracked). I am fairly new to Python so I need some advice on the smartest way to implement such a concept? It needs to be efficient and scalable – I’m currently using a Heroku Free account so have limited system resources, but efficiency would also be important for future production implementations of course. I have looked at the Python threading Timer, and this seems to work on a basic level, but I’ve not been able to determine what kind of constraints this places on the system – e.g. whether the spawned Timer thread might prevent the … -
django clear stale cache entry
I am using database as cache backend. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', } } The problem is that after few times, there are stale entries which are not getting cleared up. Do I need to configure something to get them cleared once they are stale (past their expiration date)? Or need to setup some job to clear? I tried using cache.clear(). But it clears up the non-expired entries as well. -
How to hide all forms in a formset except the clicked one in django template
I am new to Django. I recently started to work with Django-formset, I have 12 forms in Django-formset, each form has atleast 20 fields. My requirement is make a user-friendly design. I decided to make 12 buttons in a row corresponding to each form, initially all the forms will be hidden. When I click on one button, let's say first button then only form corresponding to that button will show up in the same page and rest of the forms will hide. If user click on the same button again then the form should collapse, if user click on other button then form corresponding to that button should show and rest of the forms should hide. After a lot of reading online I could not find a solution to this problem but I came to know that I need to use jQuery or javaScript to solve this. Here is what I have tried so far, but it only hide/show the form that I have clicked and not affect other forms. <form action="{% url 'my_formset' %}" method="POST"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h4> Time </h4> {% for form in formset %} <a id="{{forloop.counter}}-btn" class="btn btn-success mt-2">{{ form.time.value … -
Django got an unexpected keyword argument error
I am trying to create form to save some Data and I start it with model called it RegisterForm and created other model called Courses and I add new field "Course" to be foreignKey in the RegisterForm Model ,I am try submit the data through html form to database using PostgreSQL , and I got error "got an unexpected keyword argument" My models from django.db import models from django import forms class Courses(models.Model): CourseName = models.CharField(max_length =200) CourseTecher = models.CharField(max_length =100) CoursePrice = models.IntegerField() def __str__(self): return self.CourseName class RegisterForm(models.Model): name = models.CharField(max_length =100) phoneNumber = models.IntegerField() Course = models.ForeignKey(Courses ,related_name='Newreg', on_delete=models.CASCADE) def __str__(self): return self.name My Views from django.shortcuts import render from .models import Courses, RegisterForm def index(request): Course = Courses.objects.all() return render(request ,'index.html' , {'Course' : Course }) def register(request): name = request.POST['name'] phoneNumber = request.POST['phoneNumber'] Nclass = request.POST['Nclass'] NewRegisterForm = RegisterForm(name =name , phoneNumber =phoneNumber , Nclass =Nclass) NewRegisterForm.save() return render(request , 'bill.html') in html page {% for NewRegisterionClass in Course%} <option>{{NewRegisterionClass.CourseName}}</option> {% endfor %} and the error is TypeError at /register RegisterForm() got an unexpected keyword argument 'Nclass' Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 3.1 Exception Type: TypeError Exception Value: RegisterForm() got an unexpected … -
Need suggestions : Django UserProfile geographic address to connect with others users
I hope you're well, I'm looking for a plugin or a tutorial for : a- allow my users to fill in their address on their profile. The best would be to have a map on which they can identify their address or like on the UberEats site. b- to be able to find the closest users according to their address. If you have any ideas, I'm interested, I have already made the profile on Django, all I need is the address field. -
Getting MultiValueDictError in fetch GET data django
I am trying to fetch GET data receiving from an HTML form. But it is giving me MultiValueDictError. It is also saying During handling of the above exception, another exception occurred: My HTML code : <!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <form action="home_redirect/fd" id="redirect" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" value={{user}} name="user"> <input type="submit"> </form> <script> document.getElementById("redirect").submit() </script> </body> </html> My views.py : def home(request): user = request.GET['user'] return render(request, 'main.html', {'login': user}) -
how to make urls in django rest framework case insensitive
How to make urls case insensitive with certain parameters passed For example, assuming Stock model has a ticker. All links below should find the same ticker content, right now they are case sensitive and try to search for different values: /stocks/AAPL /stocks/aapl /stocks/AaPl views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_field = "ticker" @action(detail=True, methods=["get"], url_path="is", url_name="is") def get_income_statement(self, request, *args, **kwargs): is_qs = IncomeStatement.objects.filter(ticker=self.get_object()) serializer = IncomeStatementSerializer(is_qs, many=True) return Response(serializer.data) @action(detail=True, methods=["get"], url_path="bs", url_name="bs") def get_balance_sheet(self, requests, *args, **kwargs): bs_qs = BalanceSheet.objects.filter(ticker=self.get_object()) serializer = BalanceSheetSerializer(bs_qs, many=True) return Response(serializer.data) @action(detail=True, methods=["get"], url_path="cf", url_name="cf") def get_cashflows_statement(self, requests, *args, **kwargs): cf_qs = CashflowsStatement.objects.filter(self.get_object()) serializer = CashflowsStatementSerializer(cf_qs, many=True) return Response(serializer.data) class IncomeStatementDetail(viewsets.ModelViewSet): queryset = IncomeStatement.objects.all() serializer_field = IncomeStatementSerializer class BalanceSheetDetail(viewsets.ModelViewSet): queryset = BalanceSheet.objects.all() serializer_field = BalanceSheetSerializer class CashflowsStatementDetail(viewsets.ModelViewSet): queryset = CashflowsStatement.objects.all() serializer_field = CashflowsStatementSerializer urls.py router = DefaultRouter() router.register(r"stocks", views.StockViewSet) urlpatterns = router.urls models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] -
How to add record after bulk_create objs in django?
I want to add a record for each model object that created by bulk_create method of django, how can I make it work? It seems rewriting save method of model doesn't work. # WarningAccountsSpend class WarningAccountsSpend(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) date = models.IntegerField(blank=True, null=True) account_type = models.IntegerField(blank=True, null=True) entity = models.CharField(max_length=255, blank=True, null=True) spend_cap = models.BigIntegerField(db_column='spend cap', blank=True, null=True) # Field renamed to remove unsuitable characters. balance = models.BigIntegerField(blank=True, null=True) is_spend_over_yesterday = models.IntegerField(blank=True, null=True) growth_rate = models.IntegerField(blank=True, null=True) account_create_time = models.DateTimeField(blank=True, null=True) is_violated = models.IntegerField(blank=True, null=True) note = models.CharField(max_length=255, blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'warning_accounts_spend' unique_together = (('account_id', 'date'),) ordering = ["-spend"] def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # add operate log # It seems not work here super(WarningAccountsSpend, self).save(force_insert=False, force_update=False, using=None, update_fields=None) # bulk_create model obj WarningAccountsSpend.objects.bulk_create([...], ignore_conflicts=True) How can I add some other operation for object that I bulk created. Thanks. -
function gives wrong total of a week day between a date range in django
I have been looking at this function for hours and I can't seem to figure out why it is not giving me the result I am expecting. I have a test that generates a datetime start and datetime end. I want to calculate how many 'mondays' or any given day occur between that time range. def day_count(week_day, start, end): if week_day == 1: day = 6 else: day = week_day - 2 num_weekdays, remainder = divmod((end - start).days, 7) if (day - start.weekday()) % 7 <= remainder: return num_weekdays + 1 else: return num_weekdays to replicate, this is the data that I give it: end: 2020-08-22 00:00:00+02:00 start: 2020-08-20 22:15:55.371646+00:00 weekday: 6 I expect to give back num_weekdays = 1 but I get num_weekdays = 0 I have no clue how I can possibly fix this, num_weekdays and remainder are 0 when I debug as well. This is how i am calling the function: total_day_count = day_count(params['dt_start__week_day'], params['dt_start__gte'], params['dt_end__lte']) and this is how i get the params: params = {} if self.request.GET.get('day') == 'Today': params['dt_start__week_day'] = (timezone.now().weekday() + 1) % 7 + 1 elif is_valid_queryparam(self.request.GET.get('day')): day_of_the_week = self.request.GET.get('day') params['dt_start__week_day'] = (int(day_of_the_week) + 1) % 7 + 1 else: params['dt_start__week_day'] = … -
can't show the button inside the tooltip in bootstrap 4
As i am adding the button inside the bootstrap 4 tooltip but the data is showing in the frontend but i can't see the button inside it. everything seems to be alright but it's not showing the button https://github.com/bestcsp/problem/issues function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + "<h5> Cart for your items in my shopping cart </h5><div class='mx-2 my-2'>"; var i = 1; for (var item in cart) { popStr = popStr + "<b>" + i + "</b>. "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + cart[item] + '<br>'; i = i + 1; } popStr = popStr + "</div> <a href='/market/checkout'><button class='btn btn-primary' id ='checkout'>Checkout</button></a> <button class='btn btn-primary' onclick='clearCart()' id ='clearCart'>Clear Cart</button> " console.log(popStr); // document.getElementById('popcart').innerHTML=popStr; document.getElementById('popcart').setAttribute('data-content', popStr); $('#popcart').popover('show'); } $('#popcart').popover(); updatePopover(cart); function updatePopover(cart) { console.log('We are inside updatePopover'); var popStr = ""; popStr = popStr + " Cart for your items in my shopping cart "; var i = 1; for (var item in cart) { popStr = popStr + "" + i + ". "; popStr = popStr + document.getElementById('name' + item).innerHTML.slice(0, 19) + "... Qty: " + cart[item] + ' '; i = … -
Do I need to use the DRF if I want to handle Token Authentication?
currently I plan on using AWS Cognito to handle my authentication for users. I want to do a simple registration and login. So far, I have created a function which calls cognito's initiate_auth method. Currently my flow works like this: User goes to /signup After filling the form, I create a new user in the cognito backend and send them a verification mail User is redirected to the /login page The login function in the backend calls initiate_auth with the username and password, and retrieves some token information like this {'AccessToken': '***', 'ExpiresIn': 3600, 'TokenType': 'Bearer', 'RefreshToken': '***', 'IdToken': '***'} I believe these tokens are in the JWT format. My question now is, what exactly do I do with this? I know that I need to store this data, securely, somewhere, but I'm not sure what the best practice is. I've heard that these tokens/data need to be saved in cookies in order to access them properly, but I also heard that there are some encryption problems, which is why I was looking for a library which handles this for me. I've come across this library: https://github.com/SimpleJWT/django-rest-framework-simplejwt However, it seems like in order to use this library, I need to … -
setting up server for django project with celery, tensorflow
I am working on a django project where when an image(design pattern) is uploaded, it does below: extract dominant colors and save it for later filtering put the uplaoded image on blender 3d model and render&save it as product image tensorflow extracting features from the image and save it as npy for later similar image search I set up celery to do above tasks and everything worked fine till I set up taks #3(tensorflow). After having task #3 I'm getting caution about memory allocation from tensorflow when starting up celery. So I'm guessing django and celery both runs tensorflow which I think it's waste of memory. I started thinking seperating them for django(A server) and for blender&tensorflow(B Server). My thoughts are: A & B server both have django running and shares the same database. A handles the main website and B handles image processing tasks including blender & tensorflow. when an image is uploaded -> A post to B -> B does work and save the result to shared database. I'm new to setting up this kind of structure and looking for advices. Thanks very much for reading and help.. -
Django view returns None during Ajax request
I have a Django web application and I'm trying to make an ajax call for uploading a large image. If I can upload the image I am trying to upload, I'll read the image with the pythonocc library and return the volume information. Since this process takes a long time, I am trying to do it using the django-background-tasks library. According to what I'm talking about, the ajax request that I am trying to take the image and send it to the view is as follows. var data = new FormData(); var img = $('#id_Volume')[0].files[0]; data.append('img', img); data.append('csrfmiddlewaretoken', '{{ csrf_token }}'); $.ajax({ method: 'POST', url: '{% url 'data:upload' %}', cache: false, processData: false, contentType: false, type: 'POST', data: data, }).done(function(data) { }); my view that will work after Ajax request; def uploadFile(request): if request.method == 'POST': file = request.FILES.get('img') filename = file.name key = 'media/' + filename s3_resource = boto3.resource('s3') bucket = s3_resource.Bucket('bucket') bucket.put_object(Key=key, Body=file) new_data = Data(author=request.user) new_data.save() data_id = new_data.id initial = CompletedTask.objects.filter(verbose_name=verbose) request.session['u_initial'] = len(initial) verbose = str(request.user) + '_3D' read_3D(data_id, key, filename, verbose_name = verbose) ###background-task function is called return redirect('data:uploadStatus') The view that calls this background task function should also redirect the view, which will … -
How can I access nested JSON object in Django Template properly?
I'm trying to access some info with dot notation but I'm getting a weird error. I'll try to explain as well as I can with my code. My relevant code from views.py file: def index(request): // removed "x" assignment as it is long an irrelevant month = (datetime.datetime.now()).strftime("%B") year = str(datetime.datetime.now().year) customers = table(x, month, year) return render(request, 'index.html', {'customers': customers, "month" : month, "year": year}) Here, I call my tablequery file with table function to return a JSON object of files I have from MONGODB(I am not using MONGODB as the default DB so I do it manually). My table function is as follows: def table(user, month, year): ///// Code to access DB removed curs = col.find() list_curs = list(curs) liststring = json.dumps(list_curs) liststring = re.sub("_", "", liststring) // have to remove _ from "_id" because template doesnt allow "_id" type of variable to be used with dot notation jt = json.loads(liststring) return jt Type of "jt" appears to be "list" in python when I print it. My relevant html code: <tbody> {% for customer in customers %} <tr class="gradeX"> <td>{{ customer.id }}</td> <td>{{ customer.isim }}</td> <td> {% for ekran in customer.ekranlar %} <li> {{ ekran }} DENEME {{ … -
Fixing Django admin Dashboard
Hi i was working on my Django admin interface and whenever i am clicking on any module on left rail it doesn't gets highlighted. Please let me know how i can high lite any module i.e dashboard,project, Duplicate Test case on left side after clicking it.enter image description here my dashboard I have clicked on any module say project, dashboard it gets opened up but the same module on left doesn't gets highlighted. -
Django Internal Server Error for only some pages
I'm working on a rock, paper, scissors game. I wanted to use a base.html page and extend it with the body of the other pages. It is working for 2 Pages but not for the other two. I can't find out why i get an Internal Server Error, why my CSS File is not loading. Has anyone seen or experienced this before?? [21/Aug/2020 09:36:49] "GET /yilmaz/game_view/ii/IQ HTTP/1.1" 200 1474 Internal Server Error: /yilmaz/static/yilmaz/base.css Traceback (most recent call last): File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\views\static.py", line 36, in serve fullpath = Path(safe_join(document_root, path)) File "D:\Studium\it\repo\webproject\yilmaz\web\lib\site-packages\django\utils\_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "c:\users\güney\appdata\local\programs\python\python38-32\lib\ntpath.py", line 78, in join path = os.fspath(path) TypeError: expected str, bytes or os.PathLike object, not NoneType [21/Aug/2020 09:36:49] "GET /yilmaz/static/yilmaz/base.css HTTP/1.1" 500 72104 The HTML of the page looks like this {% extends 'yilmaz/base.html' %} {% load static %} {% block content %} <h1>Schere, Stein, Papier</h1></br> <form method="POST"> <p>{{player_name}}Spiele gegen den Computer</p> {% csrf_token %} {% for key, value in context.items %} <p>{{key}}: {{value}}</p> {% endfor %} <label> <input type="radio" class="nes-radio" name="answer" checked value="0"/> <span>Schere</span> </label <br> <label> <input type="radio" …