Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Docker: Cannot connect nginx with web application
I am new to Docker and started to containerize my Django web application. The web application with its dependencies like PostgreSQL is run by docker-compose up. Also, I have a separate docker-compose.yml file for nginx as reverse proxy. My problem is that the connection between nginx and the web application does not work and I do not understand why. For the connection between nginx and the application I have created a Docker network called nginx_network. It's external to both nginx and the web application. That's the error message: proxy_1 | 2019/02/11 19:25:16 [emerg] 1#1: host not found in upstream "my_app_web_1.nginx_network" in /etc/nginx/conf.d/my_app.conf:67 First of all, here my docker-compose.yml file for the web application: version: '3.4' services: db: image: postgres:11-alpine restart: always networks: - default volumes: - pg_data:/var/lib/postgresql/data/ web: build: . image: my_app restart: always volumes: - media_data:/my_app/media - static_data:/my_app/static command: /my_app/gunicorn_start.sh env_file: - ./.env environment: - DJANGO_SETTINGS_MODULE=my_app.settings.production expose: - "8000" networks: - nginx_network - default depends_on: - db volumes: media_data: static_data: pg_data: networks: nginx_network: external: true In my gunicorn_start.sh file there's this content: exec gunicorn ${DJANGO_WSGI_MODULE}:application \ --workers $WORKERS \ --threads 2 \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- In the nginx configuration file there's this relevant content: proxy_pass http://my_app_web_1.nginx_network:8000; And … -
Django admin without css even though nginx is serving static files
I know there are tons of similar questions like this, but I couldn't find any that fits my case: I'm using django (2.1.7) with gunicorn and nginx in a single docker container (requirement for the infrastructure we use at work), but have trouble with the admin menu. When executing locally and visiting http://localhost:8080/admin/ the page is rendered without css. After a bit of digging I found out that nginx is, in fact, serving the files. For instance, I can visit http://localhost:8080/static/admin/css/base.css in my browser and the file in question is loaded. Also the static dir in my BASEDIR contains all the expected files... I don't know how I can continue investigating this further. All related questions seem to have a flaw in their STATIC_ROOT config, forgot the collectstatic command or misuse the alias in the nginx config. All of which seem to work for me... I feel like I'm missing something pretty basic. Does anyone of you have an idea? Thanks for your help! Below my config files: settings.py: """ Django settings for mysite project. Generated by 'django-admin startproject' using Django 2.1.7. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see … -
Django views, check if user is active or not
i am trying to check if the user is active into my views code but, he doesn't execute this check and he straight to the second instruction "Invalid username or password". can somebody help me please ? Here is my code. def login(request): if request.method == 'POST': username=request.POST['username'] password = request.POST['password'] user = auth.authenticate(username=username, password=password) if user : if user.is_active: auth.login(request, user) messages.success(request, 'You are now logged') return redirect('user_home') else: messages.error(request, 'user is inactive') return redirect('login') else: messages.error(request, 'Invalid username or password.') return redirect('login') else: return render(request, 'accounts/login.html') -
django's collectstatic collects into unexpected directory
I want to upload my staticfiles to amazon s3 storage, but I can't stop django from just putting them in a directory staticfiles in the project root. I have boto3 in my requirements.txt and have set STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' I have successfully set up s3 with media files, to the same bucket (under different directory). Collectstatic also seems disregards the STATIC_ROOT variable in settings.py when I comment out the s3-settings. When running python3 manage.py collectstatic I expect it to gather static files into STATIC_ROOT as it says in the docs here https://docs.djangoproject.com/en/2.1/ref/settings/ (under static_root). But even if I give a different value to STATIC_ROOT, collectstatic always collects into a directory on the root called staticfiles. STATIC_ROOT = os.path.join(BASE_DIR, 'this_is_not_used_by_collectstatic') The rest of my s3 settings: # Amazon S3 AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID'] AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY'] AWS_STORAGE_BUCKET_NAME = 'my_bucket_name' AWS_S3_REGION_NAME = 'eu-north-1' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_DEFAULT_ACL = None AWS_LOCATION = 'static' STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' # media DEFAULT_FILE_STORAGE = 'korvir.storage_backends.MediaStorage' -
Table records to django model
Beginner question - Django Model: Hi. I have this html table: <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">First</th> <th scope="col">Last</th> <th scope="col">Email</th> </tr> </thead> <tbody class="list-to-model" > <!-- This suppouse to come from script.js --> <tr> <th scope="row">${id}</th> <td>${name}</td> <td>${surname}</td> <td>${email}</td> </tr> <!-- finished script.js code --> </tbody> </table> Some records (name, surname...) are coming through Javascript, but how would be the best practice to save it in the Django model? As it is a table possibly it will have many rows (filled dynamically), should I use a form to hold each row? I am using Django2. Thanks in advance. -
python can't show my installed librery packages
devignesh@devignesh:~/soup$ pip list Exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/init.py", line 2556, in version return self._version File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/init.py", line 2663, in getattr raise AttributeError(attr) AttributeError: _version During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pip/_internal/basecommand.py", line 141, in main status = self.run(options, args) File "/usr/local/lib/python3.5/dist-packages/pip/_internal/commands/list.py", line 143, in run self.output_package_listing(packages, options) File "/usr/local/lib/python3.5/dist-packages/pip/_internal/commands/list.py", line 208, in output_package_listing data, header = format_for_columns(packages, options) File "/usr/local/lib/python3.5/dist-packages/pip/_internal/commands/list.py", line 274, in format_for_columns row = [proj.project_name, proj.version] File "/usr/local/lib/python3.5/dist-packages/pip/_vendor/pkg_resources/init.py", line 2561, in version raise ValueError(tmpl % self.PKG_INFO, self) ValueError: ("Missing 'Version:' header and/or METADATA file", Unknown [unknown version] (/home/devignesh/.local/lib/python3.5/site-packages)) devignesh@devignesh:~/soup$ -
Django Filter Date Range ORM Issue
I am having a little bit of trouble figuring out where I am going wrong here. I am atempting to gather entries in a database with a date range of 15 days, and my query is not selecting the correct options. Here is the important part of my code: start = datetime.now().replace(tzinfo=pytz.UTC) - timedelta(days=15) end = datetime.now().replace(tzinfo=pytz.UTC) # 2019-01-27 10:26:16.235354+00:00 | 2019-02-11 10:26:16.235354+00:00 print(start, '|', end) completed_work_orders = WorkOrders.objects.using(db_alias).filter( unit_id=int(resident.unit_id), resident_dismissed=1).filter(date_created__range=[start, end]).order_by('-date_created') Which gives me: completed: <QuerySet [<WorkOrders: WorkOrders object (7)>]> Here I only select 1 row when it should be selecting 3, here are my date_created values for rows 7, 8, and 9, only row 7 is being selected: 7) Selected 2019-02-07 12:07:59.72546-08 8) Not Selected 2019-02-11 08:58:27.561245-08 9) Not Selected 2019-02-11 09:03:35.063078-08 -
Django cannot create superuser on PostgreSQL. "server closed the connection unexpectedly"
I'm having an issue with a Django site that cannot create a superuser with a PostgreSQL database. From the development machine python manage.py createsuperuser --username user1 --email email@email.com returns: django.db.utils.OperationalError: server closed the connection unexpectedly This probably means the server terminated abnormally before or while processing the request. Now, the PostgreSQL server is up. I can run python manage.py migrate and create tables over there. I can also tell the server is up by putting in incorrect credentials, and receiving an error for having bad creds. I've got Dbeaver up and running on the same machine the Django site is being developed on, and it can connect and see the database as the user the Django site's settings.py is using. From the PostgreSQL Server machine Running cat /var/lib/pgsql/data/pg_log/postgresql-Mon.log yields the following after an attempted superuser creation: LOG: could not receive data from client: Connection reset by peer LOG: unexpected EOF on client connection with an open transaction Because I can connect to the server and have success with other queries, I'm not sure where this issue lies. Where should I look next to troubleshoot this issue? -
django template tag check if image exists
I've got a portion of my app that allows a custom logo. Default object (and object view) state is no custom logo, but if one exists, replace the header with a custom logo navbar. logo is a standard ImageField on co(mpany) model: models.py: class Co(models.Model): logo = models.ImageField(blank=True) template: {% if co.logo %} {% block navbar %} {% include 'templates/navbar_logo.html' %} {% endblock %} {% endif %} I've also tried this with {% if not ... %}, {% if co.logo.url %} and trying to model the logic with co.logo|default_if_none:"" but in instances where a logo isn't set the view throws: ValueError at /co/foo The 'logo' attribute has no file associated with it. how do I get this condition to pass True only if the field has an image uploaded? otherwise don't load the nav block? thanks -
Users can see each others posts. I used @loginrequired decorator but it did not work
I want a logged in user to see only his posts. But in my site user can see all the posts posted by the users. Here is github link https://github.com/ualmaz/post. You are welcome to clone and check it if you want. I tried to use @loginrequired decorator. But it was not useful. my models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser from PIL import Image from django.db.models.signals import post_save class User(AbstractUser): first_name = models.CharField(verbose_name="First name", max_length=255) last_name = models.CharField(verbose_name="First name", max_length=255) country = models.CharField(verbose_name="Country name", max_length=255) city = models.CharField(verbose_name="City name", max_length=255) email = models.EmailField(verbose_name="Email", max_length=255) def __str__(self): return self.username class Post(models.Model): title = models.CharField(max_length=255) country = models.CharField(max_length=255) city = models.CharField(max_length=255) address = models.CharField(max_length=255) email = models.EmailField(max_length=255) phone = models.CharField(max_length=255) website = models.CharField(max_length=255) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Profile.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=User) my views.py from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.views.generic import CreateView, DetailView from .forms import UserCreationModelForm, UserUpdateForm, ProfileUpdateForm from .models import User, Profile, Post from … -
How to generate barcode in python as response of image
Views.py: def Bar(request): payload = json.loads(request.body.decode('utf-8')) a=payload["donor_n_key"] ean = barcode.get('code128', a, writer=ImageWriter()) filename = ean.save('ean13') image = ean.render() return HttpResponse(image,content_type="image/png") Here i have downloaded the barcode image but I am unable to open that image.I am getting the error is windows photo viewer can't open this picture because either photo viewer does not support this file format. I am new to this django framework so any one kindly help me. -
Get url parent param in a child view in Django
I'm trying to configure my project to use for multiple enterprises. So I need to put the urls according to the enterprise in use, for example: At the kirios store: www.kinet.com/kirios/index www.kinet.com/kirios/new_order/ . . At the checkcell store www.kinet.com/checkcell/index www.kinet.com/checkcell/new_order/ www.kinet.com/checkcell/employees/ . . . And so... I'm trying like this, in mi global urls: urlpatterns = [ url(r'^admin/', admin.site.urls), # Enterprise admin url(r'^(?P<enterprise_name>[\w]+)/', include([ url(r'^', include('app.urls')), url(r'^reparaciones/', include('reparaciones.urls', namespace='reparaciones')), url(r'^usuarios/', include('usuarios.urls', namespace='usuarios')), url(r'^equipos/', include('equipos.urls', namespace='equipos')), url(r'^empresas/', include('empresas.urls', namespace='empresas')), url(r'^reportes/', include('reportes.urls', namespace='reportes')), ])) ] And the app urls: urlpatterns = [ # The home page url(r'^$', views.index, name='index'), . . ] My views.py on app index is> # Index user loged in @login_required def index(request, empresa_name): import datetime, json from equipos.models import Equipo from reparaciones.models import OrdenReparacion from django.db.models import Avg, Count, Min, Sum And I got the following error trying http://127.0.0.1:8000/kirios/ NoReverseMatch at /kirios/ Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['(?P<enterprise_name>[\\w]+)/$'] I would appreciate your help. -
Suggest best way to manage different type of Blogs in wagtail
I am using wagtail cms, There are three different type of Blogs. some blog have videos, some blogs have photos, some blog have documents. I want to change the content (photo, video, doc) depending on Blog type in cms. -
Django Rest Framework - add a field from database to CreateAPIView
I want to save the model, but one field must get data from db. Better to show code to illustrate my intentions class LoyaltyUserCreateSerializer(serializers.ModelSerializer): account = serializers.SerializerMethodField() class Meta: model = LoyaltyUser fields = [ 'name', 'last_name', 'gender', 'email', 'phone', 'birth_date', 'account' ] def get_account(self, obj): return Account.objects.get(pk=self.context['request'].user.pk) data that I Send {"name": "Petr1", "last_name": "Petrov", "gender": "male", "email": "email", "phone": "123", "birth_date": "2018-12-12"} The problem is that when I try to save it with CreateAPI I get 500 error with IntegrityError at /api/create_user NOT NULL constraint failed: core_loyaltyuser.account_id View class LoyaltyUserCreateAPIView(CreateAPIView): queryset = LoyaltyUser.objects.all() serializer_class = LoyaltyUserCreateSerializer -
Where is the best place to store a site specific setting?
So i'd like to be able to store a site specific setting for example, SITE_MODE = foo. Where i'd like to use the setting is in the html templates e.g. {% if SITE_MODE == 'foo' %} <p>Show this</> {% elif SITE_MODE == 'bar' %} <p>Or do this </p> {% endif %} I know there is obviously my settings.py or local_settings.py but i'm not sure i can reference the values from the views or templates? Ideally this would be stored in the database somewhere but i'm not sure of the best place to put it. was keen to find out what the pros do! thanks in advance. -
Heroku, Mezzanine and S3. Media library slow and causing server timeouts
So I've got a Django application that I've deployed on Heroku that uses the Mezzanine CMS. Furthermore, it's set up so that users can upload media files directly to S3. All works well except the Gallery / Media Library. Basically, when I go to the admin page for the Media library (note, approx 15 images were loaded in there), everything slows down and I get an H12 timeout error. I'm assuming that this is because of the creating thumbnails on the fly functionality of Mezzanine. So... two questions. 1) Am I correct in saying that the thumbnail creation via Amazon S3 (Mezzanine) is causing the slowdown?? 2) Is there a way of disabling this or changing how this is done?? Any guidance or code snippits - or hyperlinks would be helpful. Thanks -
Django Multiple search views
I have three django apps where I want to add a search function. In every search function I need to pass three things. Selected, title and url and I would like to add some details when I want. I think I can compress this code but I don't know how. Here are my search functions: article search: def search(request): return render(request, "article/search/search.html", { "selected": "news", "title": "Suche | Artikel", "categories": Article.objects.all().order_by("Category").values_list("Category__title", flat=True).distinct(), "exists": {k._meta.verbose_name.title(): k.objects.all().exists() for k in [Image, Audio, Video]}, "any_exists": Image.objects.all().exists() or Audio.objects.all().exists() or Video.objects.all().exists(), "url": reverse("ajax:news_article_search") }) poll search: def search(request): return render(request, "poll/search/search.html", { "selected": "news", "title": "Suche | Umfrage", "not_solved_exist": Poll.get_all_able(request).exists(), "must_verified_exist": Poll.get_all_able(request).filter(must_verified=True).exists(), "for_me_exist": Poll.get_all_able(request).exists(), "url": reverse("ajax:poll_poll_search") }) riddle search: def search(request): return render(request, "riddle/search/search.html", { "selected": "news", "title": "Suche | Rätsel", "not_solved_exist": Riddle.objects.filter(solvedsolution__user=request.user).exists() if request.user.is_authenticated else Riddle.objects.filter(solvedsolution__ip=get_client_ip(request)).exists(), "url": reverse("ajax:riddle_riddle_search") }) -
Is there a better way to display a long list of entries in admin.py
I am building a web site backend in Django. As the number of pages grows in my website, the list of all site pages (necessary to be able to modify a given page) is starting to become unwieldy. Are there any techniques for grouping or collapsing entries in a long list in admin.py? -
Is it possible to use Django-LDAP as single sign on
I have a Django app and it uses Django LDAP(our company AD) for authentication. Is it possible to use this as SAML-provider? I have some apps which are using Amazon-Cognito for authentication. I'm trying to find a way to configure the Django app as SAML provider. I know I can get SAML config from AD directly. I am just curious if Django can be used as SSO. -
django admin user change form replacing email with username
I am working on a project that require a custom user model, so i created a custom user model successfully, but upon editing and saving the user in Admin panel i get an error where the user email is replaced with the username. On registration, this issue doesn't manifest but only in the admin. class UserAdminChangeForm(UserChangeForm): def __init__(self, *args, **kargs): super(UserAdminChangeForm, self).__init__(*args, **kargs) class Meta: model = User fields = ('email', 'password', 'username', 'is_active', 'is_admin') class UserManager(BaseUserManager): def create_user(self, email, username, password=None, is_active=True, is_admin= False, is_staff = False, is_profiled =False): if not email: raise ValueError("User must enter an email address.") if not password: raise ValueError("User must enter a password.") if not username: raise ValueError("User must enter a username.") user_obj = self.model(email= self.normalize_email(email),username = username ) user_obj.set_password(password) user_obj.is_staff = is_staff user_obj.is_admin = is_admin user_obj.is_active = is_active user_obj.profiled = is_profiled user_obj.username = username user_obj.save(using= self._db) return user_obj def create_staffuser(self, email, username, password=None): user = self.create_user(email,username, password = password, is_staff= True) return user def create_superuser(self, email, username, password=None, is_active = True): user = self.create_user( email, username, password = password, is_staff= True, is_admin = True, is_active = True ) user.is_superuser = True return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique= True) is_active = models.BooleanField(default= … -
Python version dilemma
Hi I am very new to the python language. And I started watching tutorials and taking courses about it. I installed the latest version of python from python website. But my friend who had learned python before to install the stable version of python ie 3.6.x. Please help me with which version to choose and why should I choose it and how installing the latest version cause trouble. Thank you.. -
Check the current values of instance while doing perform_update in django rest framework
I'm using Django Rest Framework. Here is model: class TimeSlot(models.Model): date_start = models.DateTimeField(default=None, null=True, blank=True) booked = models.BooleanField(default=False) user = models.ForeignKey(User, related_name='time_slots', on_delete=models.SET_NULL, default=None) Here is my serializer: class CreateBookingSerializer(serializers.ModelSerializer): class Meta: model = TimeSlot fields = ('id','booked','user',) extra_kwargs = {'booked': {'required': True}} Here is my view: class CreateBookingViewSet(viewsets.ModelViewSet): queryset = TimeSlot.objects.all() serializer_class = CreateBookingSerializer http_method_names = ['put'] def perform_update(self, serializer): if (self.request.data['booked'] == 1): serializer.save(user=self.request.user, booked=True) I want to set booked to true only if the current value is False. I'm using PUT method. so my url is /create_booking/id/ If I could get the id in my view, I would check the current booked value! How to get the id? -
Passing form field to external URL in Django
I'm trying to pass a field from a form on a brochure site to another form that is at the same domain (subdomain) but not part of the actual brochure site. The user inputs an insurance type and a zip code, and they are redirected to a site to get a quote. I need to pass that type and zip code to the form on redirect. The only examples I've seen are redirects to templates on the same site; never an external site URL. Right now when I hit submit on the form, the form disappears, but doesn't redirect me anywhere. What am I missing? View: from django import template from django.shortcuts import redirect from .forms import QuoteForm register = template.Library() @register.inclusion_tag('quote_form.html') def get_a_quote(request): if request.method == 'POST': form = QuoteForm(request.POST) if form.is_valid(): type = form.cleaned_data['type'] if type == 'auto': zip_code = form.cleaned_data['zip_code'] return redirect(f'http://samplesite.com/?zip_code={zip_code}') else: return redirect(f'http://samplesite.com/') else: form = QuoteForm() return {'form': form} Model: from django import forms TYPES = ( ('auto', 'Auto Insurance'), ('home', 'Home Insurance'), ) class QuoteForm(forms.Form): type = forms.ChoiceField(choices=TYPES) zip_code = forms.CharField(widget=forms.TextInput( attrs={'placeholder': 'Enter Your Zip Code'} ), max_length=6, required=False) Template: (quote_form.html) <form role="form" action="" method="post"> {% csrf_token %} <div class="row"> <div class="col-md-6"> <p>{{ … -
what do <form action=“.”>
I have a basic question. I cannot find an explanation of form action="." despite searching for on google, www.w3schools.com, etc... Anyone know what the . action means for forms? Is it specific to Django? Bootstrap? Code below: {% extends "Blog.html" %} {% block blog%} <h1>Create an account</h1> <p>Please, sign up using the following form:</p> <form action="." method="post"> {{ user_form.as_p }} {% csrf_token %} <p><input type="submit" value="Create my account"></p> </form> {% endblock %} -
About Django's way to prevent multiple logins same account
Is there any "official" Django way to prevent multiple Humans to login in the same account simultaneously, or do I have to do this system by my own? I don't have any problem with more than one person using the same account. But I don't want them to use the same account simultaneously on different devices.