Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django weasyprint HTML to PDF convert is working very slow
I am covering HTML to PDF file using weasyprint in Django web app. Everything is working fine but It is working is very slow when converting HTML to PDF. It takes more than two minutes long When I convert it. I am using Bangla font in my HTML file. this is my views.py code def get_pdf_file(request, customer_id, sys_type): sys_type = customer_id area = "pdf" site_credit = site_credit1 time_now = timezone.now() customers = get_object_or_404(CustomerInfo, pk=customer_id) due_taka_track = customers.duetaka_set.all() if due_taka_track == None: due_taka_track = 0 unpaid_taka = int(customers.customer_price - customers.customer_due_taka_info) due_taka_track = customers.duetaka_set.all() sum_cost_taka = due_taka_track.aggregate( sp=Sum('customer_due')).get('sp', 0) if sum_cost_taka == None: sum_cost_taka = 0 total_paid_taka = sum_cost_taka + customers.customer_due_taka_info payment_status = 'complete' payment_message = 'Full Paid' remain_taka='PAID' remain_msg='' if customers.customer_due_taka_info < customers.customer_price: payment_status = 'incomplete' payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি' remain_msg='টাকা বাকী আছে' baki_ase="পাওনা আছে " remain_taka = customers.customer_price - customers.customer_due_taka_info context = {'customers': customers, 'sys_type': sys_type, 'area': area, 'site_credit': site_credit, 'site_name': 'Moon Telecom', 'sys_type': sys_type, 'due_taka_track': due_taka_track, 'total_paid_taka': total_paid_taka, 'payment_message': payment_message, 'time_now': time_now, 'unpaid_taka': unpaid_taka, 'payment_message': payment_message, 'remain_taka': remain_taka, 'sum_cost_taka': sum_cost_taka, 'remain_msg': remain_msg} html_string = render_to_string('shop/pdf_invoice.html', context) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=invoice'+sys_type+'.pdf' response['Content-Transfer-Encoding'] = 'UTF-8' with tempfile.NamedTemporaryFile(delete=True) as output: … -
Save is not Working in django, in shell and Model Form
Please help, I have not seen this error before.The save function is not updating my model either in Shell or in the view. It also gives no error message. >>> from course.models import Course >>> course = Course.objects.get(pk=1) >>> course.title 'test' >>> course.title = "NameChange" >>> course.title 'NameChange' >>> course.save() >>> If I exit and then Re-enter the shell >>> from course.models import Course >>> course = Course.objects.get(pk=1) >>> course.title 'test' The following will also not work on my update view where I use a model Form, I cant post the code for the model form. @superuser_required def update(request, course_id): course = get_object_or_404(Course, pk=course_id) if request.method=='POST': form = CourseForm(data=request.POST, instance=course) if form.is_valid(): form.save() messages.info(request, _("The course has been updated")) return redirect(reverse("course:admin:index")) else: form = CourseForm(instance=course) context = {'form': form,} return render(request, 'course/admin/update.html', context) I would post my models.py file but StackOverflow won't let me, says there is too much code. -
MultiValueDictKeyError when trying to upload image in Django
Hi I'm trying to upload an image file through a form field using Django and i'm getting django.utils.datastructures.MultiValueDictKeyError when trying to submit the form. This is my forms.py: class UserProfileForm(forms.ModelForm): type = forms.ModelChoiceField(queryset=UserType.objects.all(), required=True) phone = forms.CharField(required=False) address = forms.CharField(required=False) picture = forms.ImageField(required=False) class Meta: model = UserProfile # matches data model fields = ('type','phone','address','picture') # shown on the form This is my models.py: class UserProfile(models.Model): user = models.OneToOneField(User) type = models.ForeignKey(UserType, on_delete=models.CASCADE) phone = models.CharField(max_length=10, blank=True) address = models.CharField(max_length=128, blank=True) picture = models.ImageField(upload_to='profile_images', blank=True) def __str__(self): return self.user.username This is my views.py: def register(request): if request.method == 'POST': response = {} username = request.POST.get('username') password1 = request.POST.get('password1') password2 = request.POST.get('password2') type = request.POST.get('type') first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') email = request.POST.get('email') phone = request.POST.get('phone') address = request.POST.get('address') picture = request.POST.get('picture') data = {'username': username, 'password1': password1, 'password2': password2, 'type': UserType.objects.get(type=type).pk, 'first_name': first_name, 'last_name': last_name, 'email': email, 'phone': phone, 'address': address, 'picture': picture} user_form = UserForm(data) profile_form = UserProfileForm(data) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(data['password1']) user.save() profile = profile_form.save(commit=False) profile.user = user #if 'picture' in request.FILES: #profile.picture = request.FILES['picture'] #picture = Image.open(StringIO(profile_form.cleaned_data['picture'].read())) #picture.save(MEDIA_DIR, "PNG") #newPic = Pic(imgfile=request.FILES['picture']) newPic=request.FILES['picture'] newPic.save() profile.save() return JsonResponse({'response': 'success'}) else: errors = user_form.errors.copy() … -
@route not working for Home page
I'm working on a Python/Django project. I have to implement AMP (Accelerated Mobile Page) to some pages. In order to achieve that I'm using route in the models this way: @route(r'^$') def vanilla(self, request): return Page.serve(self, request) @route(r'^amp/$') def amp(self, request): context = self.get_context(request) return TemplateResponse(request, '/pages/article_amp.html', context) That works perfectly fine. When I go to localhost:3000/article/ I get the normal layout, when I go to localhost:3000/article/amp/ I get the AMP version of the page. However when trying with the homepage I get a 404 error: localhost:3000 ==> Works fine localhost:3000/amp/ ==> 404 error Why is this happening? Alternatively, how can I achieve the same for the homepage? -
How to upload the image into the profile (ImageField in Django doesn't work)?
Everybody hello! Somebody help me please, what do i do wrong? I try to upload image (avatar) but something goes wrong. If i use form.save() user is created, but the photo isn't uploaded. If i use instance - photo is uploaded, but i have Exception Value: NOT NULL constraint failed: user_management_app_person.user_id model from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save class Person(models.Model): user = models.OneToOneField(User) phone_number = models.CharField(verbose_name="Контактный номер:", max_length=255, null=True, blank=True) birthdate = models.DateField(verbose_name="Дата рождения:", null=True, blank=True) photo = models.ImageField(verbose_name="Загрузите Ваше главное фото:", upload_to="images/avatars/", name="photo", null=True, blank=True) rules = models.BooleanField(max_length=32, blank=True, default='True') def __str__(self): return self.user.username def create_user(sender, **kwargs): if kwargs['created']: user = Person.objects.create(user=kwargs['instance']) post_save.connect(create_user, sender=User) view from django.http import HttpResponseRedirect from django.shortcuts import render from user_management_app.forms import MyRegistrationForm from user_management_app.models import Person def registration(request): if request.method == 'POST': form = MyRegistrationForm(request.POST, request.FILES) if form.is_valid(): form.save() # instance = Person(photo=request.FILES['photo']) # instance.save() return HttpResponseRedirect("/privateroom/") else: form = MyRegistrationForm() args = {'form': form} return render(request, "registration.html", args) form from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class MyRegistrationForm(UserCreationForm): username = forms.CharField(max_length=32, widget=forms.TextInput(attrs= {"type": "text", "class": "form-control", "placeholder": "Username"})) last_name = forms.CharField(max_length=32, widget=forms.TextInput(attrs= {"type": "text", "class": "form-control", "placeholder": "Фамилия"}), required=False) first_name = forms.CharField(max_length=32, … -
How add a domain and port in imagefield sended by django channels?
I have a application written in Angular and Django (with Django REST framework and Django channels). I created a model with "ImageField" and added a data binding (for this field). The problem: When I want get all images (by API), in the response I have a absolute image url: "url": "http://192.168.0.164:8000/media/photos/2017-10-19_20%3A50%3A26.jpg", but... When I add a new Photo, a channel send me by websocket field with relative url (without domain and port and MEDIA_URL) "url": "photos/2017-10-19_20%3A50%3A26.jpg" How to fix it? How add a domain and port in channels? -
Adding Cookiecutter-django users urls to i18n_patterns breaks tests
I'm having a problem with tests and internationalization. Project is Django 1.11 Python 3.5 project created with cookiecutter-django Internationalization code in settings.py: TIME_ZONE = 'UTC' LANGUAGE_CODE = 'en-us' SITE_ID = 1 USE_I18N = True USE_L10N = True USE_TZ = True LANGUAGES = [ ('en', _('English')), ('fr', _('French')), ('es', _('Spanish')), ('de', _('German')), ] Running pytest on the standard Cookiecutter tests for Users, without adding i18n_patterns, successfully completes. Once the urls are updated like this: urlpatterns += i18n_patterns( .... # User management url(r'^accounts/', include('allauth.urls')), url(r'^users/', include('users.urls', namespace='users')), .... ) The url tests then fail. The output looks like this: ====================================================================== FAIL: test_get_redirect_url (users.tests.test_views.TestUserRedirectView) ---------------------------------------------------------------------- Traceback (most recent call last): File "users/tests/test_views.py", line 33, in test_get_redirect_url '/users/testuser/' AssertionError: '/en-us/users/testuser/' != '/users/testuser/' - /en-us/users/testuser/ ? ------ + /users/testuser/ As you can see, the issue is that /en-us/ is the prefix being used on the url. Now, I could fix this by adding /en-us/ to my assertions. However, the /en-us/ prefix is incorrect. This is a language code and not the regular language prefix as shown in my settings file. Outside of testing, and using runserver, if I navigate to the /users// url it is prefaced with /en/ not /en-us/ So, the big question is … -
NameError for defined class variable [duplicate]
This question already has an answer here: Nested list comprehension scope 1 answer Below, the artifact_urls class variable is clearly defined, and there is no problem referencing it in a print statement or dict constant, but referencing it from within a list comprehension raises a NameError. Why?!?! Here's the code and output. from otree.api import ( models, widgets, BaseConstants, BaseSubsession, BaseGroup, BasePlayer, Currency as c, currency_range ) class Constants(BaseConstants): artifact_urls = ["Hello, world!"] print(artifact_urls) artifact_const = { "url": artifact_urls[0] } artifact_const = [{ "url": artifact_urls[i] } for i in range(1)] Output: ['Hello, world!'] Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1085426a8> Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 107, in inner_run autoreload.raise_last_exception() File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 252, in raise_last_exception six.reraise(*_exception) File "/usr/local/lib/python3.6/site-packages/django/utils/six.py", line 685, in reraise raise value.with_traceback(tb) File "/usr/local/lib/python3.6/site-packages/django/utils/autoreload.py", line 229, in wrapper fn(*args, **kwargs) File "/usr/local/lib/python3.6/site-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.6/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "/usr/local/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 978, in _gcd_import File "<frozen importlib._bootstrap>", line 961, in _find_and_load File "<frozen importlib._bootstrap>", line 950, in _find_and_load_unlocked … -
Django's LoginView doesn't accept custom AuthenticationForm
I have a class LoginForm which is a subclass of Django's AuthenticationForm. In urls.py there is the following line for routing to auth_views.LoginView: from django.contrib.auth import views as auth_views from my_app.forms import LoginForm url(r'^login/', auth_views.LoginView.as_view(authentication_form=LoginForm), name='login'), As you can see, I've been trying to replace the default AuthenticationForm with my LoginForm by using the authentication_form keyword argument mentioned in the Django documentation but the LoginView will still display the default AuthenticationForm. What am I missing? -
How to refresh the selection box when new option is added in Django?
I have a form with a selection box related to a foreign key (for example, category). And on the same page, I have another link that opens a new page to add a new instance of the foreign key. Once the new instance is added, how can I update the current form to add the new option, and preserve the text in the text field (just like how the admin page behaves)? -
Django query add counter
I have 3 tables: Truck with the fields: id, name.... Menu with the fields: id, itemname, id_foodtype, id_truck... Foodtype with the fields: id, type... And I have a query like this: SELECT ft.id, ft.name, COUNT(me.id) total FROM foodtype ft LEFT JOIN menu me ON ft.id = me.id_foodtype LEFT JOIN truck tr ON tr.id = me.id_truck AND tr.id = 3 GROUP BY ft.id, ft.name ORDER BY ft.name And returns something like: id name total 10 Alcoholic drink 0 5 Appetizer 11 My problem is to return the results with 0 elements. At the moment to convert this query to Python code, any of my queries return the exact result than I expected. How I can return the results with the Left Join including the foodtypes with zero elements in themenu`? -
Django Annotating Model with Count() by Chaining related_name Lookups
So I would like to use Count() to aggregate the number of Listings that I have through multiple related_name lookups. For example: Category.objects.annotate(listings_count=Count(productsAsCategory__listingsAsProduct)) ^ This only works if I use Count(productsAsCategory), but chaining it with another field (as done above) doesn't return anything. models.py: class Category(models.Model): [...] class Product(models.Model): category = models.ForeignKey(Category, related_name='productsAsCategory') [...] class Listing(models.Model): product = models.ForeignKey(Product, related_name='listingsAsProduct') [...] -
Pass value to Django model attribute
I am building a file upload page where files will be saved with a different prefix in their name (get_file_path function uses instance.mname) but will go through the same upload model/form. I want the prefix to be declared in the views in form in mname='prefix'. How can I pass this value from views to form? Thank you! models.py class Upload(models.Model): mname = ###need it to be passed#### document = models.FileField(upload_to=get_file_path, validators=[validate_file_extension]) upload_date=models.DateTimeField(auto_now_add =True) forms.py class UploadForm(forms.ModelForm): class Meta: model = Upload fields = ('document',) views.py def uploadFile(request): if request.method == "POST": file = UploadForm(request.POST, request.FILES, mname='....') if file.is_valid(): file.save() -
Add extra metadata to model info Django returns for OPTIONS
In my Django application I have a list of Event_Types that users can subscribe to. Pretty simple with: event_type = models.CharField(choices=EVENT_TYPES, max_length=128) And the UI gets a list of available event types when it calls OPTIONS. The challenge is that certain levels of permissions open up additional choices. So the UI sees a bunch of event types that are unavailable to that user. It's not a security concern to know that the options are there, but it requires per-event_type filtering in the UI, which I would like to rather be driven by the OPTIONS. Is there a way to manually add metadata to what OPTIONS returns? -
How to display the data contained in Django models in a Django Dropdown menu form?
Currently, I have some data stored in a Django model with the following structure: #Django model from django.db import models class Customer(models.Model): first_name = models.Charfield(max_length = 120, null = False, blank = False) last_name = models.Charfield(max_length = 120, null = False, blank = False) def __str__(self): return self.first_name+ " " + self.last_name I want to display all the customers that are stored in the Customer model in the DropDown menu form. What I tried was the following but I've got no success: #Django form from .models import Customer # This throws as a result <Django.db.models.query.utils.deferred.attribute at 0x00013F> inside of the DropDown Menu form class DropDownMenuCustomer(forms.Form): Customer = forms.ChoiceField(choices=[(x,x) for x in str(Customer.first_name)+str(" ")+ str(Customer.last_name))]) Another possibility without success was: #Django form from .models import Customer class DropDownMenuCustomer(forms.Form): querySet = Customer.objects.all() list_of_customers = [] for customer in querySet: list_of_customers.append(customer.first_name + " " + customer.last_name) customer= forms.ChoiceField(choices=[(x) for x in list_of_customers)]) This last possibility does not find list_of_customers, just as if the variable has not been declared. How can I display the data stored in the Django models in the Django forms? -
Django TypeError 'NoneType' when adding objects to ManyToMany field
I'm trying to add an app to my Django project called "clinicaltrials" (CT) that stores data from the clinicaltrial.gov API. Each trial may have multiple collaborators and multiple diseases, so I've set up additional models for them with a ManyToManyField. (note: I originally tried to connect CT directly to my Company model, however not all possible companies are in my database so I'm capturing names as well in the CT model) The problem I'm running into is when I try to add the CT record to either of the additional models I get an error TypeError: 'NoneType' object is not iterable. I would think that looking it up by pk as I'm doing would work. This is my first time using a ManyToManyField and I've been wresting this for the past two days. Where am I going wrong here? This is the function that I'm using to write to the models: def write_database(data): for trial in range(len(data)): # if the trial exists in the database continue to the next one if ClinicalTrial.objects.filter(nct_id=data[trial].get('nct_id')).exists(): continue # create list of collaborators for later if data[trial].get('collaborators') is not None: collaborators = [] collaborator_len = len(data[trial].get('collaborators')) for x in range(collaborator_len): collaborators.append(data[trial].get('collaborators')[x].get('name')) else: collaborators = None … -
getting value and summation from relationship tables on django
I have tow modules (classes) on python django like this sample bellow : #first one class Names(models.Model): name = models.CharField(max_length=200) type = models.ForeignKey(Types) value = models.IntegerField() #second one class Type(models.Model): name = models.CharField(max_length=200) as you see, the class names have relationship with class type so how to make a formula to get the total number of names and the summation of values in every class of type to get result something like this for example : type1_total_names = 4 type1_sum_val = 22 -
Django won't display image from database in HTML
Hi I am trying to get user profile images to display from a Django MySQL database corresponding to the user that is logged in.. Here is my settings.py # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') MEDIA_DIR = os.path.join(BASE_DIR,'media') # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.10/howto/static-files/ STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] # Media files MEDIA_ROOT = MEDIA_DIR #MEDIA_DIRS = [MEDIA_DIR, ] MEDIA_URL = '/media/' ADMIN_MEDIA_PREFIX = '/admin/media/' Here is my urls.py: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^smartcity/',include('smartcity.urls')), #url(r'^accounts/register/$', MyRegistrationView.as_view(), name='registration_register'), #url(r'^accounts/register/$', views.register, name='registration'), url(r'^accounts/', include('registration.backends.simple.urls')), url(r'^admin/', admin.site.urls), url(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}), ] And this is what I have in the html file: src="{% static 'user.userprofile.picture.url' %}" This is my table i am trying to retrieve the picture from: Database screenshot I'm not sure how to get it to display, I thought my URL mapping was correct as i can view the image if i go to http://127.0.0.1:8000/media/profile_images/trump.jpg Any ideas? Sorry I am a bit of noobie. -
'Options' object has no attribute 'get_all_related_objects' but I'm already using Django 1.11
I keep getting an 'Options' object has no attribute 'get_all_related_objects' error. I've researched and people say it is often an issue with using an old version of django, but I'm using 1.11.6 when I navigate to the url: app/employees I get this error. What am I doing wrong? Django Version: 1.11.6 Exception Type: AttributeError Exception Value: 'Options' object has no attribute 'get_all_related_objects' other version numbers: python: 2.7.14 rest framework: 3.1.1 virtualenv: 12.1.1 app/model: class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) supervisor = models.ForeignKey('self', blank=True, null=True) is_active = models.BooleanField(default=True) is_supervisor = models.BooleanField(default=False) class Meta: ordering = ('last_name',) def __str__(self): return "{}".format(self.first_name + ' ' + self.last_name) app/serializer: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee app/api.py: class EmployeeApi(ListAPIView): queryset = Employee.objects.all() serializer_class = EmployeeSerializer app/url.py urlpatterns = [ ... url(r'^employees$', EmployeeApi.as_view()), ] -
Create subdomain progamatically with Python through Django
I have an application hosted at Digital Ocean. My boss wants that some users have a particular subdomain, i.e., user.mydomain.com Can I do that using Django? I am using gunicorn and nginx. -
How can I load data to the PostgreSQL database in Django project with Docker container?
I have a data which after printing looks in this way: print(myData): 2007-01-01 Estimates of Iraqi Civilian Deaths. Romania and Bulgaria Join European Union. Supporters of Thai Ex-Premier Blamed for Blasts. U.S. Questioned Iraq on the Rush to Hang Hussein. States Take Lead on Ethics Rules for LawsraeCanadian Group. 2007-01-02 For Dodd, Wall Street Looms Large. Ford's Lost Legacy. Too Good to Be Real?. A Congressman, a Muslim and a Buddhist Walk Into a Bar.... For a Much-Mocked Resume, One More Dig. Corporate America Gets the (McNulty) Memo. Completely. Floating Away From New York. National Mourning. The NYSE's Electronic Man. Developer Accuses Hard Rock of Rigging Sale. Shoney's Chain Finds New Buyer. Nucor to Acquire Harris Steel for $1.07 Billion. Will Bill Miller Have a Happier New Year?. 2007-01-03 Ethics Changes Proposed for House Trips, K Street. Teatime With Pelosi. Turning a Statistic On Its Head. War Protest Mom Upstages Democrats. An Investment Banking Love Story. Revolving Door: Weil Gotshal. Should U.S. Airlines Give Foreign Owners a Try?. 2007-01-04 I Feel Bad About My Face. Bush Recycles the Trash. A New Racing Web Site. What&#8217;s the Theme?. The Product E-Mails Pile Up. ... I would like to add this data … -
Error Installing/Launching Django Using Pip
I have downloaded and pip installed Django, but I can't find an icon or the right link to launch the Django app. When I search installed files using "Django" I get a zip file, This is the error I get: Traceback (most recent call last): File "", line 1, in ModuleNotFoundError: No module named 'django' Plus when I attempt to unzip the Django file, WinRar asks me to purchase a license. So how do I launch the installed Python environment? I use WIN10, Python 3.6.2 Thank you -
How to get specific fields of Django Serialization to JSON
data = serializers.serialize("json", labor_info.labor_selection.all()) print(data) Currently I have a Model Labor which is a ManyToMany Field with another Model LaborSelection. A single object labor_info has 3 labor_selection objects attached to it. Since I cannot return JsonResponse of a ManyToMany field, I must serialize it (from what I have read). This is still new to me, but when I print the data from above, I receive below. If I try to print data[0] I only receive the very first character [. I need to know how I can get each of the choices values from within the fields. [{"model": "inventory.laborselection", "pk": 149, "fields": {"choices": "1-Hole"}}, {"model": "inventory.laborselection", "pk": 150, "fields": {"choices": "2-Holes"}}, {"model": "inventory.laborselection", "pk": 151, "fields": {"choices": "4-Holes"}}] Essentially I with be doing a JsonResponse back to my template where each choice will be displayed. -
Django: how to get the request object in urls.py
I cannot figuring out how I can get ahold of the request object in the urls.py file. I tried to import from django.http.request import HttpRequest But I am stuck here. Can anybody help? -
user conflicts running nginx and uwsgi
I am running a cloud server with root access. I have tried two user combinations for nginx and uwsgi. 1) both as root nginx as root uwsgi as root result: the server is up @port:80 2) both as non root nginx -> www-data uwsgi -> www-data result: uwsgi : error removing unix socket, unlink(): Permission denied [core/socket.c line 198] bind(): Address already in use [core/socket.c line 230] nginx: default welcome page @port:80 I think no webservers must be run as root. I am connecting to a unix socket. The permissions of the socket: srw-rw-rw- 1 root root 0 Oct 20 01:51 project.sock my /etc/nginx/nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; events { worker_connections 768; } http { include /etc/nginx/mime.types; default_type application/octet-stream; access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log; include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; upstream django { # server 127.0.0.1:8001; server unix:/root/project/project.sock; } server { listen 80; server_name my_ip_address_here; location / { uwsgi_pass django; include /root/project/uwsgi_params; } } } and uwsgi configuration [uwsgi] ini = :base socket = /root/project/project.sock master = true processes = 1 [dev] ini = :base socket = :8001 [local] ini = :base http = :8000 [base] chdir = /root/project/ module=project.wsgi:application chmod-socket = 666 uid = user_here what can i do to …