Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I was making Mood Based Recommendation system website and faced this issue while running the server. used django framework and python language
C:\Users\abc Sharma\Firefox Downloads\MoodieFoodie-master\MoodieFoodie-master>python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\threading.py", line 954, in _bootstrap_inner self.run() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\threading.py", line 892, in run self._target(*self.args, **self.kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise exception[1] File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 375, in execute autoreload.check_errors(django.setup)() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django_init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\apps\config.py", line 224, in create import_module(entry) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\importlib_init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in find_and_load File "", line 984, in find_and_load_unlocked ModuleNotFoundError: No module named 'bootstrap3' Traceback (most recent call last): File "C:\Users\abc Sharma\Firefox Downloads\MoodieFoodie-master\MoodieFoodie-master\manage.py", line 22, in execute_from_command_line(sys.argv) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management_init.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\runserver.py", line 61, in execute super().execute(*args, **options) File "C:\Users\abc Sharma\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\abc … -
Custom Authentication Login in Django via email
I am trying to understand login methods in Django. So because I want to login with email not username. I wrote a custom authentication backend and exposed it in settings.py AUTHENTICATION_BACKENDS = ( 'accounts.backend.EmailAuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ) class EmailAuthenticationBackend(ModelBackend): def authenticate(self, request, email=None, password=None, **kwargs): try: user = Account.objects.get(email=email) if user.check_password(password): return user except user.DoesNotExist: pass And in view user_login how I authenticate the user. And it's actually works. I mean kind of... def user_login(request): nxt = request.GET.get("next") form = UserLoginForm(request.POST or None) if form.is_valid(): email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(email=email, password=password) login(request, user) if next: return redirect(next) return redirect("/") context = { "form": form } return render(request, "accounts/user_login.html", context) the authenticate() method is returns the user. But redirect() is not working because in browser thinks user not logged in. I am not sure about how to handle the session part. and custom UserLoginForm class UserLoginForm(forms.Form): email = forms.CharField() password = forms.CharField() def clean(self, *args, **kwargs): email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") if email and password: user = authenticate(email=email, password=password) if not user: raise forms.ValidationError("user not exist") if not user.check_password(password): raise forms.ValidationError("incorrect password") return super(UserLoginForm, self).clean(*args, **kwargs) The second issue is if email or password wrong. it doesn't … -
django IIS maxAllowedContentLength
I have a django web site with a form uploading a video. It's running on IIS. When I click the upload button it writes The page was not displayed because the request entity is too large. I tried according to this answer to set Maximum allowed content length to 104857600 but it didn't help. How can I fix it? -
Highlight new posts in django/react
I have Post model in django which has Channel as foreign key. What I want to do is , whenever there is a new post in post model, that channel should get highlighted and that should be user specific. What I am thinking is whenever new post is created, there will be one flag is_highlighted which will be set to true. Is this the right way to do? any other better way? TIA class Post(models.Model): user = models.ForeignKey( User, on_delete=models.DO_NOTHING, blank=True, null=True, related_name="post_user_id") channel = models.ForeignKey( Channel, on_delete=models.DO_NOTHING, blank=False, null=False, related_name="post_channel_id") and channel model is class Channel(models.Model): channel_name = models.CharField( max_length=250, help_text="Channel channel_name") -
Example domain error in django on reset password
I am writing program to reset password in django. After filling email id and send link to change password when i click on link it goes to example domain page.why this is happning. setting.py INSTALLED_APPS = ['django.contrib.auth',] EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'rexhoney4@gmail.com' EMAIL_HOST_PASSWORD = 'mecgfweiszkipmgw' EMAIL_USE_TLS = True DEFAULT_FROM_EMAIL = 'TestSite Team <noreply@example.com>' enter image description here -
Django add_argument invalid literal for int() with base 10: '--s_p=test'
I want to get --s_p as str and --s_t as str, --places for multiple int def add_arguments(self, parser): parser.add_argument("--s_p",type=str), parser.add_argument("--s_t",type=str), parser.add_argument('--places',nargs='+', type=int) So, I use this command, but I have error as title python manage.py mycommand --s_p=test --s_t=test --places=1 2 Why does this happen??? -
Update View - Page not found
I am attempting to create an update view for a build log(subpost). My URL structure is /post/pk/buildlog/pkz/update The error I am getting is Page not found Raised by: blog.views.UpdateBuildLog ... post/<int:pk>/build-log/<int:pkz>/update/ [name='build-log-update'] The current path, post/118/build-log/53/update/, matched the last one. view class UpdateBuildLog(UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' url path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update') I believe the error is being caused because of the two primary keys not being passed into the view but I cant figure out how to pass the second primary key(pkz) into the view -
How to maintain user session across different devices and browsers from the access code email link in django
After validating the user, I'm sending out the access token to user's email along with the link to come back to the same page. [![Access Token email][1]][1] [1]: https://i.stack.imgur.com/OWezf.png This works well when the user opens the email in the same browser where he has been validated but if he opens the mail on his mobile or some other browser and clicks the link, he is taken back to the first validation page where he has to enter his user details again. How can I maintain the same session across different platforms in Django. I know there are some methods to do that like, we need an API which takes an encrypted request id as a parameter which will be included as a token in the access code email link to landing page. The API will decrypt the encrypted request id and then return the payload back associated to the same request id and we can use the data on the Front End to identify the user and resume the access-code verification step. But I donno, how to implement that or if there is any better solution? -
Django server not starting
I am unable to start the server, it's giving me the error below, i am using only one model and migrations seems to be fine, any clue where i am going wrong in this File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\management\commands\runserver.py", line 138, in inner_run handler = self.get_handler(*args, **options) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\contrib\staticfiles\management\commands\runserver.py", line 27, in get_handler handler = super().get_handler(*args, **options) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\management\commands\runserver.py", line 65, in get_handler return get_internal_wsgi_application() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\servers\basehttp.py", line 45, in get_internal_wsgi_application return import_string(app_path) File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\utils\module_loading.py", line 17, in import_string module = import_module(module_path) File "C:\Users\atifs\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 850, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\Users\atifs\Documents\pythonmate_website\pythonmate\mysite\wsgi.py", line 17, in <module> application = get_wsgi_application() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\wsgi.py", line 13, in get_wsgi_application return WSGIHandler() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\handlers\wsgi.py", line 127, in __init__ self.load_middleware() File "C:\Users\atifs\Documents\pythonmate_website\env\lib\site-packages\django\core\handlers\base.py", line 58, in load_middleware mw_instance = middleware(adapted_handler) TypeError: __init__() takes 1 positional argument but 2 were given -
Free text in Select2ListView django-autocomplete-light
:) I'll expose my case as detailed as possible: I'm using the functionality of autocomplete to automatically populate a value that is dynamic into the form. The form has several values, when you fill the first 3 I'm able to run an operation (with those values) and return a suggested value to the user. I needed to adapt a bit the return of parameters but I achieved it with Select2ListView class MyFunctionAutocomplete(autocomplete.Select2ListView): def get_list(self): if not self.request.user.is_authenticated: return [""] try: field1_pk = self.forwarded["field1"] field2_pk = self.forwarded["field2"] field3_pk = self.forwarded["field3"] except AttributeError: return [""] try: ObjField1 = ModelField1.objects.get(pk=field1_pk) ObjField2 = ModelField2.objects.get(pk=field2_pk) ObjField3 = ModelField3.objects.get(pk=field3_pk) return_value = ObjField1.get_result(param1=ObjField2, param2=ObjField3) except (ModelField1.DoesNotExist, ModelField2.DoesNotExist, ModelField3.DoesNotExist): return [""] return [return_value] With this code I'm able to do what I need when the requirements (forwarded value) are present. So far, so good My problem: I cannot ADD any value as an extra option. This value IS NOT a ForeignKey, it's a simple Float. I want the user to be able to use my suggested value or instead just replace it by another value of their choice. Let's say in the dropdown they have the value 3.22221 and they want to write 12.11. Since it can be … -
Issue Django Migrations Tree - Deployment Pythonanywhere
guys I have been having this issue when managing Django migrations on deployment, and I would like yo know what approach should I take: I am developing an application using Django and I am using Pythonanywhere to deploy the webapp, I am using sqlite as the database. I understand the Django Migrations work like a tree or a sequence (001, 002), but every time I make a change in a field locally it works fine because the tree have been save and the sequence have not changed, but when deploying the changes through github (having deployed the webapp and calling the migrations and migrate command, which creates another migrations files and sequence), usually I got an error indicating that the migration tree is broken; so I have to go to the app's migration folder and delete them and call again the migrations and migrate command. This is causing me a lot of problems due that I do not want to mess with schema of the database and loss the information. So, It is just me or anyone else is having this issue the migrations tree, not only on pythonanywhere but on others servers. Thank you guys! -
How do I use the Django rest framework to prolong a JWT session token?
I'm using Django 3.2 with the django.auth.contrib app and djangorestframework-jwt==1.11.0. How do I prolong/reissue a new session token upon receiving a request for an authenticated resource and validating the user can access that resource? I use the following serializer and view to login the user and issue the initial token class UserLoginSerializer(serializers.Serializer): username = serializers.CharField(max_length=255) password = serializers.CharField(max_length=128, write_only=True) token = serializers.CharField(max_length=255, read_only=True) def validate(self, data): username = data.get("username", None) password = data.get("password", None) user = authenticate(username=username, password=password) if user is None: raise serializers.ValidationError( 'A user with this email and password is not found.' ) try: payload = JWT_PAYLOAD_HANDLER(user) jwt_token = JWT_ENCODE_HANDLER(payload) update_last_login(None, user) except User.DoesNotExist: raise serializers.ValidationError( 'User with given email and password does not exists' ) return { 'username':user.username, 'token': jwt_token } class UserLoginView(RetrieveAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) response = { 'success' : 'True', 'status code' : status.HTTP_200_OK, 'message': 'User logged in successfully', 'token' : serializer.data['token'], } status_code = status.HTTP_200_OK return Response(response, status=status_code) I have this in my settings file to keep the session to 1 hour initially JWT_AUTH = { # how long the original token is valid for 'JWT_EXPIRATION_DELTA': datetime.timedelta(hours=1), } The client submits the session token … -
How settings Redis not working in channels Layer?
I am trying to use django_redis's RedisChannelLayer as django channels's channel layer backend. Which results in the websocket opening and closing instantly. But it work fine with In memory channel layer. CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("127.0.0.1", 6379)], }, }, } -
Tempus Dominus DatePicker in Django showing one day less when I get the data for edit
I have a Table with all my data, and when I try to edit one row I catch all data to a form, but the datepicker is showing ALWAYS one day less than the one entered. How can I solve this?. I read something about the DateTime from JS but I didn't find anything to solve my problem. This is how the data is displayed in my table: And in my form this is how it is received when I clicked the edit button (SubTotal, Calculated IVA and Total are in 0, ignore it, It is not relevant :D ): Form.py from datetime import datetime from django.db.models.base import Model from django.forms.fields import DecimalField from django.forms import * from core.erp.models import Sale from tempus_dominus.widgets import DatePicker class SaleForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = Sale fields = '__all__' widgets = { 'cli': Select( attrs={ 'class': 'form-control select2' } ), 'date_joined' : DatePicker( options={ 'maxDate': datetime.now().strftime('%Y-%m-%d'), 'useCurrent': True, 'collapse': False }, attrs={ 'append': 'fas fa-calendar', 'icon_toggle': True, } ), 'subtotal': NumberInput( attrs={ 'class':'form-control', 'disabled' : True, 'autocomplete': 'off' } ), 'iva': NumberInput( attrs={ 'class':'form-control' } ), 'total': NumberInput( attrs={ 'class':'form-control', 'disabled': True, 'autocomplete': 'off' } ) } exclude … -
does it make sense to use django urls for view test?
im new to django and im working on a webesite and i want to right unit tests for it and im kind of confused how to do it. does it make any sense to get urls from django its self and test their views? from django.test import TestCase from django.urls import get_resolver from kernel.settings.base import TEMPLATES_DIR class ViewNameViewTest(TestCase): Site_urls= list(set(v[1] for k,v in get_resolver().reverse_dict.items())) Site_urls= [i.replace('\\','') for i in Site_urls] Site_urls= [i.replace('/','') for i in Site_urls] Site_urls= [i.replace('$','') for i in Site_urls] def test_url_exists(self): for i in self.Site_urls: with self.subTest(line= i): response = self.client.get(f'/{i}/') self.assertEqual(response.status_code, 200) also other tests like if view uses correct template which acquires url names... my url examples: urlpatterns = [ path('about/', aboutView.as_view(),name='About'), ] so is this the correct way of doing it or should i use static files? -
How do I get website to display local time?
If I run this in VS Code, it gives me the correct local time: from time import strftime time = strftime("%H:%M %p") print(time) But if I use the same code in a Django project, my website displays a time which is 8 hours behind local time. from time import strftime,localtime def time_display(request): context = { "date":strftime("%b %d, %Y",localtime()), #DOESN'T DISPLAY LOCAL TIME "time1": strftime("%H:%M %p",localtime()), #DOESN'T DISPLAY LOCAL TIME "time3": strftime("%H:%M %p"), #DOESN'T DISPLAY LOCAL TIME } return render(request,'time_display.html',context) How do I fix it to display correct local time where the webpage is being viewed? -
Django: How to locate caller of the "/device/event" route?
I am using Datadog to understand the frequency of the routes in a Django project. Datadog reports that the most frequent route is /device/event, and I have no idea what this route is or what is calling it. How would a person figure out its origin or where it's defined? -
count each occurrences when date falls within a range
I am trying to count each time the value of month in created_on falls within different months, using this django orm below: result_qs = Model.objects.all().annotate( spring=Count(Case(When(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1))), summer=Count(Case(When(ExtractMonth("created_on") in [6, 7], then=1))), fall=Count(Case(When(ExtractMonth("created_on") in [8, 9, 10, 11, 12], then=1))), year=ExtractYear("created_on") ) I'm getting the error When() supports a Q object, a boolean expression, or lookups as a condition. When I apply Q notations to one of the cases, such as: spring=Count(Case(When(Q(ExtractMonth("created_on") in [1, 2, 3, 4, 5], then=1)))), cannot unpack non-iterable bool object Any suggestions? -
Why we need to setup AWS and POSTgres db when we deploy our app using Heroku?
I'm building a web api and the training video that I follow at first deploy everything locally then after making sure everything works he is transfering all static files to AWS and for DB he switches from SQLdb3 to POSgres. django portfolio I still don't understand this part why we need to put our static files to AWS and create POSTgresql database even there is an SQLdb3 default database from django. I'm thinking that if I'm the only admin and just connecting my GitHub from Heroku should be enough and anytime I change something in the api just need to push those changes to github master and that should be it. Why after deploying everything locally we are moving to AWS and Postgres setup and do the things from the beginning. Still not get it! Can anybody explain this ? Thanks -
Forms in Django. Drop-down list
In a django (python) project, I have a foreign key model that reflects a form to fill out. Is it possible to make it so that if the user does not find his option in the drop-down list, he has the opportunity to fill in this field, but with his own option (respectively, with saving to the database). And in the future this option will be shown in the drop-down list. Like in the picture. https://i.stack.imgur.com/APDr5.png So that the user can create a new tag if it is not in the drop-down list. What should be applied to implement this idea? What can be found in the documentation? -
Backend and Frontend in Docker work locally but not remotely
Problem I have three Docker containers: a backend, a frontend and an nginx container that handle requests. When I run it on my computer (windows laptop with docker engine), everything works perfectly. I can see the call are made in the logs of the containers: reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/bundle.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/vendors~main.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:00 +0000] "GET /static/js/main.chunk.js HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:01 +0000] "GET /favicon.ico HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - [10/Oct/2021:21:15:01 +0000] "GET /manifest.json HTTP/1.1" 304 0 "http://localhost/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/94.0.4606.71 Safari/537.36" reverse_proxy_1 | 172.19.0.1 - - … -
Why is the View returning None when I navigate to the payment page in Django?
The rest of the application is working well but a problem arises when I navigate to the payment page, the app returns None. I can't figure out where the error is. This is the payment_page.html, the error arises when I try to access this page {% extends 'customer/base.html' %} {% load bootstrap4 %} {% block head %} <script src="https://js.stripe.com/v3/"></script> {% endblock %} {% block main %} {% if not request.user.customer.stripe_payment_method_id %} <div class="alert alert-danger alert-dismissible fade show" role="alert"> Let's add your credit / debit card to <strong>Create a Job</strong> <button type="button" class="close" data-dismiss="alert"> <span aria-hidden="true">&times;</span> </button> </div> {% endif %} <b class="text-secondary">Your Credit / Debit Card</b> <style> .StripeElement { height: 40px; padding: 10px 12px; width: 100%; color: #32325d; background-color: white; /*border: 1px solid transparent; */ border: 1px solid #cfd7da; border-radius: 4px; } .StripeElement--focus { border-color: #80bdff; box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, .25); } .StripeElement--invalid { border-color: #fa755a; } .StripeElement--webkit-autofill { background-color: #fefde5 !important; } </style> <div class="card bg-white mt-2 mb-5"> <div class="card-body"> {% if request.user.customer.stripe_payment_method_id %} <div id="change-card" class="input-group"> <input type="text" class="form-control" disabled value="**** **** **** {{request.user.customer.stripe_card_last4}}"> <div class="input-group-append"> <form method="POST"> {% csrf_token %} <button type="submit" class="btn btn-danger">Remove</button> </form> </div> </div> {% else %} <form id="setup-form" data-secret="{{ … -
Updating many to many model in Django Rest Framework
I have the following models: class Settings(models.Model): ... category = models.ManyToManyField( Category) hsk = models.ManyToManyField( HSKLevels) class Meta: db_table = 'settings' I can quite easily update my main table via REST. The problem is that I cannot figure out how to update the hsk table with REST. class HSKLevels(models.Model): level = models.PositiveIntegerField(primary_key=True) label = models.CharField(max_length=50) value = models.CharField(max_length=50) class Meta: db_table = 'hsk_levels' This is my serializer: class SettingsSerializer(serializers.ModelSerializer): class Meta: model = Settings fields = ["user","traditional","category", "hsk","audio_download","show_read","show_pinyin","char_size","pinyin_size","start_date","end_date","speed","volume", "char_colors", "pinyin_colors", "global_dash","first_tone","second_tone","third_tone","fourth_tone","fifth_tone","word_selection","limit_selection","hsk_selected","sentence_selection","mem_limit_selection","show_outline","show_character","show_hint_after_miss"] depth = 1 With this setup, I am able to add many to many connections, but I cannot delete any many to many connections. What I'd prefer is if a given connection isn't present - is to delete it. So I'd have a JSON object like this (or alternatively, an array, I am not picky): hsk: { hsk1: true, hsk2: true, hsk3: true, hsk4: true, hsk5: true, hsk6: true, hsk7: true, hsk8: true, hsk9: true, hsk9plus: true, }, And if one of these values is false or not present, it gets deleted. -
Django & Leaflet & modal fade
Can someone send me an example of programs (views.py, urls.py, template ...) which uses class = "modal fade" to introduce latitude and longitude of a PointField, then search if this point exists with the filter command and display it on a map. I inform you that I use Django and Leaflet. Thank you so much. -
display multiple selected checkboxes ticked in update form in django
In my create form i have saved certain values of season_interest as summer, winter in my database now these values should be shown ticked in update form let us consider my forms.py as SEASON_INTEREST_CHOICES = ( ('Spring','Spring'), ('Summer','Summer'), ('Autumn','Autumn'), ('Winter','Winter'), ('Year round','Year round'), ) class HorticlutureUpdateForm(BetterModelForm): season_interest = forms.MultipleChoiceField( required=False,label=('Season of Interest'), widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}), choices=SEASON_INTEREST_CHOICES, ) here is my models.py class Items(models.Model): SEASON_INTEREST_CHOICES = ( ('Spring','Spring'), ('Summer','Summer'), ('Autumn','Autumn'), ('Winter','Winter'), ('Year round','Year round'), ) season_interest = models.CharField(max_length=200,blank=True, null=True,verbose_name='Season of Interest') When i am using widget=forms.CheckboxSelectMultiple(attrs={'checked' : 'checked'}) in updateform it is showing all the choices as ticked rather than the values that are saved in database(i.e clay, chalk only should be ticked in updateform display) Currently it is showing in this way in update form How i need the image to be in update view of item in chrome