Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
modelForm instance not coming through
I'm passing an instance of a model into a modelForm, but, within the view, when I print the form, the values within the model don't show up. Also, when the form is rendered on my template, the values from the instance don't show up. Views.py def support_ticket_view(request, id=None): id = int(id) instance = SupportTicket.objects.get(id=id, user=user) form = SupportTicketEditForm(request.POST or None, request.FILES or None, instance=instance) context = { 'form': form, } return render(request, 'accounts/support_ticket_view.html', context) forms.py class SupportTicketEditForm (forms.ModelForm): def __init__(self, *args, **kwargs): self.instance = kwargs.pop('instance',None) super(SupportTicketEditForm, self).__init__(*args, **kwargs) class Meta: model = SupportTicket fields = ( 'image', 'body_question', 'urgency', 'question_type', 'status', ) widgets = { 'image': ImageThumbnailFileInput } models.py class SupportTicket(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.TextField(max_length=10000, null=True, blank=False) def __str__(self): return self.user.username -
Shuffle "PASSWORD-HASHERS" every hour Django
Im trying to make a website with Django, and what i saw that if you change the default django hasher, it will automatically change it for the user who logs in too. For example, you have an user password encoded with Bcrypt, and you change in Django settings file the hasher with Argon. Next time the user logs in, Django will automatically change the password encriptaion with Argon. Basically what i want to do is change the hasher automatically every hour. I tried with threads but the only problem is that i need to restart the server to apply the new hasher. PASSWORD_HASHERS = [ 'django.contrib.auth.hashers.BCryptSHA256PasswordHasher', 'django.contrib.auth.hashers.PBKDF2PasswordHasher', 'django.contrib.auth.hashers.PBKDF2SHA1PasswordHasher', 'django.contrib.auth.hashers.Argon2PasswordHasher', ] def randomizeHasher(): global PASSWORD_HASHERS while(True): hasher = PASSWORD_HASHERS random.shuffle(hasher) PASSWORD_HASHERS = hasher time.sleep(20) t = threading.Timer(0,randomizeHasher) t.start() -
Django "Forbidden (CSRF cookie not set.)" on localhost:8000
I have a Django app running locally on 127.0.0.1:8000. When I access it via 127.0.0.1:8000 on my browser, everything is fine. However, when I access it via localhost:8000, CSRF errors occur : I think it is due to an AJAX POST request not properly sending the csrftoken cookie. On the same HTML page, I have two actions that submit POST requests : one with an html form using the Django template tag {% csrf_token %} (that one works perfectly well) another one that uses the Fetch API (AJAX) to submit a POST request to a view in my Django app that sends back a JSON (note that I am not using django-rest-framework), and this one doesn't work. The fetch request looks like this : const csrftoken = getCookie('csrftoken'); fetch(route, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken }, credentials: 'include', body: JSON.stringify(reqBody) }).then(...) But my view returns a Forbidden (CSRF cookie not set.) error when I make that request. If I add a @csrf_exempt decorator (which removes the error, but I don't want to deactivate CSRF permanently) to it and print request.META.get("CSRF_COOKIE"), request.META.get("HTTP_X_CSRFTOKEN") and request.META.get("HTTP_COOKIE"), this is what I obtain : CSRF_COOKIE: None HTTP_X_CSRFTOKEN: cdd9hIG22C39heME5aUvBU8VfB9hpnnvf8TWLYMQBJsS8jqoPh0ErA7iq1fdHSt2 HTTP_COOKIE: isNotIncognito=true; … -
Django - How to edit specific row in database based on multiple fields?
So, I'm fairly new to this and haven't had time to sit down and do proper learning. What I'm trying to eventually achieve is modifying a timestamp that is initially NULL to the current time, based on employee # and work area. The idea behind this, is a "check-in/check-out" system. First the user enters # and work area and when they "Enter", an entry is created in the database with the #, work area, time in, and a "time out" that is set to NULL. Once they're done, they'd just enter their # again, work area, and "Leave" and this should look for the last entry with NULL in time out, and same # and work area and update the time out to the new timestamp. In the case this doesn't exist then it would create a new entry but alert the user. forms.py class WarehouseForm(forms.Form): class Meta: model = EmployeeWorkAreaLog fields = ('employee_number', 'work_area', 'station_number') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['station_number'].queryset = StationNumber.objects.none() if 'work_area' in self.data: try: work_area_id = int(self.data.get('work_area')) self.fields['station_number'].queryset = StationNumber.objects.filter(work_area_id=work_area_id).order_by('name') except (ValueError, TypeError): pass elif self.instance.pk: self.fields['station_number'].queryset = self.instance.work_area.stations.order_by('name') models.py class WorkArea(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class StationNumber(models.Model): work_area = models.ForeignKey(WorkArea, … -
DataTables: Howto send Checkbox selection items by email
I have a Table. I can select items from the table by using DataTables, and Checkbox selection. My aim is to make a selection and send an email with the id of the selected items. Each item in the Table has an unique reference, accessible through a button in the table with reference: href="{% url 'person-detail' object.person_detail_uid %}" In my initial try, I created a "Send Button" for each item, linking to: href="{% url 'person-send' object.person_detail_uid %}", but it looks horrible when scaling it up, instead I would like to select those items to send and have one send button instead. How do I do that? Many thanks for input. URLs and Product Send looks like this: path('person/<uuid:slug>/send/', send_person, name='person-send'), def send_person(request, slug): slug_field = 'person_detail_uid' subject = "Hello" message = f'website/person/{slug}/' send_mail_from = 'nnnnnn@nnnnnn.nnn' recipients = ['nnnnnn@nnnnnn.nnn'] send_mail(subject, message, send_mail_from, recipients) return HttpResponseRedirect('/person/list') -
Displaying the next form below the previous one only once validated
I am experienced in Python, but I'm quite new to Django. So I apologize in advance if the answer to my question is quite obvious. That being said, I couldn't figure out how to make the below work after several days. I have a set of 20 questions which can be either of type: 1. forms.CheckboxSelectMultiple 2. forms.RadioSelect 3. forms.TextInput What I am aiming for is that as soon as the user submits the answer to the first question, the second question displays just below (the first question turning into read only)... an so on until the user reaches the last question where he gets redirected to a page with the answers. So far, what I have been able to achieve is to have all questions displayed all thogether with a "Validate" button at the bottom (redirecting to the answer page). I would gratefully accept any lead or piece of advice. Thanks. Eric -
How to install django-wkhtmltopdf in Pythonanywhere.?
How to install django-wkhtmltopdf in pythonanywhere.? When I try to install with pip3. It’s already satisfying When I run the project its server error (500) Bash Console Requirement already satisfied: django-wkhtmltopdf in ./.local/lib/python3.7/site-packages (3.2.0) Server Error Log FileNotFoundError: [Errno 2] No such file or directory: 'wkhtmltopdf': 'wkhtmltopdf' Can wkhtmltopdf be installed on Pythonanywhere? When I choose an AWS server, do I face a similar problem? Do AWS support wkhtmltopdf.? How to solve this.? My entire project depends on the PDF reports -
sorting a query set after a for loop on it
I want to apply a method on all of the objects in a query set and then sort them. for product in products: product.update_exist_flag() products = products.order_by('-exist_flag') it raises this error: AssertionError: Cannot reorder a query once a slice has been taken. how can I fix it? -
Linking my Django docker container to a postgres container
I create a django docker application image. in my django app, in settings.py DATABASE entry is: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'cath_local', 'USER': 'postgres', 'PASSWORD': 'mypass', 'HOST': 'postgres', 'PORT': '5432', 'OPTIONS': { 'client_encoding': 'UTF8', }, } } well, at this point i create my docker image using docker build command; all done. Before running my django app docker image i run: docker run -it postgres image is downloaded and container start correctly but when i run my django app docker run -it cath2019/cathedral_studio:latest but wher python manage.py runserver command into my Dockerfile start i get this error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError: could not translate host name "postgres" to address: Name does not resolve here my app Dockerfile: FROM python:3.6-alpine RUN apk add --no-cache make linux-headers libffi-dev jpeg-dev zlib-dev RUN apk update && apk add postgresql-dev gcc python3-dev musl-dev #RUN apk update && apk add build-essential libssl-dev libffi-dev RUN mkdir /Code WORKDIR /Code COPY ./requirements.txt . RUN pip install --upgrade pip RUN pip install -r requirements.txt ENV PYTHONUNBUFFERED 1 COPY . /Code/ ENTRYPOINT python /Code/core/manage.py runserver 0.0.0.0:8000 How can i connect into my django settings DATABASE to running postgres container? So many thanks in advance -
Table as field in model
I have such models: class Department(models.Model): name = models.CharField(max_length=30) schedule = models.ForeignKey('Schedule', on_delete=models.CASCADE) class Schedule(models.Model): post_name = models.CharField(max_length=30) shift_start = models.TimeField(auto_now=False, auto_now_add=False) shift_end = models.TimeField(auto_now=False, auto_now_add=False) Each department have a schedule - some [post_name, shift_start, shift_end] lines for each post. If use ForeignKey there will be only one line instead of a list. Is it possible to create some Schedule tables and link each with certain Department? -
I need to develop a page for displaying data by bank branches
I am new on django. I need an advice. How can I: • develop a structure and create a database of data by bank departments, • develop a web page for displaying data by department with the ability to filter, show / hide certain data, charts, color codes I finished the documentation of django. Dont link me there, please. I know the models and can create database and play with it on a server side. But how can I actually display it on web-page? -
How to re-enter my virtual environment using cmd in windows
I have created a virtual environment for django using cmd pip install virtualenvwrapper-win mkvirtualenv test and here I have installed Django using pip install django But suppose I close my cmd prompt and restart it. What is the command to re-enter in the (test) environment that I have created. -
What does it mean ** in Django update query? [duplicate]
This question already has an answer here: What does ** (double star/asterisk) and * (star/asterisk) do for parameters? 19 answers Currently I am working on old project developed in python 2.7 & django 1.9.13 & during development I have found below kind of code. from django.contrib.contenttypes.models import ContentType model_type = ContentType.objects.get(app_label=app_name, model=model_name) model_type.model_class().objects.filter(id=10).update(**{'emp_comment': 'hello'}) I have read about ContentType & know how it works but still not have much clear ideas but what I am not able to figure out is **{'emp_comment': 'hello'}. I have search online for such kind of syntax but not able to find so anyone have idea how above code works ? -
How to modify the Sidebar AWX admin template in django
picture : AWX template How to modify the Sidebar AWX admin template in django -
Django Sitemap: How to use filter instead of pagination
My sitemap is a bit huge now (100k pages) and I would like to split it using filter instead of pagination A.K.A the limit field. So for my sitemap is like that /sitemap-country.xml?p=3. But I would like it like that /sitemap-country-DE.xml or /sitemap-country.xml?p=DE. Any idea on how to do it? -
Docker Django installation error of Pillow Package
I am dockerising my django apps, you know all if you use django image field, you need to use Pillow package but currently my docker installing all the package and show error when it try install pillow my Dockerfile # pull official base image FROM python:3.7-alpine # set work directory WORKDIR /app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 ENV DEBUG 0 # install psycopg2 RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && pip install psycopg2 \ && apk del build-deps # install dependencies COPY ./requirements.txt . RUN pip install -r requirements.txt # copy project COPY . . # collect static files RUN python manage.py collectstatic --noinput # add and run as non-root user RUN adduser -D myuser USER myuser # run gunicorn CMD gunicorn projectile.wsgi:application --bind 0.0.0.0:$PORT and this is requirements.txt file Django==2.2.2 Pillow==5.0.0 dj-database-url==0.5.0 gunicorn==19.9.0 whitenoise==4.1.2 psycopg2==2.8.4 I am not getting whats wrong with it, why pilow not installing, it throws an error, this is below: The headers or library files could not be found for zlib, remote: a required dependency when compiling Pillow from source. remote: remote: Please see the install instructions at: … -
Django: How to create file directory, upload file into that directory, access that file for calculation, and store it for download?
I'm making a django project that lets specific users to: * first, upload a file with specified file-type; * second, use that file to perform some calculations; and * third, provide a derivative file for download. The user can then view the list of all the files that was uploaded including the files uploaded by other users and choose which files to download or delete. I made an app to manage the user's accounts and another app (core) for file uploads and calculations. Now I want to store the uploaded file in a specific directory so that I can easily access the file for data retrieval. I tried doing this: core_app/models.py def file_path_dir(instance, filename): return 'files/{0}/{1}'.format(instance.id, filename) class Core(models.Model): id = models.AutoField(primary_key=True, editable=False) date_created = models.DateField(auto_now_add=True) user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) csv = models.FileField(upload_to=file_path_dir, validators=[FileExtensionValidator(allowed_extensions=['csv'])]) # NOT SAFE Here, I want the file to be uploaded in a directory using the id that will be stored in the database. However, the file was stored in this directory instead - files/None/filename. I don't know why it says 'None' when I have successfully saved the file in the database (using postgresql). I need help how to solve this or how to properly do … -
Get OHCLV values from a table with timestamp in django
Assume I have a model which has transactions in each time such as: class Transaction(models.Model): timestamp = models.DateTimeField(auto_now_add=True) price = models.DecimalField(max_digits=15, decimal_places=6) vol = models.DecimalField(max_digits=15, decimal_places=6) I want to write a query on django that gets me the OHCLV(open, high, closed, low, volume) values for each minute in a defined region. I wrote a query like below: window = { 'partition_by': [ExtractMinute('timestamp'),], 'order_by': F('id').asc() } Transaction.objects.\ annotate( open_value=Window( expression=FirstValue( F('price'),), **window), closed_value=Window( expression=LastValue( F('price'),), **window), high_value=Window( expression=Max( F('price'),), **window), low_value=Window( expression=Min( F('price'),), **window), volume=Window( expression=Sum( F('volume')), **window)).values(open_value, closed_value, high_value, low_value, volume) But it got me some errors (You have an error in your SQL syntax), also it does not cover times that there was no entry for that minute in table, there is another way using group on minute of time but it also would not cover empty entry times. Please give me a suggestion to write this query correctly, I am using django 2.2.5 and mysql 14.14. -
How can we use multiple keras models in a single django view?
I initialized all my keras models in settings.py and imported it in views to make predictions and received following error : Traceback (most recent call last): File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/hrithik/Desktop/document_processing_app/api/views.py", line 60, in index op_ae = autoencoder(x_test) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/training.py", line 1078, in predict callbacks=callbacks) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/tensorflow/python/keras/engine/training_arrays.py", line 363, in model_iteration batch_outs = f(ins_batch) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/tensorflow/python/keras/backend.py", line 3292, in __call__ run_metadata=self.run_metadata) File "/home/hrithik/anaconda3/envs/test_env/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1458, in __call__ run_metadata_ptr) tensorflow.python.framework.errors_impl.FailedPreconditionError: 2 root error(s) found. (0) Failed precondition: Error while reading resource variable conv2d_2/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv2d_2/bias) [[{{node conv2d_2/BiasAdd/ReadVariableOp}}]] [[flatten/Reshape/_5]] (1) Failed precondition: Error while reading resource variable conv2d_2/bias from Container: localhost. This could mean that the variable was uninitialized. Not found: Container localhost does not exist. (Could not find resource: localhost/conv2d_2/bias) [[{{node conv2d_2/BiasAdd/ReadVariableOp}}]] 0 successful operations. 0 derived errors ignored. Kindly let me know if question needs to be updated. Thanks in advance -
Set range in calendar where if user can not select date before and after current week if user still select then it show error message
class Tech(models.Model): week_start_date = models.DateField(default=get_week_start_date) week_end_date = models.DateField(default=get_week_end_date) def clean(self): if self.week_start_date > self.week_end_date: raise ValidationError("Dates should be in Monday to Saturday") I want to set range Monday to Saturday in the calendar in Django where user can select the date between [ONLY CURRENT] Monday to Saturday and on Sunday user can not change the date -
why a function could return the function itself
I am reading django's source code, and i can not understand what this code is doing. def check_password(self, raw_password): """ Return a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) # Password hash upgrades shouldn't be considered password changes. self._password = None self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) why the function return itself, why there is no infinite loop? this a code snippet from django/contrib/auth/base_user.py -
Why does NullBooleanField in form give a dropdown when rendered in template?
When I change the form field to CharField, there is no dropdown in the template, BooleanField does not have one either. Why does NullBooleanField get a dropdown(in forms)? What if I dont want a drop down? Is this in built in generic view? -
#Django - 'list' object has no attribute 'id'
I have this code, def delivery_date(request): today = datetime.today().date() results = [get(today)] stages = Stage.objects.prefetch_related('Stage').all() for i in range(3): results.append(get(results[i])) results = [{'date': i} for i in results] stages = [{'menu': s} for s in stages] for i in results: for stage in stages: stage['id'] = stage['menu'].id stage['name'] = stage['menu'].name stage['desc'] = stage['menu'].desc stage['menu'] = stage['menu'].Stage.filter( delivery_date__exact=i['date']) stage['menu'] = serializers.serialize('python', stage['menu']) i['menu'] = stages i['date'] = i['date'].strftime('%b %-d') return JsonResponse(results, safe=False) But the results says, this image But if the results has only one date, it works. Like this, def delivery_date(request): today = datetime.today().date() results = [get(today)] stages = Stage.objects.prefetch_related('Stage').all() # for i in range(3): # results.append(get(results[i])) results = [{'date': i} for i in results] stages = [{'menu': s} for s in stages] for i in results: for stage in stages: stage['id'] = stage['menu'].id stage['name'] = stage['menu'].name stage['desc'] = stage['menu'].desc stage['menu'] = stage['menu'].Stage.filter( delivery_date__exact=i['date']) stage['menu'] = serializers.serialize('python', stage['menu']) i['menu'] = stages i['date'] = i['date'].strftime('%b %-d') return JsonResponse(results, safe=False) The results, [ { "date" : Oct 25, "menu" : [ { "menu" : [ { "model" : backend.product, "pk" : 13, "fields" : { "name" : Tasty Tempeh, "desc" : Nasi, Ayam, Wortel, Buncis, Bawang Merah, Bawang Putih, Daun Salam, Serai, … -
SOLID/Bad practice if methods do exactly the same?
I'm busy refactoring a project and trying my best to adhere to the SOLID principles. Everything is going fine, but while separating database actions from the views, I noticed the create and update operations are exactly the same. from ..models import AccessLevel def create(access_level): access_level.save() def update(access_level): access_level.save() def delete(pk): AccessLevel.objects.filter(pk=pk).delete() It could obviously be a single method, but keeping them separated allows for easier refactoring/changes if they're ever needed. But then again it feels unnecessary to have two methods that do exactly the same thing but are just named differently. What is the best practice in cases like these? -
Coveralls is not being submitted on a Django app with Docker
I'm working on a Django project using Docker. I have configured Travis-Ci and I want to submit test coverage to coveralls. However, it is not working as expected. any help will be highly appreciated. Here is the error I'm getting Submitting coverage to coveralls.io... No source for /mwibutsa/mwibutsa/settings.py No source for /mwibutsa/mwibutsa/urls.py No source for /mwibutsa/user/admin.py No source for /mwibutsa/user/migrations/0001_initial.py No source for /mwibutsa/user/models.py No source for /mwibutsa/user/tests/test_user_api.py No source for /mwibutsa/user/tests/test_user_model.py Could not submit coverage: 422 Client Error: Unprocessable Entity for url: https://coveralls.io/api/v1/jobs Traceback (most recent call last): File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/coveralls/api.py", line 177, in wear response.raise_for_status() File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/requests/models.py", line 940, in raise_for_status raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 422 Client Error: Unprocessable Entity for url: https://coveralls.io/api/v1/jobs During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/coveralls/cli.py", line 77, in main result = coverallz.wear() File "/home/travis/virtualenv/python3.7.1/lib/python3.7/site-packages/coveralls/api.py", line 180, in wear raise CoverallsException('Could not submit coverage: {}'.format(e)) coveralls.exception.CoverallsException: Could not submit coverage: 422 Client Error: Unprocessable Entity for url: https://coveralls.io/api/v1/jobs **Here is my Travis.yml file** language: python python: - "3.7" services: docker before_script: pip install docker-compose script: - docker-compose run web sh -c "coverage run manage.py test && flake8 && coverage report" after_success: - coveralls language: python python: …