Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting errro A server error occurred. Please contact the administrator. in django python
I am new in python, when i run the app i am getting error A server error occurred. Please contact the administrator., can anyone please help me why i am getting this error ? Here i have added my whole code here, When i run this URL http://127.0.0.1:8000/crud/, It gives me that error, Can anyone please check my code and give me solution for that ? I tried lot to resolve this error but not getting any proper solution models.py import datetime from django.utils import timezone from django.db import connection class Question(): global cursor cursor = connection.cursor() def __str__(self): db_table = "polls_question" cursor.execute('''SELECT * FROM ''' + db_table) allquestions = cursor.fetchall(); print("1"); exit(); return self.allquestions class Choice(): def __str__(self): db_table = "polls_choice" cursor.execute("SELECT * FROM "+ db_table+" WHERE question_id = '1' ") choice_text = cursor.fetchall(); print("1"); exit(); return self.choice_text urls.py from django.urls import path from . import views app_name = 'crud' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), path('<int:question_id>/vote/', views.vote, name='vote'), ] Views.py from django.shortcuts import render # Create your views here. from django.http import HttpResponse, HttpResponseRedirect from django.template import loader from .models import Choice, Question from django.urls import reverse from django.shortcuts … -
How to iterate over an object of queryset if the object contains more than one character and spaces?
I tried to sort the string that was input through form by converting to list,but I am getting the error that the object is not iterable. How do I sort it without the inbuilt method ? models.py class LinkedList(models.Model): post = models.TextField(max_length=256) def __str__(self): l1=list(self.post.split(" ")) return str(l1) views.py def listform(request): form = LLForm(request.POST) if request.method == 'POST': if form.is_valid(): form.save(commit=True) list1 = LinkedList.objects.all().last() listll=list(list1) for i in range(1, len(listll)): key = listll[i] j = i-1 while j >= 0 and key < listll[j] : listll[j + 1] = listll[j] j -= 1 listll[j + 1] = key cont={'ll': listll} return render(request,'basicapp/linked.html',context=cont) else: form = LLForm() return render(request,'basicapp/listform.html',{'form':form}) -
How to group by and aggregate conditional in Django ORM
I have a Django query to get worklogs (hours) per employee. I want to split these up in weekday and weekend work. I have tried the following: qs = Worklog.objects.filter( day__range=[start,end] ).values( 'worker__fullname' ).annotate( weekday=Case( When(Q(day__week_day=1) | Q(day__week_day=7), then=1), default=0, output_field=IntegerField(), ) ).values( 'worker__fullname' ).annotate( weekdayAvg=Case( When(Q(weekday=0), then=Cast( Sum('effort')/Count('day', distinct=True)/60/60, FloatField() )), default=0, output_field=FloatField(), ), weekendAvg=Case( When(Q(weekday=1), then=Cast( Sum('effort')/Count('day', distinct=True)/60/60, FloatField() )), default=0, output_field=FloatField(), ) ).order_by('worker__fullname') which gives me the result weekdayAvg weekendAvg worker__fullname 0 9.125000 0.00 Klaus 1 0.000000 11.00 Klaus 2 6.977273 0.00 Peter 3 7.827586 0.00 Carl 4 0.000000 13.00 Carl 5 8.169643 0.00 Chris 6 0.000000 2.25 Chris However, the expected result would be more like: weekdayAvg weekendAvg worker__fullname 0 9.125000 11.00 Klaus 1 6.977273 0.00 Peter 2 7.827586 13.00 Carl 3 8.169643 2.25 Chris Any ideas how to achieve that? Also I am happy about some simplification of my query. Thanks! -
Redirecting URLs with Django to an external site
I am trying to redirect a number of pages to an external website away from my Django site. Normally I use htaccess for this kind of redirecting but in this case I can not change the configuration on the server and need to do the redirection within Django. Here are some examples: http://djangosite.com/products/10 -> http://example.com/products/10 http://djangosite.com/products/search -> http://example.com/products/search http://djangosite.com/products/10/edit -> http://example.com/products/10/edit http://djangosite.com/products/10/review -> http://example.com/products/10/review Can I do this redirection with Django? Here is what I have: path('products/<slug:slug>', RedirectView.as_view(url='http://example.com/products/'+slug, permanent=True)), But it returns NameError: name 'slug' is not defined Is there a way to do this? -
Django value too long for type character varying(20) error after migration from sqllite to postgree
I have a slightly weird issue: After migration from sqllite to postgree I am keep getting this error from db backend: “value too long for type character varying(20)” code of this field is like bellow boat_name = models.CharField(max_length=50, unique=True, db_index=True, verbose_name="Boat model", help_text="Please input boat model") all migrations has been made and ran max_length has been changed in PGADMIN to 50 – no effect. Command: ALTER TABLE boats_boatmodel ALTER COLUMN boat_name TYPE VARCHAR(50) has been ran -no effect. What it might be? Will changing to TextField with CharField widget be helpful in this case??? Thank you! -
UnboundLocalError: local variable 'region' referenced before assignment
I am trying to create an object but stacked with this problem, but it seams for me that i didn't make any mistake. def handle(self, *args, **options): for entry in get_dataset(): oblast = Place.objects.get_or_create(name=entry.get('OBL_NAME')) if entry.get('REGION_NAME') is not None: region = Place.objects.get_or_create(name=entry.get('REGION_NAME'), parent=oblast) if entry.get('CITY_NAME') is not None: city = Place.objects.get_or_create(name=entry.get('CITY_NAME'), parent=region) I could not understand why region variable doesn't work -
values_list() in query_set is showing only numbers but not the names of countries
I selected my field with 'values_list' which contains name of countries. But what I get is country_id numbers. I already used flat=True but it did not help any. my models.py: class Report(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) church_name = models.CharField(max_length=255) area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.CASCADE, null=True, blank=True) water_baptism = models.IntegerField(default=0) holy_ghost = models.IntegerField(default=0) def __str__(self): return '%s' % self.area def get_absolute_url(self): return reverse('users:report_view') my views.py: def report_cities(request, pk): countries = Report.objects.values_list('country', flat=True) context = { 'countries':countries } return render(request, 'users/report_countries.html', context) my html <h1>Report Countries</h1> {% for country in countries %} {{country}} {% endfor %} -
How to add a class to the input field of a Django widget using Django-Widget-Tweaks
So I have this piece of HTML code: <div class="custom-control custom-checkbox"> <input class="custom-control-input"> <label class="custom-control-label"></label> </div> And a Django Filter like this: class PlayerDetailPageFilter(FilterSet): field_position_relationship__field_position = filters.MultipleChoiceFilter(choices=FIELD_POSITION_CHOICES, widget=forms.CheckboxSelectMultiple) It uses the CheckboxSelectMultiple from Django forms. So in my template I render the form like this: {% for choice in filter_page.form.field_position_relationship__field_position %} <div class="custom-control custom-checkbox"> {{ choice.tag }} {{ choice.choice_label }} </div> {% endfor %} So by using Django-Widget-Tweaks I would suspect I can do this: {{ choice.tag|add_class:"custom-control-input" }} However I can't because I get this traceback: Traceback: File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 35. response = get_response(request) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 158. response = self.process_exception_by_middleware(e, request) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 156. response = response.render() File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/response.py" in render 106. self.content = self.rendered_content File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/response.py" in rendered_content 83. content = template.render(context, self._request) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/backends/django.py" in render 61. return self.template.render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/base.py" in render 175. return self._render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render 98. return self.nodelist.render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/base.py" in render_annotated 910. return self.render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/loader_tags.py" in render 155. return compiled_parent._render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/test/utils.py" in instrumented_test_render 98. return self.nodelist.render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/base.py" in render 943. bit = node.render_annotated(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/base.py" in render_annotated 910. return self.render(context) File "/Users/rafrasenberg/myoden/lib/python3.6/site-packages/django/template/loader_tags.py" in render 67. result … -
Refresh a OAuth2Session without a refresh_token
A provider offers a new OAuth2 based API which I am integrating in a Django application. I am stuck at the token_expired error which will raise after e few minutes. In the documentation there are examples to update an expired token with the refresh_token. The API provider does not offer a refresh_token, for security reasons. They say they do not want to use the refresh token but want to go through the standard OAuth flow per session. After a lot of searching I cannot find alternative cases without updating without this refresh_token. Can anyone provide me with a hint of missing knowledge? This is my API class: client_id = "CLIENT_ID" client_secret = "CLIENT_SECRET" auth = HTTPBasicAuth(client_id, client_secret) client = BackendApplicationClient(client_id=client_id) refresh_url = 'https://theprovider.com/token' oauth = OAuth2Session(client=client) try: fetch = oauth.fetch_token(token_url='https://the provider.com/token', auth=auth, timeout=10) except TokenExpiredError: print(fetch) The print shows: { "access_token":" utTJFMrOKwlyB5rcBpCIP6Dtn0k4w8vtqR6TJtu-fvEIm9tXTZf6q4JSaRaxRc7eSgO4EAggELN5bqADCSGq4mDEQgM-k-VPUi7IVIkKrVAFdwyb9Yz1cXy9 BspU96tZSmxjNiNzMiLCJvcmciOiJTTFI6MTMyMjAzNiIsImF6cCI6IjMwODE4NWVhLTkyZTAtNGE0NS1iNzg2LWU5MzI1OTIyM2I3MyIsImNsaWVudG5hbWUiOiJDaGFubmFWFmYyRdvKZyB4PibGUiLCJpc3MiOiJsb2dpbi5ib2wuY29tIiwic2NvcGVzIjoiQ3VzdG9tU2NvcGU0IEN1c3RvbVNjb3BlMyIsImV4cCI6MTUzOTI0NDkwMSwiaWF0IjoxNTM5MjQ0NjAxLCJhaWQiOiJTTFI6MTMyMjAzNiIsImp0aSI6IjI1YzcxZDY2LTU0YzgtNDQ3ZS04NTk0LWEwMzFlZDNkNGUzOSJ9.Nkc90mTB-BLVJEnSDHx2o1bkJ-eyJraWQiOiJyc2ExIiwiYWxnIjoiUlMyNTYifQ.eyJzdWIiOiIzMDgxODVlYS05MmUwLTRhNDUtYjc4Ni1lOTMyNTkyM7Dan9VaFQF1o8EvlGCV42n61KAjeEg8PrjVwqFvJ8y9QUzcpTFXQ5f4VFgIfZfYaqZyM2iJWFlpSpVl-jQAiGjOp0xSForKtGe2-FdyXmmQNpw_IltcPmvJIGABU3Xngx5O- _F13sG_zRoy7g1CBspU9dx5DLDuOa17PBmj52kQVEV8Q", "token_type": "Bearer", "expires_in": 299, "scope": "{scopes}" } -
Django - How to create checkbox form separated by foreign key
I'm developing food site, where users can register favorite foods to this web site. So, I would like to create checkbox form separated by foreign key like this. Fruits □ Apple ☑︎ Orange ☑︎ Lemon Vegetable □ Tomato ☑︎ Eggplant ☑︎ Cucumber Here is my code: ▪️ models.py class FoodsType(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Foods(models.Model): name = models.CharField(max_length=255) type = models.ForeignKey(FoodsType, on_delete=models.CASCADE) def __str__(self): return self.name class UserFoods(models.Model): foods = models.ManyToManyField(Foods) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) ▪️ form.py class FoodsFrom(forms.ModelForm): foods = forms.ModelMultipleChoiceField(label='favorite foods', queryset=Foods.objects.all(), widget=forms.CheckboxSelectMultiple) class Meta: model = Foods fields = ('name', 'type') ▪️ view.py class registerForm(generic.CreateView): def get(self, request): food_form = FoodsFrom() context = { 'food_form': food_form } return render(request, 'register.html', context) ▪️ register.html {% for field in food_form %} <tr> <th><label for="{{ field.id_for_label }}">{{ field.label }}</label></th> <td>{{ field }} {{ field.errors }}</td> </tr> {% endfor %} -
how to display already selected option in dropdown while updating the form
how can i display already selected teacher in a select option in first while updating my data through forms models.py class TeacherSalary(models.Model): name = models.ForeignKey(Teacher,on_delete=CASCADE) total_num_of_students = models.IntegerField(default=0) fee_per_student = models.IntegerField(default=0) total_fee = models.IntegerField(default=0) percent_for_teacher = models.FloatField(default=0.0) salary = models.IntegerField(default=0) views.py def editteachersalary(request,id): if not request.user.is_superuser: messages.info(request, 'You have to logged in first as a admin') return redirect('%s?next=%s' % (settings.LOGIN_URL, request.path)) teachers = Teacher.objects.all() teacher = TeacherSalary.objects.get(id=id) # for teacher1 in teachers: # if teacher1.id == teacher.id and teacher1.name == teacher.name: # selected_option = True return render(request, 'students/edit_teacher_salary.html', {'teacher': teacher,'teachers':teachers}) edit template <div class="form-group"> <h5>Teacher <span class="text-danger">*</span></h5> <div class="controls"> <select name="name" id="select" required class="form-control"> {% for teacher1 in teachers %} <option value="{{teacher1.id}}" {% if teacher1.id == teacher.id and teacher1.name == teacher.name %} selected="selected"{% endif %}>{{teacher1.name}} </option> {% endfor %} </select> </div> </div> -
How to get all record related parent and child in Django?
NoteID(PK) NoteText ParentNoteID 1 x - 2 y 1 3 z - 4 a 2 5 b - 6 z 4 How to get all record relating key ex. get NiteID 4 than result should be 1,2.4,6 all id or all object filter. -
Django-Channels: Lock critical section in class
I have a class that extends WebsocketConsumer and thus communicates to the client via a websocket. From my understanding the whole process is event-driven and I have one method that has a critical section (I don't want to get the function triggered again while it still processes). Can I just use python's builtin threading module to lock this section. E.g: import threading class UserCharacterConsumer(WebsocketConsumer): def __init__(self, *args, **kwargs): super().__init__(*args, *kwargs) self.lock = threading.Lock() def critical_method(self): self.lock.acquire() try: # critical section pass finally: self.lock.release() Or wouldn't this work for Django-Channels because it does not use threads in that way? -
How to save unicode string in admin site django?
I want to change data in admin site of django but when I save it, it will turn to something like 'C?a 4'. '?' is the unicode word. This is my model class Camera(models.Model): camera_id = models.AutoField(primary_key=True) camera_name = models.CharField(max_length=45, blank=True, null=True) stream_url = models.CharField(max_length=2083, blank=True, null=True) class Meta: managed = True db_table = 'camera' def __str__(self): return self.camera_name -
Django Project - CSS failing to render for a list (ul and li)
I have the following css in a style sheet that is being applied to a Django-based html template. Everything else works fine, but the css (see below) that I've added for ul and l does not seem to be rendering or being recognised at all. styles.css (first half of the sheet) @import url(https://fonts.googleapis.com/css?family=Open+Sans); .ul { font: 25px arial, sans-serif; list-style: none; /* Remove HTML bullets */ padding: 0; margin: 0; } .li { padding-left: 16px; list-style-type: square; } .li::before { content: "•"; /* Insert content that looks like bullets */ padding-right: 8px; color: red; /* Or a color you prefer */ } .btn { display: inline-block; *display: inline; *zoom: 1; padding: 4px 10px 4px; margin-bottom: 0; font-size: 13px; line-height: 18px; color: #333333; text-align: center; text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; background-color: #f5f5f5; background-image: -moz-linear-gradient(top, #ffffff, #e6e6e6); background-image: -ms-linear-gradient(top, #ffffff, #e6e6e6); background-image: -webkit-gradient( linear, 0 0, 0 100%, from(#ffffff), to(#e6e6e6) ); The html part of the code <!--End mc_embed_signup--> </div> </div> <!-- /end of Row--> </div> <!-- End of container--> <ul> {% for guestbookitem in all_items %} <li> {{ guestbookitem.content }} </li> {% endfor %} </ul> </body> </html> Have I made a mistake in the css? Not … -
Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' Django Channels 2.1.2
I have a Django project which has multiple apps and uses Django Channels 2.1.2 for its WebSockets capabilities (for notifications and chat messages). When I run daphne -b 127.0.0.1 -p 8000 myproject.asgi:application I get the error 'ERROR Exception inside application: Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default` The traceback is below 127.0.0.1:59202 - - [25/Apr/2019:10:23:09] "WSDISCONNECT /messages/bob" - - 127.0.0.1:59215 - - [25/Apr/2019:10:23:11] "WSCONNECTING /messages/bob" - - 2019-04-25 10:23:11,952 ERROR Exception inside application: Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default File "/Users/me/myapp/lib/python3.7/site-packages/channels/sessions.py", line 175, in __call__ return await self.inner(receive, self.send) File "/Users/me/myapp/lib/python3.7/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/Users/me/myapp/lib/python3.7/site-packages/channels/consumer.py", line 42, in __call__ self.channel_layer = get_channel_layer() File "/Users/me/myapp/lib/python3.7/site-packages/channels/layers.py", line 344, in get_channel_layer return channel_layers[alias] File "/Users/me/myapp/lib/python3.7/site-packages/channels/layers.py", line 76, in __getitem__ self.backends[key] = self.make_backend(key) File "/Users/me/myapp/lib/python3.7/site-packages/channels/layers.py", line 46, in make_backend return self._make_backend(name, config) File "/Users/me/myapp/lib/python3.7/site-packages/channels/layers.py", line 69, in _make_backend "Cannot import BACKEND %r specified for %s" % (self.configs[name]["BACKEND"], name) Cannot import BACKEND 'channels_redis.core.RedisChannelLayer' specified for default I have a virtual environment activated and everything is properly installed. settings.py (base file) CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [os.environ.get('REDIS_URL', 'localhost'),6379], }, }, } routing.py (located on the same level as settings.py) from django.conf.urls import url from django.urls … -
i would like have only month and year columns for django datefield in forms file
class OrderForm(forms.Form): exp= forms.DateField() zip=forms.IntegerField() card=forms.IntegerField() i want to show only month and year for DateFiled for exp variable for credit card expire date -
How to decide the proper layout of django models?
Yes, so I had been working on a django project, where I can extend a model class or use the same model putting the unused fields null. I am not sure which approach is better? I am using Postgres as my db. So, there are two cases: Case1: class Model1(models.Model): field1 = models.CharField(max_length=255,null=True) field2 = models.CharField(max_length=255) ... field7 = models.CharField(max_length=255) field8 = models.CharField(max_length=255,null=True) field9 = models.CharField(max_length=255,null=True) field10 = models.DecimalField(max_digits=6, decimal_places=3, default=0) The thing is I have to store data in two forms. For one case, field 1, field8, field9 will always remain null and field10 will always remain 0. In case 2, I can split this models in two ways, as shown below: class Model1(models.Model): field2 = models.CharField(max_length=255) ... field7 = models.CharField(max_length=255) class Model2(Model1): field1 = models.CharField(max_length=255) field8 = models.CharField(max_length=255) field9 = models.CharField(max_length=255) field10 = models.DecimalField(max_digits=6, decimal_places=3) I was curious about how much memory will we be able to save on using the second case of model creation. Or how advantageous is it to use the second method than the first method? As much as I have studied, postgres saves the null cases with null bitmaps, which take 1 byte for upto 8 fields and 2 bytes for 9-16 fields. … -
What is the Django Form Action?
Many Django Forms examples does not include an action. Example, <form method="post"> {% csrf_token %} {{ form.as_p }} <div class="form-actions"> <button type="submit">Send</button> </div> </form> Page source confirms that there is no form action. So what is the url for the form action upon submit which can be used for Jquery Ajax? Thanks. -
Getting error for created new app in python
i am new in python, I have created new app as crud, i am using django, app is created, but when i run the server it gives me below error, not getting what exactl error in that, In mysite/settings.py i have added in INSTALLED_APPS added crud.apps.CrudConfig still getting this error C:\Users\Nikul\PycharmProjects\mysite>python manage.py runserver Watching for file changes with StatReloader Exception in thread Thread-1: Traceback (most recent call last): File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 917, in _bootstrap_inner self.run() File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 77, in raise_last_exception raise _exception[0](_exception[1]).with_traceback(_exception[2]) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\apps\config.py", line 134, in create % (mod_path, cls_name, ', '.join(candidates)) django.core.exceptions.ImproperlyConfigured: 'crud.apps' does not contain a class 'CrudConfig'. Choices are: 'PollsConfig'. Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\Nikul\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, … -
Expecting expected string or bytes-like object
I'm having an issue on my django app however, it seems to be more of a python issue, although I don't seem to see where the issue lies This is my code for q in qs: untouched_question_in_term_of_minutes = (now() - q.date) #take the current date #and substract the date when the question was created certain_mn_ago = untouched_question_in_term_of_minutes.total_seconds() / 60 #that gives me the number of minutes where #the question has not been touched limit_of_mn = 50 print(untouched_question_in_term_of_minutes) print(certain_mn_ago) if certain_mn_ago >= limit_of_mn: #if the condition is fulfilled, then the action below are done ae = AssociatedExpert.objects.filter(question=q, state='P') ae.update(state='C') Question.objects.filter(id=q.id, state='P').update(state='C') qs.filter(date__lte=two_days_ago, state='C').update(email='***', first_name='***', last_name='***', phone='***', extra='***') else: ae = AssociatedExpert.objects.filter(question=q, state__in=['D', 'T', 'A', 'F']).first() if ae: qs.filter(id=q.id).update(state=ae.state) As you see, the logic seems to bere here. Yet, it is giving me the traceback below. TypeError at /temp_app/question/ expected string or bytes-like object Request Method: GET Request URL: http://127.0.0.1:8000/temp_app/question/ Django Version: 2.0.3 Exception Type: TypeError Exception Value: expected string or bytes-like object Exception Location: /home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/django/utils/dateparse.py in parse_datetime, line 107 Python Executable: /home/andykw/cloned_projects/findoor-backend/.venv/bin/python Python Version: 3.6.7 Python Path: ['/home/andykw/cloned_projects/findoor-backend/findoor_backend', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python36.zip', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/lib-dynload', '/usr/lib/python3.6', '', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages', '/home/andykw/cloned_projects/findoor-backend/.venv/src/django-s3-upload', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/IPython/extensions', '/home/andykw/.ipython', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf', '/home/andykw/cloned_projects/findoor-backend/.venv/lib/python3.6/site-packages/odf'] Server time: Thu, 25 Apr 2019 11:49:27 … -
Please help me for making a django app for online classes?
I am making a live streaming classes for student so how can I process from scratch? Please help me to build a django app for online class. -
Is there any way to pass value to custom context_processor function from view?
I am trying to show related posts, relatedness is based on category. Currently I am sending category_name from single_post_detail_view using the session to custom context_processor function, which then returns the posts related to that category. views.py class PostDetailView(DetailView): def get(self, request, slug): post = Post.objects.get(slug=self.kwargs['slug']) context = { 'post' : post } request.session['category'] = post.category.name return render(request, 'blog/post_detail.html', context) context_processors.py from blog.models import Category def related_posts(request): if request.session['category']: category = request.session['category'] return { 'related_posts': Category.objects.get(name=category).posts.all() } and then in HTML {% for post in related_posts %} <a href="post.get_absolute_url()">{{post.title}}</a> {% endfor %} -
save formset one row at a time through ajax call
I want to save row by row formset data, when i was submitting form, form getting in valid, In Post Request attribute name is form-1-Name I think that's why form is getting invalid. @method_decorator(login_required, name='dispatch') class ProductionProcessCreateView(CreateView): model = ProductionProcess form_class = ProductionProcessForm template_name="master/productionprocess_form.html" ExampleFormSet = modelformset_factory(ProductionProcess,form=form_class,formset=BaseProductionProcessFormSet,extra=1,) def get(self, request, *args, **kwargs): self.object = self.get_object() context = super(ProductionProcessCreateView, self).get_context_data(**kwargs) if self.request.POST: context['ProductionProcessForm'] = self.ExampleFormSet(self.request.POST) else: context['ProductionProcessForm'] = self.ExampleFormSet() return self.render_to_response(context) def post(self, request, *args, **kwargs): try: ExampleFormSet = self.ExampleFormSet(self.request.POST) except ValidationError: ExampleFormSet = None self.object = self.get_object() if ExampleFormSet.is_valid(): for form in ExampleFormSet.save(commit=False): form.user = self.get_object().user form.instance.ProductName_id = self.kwargs.get('pk') form.save() messages.success(self.request, _('Production Process added successfully')) return redirect("tailoringproducts") else: return self.render_to_response(self.get_context_data(ExampleFormSet=ExampleFormSet)) Expected every row has save button when click on save button data will be save in database, how we can store data through ajax call -
How to define a Model relationship with itself in Django
I'm writing a model which goes to handle a child-parent data structure. So I defined a "parent_id" as a foreign key and tried to relate it with "id" (primary key) in my model. According to official docs in https://docs.djangoproject.com/en/2.2/ref/models/fields/#foreignkey I would have used 'self' as model reference. from django.db import models class Department(models.Model): title = models.CharField(max_length=255) parent_id = models.ForeignKey('slef', on_delete=models.CASCADE) department_type = models.CharField(max_length=255) I got the errors below: baseinform.Department.parent_id: (fields.E300) Field defines a relation with model 'slef', which is either not installed, or is abstract. baseinform.Department.parent_id: (fields.E307) The field baseinform.Department.parent_id was declared with a lazy reference to 'baseinform.slef', but app 'baseinform' doesn't provide mod el 'slef'.