Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
permission denied while collect static django
I had project with django + guicorn + nginx (this tutorial) I delete virtualenvironment and get a new one, everything works correctly but, when I try to use command: source projectenv/bin/activate folder1/project/manage.py collectstatic I got an error: -bash: folder1/folder/manage.py: Permission denied even when I try: folder1/folder/manage.py runserver 0.0.0.0:8000 -bash: folder1/folder/manage.py: Permission denied What should I do to make this virtualenvironment work correctly? -
How Django inlineformsets works internally
I have a form with two inline formsets. At the HTML level Django use the hidden fields for the formset management, and use the prefix to know which fields are related to a formset. Also it has ids in the html id, to group like in a virtual form the fields. <input name="documents-0-document" id="id_documents-0-document" type="file"> <input name="documents-0-filename" class="vTextField" maxlength="255" id="id_documents-0-filename" type="text"> <input name="documents-0-DELETE" id="id_documents-0-DELETE" type="checkbox"> On retrieve by default I get the path to the file in a paragraph and the inputs (html elements) are empty. <p class="file-upload">Currently: <a href="/media/Test%20Insieme/documents/sdsasa7">Test Insieme/documents/sdsasa7</a><br><input name="documents-0-document" id="id_documents-0-document" type="file"> Change: </p> On Browse(upload a different file) Django knows to update the same record in the database. Similar for click on checkbox. How Django make the correlation between the paragraph that show the path, the html id of the element and what is in the database? I want to change the UI (make it dynamic with JavaScript, use button instead of checkbox) and I want to understand how the mechanism is working. -
mysqlclient 1.3.3 or newer is required; you have 0.7.11.None
I'm using python version 3.6.3 and django version 2.0.1. I got the result below when I entered py manage.py migrate in cmd. (mysqlclient 1.3.3 or newer is required; you have 0.7.11.None) I was trying to link a mysql database to my django project. init.py codes: import pymysql pymysql.install_as_MySQLdb() settings.py codes: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join(BASE_DIR, 'mysite'), 'USER': 'root', 'PASSWORD': '', 'HOST': 'localhost', 'PORT': '8000', } } -
How to check Mail Transfer Agent availability in Python?
I'd like to check that some MTA is available on a system and change error report destination based on that from Django. Since Django uses smtplib, what's the most efficient method of checking or at least what exceptions are returned in which case on a system without MTA? -
Django how to query objects one by one
I have to query an object from a model, this object is called "exercise" and has many fields(title, body, answers, etc.) I need to get "exercise objects" one by one with all their fields, do some rendering on them and give back a pdf of the exercise as result. The problem is, if I do: exercises = ExerciseModel.objects.all() I get all of them. If I do: some_exercises = ExerciseModel.objects.filter(something=something) I get "some of them" depending on filter. And if i do: exercise = ExerciseModel.objects.get() I get error get() returned more than one exercise How can I get them one by one? I must be able to use them as input for another function. -
create a user in postgres docker container
I am trying to create a django app in docker container, but I do not know how to create a user in postgres container that django uses. I guess that is why when I start it (by docker-compose up --build --force-recreate) it tells me database_1 | FATAL: role "my_user" does not exist. What am I doing wrong? docker-compose.yaml right now looks like: version: "3.1" services: database: image: postgres:9.5 environment: POSTGRES_DB: "django_db" POSTGRES_USER: "my_user" POSTGRES_PASSWORD: "my_password" POSTGRES_DATA: /var/lib/postgresql/data/pgdata logging: options: max-size: "10m" max-file: "3" restart: always volumes: - "database:/var/lib/postgresql/data" tmpfs: - "/tmp" - "/run" networks: db-net: django: build: ./ image: django:latest environment: DATABASE_URL: "postgres://my_user:my_pass@database/django_db" ports: - 7445:80 -
Django can't find the right path for images
i just moved my project on a server and my project was working fine, no trouble loading anything when i was using localhost:port/myprojectpage/. But i had to change from localhost to an ip so anyone could reach it, and since then when i load the page it doesn't manage to load the images. i had the problem before when i was using localhost so i changed my settings.py but now with this new problem i don't know how to solve it since the path should be good. The problem doesn't come from the httpd.conf, every path is good in it. this is my settings.py : BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILE_DIR = os.path.dirname(os.path.abspath(__file__)) PROJECT_DIR = os.path.dirname(__file__) STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") STATICFILES_DIRS = ( os.path.join(PROJECT_DIR,'static'), ) My previous problem was that the path he tried to load : http://localhost:8080/gestion_mouvement//mouvementDetails/static/images/img0025.png had to be : http://localhost:8080/gestion_mouvement/static/images/img0025.png but now it's : http://localhost:8080/gestion_mouvement//mouvementDetails/static/images/img0025.png and even if i change it to this : http://localhost:8080/gestion_mouvement/static/images/img0025.png It doesn't work and get 404. Hope someone can help me on this because since my path in settings previously corrected this error i don't know what to change here to make it work. -
ajax call is not working with django
i am creating a blog just for practice and i want to mark all notifications as seen when the user view the notifications, this is working if i go to the url but when i use ajax nothing happen javascript: <script> $(document).ready(function() { $("#testb").click(function(event){ $.ajax({ type:"POST", url:"{% url 'seen' request.user.username %}", success: function(){ confirm('it worked') } }); return false; }); }); </script> url url(r'functions/user/(?P<username>\w+)/seen', views.seen, name='seen') view: def seen(request, username): nat = Nat.objects.filter(toUser=username) nat.update(show=False) return HttpResponse("test") -
Simple search engine in my Django Web is not working
I'm trying to make my search go over my query my Database in Django. The lines in form.is_valid() is other forms I added to my website of adding data and it works perfect. The only thing is that query thing.. I just don't understand why after I click search I still see the all posts and not the posts I search for.. views.py- class HomeView(TemplateView): template_name = 'serverlist.html' def get(self, request): form = HomeForm() query = request.GET.get("q") posts = serverlist.objects.all() args = {'form' : form, 'posts' : posts} return render(request, self.template_name, args) def post(self,request): form = HomeForm(request.POST) posts = serverlist.objects.all() query = request.GET.get("q") if query: posts = serverlist.filter(Project__icontains=query) if form.is_valid(): # Checks if validation passed post = form.save(commit=False) post.save() text = form.cleaned_data['ServerName'] form = HomeForm() return redirect('serverlist') args = {'form': form, 'text': text} return render(request, self.template_name,args) index.html - <div class="container"> <br> <center><h1>DevOps Server List</h1></center> <br> <form method='GET' action=''> <input type='text' name='q' placeholder='Search Item'/> <input type='submit' value='Search' /> </form> <table class="table table-hover"> <thread> <tr> <th> Server Name </th> <th> Owner </th> <th> Project </th> <th> Description </th> <th> IP Address </th> <th> ILO </th> <th> Rack </th> <th> Status </th> <th> </th> </tr> </thread> <tbody> {% for server in posts %} … -
Django Raw Query with params on Table Column (SQL Injection)
I have a kinda unusual scenario but in addition to my sql parameters, I need to let the user / API define the table column too. My problem with the params here is that the query results in: SELECT device_id, time, 's0' ... instead of SELECT device_id, time, s0 ... Is there another way to do that through raw or would I need to escape the column by myself? queryset = Measurement.objects.raw("\ SELECT device_id, time, %(sensor)s FROM measurements \ WHERE device_id=%(device_id)s AND time >= to_timestamp(%(start)s) AND time <= to_timestamp(%(end)s) \ ORDER BY time ASC;", {'device_id': device_id, 'sensor': sensor, 'start': start, 'end': end}) -
How to link two tables in django?
I use build in User model in django, but i want use some custom fields, i was create new model class Profile(models.Model): user = models.OneToOneField(User) profile_img = models.ImageField(null=True) def __str__(self): return self.user.username this is my custom model. But when i create new user it doesn't display in admin(in profile table), i need to add user from admin panel, after adding it works fine. what i should to do to display Profile info of all users? p.s. When i was create table profile and was try to select info from joined tabels, sql query wasn't return anything, but after adding existed user to Profile table sql query return all what i want -
Django accessing a JSONResponse from another views file
I have two files within views directory, /views/api.py and /views/pages.py /views/api.py has methods which return JSONResponses objects Example: @api_view(['GET']) def foos(request): foos = get_list_or_404(Foo) data = [{'id': foo.id, 'name': foo.name, 'description': foo.description, 'tag': foo.tag} for foo in foos] return JsonResponse({'foos': data}) /views/pages.py will have methods that will access some of the methods from /views/api.py and add them to context and render a page. Example: def home(request): foos = api.foos(request) print foos return HttpResponse(status=200) On the line print stacks, I can see the JSONResponse object with the correct data. How do I access individual values within foos so I can create a list or a dictionary or something that is custom for each view? -
Django Doesn't Serialize id of the model
I have a simple class : class Item(models.Model): name = models.CharField(max_length=250) I need to serialize it to JSON with the ID as part of the JSON, but the ID never gets serialized when called in the view: items_json = serializers.serialize('json', item_list) The item_list json as received by the browser contains only name, not the ID. I need the ID for the processing on the client side which returns to the server later. 1) I'd like to avoid creating another ID if possible 2) I haven't created a Serializer Class. I am not sure where and how to do that. -
Django - updating application after adding rows to database?
I have a Django web application which is synced to a PostgreSQL database. After adding some rows to a couple of tables (using pgAdmin, not the Django application itself) i started experiencing some problems with the application. For example, i would get the following error in some tables: Duplicate key value violates unique constraint "some_key_pkey" DETAIL: Key (id)=736284 already exists. My assumption is that i had to let the Django application know somehow that i have added new rows to the database. Could that really be the case? If so, how can i solve it? -
Django-Postgres: how to group by DATE a datetime field with timezone enabled
I am having this problem with prostgresql and django: I have a lot of events that were created on a certain date at a certain time which is stored in a datetime field created . I want to have aggregations based on the date part of the created field. The simplest examples is: how many event are in each day of this month?. The created field is timezone aware. So the result should change depending on the timezone the user is in. For example if you created 2 events at 23:30 UTC time on 2017-10-02 if you view them from UTC-1 you should see them on 3rd of October at 00:30 and the totals should add for the 3rd. I am struggling to find a solution to this problem that works with a lot of data. So doing for each day and SQL statement is not an option. I want something that translates into: SELECT count(*) from table GROUP BY date Now I found a solution for the first part of the problem: from django.db import connection truncate_date = connection.ops.date_trunc_sql('day', 'created') queryset = queryset.extra({'day': truncate_date}) total_list = list(queryset.values('day').annotate(amount=Count('id')).order_by('day')) Is there a way to add to this the timezone that should … -
Cant' serv static css file with Django, Heroku and whiteNoice
I'm trying to serv static files with Django and Heroku. Right now there is only a single .css file. I followed the Heroku example settings, but it doesn't work. I'm in production, so DEBUG is set to False and I'm trying to use whitenoise. If I comment out this line in my settings.py (please find the whole thing below): STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' The page is loaded bug no css is loaded. If it's not commented out I get a 500 error : raise ValueError("Missing staticfiles manifest entry for '%s'" % clean_name) ValueError: Missing staticfiles manifest entry for 'styles.css' Statics are in a folder named static in the same folder as settings.py index.html {% load staticfiles %} ... <link rel="stylesheet" href="{% static 'styles.css' %}"> settings.py import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') SECRET_KEY = 'my_secret' SECURE_SSL_REDIRECT = True SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True DEBUG = False ALLOWED_HOSTS = ['myapp.herokuapp.com'] INSTALLED_APPS = [ 'my_app', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'my_app.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', … -
How do I manually assign values to a Django Serializers fields?
I am writing a Django REST API server that will return token/credentials information from Yelp. I have URL mapped this to an endpoint for testing purposes but I don't know how to fill my serializer's fields with the information returned from the call to Yelp. When I connect to the endpoint I get the response below - there is no information... I assume this is because I need to set the values in the serializer's fields. { "client_id": "", "client_secret": "", "token_path": "", "grant_type": "", "token_type": "", "expires_in": null, "access_token": "" } My view is... from rest_framework import generics from .serializers import YelpAuthenticationSerializer from .models import YelpAuthentication # Create your views here. class AuthView(generics.ListCreateAPIView): queryset = YelpAuthentication.objects.all() serializer_class = YelpAuthenticationSerializer def perform_create(self,serializer): pass And the YelpAuthentication class is #yelp.com/developers/documentation/v3/authentication class YelpAuthentication(models.Model): #fields necessary to authenticate url = models.CharField(max_length=200, blank=False, default='https://api.yelp.com/oauth2/token') api_host = models.CharField(max_length=100, blank=False, default='https://api.yelp.com') token_path = models.CharField(max_length=100, blank=False, default='/oauth2/token') grant_type = models.CharField(max_length=200, blank=False, default='client_credential') client_id = models.CharField(max_length=200, blank=True,default='N/A') client_secret = models.CharField(max_length=300, blank=True, default='N/A') #respone body elements after authentication access_token = models.CharField(max_length=200, blank=False, default='N/A') token_type = models.CharField(max_length=7, blank=False, default='bearer') expires_in = models.BigIntegerField() def authenticate(self): #some code that works ... return token What I would like to do is...when my Serializer … -
Testing applications with dotted path name in django
All custom apps in my django project are in apps folder and I want to run tests on all the apps folder. myproject apps/ app1/ apps2/ custom_app/ settings/ manage.py When I run python manage.py test --settings=myproject.settings.test it only runs the tests in custom_app. Here is my base_settings.py INSTALLED_APPS = [ ** list of all the django default apps ** ] USER_APPS = [ 'cutoms_app', 'apps.app1', 'apps.app2'] INSTALLED_APPS = INSTALLED_APPS + USER_APPS Any help is much appreciated. Thanks -
Django - custom file uploads based on criteria
I am currently struggling to find the best way to approach the following problem: I have user registration implemented using django-registration and I want each user to be able to upload different set of documents. Each user will have an "agency", that require some extra documents, however those documents might be different. So my User base class will have a one-to-one relation with all those base documents required for each user, however I am not sure how to let each agency define their own set of documents and how to tie it to the User. Thanks. -
How to use google fusion tables as my Django project database?
Ive just started using google fusion tables to handle our data. And I'm just wondering if it's possible to use web database (google fusion tables here, ofcourse) as my Django project backend. And if so, what's the script to configure DATABASE on settings.py ? Your help greatly appreciated. -
Passing multiple parameters to Django URL - unexpected keyword argument
I wanted to document this question as much as possible in order to be able to detail the origin of the problem. I have the following model named LodgingOffer, to create a lodging offer and detail their information class LodgingOffer(models.Model): # Foreign Key to my User model created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ad_title = models.CharField(null=False, blank=False, max_length=255, verbose_name='Título de la oferta') slug = models.SlugField(max_length=100, blank=True) # ... Another fields ... def __str__(self): return "%s" % self.ad_title def get_absolute_url(self): return reverse('host:detail', kwargs = {'slug' : self.slug }) # I assign slug to offer based in ad_title field,checking if slug exist def create_slug(instance, new_slug=None): slug = slugify(instance.ad_title) if new_slug is not None: slug = new_slug qs = LodgingOffer.objects.filter(slug=slug).order_by("-id") exists = qs.exists() if exists: new_slug = "%s-%s" % (slug, qs.first().id) return create_slug(instance, new_slug=new_slug) return slug # Brefore to save, assign slug to offer created above. def pre_save_article_receiver(sender, instance, *args, **kwargs): if not instance.slug: instance.slug = create_slug(instance) pre_save.connect(pre_save_article_receiver, sender=LodgingOffer) For this model, I have a DetailView named HostingOfferDetailView . An important objective I want to pursue and for which I ask this question is that in the detail view of an LodgingOffer object, I should be able to contact the owner of that offer (object … -
Django order approval flow
Hello guys i'm new to django,i have tried a lot but didn't get any solution.My task is 'order approval form' .There are 'N' no.of users and user has to fill form with requirements,after filling and submitting its that form data/notification should sent to manager/admin,he can check/delete /approve,if he approves it should go to next state/stage of flow how to do this workflow ? -
Django shell plus invalid arguments in virtualenv
I created a virtualenv to set up for Django upgrade to version 1.8. but when trying to run shell plus I am getting an error about invalid arguments: py manage.py shell_plus Trace: Traceback (most recent call last): File "manage_sched_dev.py", line 10, in <module> execute_from_command_line(sys.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 354, in execute_from_command_line utility.execute() File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\__init__.py", line 346, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 382, in run_from_argv parser = self.create_parser(argv[0], argv[1]) File "C:\Users\MyUser\Envs\newenv\lib\site-packages\django\core\management\base.py", line 316, in create_parser help='Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, 3=very verbose output') File "c:\python27\Lib\optparse.py", line 1018, in add_option raise TypeError, "invalid arguments" TypeError: invalid arguments I have no clue why this is happening. I tried installing ipython in the virtualenv because I know shell plus uses ipython, but that didn't seem to help. -
Application not able to access the profile pic and posts using DjangoAllAuth
I am trying to access the profile picture and posts of the user using Django-AllAuth. Here is the template where I am trying to load the profile image: <html> <body> Welcome back {{ user.first_name }} {{ user.age }} <img src={{user.cover.source}} height="60" width="60"> <a href="/">Home</a> </body> </html> Here is the view.py def fb_personality_traits(request): # logger.debug('FB Page Loaded') return render(request, 'home/facebook_personality_traits.html') Settings.py SITE_ID = 1 LOGIN_REDIRECT_URL = '/facebook_personality_traits/' SOCIALACCOUNT_QUERY_EMAIL = True SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'SCOPE': ['email', 'user_posts', 'public_profile', 'user_photos'], # 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'METHOD': 'js_sdk', 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'cover', 'posts', 'age', ], 'EXCHANGE_TOKEN': True, 'VERIFIED_EMAIL': True, 'VERSION': 'v2.10', } } ACCOUNT_LOGOUT_ON_GET = True Here I am not getting the image. See the below result: What I want to achieve? 1) I want to display the profile image on the screen. 2) I want to get the posts of the user loggedin in the view.py and send it on the screen to display on the template. -
Django-storages save images webp as octet-stream
when I try to save pillow images using django-storages to store in S3, webp images save them as octet-stream. You should also save images in JPG. I leave below my configuration of django-storages AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'public, max-age=2592000', } AWS_DEFAULT_ACL = 'public-read' AWS_QUERYSTRING_AUTH = False So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='WEBP', optimize=False, ) So I save the images in WEBP new_image_bytes = BytesIO() pic.save( new_image_bytes, format='JPEG', optimize=False, ) Thanks!