Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to modify django task in external app
I need to make some changes to a 3rd party app to enable additional functionality. This app has several tasks that make RPC calls via a service proxy that need to be updated to use a different command based on whether the associated object supports the new functionality. I've managed to update one of several of these functions but I wanted to ask the community if there was a more pythonic/DRY to do this using a decorator or pattern that I'm not thinking of. More precisely, I'm trying to add support for shielded transactions to a cryptoasset wallet while maintaining backward compatibility. I've forked the django-cc library (https://github.com/limpbrains/django-cc). I've updated the currency model to include a boolean to indicate shielded transactions are supported. Within the tasks, I've put a if statement to switch between the two. It works, but before I start refactoring the rest of the code, I want to know if there's an interface or strategy pattern I can use that would be more appropriate. We're interested in the AuthServiceProxy (https://github.com/jgarzik/python-bitcoinrpc/blob/master/bitcoinrpc/authproxy.py) object coin. The object uses a call function, so getnewaddress is passed out as as param to the RPC call. The asset we're adding doesn't support this … -
How to perfrom a aggregate query with condicional filter in django
I have this data on the model: [ {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": true}, {"Field": "value2", "Flag": true}, {"Field": "value1", "Flag": false}, {"Field": "value2", "Flag": false}, {"Field": "value1", "Flag": false} ] I try to aggregate the data with this query when the flag is True: model.objects.values('Field').order_by('Field').annotate(total=Count('Field'), Flag=Count('Flag', filter=Q(Flag=True))) And I expect this output in the result of the query: [ {"Field": "value1", "total": 4, "Flag": 2}, {"Field": "value2", "total": 3, "Flag": 1} ] try with conditional aggregation but display this error: SQLDecodeError -
How to access its object query properties I know it have 5 properties in it
I wanna access <QuerySet [<User: xyz>]> this object properties it have multiple properties but i dont know how to access each property and update its value u = User.objects.filter(username=username) u.first_name=(str(first_name)) u.save(` -
Why is this ModelForm not valid
I'm new to coding with django, and I'm trying to add comments to my blog app, but I'm having trouble with the validation of this form, it always returns False with form.is_valid(), so the object is never saved views.py def blog_post_detail_view(request, slug): obj = get_object_or_404(BlogPost, slug=slug) comments = Comment.objects.filter(blog_post=obj) initial_data = { "blog_post": obj, } form = CommentModelForm(request.POST or None, initial=initial_data) if form.is_valid(): comment_obj = form.save(commit=False) comment_obj.user = request.user comment_obj.save() form = CommentModelForm() else: print('not clean') context = { "object": obj, "comments": comments, "form": form, } template_name = 'blog/detail.html' return render(request, template_name, context) forms.py from django import forms from .models import Comment class CommentModelForm(forms.ModelForm): class Meta: model = Comment fields = ['content','blog_post'] HTML <form method='POST' action='.'> {% csrf_token %} {{ form.as_p }} <button type='submit'>Send</button> </form> models.py class Comment(models.Model): content = models.TextField(max_length=300) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL, default=1) blog_post = models.ForeignKey(BlogPost, null=True, on_delete=models.CASCADE) timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) -
how to hide in the dropdown list the required value using ajax and jquery with django
i have a dropdown list that display the data from the database. i need to make dynamic using jquery and ajax where it will hide some values based on the user input. where the user will have three options to select between and based on his selection the value will show or be hidden in the dropdown list. my question is how to hide the required option based on the returning ID. until now this what i tried and it did not work as i want. views.py def getSource(request): sources = Source.objects.all() return render(request, 'create_folder.html', {'sources':sources}) create_folder.html case"1": $('#mouresaleMasdar option[data-id="40"]').hide() and i tried another solution also didn't work. $('#mouresaleMasdar option[value="{{ source.id }}== 40"]').hide() -
Django 2.2 translations not applying, LANGUAGE_CODE and i18n URL pattern correct
I'm using Django 2.2 and Python 3.7. I'm trying to set up Django translations, and everything seems to work up until the point of seeing the translations. I'm using i18n urls so the url shows up as localhost/language-locale example: localhost/en-us/ localhost/fr-fr/ url patterns: urlpatterns += i18n_patterns( path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), path('i18n/', include('django.conf.urls.i18n')), ... settings_l10_i18.py: LANGUAGE_CODE = 'en-us' LANGUAGES = [ ('en-us', _('US English')), ('en-gb', _('British English')), ('en-ca', _('Canadian English')), ('fr-fr', _('French')), ('fr-ca', _('Canadian French')), ] TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = False USE_THOUSAND_SEPARATOR = True LOCALE_PATH = [ os.path.join(BASE_DIR, "locale"), ] file structure basedir/locale ├── en_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_GB │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── en_US │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_CA │ └── LC_MESSAGES │ ├── django.mo │ └── django.po ├── fr_FR │ └── LC_MESSAGES │ ├── django.mo │ └── django.po └── README.md Language switcher in template: <li> <form action="{% url 'set_language' %}" method="post"> {% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"/> <select name="language" value="" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% for lang in LANGUAGES %} <option value="{{ lang.0 }}" {% … -
Is it possible to start using Django's migration system after years of not using it?
A project I recently joined, for various reasons, decided not to use Django migration system and uses our own system (which is similar enough to Django's that we could possibly automate translations) Primary Question Is it possible to start using Django's migration system now? More Granular Question(s) Ideally, we'd like to find some way of saying "all our tables and models are in-sync (i.e. there is no need to create and apply any migrations), Django does not need to produce any migrations for any existing model, only for changes we make. Is it possible to do this? Is it simply a case of "create the django migration table, generate migrations (necessary?), and manually update the migration table to say that they've all been ran"? Where can I find more information for how to go about doing this? Are there any examples of people doing this in the past? Regarding SO Question Rules I didn't stop to think for very long about whether or not this is an "acceptable" question to ask on SO. I assume that it isn't due to the nature of the question not having a clear, objective set of criteria for a correct answer. however, I think … -
Django Admin - Filter ManyToManyField with through model
How can I filter a queryset inside the Admin page of an object that has a ManyToManyField relation with a through model? Given models.py class Foo(models.Model): foo_field1 = models.CharField(max_length=50) class Main(models.Model): main_field1 = models.CharField(max_length=50) m2mfield = models.ManyToManyField(Foo, through="FooBar") class FooBar(models.Model): main = models.ForeignKey(Main, on_delete=models.CASCADE) foo = models.ForeignKey(Foo, on_delete=models.CASCADE) new_field = models.CharField(max_length=50) Inside admin.py class M2MInlineAdmin(admin.TabularInline): model = Main.m2mfield.through extra = 1 class MainAdmin(admin.ModelAdmin): inlines = [M2MInlineAdmin,] ... def formfield_for_manytomany(self, db_field, request, **kwargs): print('called formfield_for_manytomany') return super().formfield_for_manytomany(db_field, request, **kwargs) def get_field_queryset(self, db, db_field, request): print('called get_field_queryset') super().get_field_queryset(db, db_field, request) I try to access both of these methods, but none of them are called if I specify a through table. However, they do get called if the ManyToMany relation is simply defined as like this: class Main(models.Model): main_field1 = models.CharField(max_length=50) m2mfield = models.ManyToManyField(Foo) Is there a method to filter the queryset when a through table is specified? -
Headers are not sent in HTTP request in POST request in django
HTTP request works without gunicorn and nginx. However, when those 2 are added the headers are not sent and get an wsgi error. I've looked online with no avail. What do I need to change to read the headers? def accessWebhook(request): try: headers = request.headers #this breaks here print(headers) jsondata = request.body data = json.loads(jsondata) print(data) return HttpResponse(status=200) except: return HttpResponse(status=500) This is the error from gunicorn {'wsgi.errors': <gunicorn.http.wsgi.WSGIErrorsWrapper object at 0x7f577cffe4a8>, 'wsgi.version': (1, 0), 'wsgi.multithread': False, 'wsgi.multiprocess': True, 'wsgi.run_once': False, 'wsgi.file_wrapper': <class 'gunicorn.http.wsgi.FileWrapper'>, 'SERVER_SOFTWARE': 'gunicorn/19.9.0', 'wsgi.input': <gunicorn.http.body.Body object at 0x7f577cffe320>, 'gunicorn.socket': <socket.socket fd=9, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('172.20.0.2', 8000), raddr=('172.20.0.3', 40832)>, 'REQUEST_METHOD': 'POST', 'QUERY_STRING': '', 'RAW_URI': '/access/api/webhook/', 'SERVER_PROTOCOL': 'HTTP/1.0', 'HTTP_X_FORWARDED_FOR': '192.168.240.98', 'HTTP_HOST': '192.168.240.109', 'HTTP_CONNECTION': 'close', 'CONTENT_LENGTH': '34', 'HTTP_USER_AGENT': 'PostmanRuntime/7.13.0', 'HTTP_ACCEPT_ENCODING': 'gzip, deflate', 'HTTP_ACCEPT': '*/*', 'CONTENT_TYPE': 'application/json', 'HTTP_AUTHORIZATION': 'fZEOMAmm8Ygpaee73dRY', 'HTTP_CACHE_CONTROL': 'no-cache', 'wsgi.url_scheme': 'http', 'REMOTE_ADDR': '172.20.0.3', 'REMOTE_PORT': '40832', 'SERVER_NAME': '0.0.0.0', 'SERVER_PORT': '8000', 'PATH_INFO': '/access/api/webhook/', 'SCRIPT_NAME': ''} The headers prints correctly when running local server but once gunicorn and nginx is added. The headers are gone. -
Get related objects in Django and how to use Prefetch with related models
models.py class Press(models.Model): created = models.DateTimeField(editable=False) title = models.CharField(max_length=500, blank=True) slug = models.SlugField(max_length=600, blank=True, unique=True) def __str__(self): return self.title class Scan(models.Model): press = models.ForeignKey(Press, related_name='scans', on_delete=models.CASCADE) created = models.DateTimeField(editable=False) title = models.CharField(max_length=300, blank=True) main_scan = models.ImageField(upload_to='press/scans', blank=True) def __str__(self): return self.title views.py class PressListView(ListView): model = Press context_object_name = "press" template_name = "press.html" def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) context['press'] = Press.objects.prefetch_related(Prefetch('scans', queryset=Scan.objects.select_related('press'))) return context What I would like to achieve on the front-end of the site is to list all Press and as the cover image for each would like to use 1st main_scan image from the Scan model. I know I can add models.ImageField to Press model, but I do not want to - in the admin I am using admin.TabularInline from Scan model that is attached to Press model. I know there is documentation on prefetch but probably I am using it wrong and as well doing it wrong on the front-end in the template. Question is how to make it very optimized, that the performance is best, hitting the Database just once. Previously I was doing it this way and it worked, but this is causing … -
Django REST Framework TokenAuthentication Problem
Estoy intentando implementar la autenticación de token, el cuál busco generar al momento de dar de alta un usuario. El usuario se genera correctamente pero no se genera el token. Otro problema, al margen de la no generación del token, es que al crear el usuario el password en la base de datos se guarda como texto plano. El código es el siguiente: Python 3.7 Django 2.2.3 DRF 3.10.1 PostgreSQL En settings.py ''' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # Instaladas: 'rest_framework', 'rest_framework.authtoken', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } ''' En serializer.py ''' from django.contrib.auth.models import User from rest_framework.authtoken.models import Token class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'email', 'password') extra_kwargs = {'password':{'write_only':True}} def create(self, validated_data): user = User( email = validated_data['email'], username = validated_data['username'] ) user.set_password(validated_data['password']) user.save() Token.objects.create(user=user) return user ''' En apiviews.py ''' from rest_framework import generics from .serializers import UserSerializer class UserCreate(generics.CreateAPIView): authentication_classes = () permission_classes = () serializer_class = UserSerializer ''' En urls.py ''' from api.apiviews import UserCreate urlpatterns = [ path('v3/usuarios/', UserCreate.as_view(), name='usuario_crear') ] ''' Ingreso con la siquiente url: localhosts/api/v3/usuarios/ Creo un usuario y no me genera ningún error. El … -
Different fieldsets in Django Admin site depending on user group
In my django admin site I want to hide some fields to users within a group (Controllers group) What would be the best approach? Can we do something like this? This is my code, but it doesn't work: admin.py: class PriceFile(admin.ModelAdmin): if User.groups.filter(name='Controllers').exists(): fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description']})] else: fieldsets = [(None, {'fields':['print_url', ('model', 'client'), 'description', 'total_sum', 'margin_percent', 'final_price']})] -
Django - Group by return only value Sum
In Django how to perform the following SQL: select sum(valor_aprovado) as vla from convenios group by ano order by ano Desired result: sum_value | -------------| 472837446.59| 163438615.51| 448397994.27| 959203234.57| 739555948.32| I'm using the following syntax, but I just want it to return the VLA field and not the ANO Convenios.objects.values_list('ano').order_by('ano').annotate(vla=Sum('valor_aprovado') Result: [(2002, Decimal('36246385105.92')), (2003, Decimal('163442260.52')), (2004, Decimal('447464292.52')), (2005, Decimal('948880015.70')), (2006, Decimal('737373593.32')), (2007, Decimal('1449818896.88')), (2008, Decimal('1812889287.82')), (2009, Decimal('2306375485.81')), (2010, Decimal('8730479758.56')), (2011, Decimal('1662088139.88')), (2012, Decimal('1886396504.43')), (2013, Decimal('535507602.69')), (2014, Decimal('4279003118.70')), (2015, Decimal('1883240765.95')), (2016, Decimal('1245291830.72')), (2017, Decimal('2161176688.18')), (2018, Decimal('1346548803.43'))] Can you help me? Thanks -
Count how many fields a model has
I am wondering if there is a way to know how many fields a model contains. Example: class Post(models.Model): title = models.TextField() body = models.TextField() sub_title = models.TextField() summary = models.TextField() I can count it but I would like to know if there is an in-built method that allows me to do so. Ideally the quesry/code would be: Post.number_of_fieds-->output--> 4 Does such a thing exist? -
I Want to create a API for a User to join Specific Group in my app
I'm trying to create a RESTApi for a user to join a specific group in my app. I have the following models: User, Groups then a ManytoMany connection of User to Groups under the field members I've tried using different view and serializers, I either Get queryset isnt iterable or null value in column "max_no_members" violates not-null constraint DETAIL: Failing row contains (11, , d85743a7-ccd9-4175-984b-86c10c75aec6, null, null, , null, 2019-07-25 18:11:34.9933+00, t, null, Monthly). views.py class GroupJoinAPIView(CreateAPIView): queryset = Groups.objects.annotate(arr=ArrayAgg('members')).values_list('id', 'arr') serializer_class = JoinGroupSerializer permission_classes = [IsAuthenticated] def perform_create(self, serializer): print(sys.stderr, self.queryset) if self.request.user.id in self.queryset.all(): return 'User already in the group' else: list(self.queryset.all()).append(self.request.user.id) serializer.save() serializers.py class JoinGroupSerializer(serializers.ModelSerializer): users = UserSerializer(many=True, read_only = True) class Meta: model = Groups fields = ['members','users'] urls.py path('<int:pk>/join', GroupJoinAPIView.as_view(), name='members'), models.py(Groups) class Groups(models.Model): name = models.CharField(max_length = 50, unique = True) group_id = models.UUIDField(default = uuid.uuid4, editable = False) max_no_members = models.PositiveIntegerField() savings_amount = models.PositiveIntegerField() savings_type = models.CharField(max_length = 10, default = 'Monthly') description = models.TextField(blank=True) begin_date = models.DateField() created_date = models.DateTimeField(auto_now_add=True) searchable = models.BooleanField(default = True) members = models.ManyToManyField(User, related_name='group_members') created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete =models.CASCADE,related_name='group_admin' ) def __str__(self): return self.name I would like to be able to add an authenticated user to a … -
ApiConnectionError with Stripe Python SDK
I am developing a web app using Django and stripe payment gateway for payments. I used Ubuntu machine while integrating stripe payment(using stripe python SDK) and everything worked fine. I am running the same code again on Mac OS X system and it throws the following error: I found out different answers on StackOverFlow (found similar questions) for this but that didn't solve my issue. I tried the following things to resolve the issue: I tried connecting with a different key pair by generating it from the stripe dashboard I tried updating the OpenSSL through brew Turned off the firewall None of the above worked for me. Can someone help solve this who has faced a similar issue and resolved it? -
How to associate invited users with the inviter's Company/group?
I am using Django, django-allauth and django-invitations. I am able to successfully invite users to the platform, but I would like to associate them with the inviter's Company. I've read over the bee-keeper/django-invitations and it doesn't seem to have the information on how to do this. models.py class Company(models.Model): name = models.CharField(max_length=100, default=None) class CustomUser(AbstractUser): company = models.ForeignKey(Company, on_delete=models.CASCADE, blank=True, null=True) objects = CustomUserManager() views.py @login_required def company_users(request): # Get users that are in the company's user database as well as users that have been invited company_users = CustomUser.objects.filter(company=request.user.company.id) Invitations = get_invitation_model() # I'm afraid this is going to get all invited users, not just those that belong to the company invited_users = Invitations.objects.filter() if request.method == 'POST': print(request.POST) invitees = request.POST['invitees'] invitees = re.split(',', invitees) for invitee in invitees: Invitation = get_invitation_model() try: invite = Invitation.create(invitee, inviter=request.user) invite.send_invitation(request) except IntegrityError as e: print(type(e)) print(dir(e)) return render(request, "company_users.html", { 'message': e.args, 'company_users' : company_users, 'invited_users' : invited_users, }) return render(request, 'company_users.html', { 'company_users' : company_users, 'invited_users' : invited_users, }) In the code above, users are successfully invited to the platform, but the user is not associated with the Company of the inviter. I'm also afraid that the list of invited … -
Django Code Acting Different To Code Ran Locally
When I try and run the code ' '.join([(f'<a href="{word}">{word}</a>' if ('http://' in word or 'https://' in word) else word) for word in chat.split(' ')]) in Django it throws a SyntaxError (SyntaxError at /chat invalid syntax (views.py, line 25)) however, when I run it locally there is no SyntaxError. The Python version on the webserver is 3.5, and the version I used was 3.6, but that shouldn't matter. If it does, however, what code should I use in place of what was provided? -
How to process the URL in django
I have created a form where the user can select different dropdown. On the basis of user selection, it will create a URL on selecting the submit button and that URL is displayed in the page with the URL link. When a user clicks into it, it directs to related web pages. But What I want is instead of a user clicking on URL, the related URL page should directly open when the user selects the select button. Do we use ajax here to process the form? I am not sure how to do it. Any help is appreciated. -
Can't display the contents of postgres table in Django Admin panel
I have a postgres instance on AWS and I am using it as the database in django. To push the data in the postgres into my django models.py I did - python manage.py inspectdb > models.py The models.py has this - class TasteCluster(models.Model): id_cluster = models.IntegerField(blank=True, null=True) table_cluster_name = models.CharField(max_length=250, blank=True, null=True) cluster_description = models.CharField(max_length=250, blank=True, null=True) def __str__(self): return self.id_cluster Now when I check the tables in the admin panel in django I can see the table taste cluster like this - Select taste cluster to change ADD TASTE CLUSTER Action: Go 0 of 8 selected TASTE CLUSTER 632 644 643 639 619 614 665 621 8 taste clusters When I click on any of the id_cluster I get this error - TypeError at /admin/dbconnect/tastecluster/8/change/ __str__ returned non-string (type int) Request Method: GET Request URL: http://127.0.0.1:8000/admin/dbconnect/tastecluster/8/change/ Django Version: 2.2.3 Exception Type: TypeError Exception Value: __str__ returned non-string (type int) Exception Location: /usr/local/lib/python3.7/site-packages/django/template/defaultfilters.py in _dec, line 42 Python Executable: /usr/local/opt/python/bin/python3.7 Python Version: 3.7.3 Python Path: ['/Users/rahman/Desktop/django_exercise/03project/post', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python37.zip', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7', '/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload', '/Users/rahman/Library/Python/3.7/lib/python/site-packages', '/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/geos', '/usr/local/Cellar/numpy/1.16.3_1/libexec/nose/lib/python3.7/site-packages', '/usr/local/Cellar/protobuf/3.7.1/libexec/lib/python3.7/site-packages'] Server time: Thu, 25 Jul 2019 16:19:03 +0000 How can I get/view all the columns and rows of the table ? I am a newb at … -
I need to step out of django directory to see other url patterns
I am trying to make a simple wait-screen with js that redirects you to a django page. the wait-screen will be used alot in the script so I have it in a app called core. the app then has the necessary part linked in the root urls.py. but when I call the wait screen it will pull up but then look for the redirected url in only the core folder. I tried to include the root urls.py in my core/urls.py but that resulted in a circular url problem. here is the main urls.py from django.contrib import admin from django.urls import path, include from core.views import HomePage, wait_screen urlpatterns = [ path('', HomePage.as_view(), name="index"), ... path('Well/', include('Well.urls')), path('wait_screen/', wait_screen, name="wait_screen"), path('admin/', admin.site.urls), ] here is the core/urls.py from django.urls import path from . import views urlpatterns = [ path('wait_screen/', views.wait_screen, name="waitscreen"), ] here is the wait_screen written in js, linked with a view <script> $(function() { // Stop Watch Functions function get_elapsed_time_string(total_seconds) { function pretty_time_string(num) { return ( num < 10 ? "0" : "" ) + num; } ... } var elapsed_seconds = 0; // Set stopwatch setInterval(function() { elapsed_seconds = elapsed_seconds + 1; ... // Redirect var redirect_to = … -
Django view for quiz
I am a newbie to Django, I want to make quiz app but I am stuck in the problem. I have created 3 models(Quiz, Question, Choice). I want to write a function which returns questions which have the same quiz title. I tried this views.py def detail(request): sets = Quiz.objects.all() question = Question.objects.filter(sets.title) return render(request,'App/appdetail.html',{'question':question}) models.py class Quiz(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=100) def __str__(self): return self.title class Question(models.Model): set = models.ForeignKey(Quiz,on_delete=models.CASCADE) question_txt = models.CharField(max_length=100) def __str__(self): return self.question_txt class Choice(models.Model): question = models.ForeignKey(Question,on_delete=models.CASCADE) choice_txt = models.CharField(max_length=20) boolean = models.BooleanField(default=False) def __str__(self): return self.choice_txt error message -
how to automatically populate part of Django modal form before popup using ajax code
I have created a work schedule page with a month view, where every day of the month will be pupated by the required tasks to be done on that day. I have also created a modal popup form that appears when the user click any of the dates of the schedule table. The form includes state_time, end_time, task_name, etc. When the user fill the form, a will be created in the relevant day of the month as soon as the user submitted the form. the press button is located in the scheduler table according to the start_time value in the form. The div id of every day cell of the scheduler is the same as its date. What I would like to do is as soon as the user click on any date in the scheduler table the popup form appears automatically populated with this date , which is the same as the clicked div id. view.py def task_create_slim(request): data = dict() # print("hii55") if request.method == 'POST': form = TaskFormSlim(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True New_task_data = form.cleaned_data # getting the data from the form jsut after saving New_task_date = New_task_data['start_time'] last_task_per_day=Task.objects.filter(start_time=New_task_date).last() # last_task_per_day = [Task.objects.all().latest('start_time')] # I … -
I've ran into really weird error some templates in production doesn't load
I deployed a django app on AWS EC2 every page is working but the login page and detail view page returning a 'template not found error while both of the views working on my machine.how can i fix this ? i already see it has to do something with my virtual machine. to keep in mind here's my folder structure : /Eyelizer /app1 /app2 /Eyelizer /eyelizerenv /etc I use this folder structure as it has something to do with the nginx and gunicorn configuration. -
TypeError: Object of type Cart is not JSON serializable
I just started using session in Django framework. I have create an object cart from Cart model. And when i wan to set cart inside request.session with session['cart'] = cart, I get this error message: TypeError: Object of type Cart is not JSON serializable This is my Cart model class Cart(object): def __init__(self): self.items = [] def addItem(self, itemCart): try: # get index of itemCart if exist index = self.items.index(itemCart) # itemCart exist then set its quantity self.items[index].setQuantity( self.items[index].quantity + itemCart.quantity) except ValueError: # the item does not exits then add to items list self.items.append(itemCart) This is my view when i update the session cart = Cart() session['cart'] = cart And When i run the code i get this error: File "C:\Users\Patrick-PC\AppData\Local\Programs\Python\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.class.name} ' TypeError: Object of type Cart is not JSON serializable. Please help