Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Runtime error in Ubuntu, Warning in Windows with matplotlib and django
I am trying to render matplotlib pyplots by calling a function using ajax, creating plots and saving them to a figure and calling them to the html template however I seem to run into a warning in Windows: Warning: QApplication was not created in the main thread. and a runtime error while running it in Ubuntu: RuntimeError: main thread is not in main loop I tried using the suggestion matplotlib.use('Agg') This didn't display any error however it shutdown the django server I couldn't find any workaround to have matplotlib simply plot and save the figure without the use of a GUI and return it to HTML without disrupting the django server Here are parts of my code: dim = request.GET['dimension'] fig1 = plt.figure(figsize=(15,15)) ax1 = fig1.add_subplot(111) fig2 = plt.figure(figsize=(20,20)) ax2 = fig2.add_subplot(111, projection='3d') if dim=='2D': df.plot(x='colname1', y='colname2', ax=ax1) else: ax2.plot_trisurf(df['column1'].values, df['column2'].values, df['column3'].values, linewidth=0, antialiased=False) if(dim=='2D'): ax1.set_ylim(bottom=0) ax1.set_xlim(left=0) fig1.savefig(buf,format='png', bbox_inches="tight") buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) elif(dim=='3D'): ax2.set_ylim(bottom=0) ax2.set_xlim(left=0) fig2.savefig(buf,format='png', bbox_inches="tight") buf.seek(0) string = base64.b64encode(buf.read()) uri = urllib.parse.quote(string) plt.close() data = { 'data': uri } return JsonResponse(data) matplotlib.use('Agg') was the main suggestion in several blogs, but that terminated my server. I am not sure how to handle this, please help … -
Why does AudioSegment outputs an incomplete audio file?
I am running a Django application and in one of my views, I receive an audio file sent via POST. I save it as a temp file in the following way def save_temp_file(temp_file, filename): with open('/tmp/uploads/{0}'.format(filename), 'wb+') as destination: for chunk in temp_file.chunks(): destination.write(chunk) destination.close() Then I convert the .webm received to .mp3 format using the following function from pydub import AudioSegment def convert_wav_ogg(filename): file_path = "/tmp/heroic_uploads/" + filename AudioSegment.from_file(file_path).export('/tmp/uploads/{}.mp3'.format(filename), format='mp3') return "{0}.mp3".format(filename) The problem I get is that the output file sometimes get cut in the middle. For instance, the audio plays correctly from 0:00 to 0:05 and then cuts to 0:15. It's really weird and there doesn't seem to have any pattern to it. The problem only seems to happen in the production environment, and if I run the exact same lines of code in the Python interactive console over the same files, the output is correct. Any clues to why that is? I'm running: daphne==2.5.0 Django==2.2.14 pydub==0.24.1 -
No module named tenant_schemas.tests.template_loader - Django 1.10
I am trying to make a setup to test my application, but I am getting a erro which I cant resolve, someone knows how? I am using django in version 1.10 and django-tenant-schemas==1.9.0 this is a simples code snippet from the django tenant documentation from tenant_schemas.test.cases import TenantTestCase from tenant_schemas.test.client import TenantClient from django.shortcuts import reverse class TelemedicinaTestCase(TenantTestCase): def setUp(self): self.c = TenantClient(self.tenant) def test_user_profile_view(self): response = self.c.get(reverse('telemedicina:redirecionador')) self.assertEqual(response.status_code, 200) This is the error: ➜ python manage.py test tenant_schemas -k Using existing test database for alias 'default'... E ====================================================================== ERROR: tenant_schemas.tests (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: tenant_schemas.tests Traceback (most recent call last): File "/home/matheus/.pyenv/versions/3.6.8/lib/python3.6/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/home/matheus/.pyenv/versions/3.6.8/lib/python3.6/unittest/loader.py", line 369, in _get_module_from_name __import__(name) File "/home/matheus/.pyenv/versions/doutorfacil/lib/python3.6/site-packages/tenant_schemas/tests/__init__.py", line 1, in <module> from .template_loader import * ModuleNotFoundError: No module named 'tenant_schemas.tests.template_loader' ---------------------------------------------------------------------- Ran 1 test in 0.000s FAILED (errors=1) Preserving test database for alias 'default'... -
How to test the LoginView in Django by making a post request
I have a custom login view which redirects users to different pages based on if user has OTP setup. In test, I make a post request to login view, but I get HttpResponseBadRequest 400. If I make a get request, I get a correct 200 response. class TestLoginRedirect(TestCase): @classmethod def setUpTestData(cls): cls.password='aoisjdoaisjd' # create a user without OTP cls.user = CustomUser.objects.create_user( username='aseem', password=cls.password ) def test_login(self): response = self.client.post( path=reverse('login'), data={ 'username': 'aseem', 'password': self.password } ) print(response) -
Django view.py QuerySet with foreign keys and many-to-many relationships
I am trying to create a query that will give me the output of a "Application" and it's total sum of CPU, which is gathered from all of the Hosts that make up the Application. Here is the layout of the model: class Application(models.Model): name = models.CharField(max_length=100, null=False, unique=True) hosts = models.ManyToManyField(Host, through='Host_Application', related_name='hosts_belonging_to_app') class Host(models.Model): name = models.CharField(primary_key=True, max_length=75, unique=True, null=False) class HostStat(models.Model): host = models.ForeignKey(Host, blank=True, null=True, on_delete=models.CASCADE, related_name='host_belonging_to_stats') cpu = models.IntegerField(blank=True, null=True) Ideally, I would be able to have a list that looks something like this-- that is sorted in order of the highest CPU: Application Name, CPU Cat Application, 3435 Dog Application, 23 Random Application, 10 Another Application, 0 -
Subprocess in Django app won't write file in production
Here's the setup- It's a Windows 2016 Server with Apache as the web server. The subprocess call is as follows: subprocess_results = subprocess.run(['pgsql2shp', '-f', <path-to-output-shapefile>, '-h', '127.0.0.1', '-u', <user_name>, '-P', <password>, 'database_name', 'SELECT * FROM temp'], capture_output=True) When I run this in development (manage.py runserver), the shapefile gets created at <path-to-output-shapefile>. However, if I try to run it in the Apache production server, subprocess_results.returncode returns 0, but no shapefile is written to <path-to-output-shapefile>. I've checked the following: The postgresql table does exist. Folder permissions for <path-to-output-shapefile> has "Full Control" for SYSTEM, Administrators, USERS, and my user account. I've run the pgsql2shp command in an admin PowerShell and the shapefile gets created. Can someone tell me what I might be doing wrong? Is it a Django setting? Is it an Apache configuration I'm missing? -
django-rest-knox in production: "TypeError: create() takes 1 positional argument but 2 were given"
I am doing token authentication with Knox. It has worked perfectly through development, but now that I try to deploy on PythonAnywhere, I get the error in the title: "TypeError: create() takes 1 positional argument but 2 were given". This is the full traceback: 2020-09-10 13:42:03,788: Internal Server Error: /api/auth/login Traceback (most recent call last): File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/views/generic/base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/rest_framework/views.py", line 505, in dispatch response = self.handle_exception(exc) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/rest_framework/views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/rest_framework/views.py", line 476, in raise_uncaught_exception raise exc File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/rest_framework/views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "/home/<user>/<website>/registration/views.py", line 38, in post "token": AuthToken.objects.create(user)[1] File "/home/<user>/.virtualenvs/<website>/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) TypeError: create() takes 1 positional argument but 2 were given My registration.views (error occurs in second-to-last line): class RegisterDetail(generics.GenericAPIView): serializer_class = RegisterSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) class … -
403 error when posting to django view from react native
I am having a hard time getting data to and from django/react. I'm wondering if anyone has any suggestions. Here is the django view I would like to access from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse @csrf_exempt def getData( requests ): return JsonResponse( {"data": "hello world" } ) My react native code looks like this: const fetchSearchItems = ( query ) => { console.log( query ) fetch(url, { method: 'post', headers: {'Content-Type': 'application/json', 'Accept': 'application/json'}, body: JSON.stringify({ query: query }) }).then( (data) => { console.log( data ) }) .catch(function(error) { console.log('There has been a problem with your fetch operation: ' + error.message); // ADD THIS THROW error throw error; }); } My django settings.py ALLOWED_HOST = [] My info.plist <key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSExceptionDomains</key> <dict> <key>mydomain</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict> And finally the error message: { type: 'default', status: 403, ok: false, statusText: undefined, headers: { map: { vary: 'Accept-Encoding', date: 'Thu, 10 Sep 2020 18:05:20 GMT', 'content-type': 'text/html', 'x-frame-options': 'DENY', server: 'PythonAnywhere', 'referrer-policy': 'same-origin', connection: 'keep-alive', 'x-content-type-options': 'nosniff', 'transfer-encoding': 'Identity', 'content-encoding': 'gzip' } }, url: 'xxxxxx', bodyUsed: false, _bodyInit: { _data: { size: 2864, offset: 0, blobId: 'EA6FE4A5-BE26-4D8A-98D2-8EA76C248D52', type: 'text/html', name: 'xxxx', __collector: {} } }, … -
Style CheckboxSelectMultiple form field. Django
I have a form which has one checkboxselectmultiple field: class CreateRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = ('name', 'image', 'description', 'cooking_time', 'tags') widgets = { ... 'tags': forms.CheckboxSelectMultiple(), ... } I can iterate through field's options like: {% for option in form.tags %} {{ option.tag }} {{ option.choice_label }} {% endfor %} How would I render {{ option.tag }} as an input field? i.e: <input type="checkbox"...> Thanks. -
Django: What is the simplest way to shorten the application url?
I have a Django application that has a long name "encyclopedia". I would like the url for the application that appears on the address bar to be something shorter like "http://127.0.0.1:8000/ency" instead of "http://127.0.0.1:8000/encyclopedia" . What is the simplest way to accomplish this without compromising the functionality of the application? I suspect its something very simple like modifying ROOT_URLCONF in settings.py. There is a general lack of examples that illustrate how to in the documents. -
Django admin different list_display based on what filter is selected?
I want to display based on a Boolean field filter different list_displays for my model in Django admin. For example, if the boolean field is false I should list_display=('name', 'age') but if is true I should display list_display=('name', 'school', 'grades') assuming that my Model have all those fields. -
Why is request.user is anonymous in Django RedirectView?
There are a lot of questions similar to this one, but none quite capture the situation I am in. I am coding a Django/ React app and I have integrated with Spotify. Currently, on the Django side of things I have the user getting redirected back to their profile page after connecting to Spotify. This is done hardcoding the URL with the http response redirect: class SpotifyCallbackView(RedirectView): def handle_callback(self, request): print(self.request.META) if request.GET.get("refresh_token", False): refresh_token = request.GET["refresh_token"] code = request.GET["code"] if request.GET.get("refresh_token", False): response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "refresh_token", "refresh_token": refresh_token, }, headers=AUTH_HEADER, ) return response.json() else: response = requests.post( "https://accounts.spotify.com/api/token", data={ "grant_type": "authorization_code", "code": code, "redirect_uri": request.build_absolute_uri("callback"), }, headers=AUTH_HEADER, ) return response.json() def get(self, request, *args, **kwargs): auth_items = self.handle_callback(request) access_token = auth_items["access_token"] if "refresh_token" in auth_items.keys(): refresh_token = auth_items["refresh_token"] else: refresh_token = "" if refresh_token != "": return HttpResponseRedirect('http://localhost:3000/users/1/' + access_token + '/' + refresh_token) else: return HttpResponse(access_token) Obviously, the user's ID is not always going to be "1" so I want to be able to grab that ID from somewhere, and after some searching I saw that I can grab that info from self.request.user, except I can't. It's anonymous. Why is this the case? I am … -
add to cart without login or register
models.py class orderbook(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ordered = models.BooleanField(default=False) Book = models.ForeignKey(book, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) def __str__(self): return f"{self.quantity} of {self.Book.book_nm}" def get_total_book_price(self): return self.quantity * self.Book.book_price class Order(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) books = models.ManyToManyField(orderbook) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def __str__(self): return self.user.username def get_total(self): total = 0 for order_book in self.books.all(): total += order_book.get_total_book_price() return total views.py def add_to_cart(request, slug): Book = get_object_or_404(book, slug=slug) order_book, created = orderbook.objects.get_or_create( Book=Book, user=request.user, ordered=False) order_qs = Order.objects.filter(user=request.user, ordered=False) if order_qs.exists(): order = order_qs[0] if order.books.filter(Book__slug=Book.slug).exists(): order_book.quantity += 1 order_book.save() messages.info( request, " Cart updated") else: order.books.add(order_book) messages.info(request, "Added to your cart.") else: ordered_date = timezone.now() order = Order.objects.create( user=request.user, ordered_date=ordered_date) order.books.add(order_book) messages.info(request, "Added to your cart.") return redirect(request.META['HTTP_REFERER']) I want to make add to cart work without login or register and whenever user register or login items will be reflected in the user's cart. It may be using a session or overriding the user model. -
How to handle asynchronous requests to an API that are dependent on one another?
Background See diagram below for a hypothetical Django-rest-framework backend structure where A, B, and C are Django models in models.py which have corresponding endpoints for retrieving their data in urls.py /A, /B, and /C for example. Each one of these models contains an isDirty flag along with their own value. Model C is dependent on Model B and Model B is dependent on A. Example: One example could be: A: Timeseries data block [n x m] B: Common start date C: Calculation model. In this example, in order to calculate C, it must retrieve the common start date among all columns of data, which relies on the actual timeseries selected in A. Problem I have a frontend of a web application that is sending asynchronous requests to attempt to display both B and C on a particular screen. Assume that all three models are isDirty=True at this point in time on screen enter. Is there an industry standard approach to handling asynchronous requests to an API that are dependent on one another? If not, how do people typically handle problems such as this regarding state? Solution Attempt: I have attempted to use an atomic transaction on the model tables themselves … -
How to access django server from different network?
I have my Django application running with python manage.py runserver 0.0.0.0:8000 It is accessible within same network in every device with <your LAN ipv4 address>:8000 However. I want to access this outside my network with <your public address>:8000 What is the way to do this? Django app is running on windows 10. I have already written ALLOWED HOSTS : ["*"] Maybe there's some issue with DNS or firewall. 0.0.0.0 should let me access with <your public address>:8000 but it is not giving access. Please help.. -
How to refer to child class in Django REST framework mixin?
In Django Rest Framework, I'm trying to write a mixin for the following two methods in view sets: class OrderViewSet(viewsets.ModelViewSet): # ... def get_object(self): pk = self.kwargs.get('pk') if pk == 'me': user = self.request.user return get_object_or_404(Order, user=user.pk) return super(OrderViewSet, self).get_object() def get_queryset(self): user = self.request.user return Agent.objects.filter(user=user) This seems straight forward except for the super(OrderViewSet, self) because I'll need to somehow refer to different viewset classes in my mixin class before they're declared. Any tips? -
url not showing because of middleware file
Im trying to access my index view but i' m automatically redirected to show_login view , i think that the problem comes from my custom middleware file here is the main view: def indexmain(request): return render(request, "main_template/index.html") Urls : path('admin/', admin.site.urls), path('accounts/',include('django.contrib.auth.urls')), path('', views.ShowLoginPage, name="show_login"), path('indexmain', views.indexmain,name="index"), path('get_user_details', views.GetUserDetails), path('logout_user', views.logout_user,name="logout"), path('doLogin',views.doLogin,name="do_login"), here is my custom Middleware file: from django.http import HttpResponseRedirect from django.urls import reverse from django.utils.deprecation import MiddlewareMixin class LoginCheckMiddleWare(MiddlewareMixin): def process_view(self,request,view_func,view_args,view_kwargs): modulename=view_func.__module__ print(modulename) user=request.user if user.is_authenticated: if user.user_type == "1": if modulename == "gestion.HodViews": pass elif modulename == "gestion.views" or modulename == "django.views.static": pass elif modulename == "django.contrib.auth.views" or modulename =="django.contrib.admin.sites": pass else: return HttpResponseRedirect(reverse("admin_home")) elif user.user_type == "2": if modulename == "gestion.StaffViews" or modulename == "gestion.EditResultVIewClass": pass elif modulename == "student_management_app.views" or modulename == "django.views.static": pass else: return HttpResponseRedirect(reverse("staff_home")) else: return HttpResponseRedirect(reverse("show_login")) else: if request.path == reverse("index") or request.path == reverse("show_login") or request.path == reverse("do_login") or modulename == "django.contrib.auth.views" or modulename =="django.contrib.admin.sites" : pass else: return HttpResponseRedirect(reverse("show_login")) -
Unable to set session variable across subdomains with Django
I have a site that uses multiple subdomains to separate some apps into their own little "mini-sites". For example, I have "mydomain.io" which is a kind of landing page, "5e.mydomain.io" and "pf2e.mydomain.io" which distinguish between different RPG systems, as well as "wb.mydomain.io" which is for the worldbuilding app. They all use the same database and code, but have different templates and some different CSS. I've got it all working with django-hosts. I also managed to get it to keep a user logged in across the various subdomains. However, I'm still having trouble saving a session variable if I'm on any of the subdomains rather than just the main domain. For example, I have some JS that will send an AJAX request to a view which will set "request.session['nav']" to either pinned or unpinned (to let the user pin/collapse the main nav menu). This is only working on the main domain, though. Here's my code. settings.py - you can see I did set the cookie domain to ".mydomain.io" and that solved the login issue MIDDLEWARE = [ "django_hosts.middleware.HostsRequestMiddleware", "corsheaders.middleware.CorsMiddleware", "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", "admin_reorder.middleware.ModelAdminReorder", "django_hosts.middleware.HostsResponseMiddleware", ] ROOT_URLCONF = "config.urls" ROOT_HOSTCONF = "config.hosts" DEFAULT_HOST = "www" PARENT_HOST = … -
How to choose which model to initialize in Django
I'm working on an installable app for Django that would requires a user's ability to use it or replace it with a custom version that is a subclass from the same base class. This is very similar approach to how Django's Default User Model works. What I am looking to do is not have it generate the default model in the database if it's been overridden. Any suggestions on a strategy for this would be greatly appreciated. RB -
Switching from Django Registration to Token registration
I have a Django Rest/ Vue.js application. For now I am using regular Django authentication with registration and django_registration templates. But since I am using it for a SPA application, it seems awkward. So I tried to implement token authentication with 'rest_framework.authtoken'. I've managed to get my token but it seems that I have to rewrite all my back-end logic to make it works because since I am not logging in with Django, all of mine permissions aren't working anymore: class IsOwnReviewOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.restaurant_review.review_author == request.user class IsAuthorOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.review_author == request.user Is there a painless way to switch from Django REST authentication to token authentication so user can log in and log out straight from my SPA app? -
Is there any field which is opposite of is_superuser?
Well my problem is quite complicated I think. Actually I am making building a website and i have almost made complete login and sign up functionality and suddenly i noticed a strange behavior with my website. I was login with by admin on a tab and at the same i was logging in to my website and i notice that before logging in there was an option appearing for logout but i did not log in at that sport. When i clicked on the logout button then my superuser just log out. So that when a super user is login from admin site than every new user can see log out button so which can click and superuser will log out. What kind of logic i can apply after that when all the users are login and only logout button appear otherwise not. I am trying with the following code. Please help me if you can. -----base.html---- {% if user.is_active and user.is_authenticated and user.is_not_superuser %} <a href="{% url 'accounts:logout' %}" class="get-started-btn">Logout</a> {% endif %} {% else %} <a href="{% url 'accounts:signup' %}" class="get-started-btn">Get Started</a> {% endif %} -
What is the best way to manage/preserve querystrings in django?
So my question basically is the title, more specifically, what is the best way to preserve the current url's querystring(s), if you want to add some more parameters, like filters on the next page in django? Example: You are currently on this /search/?location=london&type=1 page, that is a search result page, and you want to sort the results, so you want the next url to be /search/?location=london&type=1&sorting_order=-date_created. The problem comes from the fact, that if you do a usual form submission, the url will be /search/?sorting_order=-date_created. I did some research and I realized that there are quite a few ways to solve this problem, I even figured out a way to do it myself: Option 1 - Send hidden form fields populated by the existing querystring parameters, when submitting the sorting form. Option 2-2.5 - Building the urls as this blogpost describe https://simpleisbetterthancomplex.com/snippet/2016/08/22/dealing-with-querystring-parameters.html Option 3 - Building the urls with javascript. So after all, I am seriously confused about the fact, that all these options feel a bit sketchy at best, and I couldn't really believe that there is no official, predefined way to solve such a common problem, so please tell me there is. -
Objects are not being added in m2m field using UpdateView Django
TL:DR All objects get vanished from many-to-many field upon updating using UpdateView. I have a model to represent an instance of recipe: class Recipe(models.Model): ... tags = models.ManyToManyField(Tag, related_name='recipes', blank=True) ... This model has a ModelForm: class CreateRecipeForm(forms.ModelForm): class Meta: model = Recipe fields = (..., 'tags') A view class is a heir of UpdateView and looks like following: class ChangeRecipe(UpdateView): template_name = 'change_recipe.html' form_class = CreateRecipeForm success_url = reverse_lazy('index') model = Recipe def form_valid(self, form): new_tags = [name for name in ('breakfast', 'lunch', 'dinner') if name in self.request.POST] ... for tag in form.instance.tags.all(): if not tag.name in new_tags: form.instance.tags.remove(tag) else: new_tags.remove(tag.name) for name in new_tags: form.instance.tags.add(Tag.objects.get(name=name)) ... The tag m2m field is renered this way: <div class="tags__item"> {% for tag, tag_value in form.tags.field.choices %} <div class="tags__item"> <input type="checkbox" name="{{ tag.instance.name }}" id="id_{{ tag.instance.name }}" class="tags__checkbox tags__checkbox_style_{{ tag.instance.style }}" {% if tag.instance in form.instance.tags.all %}checked="checked"{% endif %}> <label for="id_{{ tag.instance.name }}" class="tags__label">{{ tag.instance.template_name }}</label> </div> {% endfor %} </div> The proble as mentioned in TL:DR is that all objects simply get removed from the m2m field leaving it blank. I checked if checkboxes are properly delivered with request.POST and yes, they are. I am getting all names and Tag objects … -
Instabot :: Django , How To cache bot.login in instabot for multiple account and use anytime i want without relogin again
Instabot :: Django , How To cache bot.login in instabot for multiple accounts and use anytime i want without relogin again ! -
django update function based view of multiple models
I have a parent model and two children models and I made a view to add multiple children to one parent but I'm getting confused about making an update view for the parent with all children this is the form to create multiple children views.py def create_day_view(request,pk): mydate = get_object_or_404(MyDate,pk=pk) if request.method == 'POST': length = request.POST.get('length') sof_zman_1 = request.POST.get('sof_zman_1') sof_zman_2 = request.POST.get('sof_zman_2') sof_zman_tefila = request.POST.get('sof_zman_tefila') ad_image = request.POST.get('ad_image') day_details = MyDateDetails.objects.create( date = mydate, sof_zman_1 = sof_zman_1, sof_zman_2 = sof_zman_2, sof_zman_tefila = sof_zman_tefila, ad_image = ad_image, ) for file_num in range(0, int(length)): Image.objects.create( date = mydate, image = request.FILES.get(f'images{file_num}') ) context = {'mydate': mydate} return render(request, 'luach/create_day.html',context=context) I'm sharing the template so you will understand how the form works create_day.html {% extends 'luach/base.html' %} {% block content %} <div class='container'> <div class="jumbotron myjumbotron"> <div class="p-3 mb-2 bg-light text-center " style="border-radius: 10px;"> <h1 class='title-date text'>{{mydate.hebrew_date}}</h1> <h4 class='english-date'>{{mydate.english_date}}</h4> </div> <label>sof zman 1</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_1" class="form-control"> </div> <div class="col"> </div> </div> <label>sof zman 2</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_2" class="form-control"> </div> <div class="col"> </div> </div> <label>sof zman tefila</label> <div class="row"> <div class="col"> <input type="time" id="sof_zman_tefila" class="form-control"> </div> <div class="col"> </div> </div> <br> <!--<label>ad image</label> <input …