Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot Login to Django Admin Site
I am trying to create a simple application using Django in Pycharm. I'm using Python 3.7 and Django 3.0.3. I was following this simple guide on Jetbrains. But for some reason I keep getting the error saying that my username or password is incorrect, whereas they are actually correct. I checked my database, and django_session table is there. I can see the user I have created in auth_user table with is_staff, is_superuser and is_active all true. I also tried changing the password after creating a super user as this was the accepted answer on a similar question but that didn't work. Here is my settings.py file """ Django settings for SampleApplication project. Generated by 'django-admin startproject' using Django 3.0.3. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'some-secret-key' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS … -
Django redirects for incomplete urls
I have an Django application that has content at the url: /analyze/plot/123abc (or some other alphanumeric key). I want to redirect anything that is just /analyze/plot/ to a predetermined url with a default key (such as /analyze/plot/a1). I would also like to redirect to this same url if any bad key is attempted for a url. Here is what my url configuration looks like: urlpatterns = [ path('', views.index, name='index'), path('plot/', views.plot_redirect, name='plot_redirect'), path('plot/<int:graph_id>/', views.plot, name='plot'), ] Views: def plot_redirect(request): return redirect('analyze:plot:a1') def plot(request, graph_id): """ The plotting view for the NBA data set. :param request: HTML request object :return: The html page """ graph = get_object_or_404(pk=graph_id) When I currently go to /analyze/plot I get an error. -
Django Allauth / User Model Encrypt Username and Email For PII Compliance
Is it possible to encrypt the username and email for Allauth to be PII compliant? If so, how would you do that? If this is possible, how would a site admin go about decrypting the username and email in case they needed to contact the user? Not sure if Allauth specifically needs to be encrypted or the user model itself. I am not currently using a custom user model. All I have are the default tables that come with allauth / user model: Email Addresses, Groups, and Users. Project Github: https://github.com/pennersr/django-allauth To do this would you need to override allauth and use some sort of encryption package like https://github.com/georgemarshall/django-cryptography ? Or is there a better way? -
Getting 'PostPagos' object has no attribute 'clean_data' when adding validation error on Form
I have been trying to add a validation on the date choosen in a calendar picker, the idea is that if the user select a date in the future gets a message that it cannot be a future date. This is one of the things that I have tried so far: views.py class PagosCreate(CreateView): form_class = PostPagos template_name = "AC/add_expense.html" def form_valid(self, form): object = form.save(commit=False) object.startweek, object.endweek = self.weekdatetimeconverter( object.semana) object.save() return super(PagosCreate, self).form_valid(form) def weekdatetimeconverter(self, semana): d = semana startweek = datetime.datetime.strptime(d + '-1', "%Y-W%W-%w") endweek = datetime.datetime.strptime(d + '-0', "%Y-W%W-%w") return (startweek, endweek) forms.py class PostPagos(forms.ModelForm): def clean(self): fecha = self.clean_data.get('fecha') today = datetime.datetime.today() if fecha > today: raise forms.ValidationError( 'La Feha no puede ser mayor al día de hoy') return self.cleaned_data class Meta: model = Pagos fields = ('carro', 'pago', 'fecha', 'semana', 'renta') widgets = {'fecha': forms.DateInput(attrs={'type': 'date'}), 'semana': forms.DateInput(attrs={'type': 'week'}) } models.py class Pagos(models.Model): carro = models.ForeignKey( Carros, on_delete=models.CASCADE, blank=False, null=False) pago = models.DecimalField(max_digits=6, decimal_places=2) fecha = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) semana = models.CharField(max_length=20) startweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) endweek = models.DateField( auto_now=False, auto_now_add=False, blank=True, null=True) renta = models.ForeignKey( Renta, on_delete=models.PROTECT, blank=False, null=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name_plural … -
Ordering objects by calculating the sum of fields on a foreign key Django
Say I had some models defined as such: Class Owner(models.Model): pass Class Item(models.Model): value = models.IntegerField() owners = models.ForeignKey(Owner, related_name="items") How would I go about sorting Owners based off of the sum of the value of their items, ideally as a QuerySet that I could pass onto a template like Owner.objects.order_by('-valueofItems') -
Store data associated with a foreign Key in a Django Model
I wanna store data in a Django Table as if I am storing data into some category and item access them in FIFO manner. Here I should be able to store a data item to a category. Category: ID: 1, Name: firstname Percentage: 40 I have to store them in a different category pass if > 40 and in fail if <40. Table Fail: ID 1 --> Inserted first ID 2 --> Insrted second ID 3 --> Inserted third Table Pass: ID 4 --> Inserted first ID 5 --> Insrted second ID 6 --> Inserted third For some reason, I have to rank them using the First In First Out(FIFO) method. What is the best way to do that? -
Datatables Django table update
I'm trying to update a DataTables table such that both the columns and rows will change. I'm working with DJANGO 2 and would like to handle the AJAX call outside of Datatables. My Django function based view returns the following JSON string which looks well formed: [{"myvar1":"myval1"},{"myvar1":"myval2"} ] I can correctly remove the Datatables table and recreate a new table. I can correctly derive the columns from the JSON data and assign these to the new Datatables table. However the data will not load, instead I receive the following pop-up error: "DataTables warning: table id=example - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1" I've tried looking into this but cannot resolve the issue, any suggestions welcome. In the console the following message is printed: "jquery.dataTables.js:3952 Uncaught TypeError: Cannot set property 'data' of null" $("#myform").change(function () { // get the values from the form var dset = $("#mydset1").val(); var sub = $("#mysub").val(); $.ajax({ type: "POST", url: '/myajax/' , data: {ajax_sub:sub,ajax_dset:dset,pk:{{pk3}}, csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function(jsondata){ var newdat = JSON.parse(jsondata.var2) var columns = []; $.each(newdat[0], function (key, value) { var my_item = {}; my_item.title = key; my_item.data = key; columns.push(my_item); }); $('#example').DataTable().destroy(); $("#example").empty().remove(); $('#table_div').append('<table id="example"> … -
django app: gunicorn accessible over internet on port 8000 - Security implications?
I am auditing a django app externally (so I have no accesss to config files etc). It is quite standard: nginx reverse proxy on port 443, and behind it there is gunicorn on port 8000. nginx serves webpage via SSL, but port 8000 is accessible over internet and delivers same contents in plain text. The question: Is it normal to have gunicorn directly accessible over the Internet in a production environment? (I would assume not, why would we have nginx in front of it then) What are the security implications of this setup? Would this be attackable somehow (other than being non-SSL)? -
Display pages where DjangoCMS Snippet is being used
I'm trying to see whether it's possible to have some sort of dropdown in the Django Snippet editor which shows where the snippet is currently being used, that is, list which pages are using it as a plugin? I assume that the model will need to be modified, but I'm not quite sure how to go about this or whether it can even be done. I've searched for quite some time now, but I have not been able to find anything that has been of any use. Any help would be appreciated. -
Prepopulate ManyToManyField with multiple choices via URL?
I am trying to pass multiple variables created via formset through to another form's M2M field through the URL. For example, pretend I have 2 models: one of actors, and one of movies. The way I have my models set up, the user would add all of the actors first (assuming they didn't already exist in the database), then they are forwarded to the next form to add the movie, where I'd like the actors to be pre-filled in a M2M field. I have been able to do this with a single actor, passing the actor-id through the URL, but can't figure out how to do it with multiples. Here is some code: models.py class Actors(model.Model): name = CharField class Movies(model.Model): name = CharField actors = ManyToManyField(Actors) views.py def addmovie(request, actor_id): if request.method == 'POST': ... if request.method == 'GET': data = {'name': actor_id} form = AddMovieForm(initial = data) ... urls.py path('add/movie/<actor_id>', views.addmovie) The above will pre-populate the Actor field within the AddMovieForm with a single actor. How do I make it multiple actors? My plan was to pass them all through the URL and then parse them into the form, but can't figure out how to actually make multiple … -
Wbat is the docker command to run my Django server?
I'm trying to Dockerize my local Django/MySql setup. I have this directory and file structure ... apache docker-compose.yml web - manage.py - venv - requirements.txt - ... Below is the docker-compose.yml file I'm using ... version: '3' services: web: restart: always build: ./web expose: - "8000" links: - mysql:mysql volumes: - web-django:/usr/src/app - web-static:/usr/src/app/static #env_file: web/venv environment: DEBUG: 'true' command: [ "python", "./web/manage.py runserver 0.0.0.0:8000" ] mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" expose: # Opens port 3406 on the container - '3406' volumes: - my-db:/var/lib/mysql volumes: web-django: web-static: my-db: However when I run docker-compose up I get errors like the below maps_web_1 exited with code 2 web_1 | python: can't open file './web/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory maps_web_1 exited with code 2 maps_web_1 exited with code 2 web_1 | python: can't open file './web/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory maps_web_1 exited with code 2 Is there another way I'm supposed to be referencing … -
What is the best pattern for an overridable relationship-based default in django
I have two related django models, one of which provides a default value for instances of the second model. Here is my implementation: from django.db import models class Manufacturer(models.model): default_attribute = models.CharField() class Product(models.Model): updated_attribute = models.CharField(null=True, blank=True) manufacturer = models.ForeignKey(Manufacturer) @property def attribute(self): if self.updated_attribute is not None: return self.updated_attribute else: return self.manufacturer.default_attribute The behavior that I would like (and that is modeled here) is that if a product's updated_attribute is not specified, the product.attribute defaults to the manufacturer's default_attribute. If product.updated_attribute is specified, the Product instance's updated_attribute is used. Is there a django native pattern for this that I have missed? -
how can I put the fields itself into HTML page, not values of fields? [django]
in this question I need to put imagefield in this page I need do something like Facebook account when anyone need to change the image of an account he can select one of an image on his machine and when do that, the page redirecting him to specific page Note: I need to get this field from models not forms, also this code is just diligence from me, I'm sure I get a big mistake so if anyone can help views.py class AddImage(AddNewImage): template_name = 'account/userprofile_form.html' form = AddNewImage def my_view(self, request, user_id): forms = self.form(instance=UserProfile.objects.filter(id=user_id)) return render(request, self.template_name, {'forms': forms}) def post(self, request): form = self.form(request.POST) if form.is_valid(): form.save() return redirect('account:view_profile') forms.py # Add new logo and replace it with old logo class AddNewImage(forms.ModelForm): class Meta: model = UserProfile fields = ['logo'] urls.py urlpatterns = [ path('new-image/<int:user_id>', views.AddImage, name="add_new_image"), ] userprofile_form.html {% extends 'base.html' %} {% block title %} Add New Image {% endblock %} {% block body %} <div class="add-image"> <div class="container"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {% for form in forms %} {{ form }} {% endfor %} <input type="submit" class="btn btn-success"> </form> </div> </div> {% endblock %} models.py from django.db import models from django.contrib.auth.models import … -
Where do I copy my VirtualHost directive in my Apache docker image?
I'm trying to Dockerize my Apache/Django project locally. On my local machine (running Mac Sierra) I have this file (maps.conf) in my /etc/apache2/other/ directory ... <VirtualHost *:80> ServerName maps.example.com Alias /static /Library/WebServer/Documents/maps/maps/static <Directory /Library/WebServer/Documents/maps/maps/static> Require all granted </Directory> # Next, add the following directory block <Directory /Library/WebServer/Documents/maps/maps_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess maps python-home=/Library/WebServer/Documents/maps/venv python-path=/Library/WebServer/Documents/maps WSGIProcessGroup maps WSGIScriptAlias / /Library/WebServer/Documents/maps/maps_project/wsgi.py </VirtualHost> I found this Apache docker file ... FROM httpd:2.4 COPY ./public-html/ /usr/local/apache2/htdocs/ Where am I supposed to copy my VirtualHost directive above so that my Apache docker image connects properly? -
<Model>.objects.create(**dict) returns None and doesn't save record Django
So, I have script that generates dummy data to fill DB with something during development. Firstly, I creating dictionary with all key-value pairs that model needs. ... product = { "title": "something here" "count": random.randint(15, 200), "price": random.randint(100, 2500), "parent_category": sub_category, "manufcaturer": rnd_manufacturer, "species": rnd_species } ... Then I adding this dict to <Model>.objects.create(**product) and want to save this to any var, lets say to var a a = <Model>.objects.create(**product) But right part of declaring a var returns None, and even doesn't save inserted data to DB. If you need more info, please tell me about it. -
Django-RQ: Cassandra Models not getting committed into DB in the worker thread
I am trying to run a background process to fetch user information from the external api and persist in Cassandra. My views.py lloks like this from django.views.decorators.csrf import csrf_exempt from django.http import HttpResponse import django_rq from django_rq import job from .models import Users @csrf_exempt def post_user(request): if request.method == "POST": request_json = json.loads(request.body) user_id = request_json['user_id'] redis_conn = django_rq.get_connection('default') queue = django_rq.get_queue('default',autocommit=True) queue.enqueue(bg, user_id=user_id) return HttpResponse(status=202) @job def bg(user_id): #External api call Users.create(user_id=user_id, user_name="John") My models.py import uuid from cassandra.cqlengine import columns from cassandra.cqlengine.models import Model class Users(Model): user_id = columns.UUID(primary_key=True, default=uuid.uuid4) user_name = columns.Text() class Meta: __table_name__ = 'users' In the terminal it is printing the query like this [Connection: DEFAULT_CONNECTION] Query: INSERT INTO general.users ("user_id", "user_name") VALUES (%(0)s, %(1)s), Params: {'0': UUID('d0c54a9b-8542-4e72-969d-527e55769784'), '1': 'John'} Sending options message heartbeat on idle connection (139936469444984) 127.0.0.1:9042 But after this I check in the cassandra db using cqlsh, not able to see the inserted record. Any suggestions please? -
Column does not exist despite migration with no errors
I added a column to a model. Then ran 'makemigrations' for the app. And also 'migrate' for the app. No error. Everything seems fine when I check 'showmigrations'. But I get error on the website. 'Column does not exist'. So I went into postgres and checked the table in the database. And it does not show the added column. Very strange since the migration had no problem and saying column added. I don't know what code I can add here that will tell anything about the problem. It feels like the migrations is made to another db file or something. But how could I check this? Any idea how I ancountered this or how to overcome this? -
Art with ID "1505/change/filetag" doesnt exist. Perhaps it was deleted?
class Art(BaseArt): ART_TYPES = ( ('USR', 'User'), ('APP', 'Application'), ('SYS', 'System'), ('DWN', 'Download'), ('NET', 'Network'), ) STATUS = ( ('queued', 'Queued'), # Queued for the admin to review ('flagged', 'Flagged'), # Flagged for the user to update ('updated', 'Updated'), # Updated by user, waiting for admin to re-review ('approved', 'Approved') # Approved. This should be changed automatically if "art.is_enabled" = true ) art_name = models.CharField(max_length = 50, help_text='Please use the following naming convention: < Object Type > < OS/System Type > < OS Version Num (if applicable) > < Art Specific Name >. EXAMPLE: File iOS 10.3.1 Wifi Connections') ###add method to get name/username art_type = models.CharField(max_length=10, choices=ART_TYPES, default='USR', help_text='The type of entity that created this art.') art_object_type = models.CharField(max_length=10, choices=ART_OBJECT_TYPES) date_added = CustomDateTimeField(default=timezone.now, blank=True) #datetime.now is_featured = models.BooleanField(default = False) user = models.ForeignKey(User, related_name='art_user', default=1,on_delete=models.CASCADE) ###Location? see notes... # Status reviewer = models.ForeignKey(User, related_name='reviewer', default=1, limit_choices_to={'is_staff':True},on_delete=models.CASCADE) # The admin assigned to review the art status = models.CharField(max_length=20, choices=STATUS, default='queued') # Approval state of the art (queued, flagged, updated, approved) points_awarded = models.BooleanField(default=False, help_text='Specifies if points have been awarded to the user and organization for this art. This field is automatically updated when an admin accepts an art, so this … -
Upload a directory from a user system to S3 bucket in Django
I'm new Django File System module. We'r trying to upload files from a local user's dir to S3 as: On front-end we've a form where user selects which dir he wants to upload. And then in back-end we are trying to zip it and then upload using s3 client. Most confusing part is that we don't have much idea how to get the dir path and then start uploading the files from user's system since whole python code is running on Server Would really appreciate any pertinent input. Tried to do some research with these URLS but did find what i was looking for -
How to apply search filter to forms generated by Django
I have many forms I would like to filter using JQuery/JS on the front-end, rather than send AJAX requests to the server. The tutorials for filters I am finding online work for tables but I want to apply this type of filter to my Django form fields. To give an example: JQuery: $(document).ready(function(){ $("#myInput").on("keyup", function() { var value = $(this).val().toLowerCase(); $("#myTable tr").filter(function() { $(this).toggle($(this).text().toLowerCase().indexOf(value) > -1) }); }); }); This filters a table <tr> with the Id of #myTable. The html would look as such: HTML: <input class="form-control" id="myInput" type="text" placeholder="Search.."> <br> <table class="table table-bordered table-striped"> <thead> <tr> <th>Firstname</th> <th>Lastname</th> <th>Email</th> </tr> </thead> <tbody id="myTable"> <tr> <td>John</td> <td>Doe</td> <td>john@example.com</td> </tr> I am wondering if I am able to filter MultipleSelectCheckbox (radio button) fields using this technique as well. The form is generated in a Django template so it looks like this prior to running the server: <div class="form-row"> <div class="form-group col-md-12"> {{ form.questions|as_crispy_field }} </div> </div> The HTML after running the server is dynamically created looks like this: <div id="div_id_questions" class="form-group"> <label for="" class="">Questions</label> <div class=""> <div class="form-check"> <input type="checkbox" class="form-check-input" name="questions" id="id_questions_1" value="2" style="display: none;"> <label class="form-check-label" for="id_questions_1">True False test question</label> </div> <div class="form-check"> <input type="checkbox" class="form-check-input" name="questions" id="id_questions_2" … -
when i deployed my django application cv2.VideoCapture(0) is not working anymore
this error is what i get OpenCV(4.1.2) C:\projects\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' -
Deploying Django with Celeris to Heroku
I have developed a django app using celery with redis in Heroku and it works fine in my virtual env. I am trying to deploy the whole app to production in Heroku and can't find any docs or similar projects to use as guide. There are a few tutorials about deploying django to heroku but nothing with celeris. Could anyone tell me a step by step guide? or any tutorial or whatever? Anything would help. -
TypeError: method() takes 1 positional argument but 2 were given when running update index
update_index.Command().handle( app_label, using=None, remove=indexJob.remove ) Thats my small code, I like to know what to fix.Am migrating django 1.8 to django 2.2 and python 2.7 to python 3.6.9 Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/fdc/PycharmProjects/FDC/FDC_2_7/artifacts/DBIndexManager.py", line 56, in _update_index remove=indexJob.remove TypeError: handle() takes 1 positional argument but 2 were given -
Dynamic query_set in ListView
I have old app on functions(where all good work) and now I want to rewrite it using generic.ListView. But I don't fully understand how to correctly redefine query_set(def). Code in old app: # views def product_list(request, category_slug=None): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) html <li {% if not category %}class="selected"{% endif %}> <a href="{% url "shop:product_list" %}">All</a> </li> {% for c in categories %} <li {% if category.slug == c.slug %}class="selected"{% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} And these are my strange attempts implementation in class: class ProductView(generic.ListView): paginate_by = 3 form_class = QuantityForm categories = Category.objects.all() def get_queryset(self, category_slug=None): category = None products = Product.objects.all() if category_slug: category = get_object_or_404(Category, slug=category_slug) products = self.products.filter(category=category) return products def get_context_data(self, **kwargs): context = super(ProductView, self).get_context_data(**kwargs) context['Products'] = self.form_class context['categories'] = self.categories return context html <li {% if not category %}class="selected"{% endif %}> <a href="{{ categories.get_absolute_url }}">Все категории</a> </li> {% for c in categories %} <li {% if categories.slug == c.slug %}class="selected"{% endif %}> <a href="{{ c.get_absolute_url }}">{{ c.name }}</a> </li> {% endfor %} Please … -
django gunicorn bind fails says ImproperlyConfigure
When i execute bind command for gunicorn, it seems to work, but when i visit domain, i get error in console. for ImproperlyCOnfigured environment. Python manage.py runserver commands work find and i can access server with IP address. I am stuck at what is it i am doing wrong. Possibly its because instead of settings.py i have settings directory and it includes development.py and production.py. But i have already mentioned that address inside the wsgi file and also in manage.py file. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings.development") (env) ubuntu@ip:~/aws01/src$ gunicorn --bind 0.0.0.0:8000 wsgi [2020-02-05 20:48:06 +0000] [4390] [INFO] Starting gunicorn 19.10.0 [2020-02-05 20:48:06 +0000] [4390] [INFO] Listening at: http://0.0.0.0:8000 (4390) [2020-02-05 20:48:06 +0000] [4390] [INFO] Using worker: sync [2020-02-05 20:48:06 +0000] [4394] [INFO] Booting worker with pid: 4394 [2020-02-05 20:48:14 +0000] [4394] [ERROR] Error handling request / Traceback (most recent call last): File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 135, in handle self.handle_request(listener, req, client, addr) File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/gunicorn/workers/sync.py", line 176, in handle_request respiter = self.wsgi(environ, resp.start_response) File "/home/ubuntu/aws01/src/wsgi.py", line 28, in application return get_wsgi_application()(environ, start_response) File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/django/core/wsgi.py", line 14, in get_wsgi_application django.setup() File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/django/__init__.py", line 17, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 48, in __getattr__ self._setup(name) File "/home/ubuntu/aws01/env/local/lib/python2.7/site-packages/django/conf/__init__.py", line 42, in _setup % (desc, ENVIRONMENT_VARIABLE)) ImproperlyConfigured: Requested …