Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest Framework: Custom IsReadOnly Permission
I create a custom permission which authorizes GET, HEAD and OPTION for everyone and which authorizes NO other requests. But my code doesn't work. I can make a POST request despite my permission ... Anyone have a idea to solve my problem ? My views.py: class IsReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return False class ViewPollViewSet(viewsets.ModelViewSet): permission_classes = [ IsReadOnly, ] serializer_class = ViewPollSerializer queryset = ViewPoll.objects.all() My serializers.py: class ViewPollSerializer(serializers.ModelSerializer): class Meta: model = ViewPoll fields = '__all__' My models.py: class ViewPoll(models.Model): ''' view poll ''' class Meta: unique_together = ('poll', 'user') poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="views", null=True) user = models.ForeignKey(User,on_delete=models.CASCADE, related_name="views_poll", null=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.poll.question)[:30] -
Including JavaScript in a Django template through the static folder
In my Django project, I am storing my JavaScript function in a folder in the path: root/static/js/js_function When I include the JavaScript directly in the .html file, it runs as expected. But when I move the JS to this static folder, the HTML does not recognize the Javascript. settings.py (relevant static section): # STATIC # ------------------------------------------------------------------------------ # https://docs.djangoproject.com/en/dev/ref/settings/#static-root STATIC_ROOT = str(BASE_DIR("staticfiles")) # https://docs.djangoproject.com/en/dev/ref/settings/#static-url STATIC_URL = "/static/" # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#std:setting-STATICFILES_DIRS STATICFILES_DIRS = [str(APPS_DIR.path("static"))] # https://docs.djangoproject.com/en/dev/ref/contrib/staticfiles/#staticfiles-finders STATICFILES_FINDERS = [ "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", ] index.html: <div id="odds_calculator"> <p>Placing $<input type="number" name="hypothetical_bet" v-on:input= "update_hypothetical_bet"> on this bet would win you $[[ result() ]] if you were to win the bet.</p> <p>Bet Amount: [[ number1 ]] </p> <p>Odds: {{ basketballbet.odds }}</p> <hr> <p>Result: $[[ result() ]]</p> </div> {% load static %} <script src = "{% static 'js/odds_calculator.js' %}"></script> odds_calculator.js: new Vue({ delimiters: ['[[',']]'], el: '#odds_calculator', data: { hypothetical_bet: 0, odds: {{ basketballbet.odds }}, }, methods: { update_hypothetical_bet: function (event) { this.hypothetical_bet = event.target.value; }, result: function () { return this.odds < 0 ? (this.hypothetical_bet*(-100/this.odds)).toFixed(2) : (this.hypothetical_bet*(this.odds/100)).toFixed(2); }, }, }); -
How can I programaticaly create a directory on file upload and save the uploaded file to that direcotry using django?
I'm trying to create a directory programmatically on file upload. I'm able to create the directory using date and time stamp at the same time the file also getting uploaded. But I'm not able to save the file inside the directory during the upload. My views.py def uploadfile(request): dirname = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] fs = FileSystemStorage() os.mkdir(os.path.join('uploads', dirname)) #'uploads' is my media root folder name = fs.save(uploaded_file.name, uploaded_file) ##** this file need to be saved inside the /uploads/2010.08.09.12.08.45/files_name **## context['url'] = fs.url(name) return render(request, 'upload.html', context) The above code uploads the file using the form from the template using POST and the and it also creates a folder with current timestamp. But the issue is that I'm not able to save the file inside the folder. -
Django auto populate Drop Down with CSV data
I am using below code to populate unique data from the CSV file on the Django template. This is my view.py code df = pd.read_csv("statics/chicago_crime_2016.csv") columns = df.columns primary_type = df['Primary Type'].unique() def index(request): context = {'primary_type': primary_type, 'columns': columns} return render(request, 'index.html', context) Django And this is my HTML code: <div class="container-fluid mt-4"> <select> {% for column in columns%} <option value="{{ column }}">{{ column }}</option> {% endfor %} </select> <select> {% for type in primary_type%} <option value="{{ type }}">{{ type }}</option> {% endfor %} </select> </div> HTML Picture Next what I want when I choose a column from the first dropdown, then it shows me in the second dropdown that column value which chooses in the first dropdown. Now it's showing only one column value and it is static and I want a dynamic dropdown that makes changes according to the situation. -
Python Django NoReverseMatch Template
I configured the path and made the template but when I try to run server it gives NoReverseMatch at /password-reset/ Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. Request Method: POST Request URL: http://localhost:8000/password-reset/ Django Version: 3.0.6 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_reset_confirm' not found. 'password_reset_confirm' is not a valid view function or pattern name. error. My urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name= 'register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name = 'users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name = 'users/logout.html'), name='logout'), path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password_reset'), path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'), name='password_reset_done '), path('password-reset-confirm///', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm '), path('', include('blog.urls')) ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) and my template {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class = "content section"> <form method="POST"> {% csrf_token %} <fieldset class= "form-group"> <legend class = "border-bottom mb-4">Reset Password</legend> {{form|crispy}} </fieldset> <div class = "form-group"> <button class="btn btn-outline-info" type ="submit"> Reset Password </button> </div> </form> </div> {% endblock content %} Could you please tell me what is … -
Django 3.0.5 User Authenticate with Username or Email
i'm struggling a bit with this problem, some says i have to override AuthenticationForm but i don't know how cause i got a custom user registration and login, i'll post it: urls.py urlpatterns = [ path('login/', LoginView.as_view(), {'template_name': 'accounts/login.html'}, name='login'), Note im using default loginview right now. So in views.py i must have this def login(request): return render(request, '/login.html') ... ... Of course login.html is just like this <div class='container'> <h1>Welcome</h1> <p> you can login here! </p> <h2>Login</h2> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type='submit'>Login</button> </form> </div> In models.py my custom user is this one: class ProfiloUtente(models.Model): user = models.OneToOneField(User, related_name='profile', on_delete=models.CASCADE) utente = models.ForeignKey(Utente, on_delete=models.CASCADE) studio = models.ManyToManyField(Studio) telefono_fisso = models.CharField(max_length=20, default=None, blank=True) telefono_mobile = models.CharField(max_length=20, default=None, blank=True) indirizzo = models.CharField(max_length=40, default=None, blank=True) citta = models.CharField(max_length=50, default=None, blank=True) cap = models.CharField(max_length=5, default=None, blank=True) provincia = models.CharField(max_length=30, default=None, blank=True) cod_fiscale = models.CharField(max_length=16, default=None, blank=True) p_iva = models.CharField(max_length=27, default=None, blank=True) def __str__(self): return self.user.username And the fields i use from The default django user are these: forms.py class RegistrationForm(UserCreationForm): """docstring for RegistrationForm""" email = forms.EmailField(required=True) first_name = forms.CharField(max_length=30, required=True) last_name = forms.CharField(max_length=100, required=True) class Meta: # define a metadata related to this class model = User fields = … -
Django 'TestMiddleware' object has no attribute 'get_response'
I have a problem with my django TestMiddleware code My djando version Django 3.0.6 My code middleware.py from django.utils.deprecation import MiddlewareMixin class TestMiddleware(MiddlewareMixin): '''中间键类''' def __init__(self, request): '''服务器重启之后,接受第一个请求时调用''' print('--init--') def process_request(self, request): '''产生request对象后,url匹配之前调用''' print('--process_request--') def process_view(self, request, view_func, *view_args, **view_kwargs): '''url匹配之后,视图函数调用之前''' print('--process_view--') def process_response(self, request, response): '''视图函数调用之后,内容返回浏览器之前''' print('--process_response') return response setting.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', # 'booktest.middleware.BlockedIPSMiddleWare', 'booktest.middleware.TestMiddleware', ] Error System check identified no issues (0 silenced). June 03, 2020 - 13:38:28 Django version 3.0.6, using settings 'test5.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. --init-- --process_request-- Session data corrupted Internal Server Error: /index Traceback (most recent call last): File "/home/coco/.virtualenvs/bj19_py3/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/coco/.virtualenvs/bj19_py3/lib/python3.6/site-packages/django/utils/deprecation.py", line 94, in call response = response or self.get_response(request) AttributeError: 'TestMiddleware' object has no attribute 'get_response' I am new for python , pls I need some help -
Django filter and update atomicity
When updating filtered records, is there a need for select_for_update if you want to make sure that the filtered rows won't get changed by some other process before this update is done, or is this filter + update atomicity guaranteed out-of-the-box? I.e., is this: with transaction.atomic(): Foo.objects.select_for_update().filter(id=1).update(**kwargs) equivalent to: Foo.objects.filter(id=1).update(**kwargs) ? I'm using Django 1.6.x. -
How and where to run (heavy) functions in the server for a django web app / where to store them
I am quite beginner to Django and I am confronted with this question. provided I have the following structure: django_app/ django_app/ __init__.py asgi.py settings.py urls.py views.py wsgi.py loaddata_app/ >migrations __init__.py admin.py apps.py models.py test.py urls.py views.py >static >templates loaddata.html My loaddata app is a super easy app that contains a text field to enter (paste) text. The app should send the text to the server where a series of methods are applied to extract information out of the text and generate output data that will be presented to back to the user. The first question is: If you have a bunch of methods in various files, where do you actually "store" those methods. And where are those methods supposed to be imported (if they need at all to be imported)? What happens if those methods take (so to say) 10 minutes to run? is the connection still maintained with the browser of the user in the meanwhile? So looks the simple app: NOTE: The question is partially answered here. But it is not entirely clear where those utils are imported and run in order to process the data. Django: where to store functions common to all apps -
How to open window with html or dialog box in middle view django
I have the following scenario: In a view I do a get in an external api with the data that the user provides me via form, with this get I get a series of images, the user then needs to write the code of the image he wants and send it to me, I need then capture the answer and make new get and finally finish my view. Note: I cannot close my view before user interaction because I have a session object that cannot be lost, if this occurs the code entered will not actually match the image if request.POST['action'] == 'get_images': name = request.POST.get('name') birthday = request.POST.get('birthday') gender = request.POST.get('gender') preferences = preferences.Preferences(gender, birthday, name) preferences.login_page() preferences.add_page() images = preferences.get_images() #get images #need display dialog box with image in di response = #input user in dialog box resp = preferences.search_page(response)#new get to know some info user print(resp) -
How to save folium map in Django templates,
when I tried "In your code map is a folium.Map object, not yet a string with html/javascript. You need to render it first. Normally, this creates a single, full HTML page. For Jupyter notebooks this HTML page is put into an iframe. So there are two options: If you don't want or need to put the map in a template, you can directly render the page: m.get_root().render() returns a string with the full HTML/JS page. If you want to embed the map into a template you can use an iframe: m._repr_html_() returns a string with an iframe with the HTML/JS page." map is empty -
django-rest-framework – how to serialize nested objects?
I am trying to create an api endpoint that pulls all the FeaturedProvider and Testimonial objects from the database, serialize it and return it as a new serialized object HomepageContentSerializer I've tried multiple ways but I'm getting empty {} when I try to hit the endpoint. I'm not sure where to initialize or pass the FeaturedProvider and Testimonial objects to the HomepageContentSerializer to be serialized serializers.py class FeaturedProviderSerializer(serializers.ModelSerializer): class Meta: model = FeaturedProvider fields = '__all__' class TestimonialSerializer(serializers.ModelSerializer): class Meta: model = Testimonial fields = '__all__' class HomepageContentSerializer(serializers.Serializer): providers = FeaturedProviderSerializer(many=True, read_only=True) testimonials = TestimonialSerializer(many=True, read_only=True) views.py class HomepageContent(APIView): renderer_classes = [JSONRenderer] def get(self, request): content = HomepageContentSerializer().data return Response(content) My goal is to get this representation back { "providers": [ { ... }, { ... }, { ... }, ], "testimonials": [ { ... }, { ... }, { ... }, ], } -
How to see all the notifications in html using Django-notification package
I have implemented this django notification package in my project, but I am not able to understand how can I see those notifications in html. I can see the nofications in admin panel, as it is working fine in the views. with their template tag I can even see that I have these many unread notifications as well, but I want to see what those notifications are as wee see in facebook or twitter. Can anyone explain how to get the html for that? This is the package: https://github.com/django-notifications/django-notifications this is my view for posts likes def like_post(request, slug): user = request.user post = get_object_or_404(Post, slug=slug) is_liked = False if user in post.likes.all(): post.likes.remove(request.user) is_liked = False else: post.likes.add(request.user) is_liked = True create_action(request.user, 'liked the post', post) notify.send(sender=user, recipient=post.user, verb='liked your post', target=post) # return redirect('posts:myhome') context = { 'post':post, 'is_liked':is_liked, 'total_likes':post.total_likes() } if request.is_ajax(): html = render_to_string('posts/like_snippet.html', context, request=request) return JsonResponse({'form': html}) Thanks -
How to retrieve user selections from a previous form
I have several forms that take people through steps and below are the first two and the simplest ones and makes it easy to explain what i am having problem with. The following two views are login required and contain one form on each. First view is the new_operator where the user fills out a single text input field. Second view is the new_asset where the user fills one text input field as the asset name and selects an operator from the a select/dropdown field. The question is how can i get the form to remember the operator name the user created in the previous form and make it as the default option? To be clear, i still want the user to select any other operator if they choose to do so but i want the option they just created to be the default. Thanks a lot in advance for the help. First, here are the models: class OperatorCompany(models.Model): name = models.CharField(max_length=50, unique=True) created_at = models.DateTimeField(default=timezone.now) created_by = models.ForeignKey(User, related_name='operator_added_by', null=True, on_delete=models.SET_NULL) class Meta: verbose_name = "Operator Company" verbose_name_plural = "Operator Companies" def __str__(self): return self.name class AssetName(models.Model): name = models.CharField(max_length=50, unique=True) operator = models.ForeignKey(OperatorCompany, related_name='asset', on_delete=models.CASCADE) created_at = models.DateTimeField(default=timezone.now) … -
Dockerized Django tests only look at first $PATH location
I'm running a Django test suite in a Docker container, and some of these tests use a program I've had to apt-get install (wkhtmltopdf). Now I can see that it's been installed correctly: $ wkhtmltopdf --version wkhtmltopdf 0.12.5 but for some reason the Django test can't use it. The installation location is definitely on my $PATH (third to last element): $ echo $PATH /usr/local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin $ find / -name wkhtmltopdf /usr/bin/wkhtmltopdf However when I run tests I get a stack trace ending in: OSError: No wkhtmltopdf executable found: "/usr/local/bin/wkhtmltopdf" If this file exists please check that this process can read it. Otherwise please install wkhtmltopdf - https://github.com/JazzCore/python-pdfkit/wiki/Installing-wkhtmltopdf Now it's absolutely correct that there is no /usr/local/bin/wkhtmltopdf, because it got installed elsewhere (/usr/bin/) but both those locations are on $PATH. I've tried moving /usr/bin/ to the start of $PATH, but I then get the error: Traceback (most recent call last): File "./manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named django.core.management presumably because it's now looking in /usr/bin/ for django when it's actually in usr/local/bin/, which is no longer the first location on $PATH. I'm not sure if the problem is a Docker one, a Django one, a … -
Django, autocomplete-light, empty drop down menu instead of auto search
Autocomplete, supposedly, has to be able to bring choices under the entry field, when a person starts typing into the field... I followed this tutorial: https://django-autocomplete-light.readthedocs.io/en/master/tutorial.html#overview I tried all other recommendations, like: django-autocomplete-light displays empty dropdown in the form or django-autocompletion-light simple foreign key completion shows not editable drop-down widget And many other advices, but nothing worked for me somehow. Also I tried to tiе foreign key and use without foreign key in the model which comes from postgresql database. Nothing helped so far, sometimes followed advises brought extra errors. The search entry field, is blocked. Instead, there is drop down field, in which there is no choices. Thank you for your help! Here is my code so far: Models.py(lost tabs and spaces when copied code, but in the code it is as it should be): from django.db import models from django import forms from django.urls import reverse from django.forms import ModelForm class ForQuery(models.Model): query_id = models.BigAutoField(primary_key=True) dep_st = models.CharField(max_length=35, blank=True, null=True)//tried to make it as foreign //key from DeptDic, brings drop down menu with half of raws from the column code_dep_st = models.CharField(max_length=5, blank=True, null=True) dep_kind = models.ForeignKey(Classification, models.DO_NOTHING, db_column='met_kind', blank=True, null=True) class Meta: managed = False db_table = … -
User profile form_is_valid() doesn't save
I implemented Profile create using post save signals Models: class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') is not True: raise ValueError(_('Superuser must have is_superuser=True.')) return self.create_user(email, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): """User additional information""" email = models.EmailField(_('email address'), unique=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) users = ( ('doctor', 'Doctor'), ('patient', 'Patient'), ('assistant', 'Assistant'), ) user_type = models.CharField(choices=users, max_length=9, default='patient') USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager() def __str__(self): return self.email class Profile(models.Model): name = models.CharField(max_length=20, verbose_name='Имя', blank=True, null=True) surname = models.CharField(max_length=20, verbose_name='Фамилия', blank=True, null=True) third_name = models.CharField(max_length=20, verbose_name='Отчество', blank=True, null=True) birth_date = models.DateField(blank=True, null=True) address = models.CharField(max_length=200, verbose_name='Адрес', blank=True, null=True) mobile_phone = models.IntegerField(verbose_name='Номер телефона', blank=True, null=True) avatar = models.ImageField(upload_to='images/avatars/%Y/%m/%d/', default='/static/default_img/default.png') class Meta: abstract = True class Patient(Profile): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) diagnose … -
How to show admin specific information on my Django website?
I'm currently building a Hospital Management system with Django but encountered an issue. In this website, admins will register for their respective hospitals and manage their doctors, patients etc. But, I don't want one hospital's admin to see the informations of ther hospitals' doctors or patients. So how can I make sure that the admin only sees the data of his own hospital and not others'. What changes can I make in my models to do so? -
Link the Copyright attribute and image file with BeautifulSoup
I need to download and link the Copyright attribute and image file name. The problem is that img, together with src, is inside the tag, which has a 'Copyright' key in the date. Using BeautifulSoup I managed to download 'Copyright' but how to link it with img? code with html <wphimage data="{'FileId':6182,'Copyright':'John Smith','Alignment':'left','ZoomDisabled':false,'ImageOnly':false,'AlternativeText':'John Smith','ImageVersion':'conductorportraitlong','tabid':0,'moduleid':0}"> <span style="display:block; float:left;" class="DIV_imageWrapper"> <a data-lightview-title="Adela Frasineanu" data-lightview-caption="" class="lightview" href="//example.com/static/images/image.JPG"> <img src="//example.com/static/images/image.JPG" alt="John Smith"> </a> <a href="javascript:;">≡ <span>John Smith</span></a> <a class="A_zoom lightview" href="//example.com/static/images/image.JPG" data-lightview-title="John Smith" data-lightview-caption="">+ </a> </span> </wphimage> code in py below soup = BeautifulSoup(row['Text'], features="html5lib") wphimages = soup.findAll('wphimage') for index, img in enumerate(wphimages): dict_as_str = img["data"].replace("'", '"') copyright_text.append((row["id"], json.loads(dict_as_str)['Copyright'])) -
Django migrations and transactions in MySQL
Had an issue where one of the django (data) migrations was marked as executed, to create a record in the database, but couldn't find the actual record. That ran just fine in stage, creating the record, but in production it was only marked as executed. A migration that was executed after it failed/crashed, which could explain part of the issue. Here is the list of most recent migrations, with date/time when they were executed: network_list 0002 was supposed to create the record, and solution 0039 was the one that crashed, immediately after 0038 execution. 0039 was only executed on a next deploy. Ended up with a few questions on my head: When django migrations are executed, ALL of them run inside a transaction as I thought, OR only each individual migration run inside it's own transaction? From django docs (links below), I saw MySQL have a crappy support for transaction during migrations. Could that issue have been caused by MySQL? Any other ideas on what could have caused this to be marked as executed, but the record is missing? https://docs.djangoproject.com/en/3.0/howto/writing-migrations/#non-atomic-migrations https://docs.djangoproject.com/en/3.0/topics/migrations/#mysql Using Django 1.8 and MySQL/Aurora. -
Why does the Model Form fail to render in django
I'm trying to display a select box within a table in Django. Unfortunately, when I put the form within the HTML template it does not render although other elements do. forms.py: resultchoices = [ ('Not Started', 'Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] class checklistform(ModelForm): class Meta: model = checklist fields = "__all__" widgets = { 'INFO_001_result': Select(choices=resultchoices,), } models.py: class checklist(models.Model): resultchoices = [ ('Not Started','Not Started'), ('Pass', 'Pass'), ('Issues', 'Issues'), ('N/A', 'N/A'), ] INFO_001_result = models.CharField(choices=resultchoices,default='Not Started',null=False,max_length=11), INFO_001_remark = models.CharField(null=True,default='',max_length=400) Views.py: checklistform = checklistform # Create your views here. def checklist(request): context = { 'checklistform': checklistform, } return render(request, 'pages/Checklist.html',context ) HTML template: <td style="text-align:Center;background-color:#44546A;color:#000000;font-size:10px;width:108px;border: 1px solid #999999; " eth-cell="E5" >{{ checklistform.INFO_001_result }}</td> <td style="color:#000000;font-size:10px;width:88px;border: 1px solid #999999; " eth-cell="F5" >{{ checklistform.INFO_001_remark }}</td> </tr> Django doesn't give me any error it just fails to render that section within the template. -
Can not use opencv to read a video in Apache+WSGI+Django but ok in just Django
I use Django and Apache. When I run this: video_capture = cv2.VideoCapture(path) fps = video_capture.get(cv2.CAP_PROP_FPS) height = int(video_capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) width = int(video_capture.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_count = int(video_capture.get(cv2.CAP_PROP_FRAME_COUNT)) success, frame = video_capture.read() It will run success, frame = video_capture.read() forever and not return. But fps height width frame_count is correct. If I just use Django by python manage.py runserver 0.0.0.0:8000, the code is correct. So I think I make a mistake in using WSGI. Here is how I use WSGI+Apache+Django. I manage Python with Anaconda. If I install mod_wsgi directly it will report an error, so I download mod-wsgi in https://pypi.org/project/mod-wsgi/#files. Then tar it and run ./configure --with-apxs=/usr/bin/apxs --with-python=/home/lhl/anaconda3/envs/web/bin/python make && make install. I use whereis to find the path. Then I use pip install mod_wsgi to install mod_wsgi in anaconda env web. Finally I run mod_wsgi-express module-config and copy the output LoadModule wsgi_module "/home/lhl/anaconda3/envs/web/lib/python3.7/site-packages/mod_wsgi/server/mod_wsgi-py37.cpython-37m-x86_64-linux-gnu.so" WSGIPythonHome "/home/lhl/anaconda3/envs/web" to http.conf of Apache. Is there an error? Think you very much! -
Django REST Framework change rederer class based on response
I'm using Django 2.2 and Django REST Framework. I have an APIView which will download Zip file on success response. class MultiDownloadCode(APIView): serializer_class = MultiDownloadSerializer permission_classes = ( IsAuthenticated, CodeCanExport, ) renderer_classes = (ZipRenderer,) def post(self, request): ... mime_type = 'application/zip' file_name = '{}.zip'.format(random_string(20)) response = Response(data=in_memory_zip.read(), content_type=mime_type) response['Content-Disposition'] = 'attachment; filename=%s' % "-".join(file_name.split()) return response I have created a custom Renderer class ZipRenderer class ZipRenderer(BaseRenderer): media_type = 'application/zip' format = 'zip' charset = 'utf-8' render_style = 'binary' def render(self, data, accepted_media_type=None, renderer_context=None): return data This is working fine in case of a successful response. But in case of permission denied exception, the error messages are also binary encoded and not proper JSON rendered. When I add JSONRenderer to the renderer_classes renderer_classes = (ZipRenderer, JSONRenderer) This works fine in case of exception but then gives error in case of a success response. How can I change the renderer based on the response? -
django saving database records and using only those records, not previously saved records
I am learning django. I want to save 3 or 4 records in database and use only those records in detailed view but not previously stored records. I don't know how to implement. -
Sweetalert closes suddenly after appearing because of page reload
I'm using javascript sweetalert in Django html template. Sweetalert dialog closes after appearing because of page reload. I have applied the suggested fixes in answer to the Question-javascript-sweetalert-popup-closes-itself-after-a-quick-second My template code is <button title="Transform" id="transform_btn" type="button" class="btn" style="color:white;background-color:#fff;"> <a href="/load_to_hive/{{stu.cases_id}}/"> <i class="glyphicon glyphicon-hourglass fa-2x"></i> </a> </button> And javascript code displaying the dialog is {% block javascript %} <script src="{% static 'js/sweetalert.min.js' %}"></script> <script> var transformBtn= document.getElementById('transform_btn'); transformBtn.addEventListener("click",function(){ swal({ title: "Good job!", text: "You clicked the button!", icon: "success", }); }) </script> {% endblock javascript %}