Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Some images not appearing in google news
I wanted our website articles to be appear in google news. I went to publisher center and filled all the necessary info. In sections, I selected feed and added the feed URL (my back-end is django). Everything looks ok. All the latest news appear in the way I wanted. The issue here is images. Images for some articles are not appearing. Why do some images appear and some don't. What are the things influencing this result. All images are of same size 920x520 . The image formats are jpg or png. Please help me out. Thanks. Sample item tag in the feed is <item><title>Sample title</title><link>https://sample.com/smaple-link/</link><description>Sample decription</description><guid>https://sample.com/smaple-link/</guid><content:encoded><figure><img src="https://sample.com/link-to-image" class="type:primaryImage"></img></figure></content:encoded><media:thumbnail width="300" url="https://sample.com/link-to-image" height="300"></media:thumbnail><figure type="image/jpeg"><image src="https://sample.com/link-to-image" caption="Strength and Clarity: Why Following Crowds Will Leave You Lost In The Noise"></image></figure></item> -
printing text in vertical align in django
here my code is working fine with html code and if placed in my project its not wotking here is my views.py import pdfkit class PrintLabels(View): def get(self, request, id, value): client = request.user.client order = OtherOrder.objects.get(client=client, id=id) items = order.otherorderitem_set.all() item_quantity = OtherOrderItem.objects.filter(other_order_id=id) url = '' for c in items: item = c.item if c.item.qr_code: s3 = boto3.client('s3') url = s3.generate_presigned_url('get_object', Params={ 'Bucket': 'AAAAAAAAAAA', 'Key': c.item.qr_code.name, }, ExpiresIn=1800) url = str(url) template = loader.get_template('index.html') context_dict = { 'items' : items, 'item': item, 'order' : order, 'item_quantity': item_quantity, 'qrcode_url': url, } context = Context(context_dict) html = template.render(context) result = StringIO.StringIO() pdfkit.from_string(html, 'applicationpdf.pdf') pdf = open("applicationpdf.pdf") response = HttpResponse(pdf.read(), content_type='application/pdf') return response here is my index.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Light Degree</title> <style> html { background-color:#f4f4f4; } body { margin:0px; } @media print { @page { margin: 0; } body { margin: 0cm; } } </style> </head> <body> <table border="0" cellspacing="0" cellpadding="0"> <tr> <td style="border-left: 1px solid #cccccc;"> <div class="" style="width:94.48px; height:861.73px;"> <table border="0" cellspacing="0" cellpadding="0" style="width:94.48px; height:861.73px;"> <tr> <td style="width:94.48px; height:861.73px; vertical-align: text-top;"> <div style="transform:rotate(90deg); width: 94.48px !important;"> <table width="100%" border="0" cellspacing="0" cellpadding="0" style="width:861.73px; height:94.48px;"> <tr> <td rowspan="2" … -
Django cors middleware not working when using GET on static image url
Hi I have ran into a problem with Django CORS configuration, I have tried using django-cors-headers and configured it properly in my settings, it works for making GET/POST requests to the api from my react frontend but anytime I try loading an image using image.src with "127.0.0.1:8000/path_to_my_image" the image loads properly in the network tab BUT it gives me a CORS same origin error right after for every image. DJANGO_APPS = [ ..., 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'config.settings.middleware.middleware.CorsFixMiddleware', ... ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) To clarify the loading of the image is working (the image is found, and I can access it without problems if I go to the image url in my browser, the only thing that fails is loading the image with ".src" from an element because of the CORS error. I tried to bypass the configuration by setting the response in a middleware, the middleware is correctly executed each time there's a response but it still doesn't work and the image is not showing any … -
Django how to add members to groups through signals?
my others signals working such as updating and creating instance but I am not understanding why it's not adding members to group? @receiver(post_save,sender=settings.AUTH_USER_MODEL) def update_user_profile_from_User_model(sender,instance,created,**kwargs): if instance.email: MyAuthors.objects.filter(user=instance).update(user=instance,first_name=instance.first_name) author = MyAuthors.objects.filter(user=instance) if not author and instance.is_blog_author and instance.email: MyAuthors.objects.create(user=instance,is_blog_author=instance.is_blog_author,first_name=instance.first_name,last_name=instance.last_name,email=instance.email) my_group = Group.objects.get(name='myauthors') my_group.user_set.add(instance) instance.save() I also tried this but didn't work. group = Group.objects.get(name='myauthors') if instance.is_blog_author: instance.groups.add(group) instance.save() -
Saving sql query in runtime Django
I use Django ORM to create complex sql queries dynamically, I want to save ---while running--- the sql query that Django builds for future use, I have not found a proper way to do it. As explained here there are two ways to access a query but only connection.queries contains a valid query, and needed to set debug=True. Because I want to do it in the product environment, debug=True are not really a solution for me, and i don't want to change the Django source code. Any solution/comment can help i use Django 2.2 -
Need to add auth token to graphene-django test using pytest
I am trying to add token to graphene-django headers using pytest. But It always return that user is anonymous as shown at the end but it should return user as token is added in fixture @pytest.fixture def creat_user(): user = User.objects.create(username="abc", email="x@x.com", password="abc123") token, __ = Token.objects.get_or_create(user=user) return user @pytest.mark.django_db def test_get_login_user(client_query, creat_user): headers = {"Authorization": f"Token {creat_user.auth_token}"} response = client_query( """ query { loginUser{ id, } } """, headers=headers, ) result = json.loads(response.content) print(result) Output {'errors': [{'message': "'AnonymousUser' object is not iterable", 'locations': [{'line': 3, 'column': 11}], 'path': ['loginUser']}], 'data': {'loginUser': None}} -
Unable to log in with email in django
I have created custom user model but unable to login with valid email id and password models.py class User(AbstractBaseUser): email = models.EmailField(verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) # a admin user; non super-user admin = models.BooleanField(default=False) # a superuser objects = UserManager() # notice the absence of a "Password field", that is built in. USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] methods like has_perm,has_module_perm are written. forms.py class AuthenticationForm(forms.Form): email = forms.EmailField(widget=forms.TextInput( attrs={'class': 'form-control','type':'text','name': 'email','placeholder':'Email'}), label='Email') password = forms.CharField(widget=forms.PasswordInput( attrs={'class':'form-control','type':'password', 'name': 'password','placeholder':'Password'}), label='Password') class Meta: fields = ['email', 'password'] views.py def loginEmployeeView(request): if request.method == 'POST': form = AuthenticationForm(data = request.POST) if form.is_valid(): print("1") email = request.POST.get('email') password = request.POST.get('password') print("2") user = authenticate(email=email, password=password) print("3") if user is not None: if user.is_active: print("4") login(request,user) messages.success(request,'Logged in successfully') return redirect('dashboard') else: messages.error(request,'user is not active') return redirect('login-employee') else: messages.error(request,'invalid username or password') return redirect('login-employee') else: print("5") form = AuthenticationForm() return render(request,'accounts/login.html',{'form':form,}) I tried to logged in with valid information still it shows invalid username or password. Thank you. -
Test django sqlite3 database with pytest in CI
I have an updater class which updates database tables (modifies, removes, adds). I need to write a tests for this updater. These tests will be called in gitlab CI. python3.9 project/manage.py makemigrations python3.9 project/manage.py migrate pytest -s -v --cov --cov-config .coveragerc -ra --tb=short {posargs:} "Test" database does not contain required tables until migrations call. I feel like there is existing "pytest mechanism" which allow to create fake sqlite3 database instance with performed migrations, which I do not know :D. Django database config: DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": os.path.join(BASE_DIR, "db.sqlite3"), "TEST": { "MIRROR": "default" } }, } I have already installed pytest-django and marked test with pytest.mark.django_db. Is it appropriate way of testing? -
How to toggle class for clicked button in for loop?
trying to add post to bookmark. posts are on home page with in for loop. I have trouble getting toggle class while clicking on add bookmark button for individual post. Django view @login_required def add_post_bookmark(request): ''' add post to bookmark ''' if request.POST.get('action') == 'post': result = '' is_bookmark = False id_ = request.POST.get('id') post = Post.objects.get(id=id_) if post.bookmarks.filter(id=request.user.id).exists(): post.bookmarks.remove(request.user) is_bookmark = False post.save() result = post.get_bookmarks_count() else: post.bookmarks.add(request.user) is_bookmark = True post.save() result = post.get_bookmarks_count() return JsonResponse({'result': result, 'bookmark_count': post.bookmarks.all().count(), 'post_id': id_, 'is_bookmark': is_bookmark}) Ajax // bookmarks posts $(document).on('click', '#bookmark_add', function (e) { e.preventDefault(); var bookmarkCount; var id = $(this).data("id"); $.ajax ({ type: 'POST', url: '{% url "users:add-post-bookmark" %}', data: { 'id': id, csrfmiddlewaretoken: '{{ csrf_token }}', action: 'post' }, success: function (response) { $('#'+id).empty().append(response['bookmark_count']); console.log(response); this_id = $(this).data("data-id"); //("id") console.log(this_id); // undefined $(this).find('i').toggleClass("fad fa-bookmark far fa-bookmark"); }, error: function (xhr, errmsg, err) { console.log("Error bookmarking post!"); } }); }) index.Html <span id="{{post.id}}" class="bookmark_coun text-muted">{{ post.get_bookmarks_count }}</span> {% if request.user.is_authenticated %} {% if request.user not in post.bookmarks.all %} <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="far fa-bookmark fa-lg"></i></button> {% else %} <button id="bookmark_add" class="bookmark" name="bookmark" data-id="{{post.id}}"><i class="fad fa-bookmark fa-lg"></i></button> {% endif %} {% else %} <a href="{% url 'users:register' %}" id="bookmark_add" … -
how to iterate through list inside another list - json + js
I'm trying to iterate over a list inside another list , here is my data : (3) [{…}, {…}, {…}] 0: {id: 9, check_in: '2021-10-02T15:58:00', check_out: '2021-10-05T10:17', visitors: Array(4)} 1: {id: 10, check_in: '2021-10-06T21:12:00', check_out: '2021-10-09T15:00', visitors: Array(4)} 2: {id: 11, check_in: '2021-10-27T21:34:00', check_out: '2021-10-29T21:34', visitors: Array(4)} length: 3 my visitors array looks like this : visitors: Array(4) 0: {full_name: 'name1'} 1: {full_name: 'name2'} length: 2 and so on , and here is my js code with html $.ajax({ url:'my_url', type:'json', method:'GET', success:function(data){ let booking = data.lists let visitors = data.lists.visitors console.log(visitors) let content=''; for(j=0; j< booking.visitors;j++){ console.log(j) } for(i=0;i<booking.length;i++){ content+='<div class="border border-purple-900 rounded-xl p-1 text-sm text-center">'; content+='<p>'+booking[i]['visitors']['full_name']['full_name']+'</p>'; content+='</div>'; content+='<div class="mt-1">'; let check_in= new Date(booking[i]["check_in"]).toLocaleDateString([], { day: '2-digit',month: '2-digit',year: 'numeric' ,hour: '2-digit', minute:'2-digit'}); if(booking[i]['check_out']){ check_out = new Date(booking[i]['check_out']).toLocaleDateString([], { day: '2-digit',month: '2-digit',year: 'numeric' ,hour: '2-digit', minute:'2-digit'}); }else{ check_out = 'not mentioned' } content+='<p>'+check_in+' to ' +check_out+ '</p>' content+='</div>' } content+='</div>' $("#current-booking").html(content); }}); and console.log(visitors) return undefined ! , now i dont know how to return back list of full names from ajax ? is there something i have to change please ? and here is my views.py current_booking = Booking.objects.filter(leave=False,room_no__room_no=room_no) visitors_booking = BookingVisitor.objects.filter(booking__room_no__room_no=room_no,booking__leave=False) lists = [] visitors = [] for … -
In production bad url shows Internal Server Error instead of customized 404
I've created a simple handler404 according to documentation. In local it works fine, for example when user tries to access an url that does not exist the handler of 404 error is called. But in production it shows a classic "Internal Server Error" and I can't understan why. The handler are these: view.py: def handler500(request): context = {} return render(request, "maintenance/error500.html", status=500) def handler404(request, exception): context = {} return render(request, "maintenance/error404.html", status=404) In urls.py I addes following rows to call the correct handler: urls.handler500 = views.handler500 urls.handler404 = views.handler404 (I set DEBUG=False) I thought that the error raised before handler404 called, but why in local it works and in production not? Thanks in advance for suggestions! -
Django allauth redirects back to sign up page after email verification (which also fails)
I have a weird issue using Django allauth. The sign up works and sends an email verification email, after I click the verification link sent via email I am redirected to the email confirmation page. The problem is once I click "confirm" to confirm my email I am redirected back to the sign up page and the verification appears to fail as well (no error is thrown). When I go to login as the newly created user another verification email is sent and the cycle repeats itself. I have tried to configure my settings to redirect to http://127.0.0.1:8000/ Settings.py #django-allauth registraion settings ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS =1 ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_LOGIN_ATTEMPTS_LIMIT = 5 ACCOUNT_USERNAME_REQUIRED = True ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = False LOGIN_REDIRECT_URL = '/' # Or whatever you want to redirect to after email verification # 1 day ACCOUNT_LOGIN_ATTEMPTS_TIMEOUT = 86400 urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('testingland.urls')), path('api/', include('api.urls')), #all_auth_package url(r'^accounts/', include('allauth.urls')), ] -
How to enable image uploading option to django-ckeditor in forms.py
I am working with django-ckeditor for creating rich text editor for my django app. I have enabled image upload option in admin panel for ckeditor. But I can not enable image upload option in forms.py Here is the code: In settings.py: INSTALLED_APPS = [ ... # ckeditor 'ckeditor', 'ckeditor_uploader', ] # ckeditor Settings CKEDITOR_CONFIGS = { 'default': { 'toolbar': 'full', }, } CKEDITOR_UPLOAD_PATH = 'uploads/' CKEDITOR_IMAGE_BACKEND = 'pillow' In models.py: from ckeditor_uploader.fields import RichTextUploadingField class Post(models.Model): ... content = RichTextUploadingField(verbose_name='Post Content') With this I can see the image upload option in the Admin Panel: This is the code in forms.py: from Blog import models from ckeditor_uploader.widgets import CKEditorUploadingWidget class PostForm(forms.ModelForm): content = forms.CharField(widget=CKEditorUploadingWidget()) # This widget not enabling upload option in templates class Meta: model = models.Post fields = ['content', ] In the template.html: {{ forms.media }} {{ forms|crispy }} But the above code doesn't enabling upload option in template. It is showing like this: How can I enable upload option in forms? Thanks -
TypeError: '>=' not supported between instances of 'str' and 'int' error happening while Django wagtail querying
Working fine from django templates but from postman it's giving this error. The main query is given below - query = reduce( or_, ( Q(path__startswith=page.path) & Q(depth=page.depth + 1) & Q(primary_category__in=list_categories) | Q(additional_categories__category__in=list_categories) for page in BlogPage.objects.filter(pk__in=blog_ids) ) ) -
How to display an image from the DB using folium
I'm trying to pull out an image inside the DB that's on my computer. And display it inside the folium object popup. I searched the internet but did not find a solution I would be happy to help def search_on_map(request): loc_list = [] img_list = [] for i in Add_Item.objects.all(): city = str(i.city) street = str(i.street) home = str(i.home_number) loc_list.append(city +" "+ street +" "+ home) img = i.header_img img_list.append(img) geolocator = Nominatim(user_agent="Your_Name") m = folium.Map(width=800, height=500, location=['32.078225', '34.768516'], zoom_start=15) for index, place in enumerate(loc_list): try: loc = loc_list[index] location = geolocator.geocode(loc) lat = location.latitude long =location.longitude # Add Marker folium.Marker([lat,long], tooltip= ,popup=img_list[index] , icon=folium.Icon(color='purple')).add_to(m) except Exception as e: print(e) return render(request, 'search_on_map.html', {"loc":m._repr_html_(),}) -
How to dynamically define and generate serializers in django
I am working on an event driven service which receives a lot of events and these events have payload. I want to validate all payloads with serializers. Since the events types and huge in numbers, I don't want to define serializers in code for every event as that would require a new release every time a new event is added or an existing one is changed. So, is there a way I can define these serializers dynamically for each event in a table instead of code and use it to validate the event payload ? Any new additions/changes can be done in the table itself. -
link MCO number to Reception number
I have a web page where the user is supposed to enter the reception number and the MCO number, so whatever reception number and MCO number is enter, it is supposed to be tag together like reception number: 123 and MCO number: 456, in the database it is supposed to show 123/456, how do I make it do that? This is how my webpage looks like (when the user click the submit button the reception number and the mco number will be tag together: But as shown in the picture below, the mco number will appear in another new row and not next to the reception number. views.py @login_required() def verifydetails(request): if request.method == 'POST': form = verifyForm(request.POST) if form.is_valid(): Datetime = datetime.now() status = 'Launching' mcoNum = form.cleaned_data['mcoNum'] if Photo.objects.filter(reception=form.cleaned_data['reception']): form = Photo(Datetime=Datetime, mcoNum=mcoNum, status=status) form.save() return redirect('ViewMCO') else: messages.success(request, 'The reception number you have enter is incorrect') return redirect('verifydetails') else: form = verifyForm() return render(request, 'verifydetails.html', {'form': form, }) forms.py class verifyForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Reception number'})) mcoNum = forms.CharField(label='', widget=forms.TextInput(attrs={"class": 'form-control', 'Placeholder': 'Enter MCO Number'})) class Meta: model = Photo fields = ("mcoNum", "status") ViewMCO.html {% extends "customerbase.html" %} {% block content … -
Django: Approach on how to realize IPC with other server/process
I have a Django App for user interaction which works perfectly fine. Now I want to have a communication channel with another primitive server a colleague of mine wrote. Probably will go for multiprocessing listeners via AF_UNIX. I don't know where to open a process that listens on the other servers messages and adds information to the database (also, I request information from the server but that shouldn't be much of a problem once the channel is open) Upon searching the web I found the suggestion to add a new command to the manage.py but I couldn't find out if I can execute two commands in parallel, also the GUI won't be executed as development server forever. If you have any suggestions on what tricks/technology/terms I should search for, I really appreciate the help! Still kind of a newbie to Django, so I might have missed something essential. -
How to add or remove objects in nested serializers Django using update function
I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them. While updating the modules field using a put request, I don't want to update any rooms in it, I just want to add/remove rooms in the module. Here are my files - module/models.py - class Module(models.Model): module_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() rooms = models.ManyToManyField(Rooms) rooms/models.py - class Rooms(models.Model): room_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() level = models.CharField(max_length=100) is_deleted = models.BooleanField(default=False) module/serializers.py - class ModuleSerializer(serializers.ModelSerializer): rooms = RoomSerializer(read_only=True, many=True) class Meta: model = Module fields = "__all__" def create(self, validated_data): rooms_data = validated_data.pop('rooms') module = Module.objects.create(**validated_data) for data in rooms_data: room, created = Rooms.objects.get_or_create(**data) module.rooms.add(room) return module rooms/serialier.py - class RoomSerializerWrite(serializers.ModelSerializer): room_id = serializers.IntegerField() class Meta: model = Rooms fields = "__all__" module/views.py - class add_module(APIView): def post(self, request, format=None): module_serializer = ModuleSerializer(data=request.data) if module_serializer.is_valid(): module_serializer.save() return Response(module_serializer.data['module_id'], status = status.HTTP_201_CREATED) return Response(module_serializer.errors, status = status.HTTP_400_BAD_REQUEST) POST request body for updating a module in POSTMAN - { "module_id": 2, "rooms": [ { "room_id": 2, "title": "4", "desc": "22", "level": "2", … -
Django Rest Framework - Masking response values
I was wondering what the best way would be to mask a certain response parts. I will use an example to explain. Let's say I have a Person model with first_name, last_name and email. I use PersonSerializer to return that data. An example response can be { "first_name": "John", "last_name": "Doe", "email": "johndoe@gmail.com" } I want to "hide" an email when presenting it as response. I still want it to be present as the key, I just want to mask the value. So I want to achieve this response { "first_name": "John", "last_name": "Doe", "email": "__MSK__" // so it get's masked } So this should not impact the serialization when creating a new patient with same serializer class as well. Anyone has idea what the best way would be? Maybe overriding to_representation method or? -
Django: filter the logs which are coming from the front end
I had implemented the logging in my Django project, at Debug level. There is a whole lot of information coming to logger which make my system hang up. I want to filter the logs before going to save the logs. there are like useless logs that are unnecessarily getting saved to file. Like i have front end information from templates, i don't want frontend logs saved in the logger file. LOGGING = { 'version': 1, 'disable_existing_loggers': True, 'formatters': { 'verbose': { 'format': '%(levelname)s %(asctime)s %(module)s %(process)d %(thread)d %(message)s' }, 'simple': { 'format': '%(levelname)s %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose' }, 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.RotatingFileHandler', 'filename': os.path.join(BASE_DIR + '/logs/debug.log'), 'formatter': 'verbose' }, 'info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR + '/logs/info.log'), 'formatter': 'verbose' }, }, 'loggers': { 'django': { 'handlers': ['file','info','console'], 'level': 'DEBUG', 'propagate': True, }, }, } Kindly Suggest -
can't connect to my database which i have in hiox india wit my django
just a week we brought a hosting service in hioxindia ,they provided the databaseso i'm trying to connect my django with that database but i can't.i'm seeking solutions for that .I need to know how to connect my django with that database -
Django REST framework on primary key
I am currently trying to display multiple models with a primary key to find that specific data but I am encounter the following error: selected() got an unexpected keyword argument 'pk' Heres the code: views.py from rest_framework.response import Response from rest_framework.decorators import api_view from .serializers import DeviceSerializers, DeviceDetailSerializers @api_view(['GET']) def selected(request,pk): devices = Device.objects.all(pk=pk) devicedetail = DeviceDetail.objects.all(DD2DKEY=pk) devserializer = DeviceSerializers(devices, many = True) devdserializer = DeviceDetailSerializers(devicedetail, many = True) results = devserializer.data + devdserializer.data return Response(results) serializers.py from rest_framework import serializers from .models import Device, DeviceDetail class DeviceSerializers(serializers.ModelSerializer): class Meta: model=Device fields = '__all__' class DeviceDetailSerializers(serializers.ModelSerializer): class Meta: model = DeviceDetail fields = '__all__' models.py SUBNET_CHOICES = ( ('16','16'), ('17', '17'), ('18','18'), ('19','19'), ('20','20'), ('21', '21'), ('22', '22'), ('23', '23'), ('24', '24'), ('25', '25'), ('26', '26'), ('27', '27'), ('28', '28'), ('29', '29'), ('30', '30'), ) DEV_MODS =( ('Catalyst 9606R', 'Catalyst 9606R'), ('C9300L-48T-4X', 'C9300L-48T-4X') ) mgt_interface = models.CharField(max_length=50) subnetmask = models.CharField(max_length=2, choices = SUBNET_CHOICES) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) dev_mod=models.CharField(max_length=50, choices = DEV_MODS) ##device_model replacement DD2DKEY = models.ForeignKey(Device, on_delete=models.CASCADE) ##The key to link up the tables def __str__(self): return self.hostname urls.py (In app) from django.urls import path from .views import DeviceListView from . import views from .views … -
Django - Have function inside of a view function automatically return a response to user if error?
So I have this post request below that gets a video upload then validates it. I'd ideally like validate_video_upload() to return a 400 response if the video is larger than the allowed size rather than raise a validation error, because I'd like to notify the user that the video is too large. How do I set it up so that if validate_video_upload() returns a Response, it'll just return the call with the status and message, if there's no response returned then it just proceeds normally? View.py def post(self, request): if 'video' in request.FILES.keys(): vid = request.FILES.get('video') validate_video_upload(vid) function.py def validate_video_upload(file): if not is_valid_file_of_format(file._name, VALID_VIDEO_EXTENSIONS): raise ValidationError("Video file format is invalid") if file.size>2296000000: raise ValidationError("Maximum size allowed for a video is 287 mb") -
Invoking Django-river manually for workflow management
Our application uses Django_river for workflow management. And currently, the river is being invoked based on the post save signal created by Django. But for performance-related issues, we had to use the bulk option for inserting data that does not support signals by default. We have generated signals manually, but this is slowing down our system. Is there any way to manually invoke the river from our code based on the business conditions?