Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I use setup_class in pytest with django to cache fixtures?
I am struggling to use pytest & django & factoryboy & fixtures. I have some factories which build some really expensive classes. In order to minimize testing time, I thought I could pre-create a bunch of them in the setup_class function and re-use them for each test. However, all of the combinations of pytest decorators I use give me the following error: Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. Here is some code: models.py: from django.db import models class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, related_name="books") tests.py: import factory import pytest from faker import Faker from models import Book, Author fake = Faker() class AuthorFactory(factory.django.DjangoModelFactory): class Meta: model = Author name = fake.name() class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book title = fake.sentence() author = factory.SubFactory(AuthorFactory) # NOT SURE WHAT TO PUT HERE # @pytest.mark.django_db # @pytest.fixture def make_an_author(**kwargs): def _make_an_author(**kwargs): create = kwargs.pop("create", True) n_books = kwargs.pop("n_books", 10) author = AuthorFactory.create(**kwargs) for i in range(n_books): BookFactory.create(author=author) return author return _make_an_author(**kwargs) # NOT SURE WHAT TO PUT HERE # @pytest.mark.django_db class TestAuthor: n_authors = 10 cached_authors = [] @classmethod # NOT SURE WHAT … -
Recurring Payments in worldpay
Can anyone tell me how to implement recurring payments with worldpay in DJANGO project... Also if you can tell me the flow of recurring payments in worldpay, it would be helpful -
Can't view opencv processed videos in Django
I have a Django app that lets you upload a video or image, it sends it to an OpenCV function that returns a new image/video with some annotations on it and then shows it in the template. For images it works just fine, but for video it doesn't. The video is shown as unavailable both in the view (as HTML5 video) and when following the /media/[path_to_file], but when I'm opening it with VLC (or some other desktop player, locally), the video exists and is working as expected. Moreover, I tried removing the OpenCV function and left only the upload functionality. When I uploaded a normal video, everything was fine, but when I tried to upload a video that was previously processed with OpenCV, it appears as unavailable again. My question is: is opencv changing the video properties in any way comparing to the original so that Django doesn't recognise it anymore? What might be the problem? And how can I make it that opencv processed videos are visible in my view? Also, the processed video has the same name and extension (and type) as the original. If you have any idea it's more than helpful. Thanks a lot! -
Dynamic Choice Fileds depedending on another field
I want to build the list of choices of a django model field dynamically: def build_choices(another_model): choices = DEFAULT_CHOICES if another_model and another_model.show_extra: choices = DEFAULT_CHOICES + EXTRA_CHOICES return choices class MyOtherModel(models.Model): show_extra = models.BooleanField(default=False) class MyModel(models.Model): another_model = models.ForeignKey(MyOtherModel, blank=True, null=True) extra_choices = models.CharField(choices=build_choices(another_model)) This clearly doesn't work as the build_choices function is evaluated at load time and never more. I know I could do this in a form class but I want also to provide the same validation wether or not I create an object through a form or via other methods. To notice that the dynamically built choices depend on a related model instance, if the related model is not available (probably we are instantiating the MyModel for the first time or there are no another_model associated) then return the default choices. I've found this other solution but it seems a bit hacky. What are my options here? -
How to use multiple websocket connections using Django Channels?
I have been happily using Django-Channels for several months now. However, I went to add a second websocket dependent application to my Django project and I am running into trouble. The error I am getting is websocket connection failed websocket is closed before the connection is established. What is odd is that the first application was working before the second application was deployed. Further, the first application continues to work so long as the second application is not running. The Django Channels documentation says: Channels routers only work on the scope level, not on the level of individual events, which means you can only have one consumer for any given connection. Routing is to work out what single consumer to give a connection, not how to spread events from one connection across multiple consumers. I think this means that Django-Channels does not support routing for multiple websocket connections. That is, I think I am trying to use the same websocket connection/port for two different applications. My routing.py file looks as follows: application = ProtocolTypeRouter({ "websocket": AuthMiddlewareStack( URLRouter([ path("first_application/stream/", app_1_consumers.AsyncApp1), path("second_application/stream/", app_2_consumers.AsyncApp2), ]) ) }) When I attempted to use the setup below, it could not find the path to the … -
Stop Django server using python
I try to find usefulness packages in the Django project. Algorithm is the following: 1. Delete package 2. Try to start server (python manage.py runserver) 3. If server doesn't work => package is needed 4. If server works fine => package is usefulness If server doesn't work, I can catch error using subprocess.call(). But if server starts, I can't do anything further. How can I start and then stop server? -
Edit data from a form - Django
I'm looking for help on a very basic problem I know, but I can't get it fixed and I don't know where I did something wrong (as usual) So basically I have created a model form "formulaire_equipement" class formulaire_equipement(forms.ModelForm): class Meta: model = Formulaire fields = '__all__' based on the model "Formulaire" : class Formulaire(models.Model) : nom_equipement = models.CharField(max_length=200) constructeur = models.CharField(max_length=100) choix_categorie = [ ('Encodeur', 'Encodeur'), ('Modulateur', 'Modulateur'), ('Packager', 'Packager'), ('Playout', 'Playout') ] categorie = models.CharField(max_length=100, choices=choix_categorie) reference = models.CharField(max_length=100, null=True) IP = models.CharField(max_length=15) identifiant = models.CharField(max_length=50, null=True) mot_de_passe = models.CharField(max_length=100, null=True) From there, I can submit the form and I already created a view where I can access and display the data submitted by the user. <h3> Nom : {{Formulaire.nom_equipement}} </br> Constructeur : {{Formulaire.constructeur}} </br> Catégorie : {{Formulaire.categorie}} </br> Référence : {{Formulaire.reference}} </br> IP management : <a href="http://{{Formulaire.IP}}/"> {{Formulaire.IP}} </a> </br> Identifiant de connexion : {{Formulaire.identifiant}} </br> Mot de passe : {{Formulaire.mot_de_passe}} </br> </h3> <a class="btn" method="POST" href="{% url 'modifier_equipement' pk=Formulaire.pk %}"> modifier équipement </a> <a class="btn" href="{% url 'supprimer_equipement' pk=Formulaire.pk %}"> supprimer équipement </a> </div> The problem comes when I try to edit the form previously created, through the url path('fiche/<int:pk>/edit/', views.edit_formulaire, name='modifier_equipement') referring to the view … -
Zero length string in a patch request returns status 200 despite validation
I was previously validating my model's input in a serializer, but have had to change to validation in the model, using inherited properties from AbstractUser. In my view, I currently have the following: class SetUserProfileView(generics.UpdateAPIView): """ Use this endpoint to change user profile. """ serializer_class = settings.SERIALIZERS.user_update_profile permission_classes = [permissions.IsAuthenticated] def get_object(self): return self.request.user def patch(self, request): testmodel = self.get_object() serializer = self.serializer_class(testmodel, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(data=serializer.data, status=status.HTTP_200_OK) return Response(data=serializer._errors, status=status.HTTP_400_BAD_REQUEST) but this returns a status 200 and doesn't update the role field if I send a zero length string for the role This is despite the fact that there are constraints in the role in models.py that the field must be in ROLE_CHOICES How should I update my view to verify that the data in the model is correct using validation in the model? I can find no mention of Model: class SeaUser(AbstractUser): ... SARGENT_PEPPER = 'SGT' COLENAL_MUSTARD = 'COL' OTHER = 'OTH' ROLE_CHOICES = ( (SARGENT_PEPPER, _('sargent')), (COLENAL_MUSTARD, _('colenal')), (OTHER, _('Other')), ) role = models.CharField(_('Role'), max_length=3, choices=ROLE_CHOICES, default=CREW) The role must be one of the 3 values. I test this with the below: def test_update_user_no_role(self): payload = {"first_name": "foo", "last_name": "bar", "role": "", "preferred_timezone": "UTC" … -
Using HTML contenteditable attribute in Django to update field value and post to mysql database
I am trying to figure out how to use the contenteditable HTML attribute effectively with my django application. Ideally, I would like to allow a user to make changes to a record via an html page, then hit a submit button that would post the changes. This is fairly straight forward with regular form fields, but less obvious when utilizing contenteditable. I have taken a look at the django-contenteditable pip package, but there is virtually no documentation and the dependancies seem to be really outdated. Does anyone have any suggestions on how to approach accomplishing this or know of any examples? Thanks in advance for the help. -
Getting "cursor "_django_curs_140244427998976_3" does not exist" error
I am creating modelforms. I have managed to pull the fields i want to use from my tables (using postgresql): Table: class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, on_delete=models.CASCADE) Response = models.TextField() Client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE) Planit_location = models.ForeignKey(Planit_location, on_delete=models.CASCADE) def __str__(self): return self.Response Form: class ResponseForm(forms.ModelForm): class Meta: model = Response fields = ('Response', 'Topic', 'Client') widgets = { 'Response': Textarea(attrs={'rows':3, 'cols':200}), } I want to now add in the Planit_locaiton field, but when i do i get the cursor error as stated in the title. Not sure why. Here is the Location table: class Planit_location(models.Model): Planit_location = models.CharField(max_length=255) def __str__(self): return self.Planit_location HTML: <form method="post" name="uploadform" style="margin-left: 16px"> {% csrf_token %} <h4>Add Data</h4> <table> {{ qform.as_table }} {{ rform.as_table }} </table> <button type="submit" class="btn btn-default">Submit</button> </form> views.py: def adddata(request): if request.user.is_authenticated: username = request.user.username if request.method == 'POST': qform = QuestionForm(request.POST) rform = ResponseForm(request.POST) if qform.is_valid() and rform.is_valid(): qf = qform.save() rf = rform.save(commit=False) rf.Question = qf rf.save() return render(request, 'app/adddatatest.html', { "qform": QuestionForm(), "rform": ResponseForm(), "username": username, }) else: qform = QuestionForm() rform = ResponseForm() return render(request, 'app/adddatatest.html', { "qform": QuestionForm(), "rform": ResponseForm(), "username": username, }) -
The current path, account/login/, didn't match any of these?
i'm trying to access my project (local), and I am getting this traceback: traceback Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/account/login/ Using the URLconf defined in tutorial.urls, Django tried these URL patterns, in this order: [name='login_redirect'] admin/ account/ ^$ account/ ^login$ account/ ^logout$ account/ ^register$ [name='register'] account/ ^profile$ [name='view_profile'] account/ ^profile/edit$ [name='edit_profile'] account/ ^change-password$ [name='change_password'] account/ ^reset-password$ [name='reset_password'] account/ ^reset-password/done$ [name='password_reset_done'] account/ ^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A- Za-z]{1,13}-[0-9A-Za-z]{1,23})/$ [name='password_reset_confirm'] account/ ^reset-password/complete$ [name='password_reset_complete'] The current path, account/login/, didn't match any of these. Main/urls.py from django.contrib import admin from django.urls import path, re_path, include from tutorial import views urlpatterns = [ path('', views.login_redirect, name='login_redirect'), path('admin/', admin.site.urls), path('account/', include('accounts.urls')), ] project/urls.py from django.conf.urls import url from . import views from django.contrib.auth import views as auth_views from django.contrib.auth.views import ( PasswordResetView, PasswordResetDoneView, PasswordResetConfirmView, PasswordResetCompleteView, ) from django.urls import re_path urlpatterns = [ url(r'^$', views.home), url(r'^login$', auth_views.LoginView.as_view(template_name='accounts/login.html')), url(r'^logout$', auth_views.LogoutView.as_view(template_name='accounts/logout.html')), url(r'^register$', views.register, name='register'), url(r'^profile$', views.view_profile, name='view_profile'), url(r'^profile/edit$', views.edit_profile, name='edit_profile'), url(r'^change-password$', views.change_password, name='change_password'), url(r'^reset-password$', PasswordResetView.as_view(), name='reset_password'), url(r'^reset-password/done$', PasswordResetDoneView.as_view(), name='password_reset_done'), url(r'^reset-password/confirm(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,23})/$', PasswordResetConfirmView.as_view(), name='password_reset_confirm'), url(r'^reset-password/complete$', PasswordResetCompleteView.as_view(), name='password_reset_complete'), ] middleware.py import re from django.conf import settings from django.shortcuts import redirect class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, … -
Django - .ajax() method is not working properly
I'm writing Ajax code to hit the database to edit model instances. But the code is not working well. The first alert statement does work, but not the other alert statements. Code in success or failure does not respond. Everything seems good. I have no idea how this happened though. book/detail.html: <script> $(document).ready(function () { $("#add").click(function() { alert('clicked'); $.ajax({ url: '{% url "cart:add_to_cart" %}', // handle a successful response success: function (data) { alert("Testing."); ("#cartButton").text("Cart" + "(" + data.quantity + ")"); }, failure: function (data) { alert('Got an error'); } }); }) }); </script> cart.view.py: def add_books(request): c = Cart.objects.get(user=request.user) q = request.GET.get('quantity') book_id = request.GET.get('bookID') <some code here> data = { 'quantity': BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity'] } return JsonResponse(data) cart.urls: app_name = 'cart' urlpatterns = [ path('add_books/', views.add_books, name='add_to_cart') ] -
Couldnt't import Django
I am new to Django and I get this error while setting up."Couldn't import Django. Are you sure it's installed and "available on your PYTHONPATH environment variable? Did you "forget to activate a virtual environment?" in the manage.py file. I have created a virtual environment and activated using "env1/Scripts/activate". if __name__ == '__main__': os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'health.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) -
Django: set_cookie with special characters not working
I am using Django 1.11 with Python 3.4 and can not save cookies with a special character. This problem occurs with the Django build in development server and also on my Apache2 productive server. So I guess this problem is not related to the webserver. Please see below a very small example with one special character from the Polish alphabet: def test(request): response = HttpResponse("ERROR") response.set_cookie('br_last_name', 'ń') return respons And this is the exception which I get: Traceback (most recent call last): File "/usr/lib/python3.4/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.4/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.4/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/lib/python3.4/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/lib/python3.4/wsgiref/headers.py", line 142, in __bytes__ return str(self).encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode character '\u0144' in position 115: ordinal not in range(256) ---------------------------------------- Exception happened during processing of request from ('10.0.2.2', 51996) Traceback (most recent call last): File "/usr/lib/python3.4/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.4/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.4/wsgiref/handlers.py", line 274, in write self.send_headers() File "/usr/lib/python3.4/wsgiref/handlers.py", line 333, in send_headers self._write(bytes(self.headers)) File "/usr/lib/python3.4/wsgiref/headers.py", line 142, in __bytes__ return str(self).encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode character '\u0144' in position 115: ordinal not in range(256) During handling of … -
Elasticbeanstalk; Which is the correct alias target to configure domain name?
I'm trying to configure custom domanin name on Route 53. I'm going to choose Alias target but two official documentation seem different a bit. This documentation says Select the resource you want to point to (this will be under Elastic Load Balancers and should the resource associated with your Elastic Beanstalk deployed application), and the picture on the doc choose Elastic Load Balancers. But on the other hand, this doc says Click in the field, and choose the domain name of the environment that you want to route traffic to. This is the value that you get when you perform the procedure in the topic Getting the Domain Name for Your Elastic Beanstalk Environment. Also, if I should choose Elastic Load Balancers section, how I can check if the resource's value is associated with app on eb on eb console? -
How to convert a .png image to string and send it through Django API?
I am trying to convert a .png image to string and send it through django api but it causes error from django.shortcuts import render from django.http import HttpResponse import numpy as np import pandas as pd import matplotlib.pyplot as plt import base64 # Create your views here. from django.views.decorators.csrf import csrf_exempt import json @csrf_exempt def get_res(request): if request.method == 'POST': x = json.loads(request.body) arrx = x['x'] arry = x['y'] plt.plot(arrx,arry) plt.savefig('plot.png') with open('plot.png', 'rb') as imageFile: str = base64.b64encode(imageFile.read()) response = json.dumps([{'image': str}]) return HttpResponse(response, content_type = 'text/json') This causes error Internal Server Error: / Traceback (most recent call last): File "C:\lol\myenv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\lol\myenv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\lol\myenv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\lol\apiex\api1\views.py", line 23, in get_res response = json.dumps([{'image': str}]) File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "c:\users\new u\appdata\local\programs\python\python37\Lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON … -
What will be the Django folder structure or app structure
I am new in Django, In my projects I have to show all countries in frontend so there will be one backend section. Now I want to know what will be folder structure of this project in Django. My current structure is like this Django_Project my_env my_project assets home countries locale my_project templates admin countries countries home includes layouts registration manage.py I don't know weather this folder structure is right or not please guide me for right way to work with django. -
nginx routing with django
I'm a bit stuck on how to accomplish the setup I want. Putting aside whether it's a good idea, I am trying to setup a development/test and production django application on the same server under the same domain. I am using nginx as the public-facing server, which then should send requests to the appropriate application server based on whether the url starts with the /dev/ prefix. However, I cannot get the nginx configuration quite right. Ideally, requests to http://example.com/admin go to the production app, and http://example.com/dev/admin goes to the dev version. This way, the django urls.py is the same for both, such as: urlpatterns = [ path('admin/', admin.site.urls), ... other paths ... ] The django apps are in docker containers, which communicate with the host machine via unix sockets. That is, I start the docker container with something like: docker run -v /www:/host_dir me/mydocker and in that container, the entrypoint command is: gunicorn myapp.wsgi:application --bind=unix:/host_dir/xyz.sock My nginx conf on the host machine looks like: server { listen 80; listen [::]:80; server_name 35.231.70.176; location /dev { include proxy_params; proxy_pass http://unix:/www/dev.sock:; } location / { include proxy_params; proxy_pass http://unix:/www/production.sock:; } } In this configuration, I get the following: http://example.com/admin works as expected … -
How to add form-control class in default django admin login form
I am new in Django, I want to change class name of text-box of default djando admin login form text box. I can change he default html template of login page but cant change class name of textbox within form input. {{ form.password }} -
"TypeError statusText: "Internal Server Error" for a simple post "LIKE" feature in Django using Ajax
I am still a newbie with Ajax and jQuery I have a simple post like toggle button where a user can like a post It is working fine without adding Jquery and Ajax methods. however I need to add Ajax to remove page refresh. Below is my code adding Ajax and jQuery. What am I doing wrong. I have added the error to the bottom, It says got an unexpected keyword argument 'username' How do I fix that my models are class Post(models.Model): user = models.ForeignKey(User, related_name='posts') title = models.CharField(max_length=250, unique=True) slug = models.SlugField() message = models.TextField() likes = models.ManyToManyField(User, blank=True, related_name='post_likes') def get_api_like_url(self): return reverse('posts:like_api', kwargs={'username': self.user.username, 'slug': self.slug}) def get_absolute_url(self): return reverse('posts:single', kwargs={'username': self.user.username, 'slug': self.slug}) def get_like_url(self): return reverse('posts:like', kwargs={'username': self.user.username, 'slug': self.slug}) My views are class PostLikeAPIToggle(APIView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None): obj = get_object_or_404(Post, slug=slug) url_ = obj.get_absolute_url() user = self.request.user if user.is_authenticated(): if user in obj.likes.all(): obj.likes.remove(user) liked = False else: obj.likes.add(user) liked = True data = { "post": obj, "liked": liked, "total_likes": obj.likes.all() } return Response(data) In my template I have the below code <script> $(document).ready(function () { $(".like-btn").click(function (e) { e.preventDefault(); var this_ = $(this); var … -
Django annotate Cannot compute Sum - is an aggregate
I have Django ORM queryset and I am trying to perform the following in_month = OrderEntry.objects.filter(order__closed_date__year=self.year).filter( order__closed_date__month=month_nr) result = in_month.values('product_code').annotate( quantity=Sum('quantity'), free_count=Sum('free_count'), quantity_bottles=Sum(Case( When(product_variant__megapack_quantity=4, then=(F('quantity') * Value(4))), When(product_variant__megapack_quantity=None, then=F('quantity')), default=Value(0), output_field=IntegerField(), )) ) However, this does not work. The error I am getting : Cannot compute Sum('<Case: CASE WHEN <Q: (AND: ('product_variant__megapack_quantity', 4))> THEN <CombinedExpression: F(quantity) * Value(4)>, WHEN <Q: (AND: ('product_variant__megapack_quantity', None))> THEN F(quantity), ELSE Value(0)>'): '<Case: CASE WHEN <Q: (AND: ('product_variant__megapack_quantity', 4))> THEN <CombinedExpression: F(quantity) * Value(4)>, WHEN <Q: (AND: ('product_variant__megapack_quantity', None))> THEN F(quantity), ELSE Value(0)>' is an aggregate how can i fix it? -
Django; Is custom createsuperuser command secure?
I'm working on Django project. I deployed it into AWS elasticbeanstalk. And I created custom createsuperuser command so it can be created on eb automatically. However, tutorials don't hide the username and password when creating the file like this. class Command(BaseCommand): def handle(self, *args, **options): User = get_user_model() if not User.objects.filter(username="username").exists(): User.objects.create_superuser("username", "username@example.com", "password") Is it still secure? If not, how can I make it secure? Also I have a one more question. I'm wondering if other users can go to admin page (admin login page). If so, how can I limit people who can see the page to people who are working on the project? -
Django + Apache: cannot serve static files
I think this is common problem, but non of the solutions I tried work. The code from apache conf: <VirtualHost *:80> ServerName xxxx ServerAdmin xxxx DocumentRoot /home/matousc/apps/iacah ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/matousc/apps/iacah/www/static <Directory /home/matousc/apps/iacah/www/static> Require all granted Allow from all </Directory> <Directory /home/matousc/apps/iacah/app/mainapp> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess iacah python-path=/home/matousc/apps/iacah/app python-home=/home/matousc/apps/appenv WSGIProcessGroup iacah WSGIScriptAlias / /home/matousc/apps/iacah/app/mainapp/wsgi.py </VirtualHost> I can access the page via Internet, so I am sure that I am editing the right apache conf file. However the static files are not loaded. The static files are not downloaded with 403 error. I noticed that if I change the line: Alias /static/ /home/matousc/apps/iacah/www/static to (removed slash at the end of static: Alias /static /home/matousc/apps/iacah/www/static then I will get 404 error. In tutorials I saw both options, so I am little bit confused why it can play a role. The owner of the /www/ folder is www-data (I am using ubuntu 18): drwxrwx--x 3 www-data www-data 4096 Sep 21 10:14 . drwxr-xr-x 8 matousc matousc 4096 Sep 21 10:14 .. drwxrwxrwx 12 www-data www-data 4096 Sep 21 10:14 static I use this machine as a multihost, and I have there one other static website, … -
Django: How to change blog page on demand
I have a blog written in django, instead of view function attached to a particular view I want to change the page on demand, Similar to WordPress. How can I achieve that? -
how to call a database function using django model
I've written a database function which looks like this, CREATE OR REPLACE FUNCTION my_db_function(in_id INTEGER, in_customer_id INTEGER, in_date DATE) RETURNS BOOLEAN AS $$ DECLARE -- declarations BEGIN DELETE FROM table_1 t1 WHERE t1.date = in_date AND t1.customer_id = in_customer_id; INSERT INTO table_1 ( date, customer_id ) SELECT t2.date, t2.customer_id, FROM table_2 WHERE t2.id = in_id; RETURN TRUE; END; $$ LANGUAGE plpgsql; and I tried to call this function in python as below, MyModel.objects.raw("""SELECT * FROM my_db_function( {id} :: INT, {user_id} :: INT, '{date}' :: DATE);""".format(id=id, user_id=user_id, date=date )) The code runs successfully and continues to the next line, but it is not actually calling the database function. I followed one solution found on SO, according to that, if I append [:] to the raw query, then the database function runs. But after that it is not executing the next code written in python file. Can anyone suggest me a better way to call this database function?