Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to order fields to create a table from BaseTable in models in django
I've a model that extends from a BaseTable, eg: class BaseTable(models.Model): created_at = models.DateTimeField(auto_now_add=True, editable=False) modified_at = models.DateTimeField(auto_now=True, editable=False) created_by = models.ForeignKey(User, on_delete=models.PROTECT, related_name='%(class)s_createdby', editable=False) modified_by = models.ForeignKey(User, on_delete=models.PROTECT ,related_name='%(class)s_modifiedby', editable=False) class Meta: abstract = True In my model call the BaseTable class Produtos(BaseTable): nome_produto = models.CharField(max_length=100, verbose_name='Nome do Produto') und_produto = models.IntegerField(choices=AUX_PRODUTOS_CHOICES, verbose_name='Und') ativo = models.BooleanField(default=True, verbose_name='Ativo') When I run migrate the table Produtos is created, but the order fields are: created_at, modified_at, nome_produto, und_produto ,ativo, created_by_id, modified_by_id my question: How I order or reorder fields to: nome_produto, und_produto ,ativo, created_by_id, modified_by_id, created_at, modified_at -
TypeError and AssertionError after upgrade to Django 2
I'm tasked with upgrading a Django REST framework project from Django 1.8 to Django 2.x. I already ported the whole code from python 2.7 to python 3.7 and from Django 1.8 to 2.0.13. I'm using virtual envs. I got it running on python 3.7 and Django 2.0.13, and RESTframework 3.11, although I ran into problems while trying to create new objects. Here's the Traceback to my problem: Traceback (most recent call last): File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\exception.py", line 35, in inner response = get_response(request) File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\user1\Envs\projpy3\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\user1\projects\proj_py3\rest_framework\viewsets.py", line 114, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 505, in dispatch response = self.handle_exception(exc) File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 465, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 476, in raise_uncaught_exception raise exc File "C:\Users\user1\projects\proj_py3\rest_framework\views.py", line 502, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\user1\projects\proj_py3\rest_framework\mixins.py", line 18, in create serializer.is_valid(raise_exception=True) File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 219, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 418, in run_validation value = self.to_internal_value(data) File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 471, in to_internal_value for field in fields: File "C:\Users\user1\projects\proj_py3\rest_framework\serializers.py", line 354, in _writable_fields for field in … -
Django - ajax button not updating
I am working on a django project and I have implemented an ajax function that looks like this: $(document).ready(function(){ function updateBtnText(btn, newCount, verb){ btn.text(newCount + " " + verb) } $('#player_likebtn').click(function(e){ e.preventDefault(); var this_ = $(this); var post_like_url = this_.attr('data-url'); var post_likes_count = parseInt(this_.attr('data-likes')) | 0; var addlike = post_likes_count + 1 var remLike = post_likes_count - 1 $.ajax({ url: post_like_url, method: 'GET', post_like_data: {}, success: function(post_like_data){ if (post_like_data.liked){ updateBtnText(this_,addLike,"Unlike") } else { updateBtnText(this_,remLike,"Like") } }, error: function(error){ console.log(error); console.log("error"); } }) }); }); views.py class PostLikeApiToggle(RedirectView): authentication_classes = (authentication.SessionAuthentication,) permission_classes = (permissions.IsAuthenticated,) def get(self, request, slug=None, format=None): obj = get_object_or_404(Post, slug=slug) user = self.request.user updated = False liked = False if user in obj.post_likes.all(): liked = False obj.post_likes.remove(user) else: liked = True obj.post_likes.add(user) messages.add_message(self.request, messages.INFO, '1') updated = True post_like_data = { "updated":updated, "liked":liked } return Response(post_like_data) When I click the player_likebtn the button does not change. When I reload the page, the button changes and shows the correct value. Why is the updateBtnText function called only after I reload the page? Thank you -
Use latest version of python as default
On my Debian server if I run python -V it says it's using Python 2.7.13 even though I have python 3 installed. Why isn't it using python 3 as default by now? I'm trying to deploy a Django app and it's expecting python 3. -
Django 3 Protecting access to media files
I have a simple file upload system to upload and store multiple files model: from django.db import models class Localhost (models.Model): name = models.CharField(max_length=255) date = models.DateTimeField() def __str__(self): return self.name class LocalhostFile(models.Model): file = models.FileField(upload_to="files/%Y_%m_%d") localhost = models.ForeignKey(Localhost, on_delete=models.CASCADE) admin (that I am using to upload files) from django.contrib import admin from .models import Localhost, LocalhostFile class LocalhostFileInline(admin.TabularInline): model = LocalhostFile class LocalhostAdmin(admin.ModelAdmin): inlines = [ LocalhostFileInline, ] admin.site.register(Localhost, LocalhostAdmin) and the urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.home, name='home'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) all works as expected but what I would like to do is to restrict access to the MEDIA_URL (so all uploaded files) to logged in users with a staff role. I have found a lot of examples on how to do it for a traditional view (e.g. linked to a template) but nothing clear on how to do it for the MEDIA files in Django 3. I will certainly create a restricted view but this will not help if all files in the media folder can be accessed. Note: I don't want to have a complex setup to use Apache or … -
How to pass object assignment to a foreign key relationship in REST Framework?
I have two models: class Group(models.Model): name = models.CharField(max_length=50, null=False, blank=False) class User(models.Model): username = models.CharField(max_length=50, null=False, blank=False) password = models.CharField(max_length=50, null=False, blank=False) group = models.ForeignKey(Group, null=False, on_delete=models.CASCADE) And I have serializers for both of them: class GroupSerializer(serializers.Serializer): name = serializers.CharField() class UserSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() group = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all()) Then in the registration view, I'm trying to automatically create a group when user is registering their account: @api_view(['POST']) def registration(request): # Creates a new group g_serializer = GroupSerializer(data=request.data, partial=True) g_serializer.is_valid(raise_exception=True) group = g_serializer.save() # Creates a new user u_serializer = UserSerializer(data=request.data, partial=True) u_serializer.is_valid(raise_exception=True) user = u_serializer.save() As you can imagine the error I'm getting is that group field for User class violates not null restriction. I tried to fix it by doing u_serializer['group'] = group.id or u_serializer['group'] = group but it throws the following error: TypeError: 'UserSerializer' object does not support item assignment How can I handle this? The new Group object is being properly created and inserted into the db and I need to assign that object to user.group. -
Editing many-to-many field in related model on the admin site
Suppose I have a Person model and Interest model related to each other as Many-To-Many relation (each person can have multiple interest and vice versa), class Person(models.Model): name = models.CharField(max_length=50) class Interest(models.Model): pers_name = models.ManyToManyField(SciAdviser) interest = models.CharField(max_length=50) Further I want to be able to specify Person's Interests on the django admin site. This can be easily done by registering 2 new classes for admin page, class PersonInterestInline(admin.TabularInline): model = Interest.pers_name.through class PersonAdmin(admin.ModelAdmin): inlines = [PersonInterestInline] This allows one to choose Person's Interests from drop-down list on admin page. However, what if I would like to allow users to add new Interest there, the ones which do not exist in the database (yet)? Is there any way to implement this? In particular, django should add new record to the Interest table if and only if the interest entry specified by a user does not exist. Without this requirement I can use the ForeignKey instead of ManyToManyField. However, in this case there will be many duplicating interest fields in Interests. Ideally, I want to use the Interest field for tagging. Maybe I should use a different approach to the problem at all? However, the possibility to add new interests by users … -
Need to reset whole postgres database, want to backup a table in the database
I give up. Migrations are effed up. encountering error after error. I'm so sick and tired of this shit right now. I just want to move on. So I guess it better to wipe all data because of one table is messed up. Is it possible to backup ONE table, not a database, before wiping? And then after import this back to that table? I use postgres db. -
"except ImportError,e:" Syntax Error with Python 3.7
I am working on a Django web project, and after I updated Django to 1.4.22 it gave me this syntax error when trying to run my project: File "/Users/ethanjay/env/py37/lib/python3.7/site-packages/django/core/management/init.py", line 54 except ImportError,e: ^ SyntaxError: invalid syntax I went online to try and fix this, and it seemed that this was a Python Version error, and the solution would be to use Python 2.7 instead of 3.7, yet I've been successfully using a virtualenv with 3.7 up until I updated my Django version. Let me know if I need to be more specific or add any other pieces of information -
How do I configure my ProxyPass with Apache and Django (and Docker)?
I'm trying to build a local docker container to have Django 2/Python 3.7, Apache 2.4, and MySql 5.7 images. I'm having trouble configuring my Apache proxy to properly interact with my Django instance. I have my apache/my-vhosts.conf file like so ... <VirtualHost *:80> ServerName maps.example.com ProxyPreserveHost On ProxyPass / http://127.0.0.1/ ProxyPassReverse / http://127.0.0.1/ </VirtualHost> My Apache 2.4 Dockerfile looks like FROM httpd:2.4 COPY ./my-httpd.conf /usr/local/apache2/conf/httpd.conf COPY ./my-vhosts.conf /usr/local/apache2/conf/extra/httpd-vhosts.conf COPY ./maps /usr/local/apache2/htdocs/maps and my overall docker-compose.yml file looks like ... version: '3' services: web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 apache: restart: always build: ./apache/ ports: - "80:80" #volumes: # - web-static:/www/static links: - web:web mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql volumes: my-db: Sadly, when I fire everything up with "docker-compose up," my request to "http://127.0.0.1/" dies with a "The proxy server received an invalid response from an upstream server.". In my … -
Overriding Django User model goes wrong on username field
I am making a personal project in order to learn more and more and even more about Django with some advanced code. In my project, I have substituted a custom User model by the following: (Take into account that I am using REST Framework) class Account(AbstractUser): """Account model. Extends from Django's AbstractUser.""" USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['password'] palta = models.ForeignKey( Palta, null=False, db_column='palta', on_delete=models.CASCADE ) name = models.CharField( max_length=200, null=True ) email = models.EmailField( 'email address', unique=True, max_length=70, null=False, blank=False ) password = models.CharField( max_length=30, null=False, blank=False ) registration_date = models.DateField(null=False, auto_now_add=True) last_session = models.DateTimeField(null=True, auto_now=True) birthday = models.DateField(null=True) exists = models.BooleanField(null=False, default=True) class Meta: db_table = 'accounts' unique_together = ['id', 'palta'] I added the following line in settings.py: # Django's User model override AUTH_USER_MODEL = 'accounts.Account' And my serializer for this class looks like this: class CreateAccountSerializer(serializers.Serializer): """Creates a new Account.""" palta = serializers.PrimaryKeyRelatedField(queryset=Palta.objects.all()) email = serializers.EmailField() password = serializers.CharField() def create(self, data): """Account creation serializer.""" return Account.objects.create_user(**data) Note that I'm trying to use the method create_user(), which is expecting a username. The problem is that I have overridden the username field with just an email field, it means that the email in the registration request is the … -
How do I run Django seed data in my MySql docker image?
I'm using Python 3.7, Django 2 and attempting to build a docker container housing both MySql and Django app images. I have this docker-compose.yml file ... version: '3' services: web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql volumes: my-db: Here is my web/Dockerfile ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY . /app/ If I want to seed my MySql image with Python data, how would I achieve that? Without docker, I would normally run this python manage.py loaddata maps/fixtures/country_data.yaml in a virtual environment. Not quite sure where this command … -
Why they are showing error in my django project by importing models that Board has no objects member?
from .models import Board from django.http import HttpResponse Create your views here. def home(request): boards = Board.objects.all() boards_names = list() for board in boards: boards_names.append(board.name) response_html = '<br>'.join(boards_names) return HttpResponse(response_html) -
I'm have received an error whilst trying to do a " python makemigrations core" to one of the apps in a project
from uuid import uuid4 from django.db import models from django.conf import settings from django import forms from django.db.models.aggregates import ( Sum ) from core.models import ( Vote, Movie ) def movie_directory_path_with_uuid(instance, filename): return '{}/{}'.format(instance.movie_id, uuid4()) class MovieImage(models.Model): image = models.ImageField(upload_to=movie_directory_path_with_uuid) upload = models.DateTimeField(auto_now_add=True) movie = models.ForeignKey('Movie', on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) -
TypeError at /profiles/userLogin/: Django
So I have created a web app where a user can pay to a particular vendor(total 2 vendors). When I try to submit the form, I get the above mentioned error. Also, it says 'employee' object is not iterable .Given below ar the HTML, views.py and models.py files: HTML: <div class="container boxes" style="margin: auto; text-align: center;background-color: #ede8e8;border-radius: 10px;opacity: 0.95;width: 60%;"> <br> {% if model %} <h3>Balance amount is {{ model.balance }}</h3> {% endif %} <h3>Select vendor to pay!</h3> <br> <form method="POST" action="/profiles/userLogin/"> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample1" name="groupOfDefaultRadios" value="1"> <label class="custom-control-label" for="defaultGroupExample1">Vendor 1</label> </div> <div class="custom-control custom-radio"> <input type="radio" class="custom-control-input" id="defaultGroupExample2" name="groupOfDefaultRadios" value="2"> <label class="custom-control-label" for="defaultGroupExample2">Vendor 2</label> </div> <input type="" class="form-control" id="amount1" name="amt" aria-describedby="emailHelp" placeholder="Enter amount"style="width: 25%;margin: 0 auto"> <button type="submit" class="btn btn-primary" style="margin: 5px;" name="form1">Submit</button> <br> </form> </div> views.py: if 'form1' in request.POST: ven_id = request.POST.get("groupOfDefaultRadios") amount = request.POST.get("amt") x = employee.objects.get(name = request.user) x.balance = x.balance - int(amount) x.save() v = vendor.objects.get(id=ven_id) w = employee.objects.get(id=x.id) transaction.objects.create(vendor_id = v, emp_id=w,debit=amount,credit=0) y = employee.objects.get(name = request.user) return render(request, 'profiles/userLogin.html', {'model':y}) Models.py: class vendor(models.Model): id = models.CharField(max_length=20, primary_key=True) name = models.CharField(max_length=30) class employee(models.Model): name = models.OneToOneField(User, on_delete=models.CASCADE) id = models.CharField(max_length=20, primary_key=True) balance = models.IntegerField(default=0) class transaction(models.Model): vendor_id = models.ForeignKey(vendor, … -
Error occured while saving a form created through model formset
I am a Django learner. 1.I have a requirement to create the multiple forms in a single page for a model. 2.So i created the formset using modelformset_factory. 3.I have 2 models.a)ModelRegister b)ModelGSPRequest. 4.ModelGSPRequest has a field named registered_model which is a foreignKey to ModelRegister. 5.But after i input all the fields for a modelformset and click on submit to save. I am facing below error with the foreign key field. Please help how to proceed further. ---------------------------------------------------------------------------------------------------- Exception Type: ValueError Exception Value: Cannot assign "'G6'": "ModelGSPRequest.registered_model" must be a "ModelRegister" instance. Exception Location: C:\Python3.6.0\MyScripts\djangoprojects\gsptracker\venv\lib\site-packages\django\db\models\fields\related_descriptors.py in __set__, line 211 ---------------------------------------------------------------------------------------------------- Below is my code: models.py: --------- class ModelRegister(models.Model): """ This class is used to register the model. """ FLOAT_CHOICES = [[float(x), float(x)] for x in range(1, 21)] model_leader = models.CharField("Model leader", max_length=128) model_name = models.CharField(max_length=128, verbose_name="ModelName") model_no = models.CharField(max_length=128, verbose_name="ModelNo") os_name = models.ForeignKey(OSName, on_delete=models.CASCADE, verbose_name="OSName",default=" ") os_version = models.FloatField(choices=FLOAT_CHOICES) chipset_type = models.ForeignKey(ChipsetType,on_delete=models.CASCADE, verbose_name="chipsetType") chipset_name = models.ManyToManyField(Chipset) class Meta: verbose_name_plural = "ModelRegisteredList" def __str__(self): return self.model_name class ModelGSPRequest(models.Model): """ This class is used to raise Model GSP request. """ FLOAT_CHOICES = [[float(x),float(x)] for x in range(1,21)] registered_model = models.ForeignKey(ModelRegister,on_delete=models.CASCADE, verbose_name="ModelName") model_nos_for_reg_model = models.ManyToManyField(ModelNumber,default="") #registered_model_no = models.CharField(max_length=128, verbose_name="ModelNo",default=" ") registered_os_name = models.ForeignKey(OSName, … -
My custom login form in Django attempts to create a new user rather than log a user in
I set up a custom user class and I'm using all custom user management templates, views, urls, etc... All of them work except my login view. I can get it to work by pulling taking the username and password straight from the request and skipping form cleaning. That however, sounds like a really bad idea. When I try to use forms.is_valid() The function gives me errors indicating it's trying to create a new user rather than log an existing one in. I've been looking around and doing trial and error for a few hours now and I still have no clue why its doing this and why no one seems to be concerned about cleaning their login forms. Here is my login view: def loginView(request): if not request.user.is_authenticated: if request.method == 'POST': form = forms.LoginForm(request.POST) authError = False if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') post = CustomUser.objects.filter(username=username) if post: username = form.cleaned_data.get('username') user = authenticate(username=username, password=password) login(request, user) return redirect('home') else: authError = True print("form failed") #print(form) #print(form.errors) return render(request, 'login.html', context={'form': form, 'form_errors': form.errors, "auth_error": authError}) else: print("get request") form = forms.LoginForm() print(form) return render(request, 'login.html', context={'form': form}) else: return redirect('home') and here is my form: class … -
Nextjs or Gatsby for an e-commerce website with django?
I want to make an e-commerce web app where in backend I use Django and Django Rest Framework. I want to use React, Redux and React-Router with axios library in frontend. But I found to other framework for React. They are Nextjs and Gatsby. Now, Which one will better for me to make an e-commerce web app between Nextjs and Gatsby? And, Is it necessary to use Redux, React-Router with Nextjs and Gatsby? -
Django save variable name in db
I am writing somekind of custom cms and I need to save variable names For example user can write this in textarea(and I need to save it to database as is: My dog is {{dog_name}} And somewhere on dog_settings.html page he can set dog_name=Max And when he clicks- show me combination of template and settings: I need to show him result string: My dog is Max How do I do this? -
Sub query result in Django not looping from drop down select box
The subquery obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1))) is not displaying any result please can any one help if request.method == 'POST': selected_item = request.POST.get('item_id') queryset.annotate(val=RawSQL("select col from sometable where othercol = %s", (someparam,))) Lga.objects.all().values('uniqueid').filter(uniqueid__in=selected_item) obj = Lga.objects.get(lga_id=selected_item) obj1 = obj.lga_id obj3 = Pu_results.objects.filter(polling_unit_uniqueid__in=Subquery(Unit.objects.filter(lga_id=obj1))) for obt in obj3: print(obt.party_score) -
django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG
I'm getting the below traceback and it seems to be related to changes made in Django 3.0.2? I'd appreciate if someone could explain what I'm doing wrong here. (myDjangoEnv) D:\Django\django_lectures\first_project>python populate_first_app.py Traceback (most recent call last): File "populate_first_app.py", line 5, in <module> django.setup() File "C:\Users\ABC\.conda\envs\myDjangoEnv\lib\site-packages\django\__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "C:\Users\ABC\.conda\envs\myDjangoEnv\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\ABC\.conda\envs\myDjangoEnv\lib\site-packages\django\conf\__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Here is my code: import os os.environ.setdefault('DJANGO_SETTING_MODULE', 'first_project.settings') import django django.setup() ##FAKER POP SCRIPT import random from first_app.models import AccessRecord, Topic, Webpage from faker import Faker fakegen = Faker() topics = ['Search', 'Social', 'Marketplace', 'News', 'Game'] def add_topic(): t = Topic.objects.get_or_create(top_name = random.choice(topics))[0] t.save() return t def populate(N = 5): for entry in range(N): #get the topic for the entry top = add_topic() #Create fake data for that entry fake_url = fakegen.url() fake_date = fakegen.date() fake_name = fakegen.company() #Create new webpage entry webpage = Webpage.objects.get_or_create(topic = top, url= fake_url, name = fake_name)[0] #Create a fake AccessRecord for that webpage acc_rec = AccessRecord.objects.get_or_create(name = webpage, date = fake_date)[0] if __name__ == '__main__': … -
502 bad gateway because of permissions denied
I am trying to deploy django project on digitalocean using nginx and gunicorn. My project have the following structure projects |_isli |_isli |_forecast #project directory |_manage.py |_forecast |_forecast.sock |_wsgi.py |_settings.py |_urls.py My project created inside root directory without creating additional sudo user. I know that isn't right solution but i decide so. In my settings.py file inside allowed hosts i specified ip address ALLOWED_HOSTS = ['165.22.23.233'] In official digitalocean docs have tutorial about deploying django using nginx and gunicorn Deploying django using Nginx and Gunicorn in this article used method where gunicorn setted up as socet here is my setup /etc/systemd/system/gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=root WorkingDirectory=/root/projects/isli/isli/forecast ExecStart=/root/projects/isli/env/bin/gunicorn --log-level debug --error-logfile /var/log/gunicorn/error.log --access-logfile /var/log/gunicorn/access.log --workers 3 --bind unix:/root/projects/isli/isli/forecast/forecast.sock forecast.wsgi:application [Install] WantedBy=multi-user.target after creating gunicorn.service file i run systemctl start gunicorn than systemctl enable gunicorn after it in my project directory was created forecast.sock file Than i setup nginx in /etc/nginx/sites-available/forecast with following server { listen 165.22.23.233:80; location = /favicon.ico {access_log off; log_not_found off;} location / { include proxy_params; proxy_pass http://unix:/root/projects/isli/isli/forecast/forecast.sock; } } Than systemctl restart nginx When i am trying to access http://165.22.23.233:80 from browser its promt me 502 bad gateway. After it in /var/log/nginx/error.log file i see … -
Geo Django GDAL Exception OGR Failure
I'm using geo django and running on windows. I do have GDAL and OSGEOS configured in the settings. Here is my settings.py code for gdal. import os if os.name == 'nt': import platform OSGEO4W = r"C:\OSGeo4W" if '64' in platform.architecture()[0]: OSGEO4W += "64" assert os.path.isdir(OSGEO4W), "Directory does not exist: " + OSGEO4W os.environ['OSGEO4W_ROOT'] = OSGEO4W os.environ['GDAL_DATA'] = OSGEO4W + r"\share\gdal" os.environ['PROJ_LIB'] = OSGEO4W + r"\share\proj" os.environ['PATH'] = OSGEO4W + r"\bin;" + os.environ['PATH'] I have a model that has a pointfield. model: class Event(models.Model): user = models.ForeignKey(User, on_delete=models.SET, blank=True) name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE) location = models.PointField(srid=4326, blank=True) Whenever I try to create an event and set the pointfield value, I get this error: GDAL_ERROR 6: b'Unable to load PROJ.4 library (proj.dll), creation of\nOGRCoordin ateTransformation failed.' Error transforming geometry from srid '4326' to srid '3857' (OGR failure.) -
Django Form wizard - How to save selected items in many to many field
So I have a form divided in two steps using the Django formtools Form wizard. The form is working, the data is being saved, except for the manytomanyfield items. Users can create an Ad which can be filtered by tags. The Tag model is related to the Ad model through a manytomanyfield, however on saving the form, the selected tags are not saved within the Ad model. models.py class Ad(models.Model): title = models.CharField(max_length=200) description = RichTextField() tags = models.ManyToManyField('Tag') class Tag(models.Model): name = models.CharField(max_length=200) views.py FORMS = [ ('title', AdCreateFormStepOne), ('tags', AdCreateFormStepTwo), ] TEMPLATES = { 'title': 'grid/ad_form_title.html', 'tags': 'grid/ad_form_tags.html', } class AdWizardView(SessionWizardView): form_list = FORMS def get_template_names(self): return [TEMPLATES[self.steps.current]] def done(self, form_list, **kwargs): instance = Ad() for form in form_list: instance = construct_instance(form, instance, form._meta.fields, form._meta.exclude) instance.save() return redirect('index') So I guess I still have to handle the manytomany relation in the done method for the AdWizardView. I saw the following question answered but the solution throws an error... 'odict_values' object does not support indexing Does anyone know what I'm missing here? With best regards, -
Replacing a request to an external resource with a json object (inside another function) in Django testing
I have function: def payment(self): #some logic ... #more logic ... # request to external api resource (f.e. stripe.Event.create) # logic #... How can to write test (using patch?) for testing request to external api (stripe.Event.create) without transfering him from main function.