Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using the 'for' loop in django tags for 'ForeignKey'
My django loop in the templates does not work correctly. Why, because of me, everything looks good? Any help will be appreciated. My models.py class Tags(models.Model): name = models.CharField(max_length=10) class Person(models.Model): keywords = models.ForeignKey(Tags, on_delete=models.CASCADE) My views.py def person_detail(request, user_id): person = get_object_or_404(Person, pk=user_id) context = {'person': person} return render(request, 'person_detail.html', context) My templates.html {% for tag in person.tags %} <span class="badge badge-lg badge-pill badge-info"># {{ person.tags.name } </span> {% endfor %} This gives no results even though there is data in the database. -
ERROR: Could not find a version that matches urls, when installing pipenv dependancies for django app
I'm getting this error when trying to install dependencies for my pipenv (virtual environment): [pipenv.exceptions.ResolutionFailure]: Warning: Your dependencies could not be resolved. You likely have a mismatch in your sub-dependencies. First try clearing your dependency cache with $ pipenv lock --clear, then try the original command again. Alternatively, you can use $ pipenv install --skip-lock to bypass this mechanism, then run $ pipenv graph to inspect the situation. Hint: try $ pipenv lock --pre if it is a pre-release dependency. ERROR: ERROR: Could not find a version that matches urls No versions found Was https://pypi.org/simple reachable? Pipfile: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] pylint = "*" [packages] django = "*" pylint = "*" urls = "*" [requires] python_version = "3.6" Does anyone have an idea how to resolve this? I hear that it's probably an issue with my python installation, and that's probably true, I just don't know how to resolve. Mayday Maday -
Querying the database in a Django unit test
I am creating a web application which has a POST endpoint, that does two things: Saves the POSTed data (a university review) in the database. Redirects the user to an overview page. Here is the code for it: if request.method == 'POST': review = Review(university=university, user=User.objects.get(pk=1), summary=request.POST['summary']) review.save() return HttpResponseRedirect(reverse('university_overview', args=(university_id,))) I haven't yet implemented passing the user data to the endpoint, and that's why I'm saving everything under the user with pk=1. My test is as follows: class UniversityAddReviewTestCase(TestCase): def setUp(self): user = User.objects.create(username="username", password="password", email="email") university = University.objects.create(name="Oxford University", country="UK", info="Meh", rating="9") Review.objects.create(university=university, summary="Very nice", user_id=user.id) Review.objects.create(university=university, summary="Very bad", user_id=user.id) new_review = { 'summary': 'It was okay.' } self.response = Client().post('/%s/reviews/add' % university.id, new_review) def test_database_updated(self): self.assertEqual(len(Review.objects.all()), 3) The result is this: File ".../core/views.py", line 20, in detail user=User.objects.get(pk=1), File ".../ENV/lib/python3.6/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File ".../ENV/lib/python3.6/site-packages/django/db/models/query.py", line 403, in get self.model._meta.object_name django.contrib.auth.models.DoesNotExist: User matching query does not exist. Why is this happening? I know the user I'm creating has a pk=1, as when I actually print it during the test it's 1. -
How to tell if my Python packages use C extensions?
I am considering using the shiv package as a way to create a Python zipapp of my Django project (rather than resorting to Docker). It's my understanding that this approach is not feasible if any of my Python packages have C extensions. Is there any tool that could examine my pip requirements file and tell me if any of the packages it contains (as well as their dependencies) utilize C extensions? I know that the Python interpreter is written in C so I would imagine many Python packages are written in C as well (or perhaps not?). So if this sounds like a stupid question, it's because I don't understand what the difference is between a program like the Python interpreter that is written in C and what a C extension is as I've never studied the C language. -
ERROR: "No ecs task definition" on Deploying docker/django app on Elastic Beanstalk
I have an issue while deploying my application using docker/django on AWS Elastic Beanstalk. I have already uploaded my code to the cloud, however, I still getting an error "No ecs task definition (or empty definition file) found in environment". I already have my Dockerrun.aws.json file created as fallows: { "AWSEBDockerrunVersion": 2, "volumes": [ { "name": "djangoapp", "host": { "sourcePath": "/opt/services/djangoapp" } }, { "name": "nginx", "host": { "sourcePath": "/etc/nginx/conf.d" } } ], "containerDefinitions": [ { "name": "nginx", "image": "nginx:1.13", "essential": true, "memory": 200, "cpu": 1, "portMappings": [ { "hostPort": 80, "containerPort": 80, "protocol": "tcp" } ], "links": [ "djangoapp" ], "mountPoints": [ { "sourceVolume": "djangoapp", "containerPath": "/opt/services/djangoapp", "readOnly": true }, { "sourceVolume": "nginx", "containerPath": "/etc/nginx/conf.d", "readOnly": true }, { "sourceVolume": "awseb-logs-nginx-proxy", "containerPath": "/var/log/nginx" } ] }, { "name": "djangoapp", "image": "nginx:1.13", "essential": true, "memory": 128, "mountPoints": [ { "sourceVolume": "djangoapp", "containerPath": "/opt/services/djangoapp", "readOnly": true } ] } ] } I read the tutorial on the AWS page (https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create_deploy_docker_v2config.html#create_deploy_docker_v2config_dockerrun), but it still not working. To build this file, I tried to do a reverse engineer on my docker-compose file. As fallows: version: '3' services: # database containers, one for each db database1: image: postgres:10 volumes: - database1_volume:/var/lib/postgresql/data env_file: - config/db/database1_env … -
django render function not loading html
I am following a Django course through udemy and I can't render a simple html page but i keep getting this error. I have tried looking up different ways to overcome this error but there is nothing I could find that was similar. Environment: Request Method: GET Request URL: http://localhost:8001/ Django Version: 2.1.3 Python Version: 3.7.1 Traceback: File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\utils.py" in __getitem__ 66. return self._engines[alias] During handling of the above exception ('django'), another exception occurred: File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\core\handlers\base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\deemal.g.patel\Desktop\btre_project\pages\views.py" in index 5. return render(request,'index.html') File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\shortcuts.py" in render 36. content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\loader.py" in render_to_string 61. template = get_template(template_name, using=using) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\loader.py" in get_template 12. engines = _engine_list(using) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\loader.py" in _engine_list 66. return engines.all() if using is None else [engines[using]] File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\utils.py" in all 90. return [self[alias] for alias in self] File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\utils.py" in <listcomp> 90. return [self[alias] for alias in self] File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\utils.py" in __getitem__ 81. engine = engine_cls(params) File "C:\Users\deemal.g.patel\Desktop\btre_project\venv\lib\site-packages\django\template\backends\django.py" in __init__ 27. self.engine = Engine(self.dirs, self.app_dirs, **options) Exception Type: TypeError at / Exception Value: __init__() got an unexpected … -
Django Registration Form
I am not sure whether I am asking a silly question or not. I am new to Django. Default Django gives me a user model that contains username, email, password. But I need a user model which contains email, password, full_name, image, codeforces_handle, Uva_handle. How can I do that? -
Multiple attachment django email
Hi i'm try send email with multiple attach as pdf, xml.etc... but get error: 'list' object has no attribute 'rfind' this is my code: from security.views import SendEmail Envia = settings.DEFAULT_FROM_EMAIL files =['media/Facturas/facturaElectronica.pdf', 'media/Facturas/template/factura.xml'] SendEmail('test', 'Test ',Envia,['pocholo199037@gmail.com'],files) i don't understand why get this error maybe some one idea or suggest , thanks -
UNIQUE constraint failed: "app"_customuser.username
I´m new in Django. I registered a superuser with "createsuperuser" and now I want to create a normal user with my custom registration form but this send me this error about unique constraint: IntegrityError at /registro/registrar/ UNIQUE constraint failed: registroUsuario_customuser.username Request Method: POST Request URL: http://127.0.0.1:8000/registro/registrar/ Django Version: 2.0.9 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: registroUsuario_customuser.username Exception Location: C:\Users\riria\Desktop\perrosUnidad3\myvenv\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 303 Python Executable: C:\Users\riria\Desktop\perrosUnidad3\myvenv\Scripts\python.exe Python Version: 3.7.0 Python Path: ['C:\Users\riria\Desktop\perrosUnidad3', 'C:\Users\riria\Desktop\perrosUnidad3\myvenv\Scripts\python37.zip', 'C:\Users\riria\AppData\Local\Programs\Python\Python37\DLLs', 'C:\Users\riria\AppData\Local\Programs\Python\Python37\lib', 'C:\Users\riria\AppData\Local\Programs\Python\Python37', 'C:\Users\riria\Desktop\perrosUnidad3\myvenv', 'C:\Users\riria\Desktop\perrosUnidad3\myvenv\lib\site-packages'] Server time: Lun, 19 Nov 2018 17:56:33 -0300 This is my code: models.py class CustomUserManager(UserManager): def create_user(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password=None): if not run: raise ValueError("Usuario debe ingresar su run") user = self.model( run = run, email = self.normalize_email(email), fechaNac = fechaNac, nombre = nombre, apellido = apellido, telefono = telefono, regiones = regiones, comunas = comunas, tipo_vivienda = tipo_vivienda, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, run, email, fechaNac, nombre, apellido, telefono, regiones, comunas, tipo_vivienda, password): user = self.create_user( run = run, password=password, email=email, fechaNac=fechaNac, nombre=nombre, apellido=apellido, telefono=telefono, regiones = regiones, comunas = comunas, tipo_vivienda = tipo_vivienda, ) user.is_admin = True user.save(using=self._db) return user class CustomUser(AbstractUser): run = models.CharField(max_length=9, unique=True, primary_key=True) email = … -
Django: import model to script that is not part of the project
I have models.py and my_test.py files in my Django app folder. My project is named strava, app: explorer_api How do I import a model into my_test.py? I have tried: from strava.explorer_api.models import Activity from explorer_api.models import Activity from .models import Activity from models import Activity but: SystemError: Parent module '' not loaded, cannot perform relative import -
Invalidate HTTP download if error or corrupted
I have a Django view that uses a StreamingHttpResponse to return a possibly large file (as a download). Near the end of streaming I check the integrity of the content against an HMAC signature. If that fails, the stream simply stops and the user still has most of the file saved. Is there any sort of way to get the browser to toss out what it's downloaded so far? Right now I have it sending a "Content-Length" header, but the fact that it stops before it's reached that length doesn't seem to effect anything. I read about using a "Trailer" header and then putting something in the trailer to indicate that the download should not be trusted, but I don't think there's any sort of built-in support in browsers to do anything with that (that I know of). -
Python - Django Models - One Model different Tables to store value
Can someone help me in Python Django models to create dynamic table name based on value received from the post request for same model i.e one model for different table and each table has a unique name so it doesn't overlap and therefore value in these table can be saved accordingly?? -
How to set a value in User based on another model? [ django ]
custom User have feedbackscore which calculates this way ((positive-negative)+neutral)/(positive+negative+neutral)*100 there is feedback app where everyone can give a single feedback to each User What is the most convenient way to approach this problem, I do need to store it in User because some functions will be limited to users with a good score. So how should I archive this? should I do a Manager? should I set a Property? anything else? -
Django Rest Framework basic auth vs Apache 2.4 Basic Auth - Where is my API request being authenticated?
I have a basic DRF API incorporated into to a basic Django application, hosted on Apache 2.4. In the Apache configs, I give authorization/access to the application to anyone on our local server, with an additional basic authentication set-up (for testing) to allow an API call from an outside server to interact with some models. When I make a GET request to the application itself with Basic Auth credentials, I get a 200 response with content (I am denied if I do not include credentials). But when I make a GET request to a DRF API endpoint, I get a 401 Unauthorized response. The 401 suggests that the response is not being authenticated. My question is - why would (or how does) a DRF oriented API call go looking for authentication credentials in a different location than a call to the django app itself (if that's indeed what's going on)? The Apache configuration looks like this: DocumentRoot /var/www/html LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so WSGIDaemonProcess portal python-home=/home/bio_admin/envs/dj python-path=/var/www/portal/html/bpp WSGIScriptAlias /portal /var/www/portal/html/bpp/bioworks/wsgi.py process-group=portal WSGIProcessGroup portal WSGIPassAuthorization On Alias /static/ /var/www/portal/html/bpp/static/ <Directory /var/www/portal/html> AuthType Basic AuthName "portal" AuthUserFile "/var/www/portal/html/.htpasswd" Require user bio_admin Require ip 74.xxx.xxx.x </Directory> The DRF part of settings.py file looks like this: … -
Django REST API: model field gets serialized with backslashes to escape double qoutes
I have a model like this: class Activity(models.Model): date_added = models.DateTimeField(auto_now_add=True) start_date = models.DateTimeField(default=datetime.datetime.now) data = models.TextField() # stores activity's JSON in text format, not as Python object number = models.IntegerField(default=0) athlete = models.ForeignKey(Athlete, on_delete=models.CASCADE, default=None) Field data stores JSON as text. I have created an API, but this model gets serialized with backslash to escape double quotes as below, event though it is stored in database without them: { "id": 1, "date_added": "2018-11-18T17:34:04.305381Z", "start_date": "2018-11-17T11:17:32Z", "data": "{\"resource_state\":3,\"athlete\":{\"id\":3255732,\"resource_state\":1},\"name\":\"Lunch Ride\",\"distance\":41993.5,\"moving_time\":6072,\"elapsed_time\":6180,\"total_elevation_gain\":75.0,... } So when I print the API response like so: response = requests.get(url).text print(response.text) I also get those slashes. How do I make the API expose data without them? -
Why does authenticate require two parameters?
I noticed that authenticate() requires two parameters. For example, if I structured my code like this: from django.contrib.auth import authenticate user = authenticate(username='john', password='secret') if user is not None: # A backend authenticated the credentials else: # No backend authenticated the credentials A user object is returned as it should. But if I provided only one parameter such as password, no user object is returned. Is this for security purposes or is a custom authentication system required for handling a login with only a password for example? -
Django DeleteView don't delete the object from data
first of all thanks for your time. i've just learned CreateView UpdateView and DeleteView models. and them i got all of them working. i can change my object i can delete them but after deleting an object i try to create another and gives me this error: NoReverseMatch at /webdeve/dream/add/ Reverse for 'index' with keyword arguments '{'pk': 11}' not found. 1 pattern(s) tried: ['webdeve/$'] it still creates de object although the pk at the moment should be 3, i think after i click de delete button and confirm delete it isnt deleting from data. Those are my models: > from django.db import models from django.urls import reverse > > > > class Dreams (models.Model): > titulo = models.CharField(max_length=100) > objetivo = models.CharField(max_length=100) > imagem = models.CharField(max_length=100) > > def get_absolute_url(self): > return reverse ('webdeve:index', kwargs={'pk': self.pk}) > > def __str__(self): > return self.titulo + ' - ' + self.objetivo > > > class Wich (models.Model): > lets = models.ForeignKey(Dreams, on_delete=models.CASCADE) > make = models.CharField(max_length=100) > it = models.CharField(max_length=100) > favorite = models.BooleanField(default=False) > > def __str__(self): > return self.make my views.py: from django.views import generic from django.views.generic.edit import CreateView, UpdateView, DeleteView from .models import Dreams, Wich from django.urls import reverse_lazy … -
Conditionally change field value for lookup in Django ORM
I'm trying to conditionally change field value during lookup - I have some specific order in mind and I do not want to overwrite field value, just to sort it my way. Let's say, I have classProduct and every class object has product_code field. Now I want to get less than or equal, but it's not trivial - product_code is for most of the time like this A01, B02 and so on and Django lookup lte would work. But now I have fields 0001C01 which I would like to be the biggest value. So during lookup I would like to add 0000 at the begining of every string that does not have this prefix, so it would look like 0001C01, 0000B02, 0000A01. -
Allow/block access to a specific path with apache 2.4 failing
I have a django website project deployed in an enviroment from AWS Beanstalk. I'm trying write configs to apache block access to a specific path (/admin). I avoid change wsgi.conf file, instead I writing package.config in .ebextensions folder, like following: "/etc/httpd/conf.d/block_admin.conf": mode: "000644" owner: root group: root content: | <Location /admin> <RequireAll> Require ip <my_ip>/32 Require all denied </RequireAll> </Location> That code is denying all access to "/admin", include from my ip. I get my ip from services like what is my ip. What am i doing wrong? PS: My english is a working in progress.... [edit] I tryed change the order of Require(all denied/ip) directives -
Query Set Annotate with two different query sets
I'm new to joining two query sets with django orm manipulations. Here is my request. I have two data sets. 1st data set has three columns which are datetime, col1 and 2nd data set has start_date,end_date,week_num. Output data should be weeknum, col1. How can I use django to combine these two models? First data set: datetime col1 2018-10-04 08:00:00 10 Second data set: start_date end_date week_num 2018-10-04 07:00:00 2018-10-11 07:00:00 42 Output data set: weeknum col1 42 10 My code so far: qs1=models.dataset1.objects.all() qs2=models.dataset2.objects.all() I know I'm just putting in the basic datasets, but I'm unable to move any further. SQL Query for this would be like: select weeknum, col1 from datatset1 d1, dataset2 d2 where d1.datettime>d2.start_date and d1.datetime<d2.end_date; Any help on this is greatly appreciated. Thanks. -
django-mongo db docker migration setup
version: "3" services: rango_api: container_name: rango build: ./ # command: python manage.py runserver 0.0.0.0:8000 command: python manage.py runserver 0.0.0.0:8000 working_dir: /usr/src/rango_api environment: REDIS_URI: redis://redis:6379 MONGO_URI: mongodb://rango:27017 ports: - "8000:8000" volumes: - ./:/usr/src/rango_api links: - redis - elasticsearch - mongo #redis redis: image: redis environment: - ALLOW_EMPTY_PASSWORD=yes ports: - "6379:6379" elasticsearch: image: docker.elastic.co/elasticsearch/elasticsearch:6.5.0 ports: - "9200:9200" - "9300:9300" mongo: image: mongo ports: - "27017:27017" here is my docker-compose file for django with mongodb. I am not able to understand where to write 'python manage.py migrate'. when i am writing before 'runserver' command it is not working. -
Django API Rest Framework and Angular 7 Authentication with jwt token
I am using Django Rest Framework for the back-end and Angular 7 for the user interface. I'm trying to create a login page to my single page application and authenticate with a jwt token. I've already managed the back-end and it works. Whenever i go to /api-token-auth/ and type the credentials i get a token in the rest framework interface. The front-end part though troubles me. I have created the login component, the authorization service and a token interceptor. I believe i did the right adjustments but whenever i try to login from angular this error appears in the django command promt. "Bad Request: /api-token-auth/ [19/Nov/2018 20:16:16] "POST /api-token-auth/ HTTP/1.1" 400 68 Traceback (most recent call last): File "C:\Python36\lib\wsgiref\handlers.py", line 138, in run self.finish_response() File "C:\Python36\lib\wsgiref\handlers.py", line 180, in finish_response self.write(data) File "C:\Python36\lib\wsgiref\handlers.py", line 274, in write self.send_headers() File "C:\Python36\lib\wsgiref\handlers.py", line 332, in send_headers self.send_preamble() File "C:\Python36\lib\wsgiref\handlers.py", line 255, in send_preamble ('Date: %s\r\n' % format_date_time(time.time())).encode('iso-8859-1') File "C:\Python36\lib\wsgiref\handlers.py", line 453, in _write result = self.stdout.write(data) File "C:\Python36\lib\socketserver.py", line 775, in write self._sock.sendall(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine [19/Nov/2018 20:16:16] "POST /api-token-auth/ HTTP/1.1" 500 59 ---------------------------------------- Exception happened during processing of request … -
Send E-mail to User When Account is Activated though Django Admin Application
Is there a way to send an e-mail to a user when their account is activated through the Django admin application? I can do it independently of the Django admin application but I want the admin to be signed in before they activate a user. Is there a way to achieve this without customizing the Django admin application code? Thanks in advance. -
Getting loged out User object based on url keyword and saving in class based view
decorators = [login_required] @method_decorator(decorators, name='dispatch') class leave_feedback(CreateView): model = FeedbackModel fields = ['feedback', 'opinion'] success_url = '/' #template_name = "feedback/leave_feedback.html" def form_valid(self, form): form.instance.sender = self.request.user form.instance.recipient = get_object_or_404( User, username=self.kwargs['recipient']) # here enter another instance to know what user is feedback given to :D return super().form_valid(form) Url.py from django.urls import path from . import views app_name = 'feedback' urlpatterns = [ path('leave_feedback/<str:recipient>/', views.leave_feedback.as_view(), name='leavefeedback'), ] How do I link unlogged User based on url keyword? Right now im getting KeyError, what does it really mean? -
django collection of model fields
I am trying to setup different models in django. Some of my models includes fields for a text. A text is defined by: - CharField (tex) - CharField (font-size) - CharField (font-weight) - CharField (color) So some of my models need one to n of these texts. Is it possible to create a collection of Fields, for example "Test-Collection" that includes all 4 fields. So that i didn't have to write all 4 field manually for each text i need in a model? Some thing like that: class Box(CMSPlugin): text1 = models.CharField(max_length=100) text1_font_weight = models.CharField(max_length=100) text1_font_size = models.CharField(max_length=100) text1_color = models.CharField(max_length=100) text2 = models.CharField(max_length=100) text2_font_weight = models.CharField(max_length=100) text2_font_size = models.CharField(max_length=100) text2_color = models.CharField(max_length=100) text3 = models.CharField(max_length=100) text3_font_weight = models.CharField(max_length=100) text3_font_size = models.CharField(max_length=100) text3_color = models.CharField(max_length=100) Into that: class Box(CMSPlugin): text1 = TextColelction... text2 = TextColelction... text3 = TextColelction...