Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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: … -
Is there any tool to automatically create template for model in django
I am new in django and I have some experience in Jsf within Netbeans. In netbeans, when we have entity classes, it can automatically create jsf page from entity classes for list, create and view. Is there any tool to automatically create template for model in django? -
django rest serializer: ordering fields appearance
Is it possible to specify in which order fields will appear in a serialised model? To make sure there is no confusion, while searching answers for this I have found lots of suggestions for ordering objects in a list view but this is not what I am looking for. I really mean for a given model, I'd like their fields, once serialized to appear in a specific order. I have a fairly complex serialized object containing a lot of nested serializers, which appear first. I'd prefer instead key identifying fields such as name and slug to show up first, for readability. Apologies in advance if this question is a duplicate, but I didn't find any relevant responses. -
django form is not working properly. getting error at form.is_valid()
I am getting error "init() got an unexpected keyword argument 'sub_category'" in form.py on line super(LeadForm, self).init(*args, **kwargs) and in views.py on line form.is_valid(). Please help. I am sharing github link for the project, just look into 'leads' app. check on create_lead function in views.py and Leadform in forms.py and Lead model in models.py https://github.com/admill1519/django-crm -
How to log in and check, if user is staff, can access to url or use a views class?
At my question, my problem is How to log in and check, if user is staff, can access to url or use a views class ? I want to user login on website (Not admin-console) and user is staff (in admin-console) can post. And someone just have a account create on web (they dont have permission staff) thay just can login. Thank you so much ! class PostCreateView(LoginRequiredMixin, CreateView): model = Post fields = ['title','content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) -
Show all languages in form using django-translations
I am using django-translations for translating some fields of my model. Using the Django Admin I can enter the translations and the form in the frontend shows the matching language values. But I want to show one field for each language "similar" to the Django Admin, except I don't want to manually add the fields for non translated languages. So if I have the languages en (default) and de I want to output title or title_en and title_de as fields. I tried to add the translation fields myself e.g. title_de to the model, layout and meta class, but it didn't work. How can I show all the fields for different languages simultaneously? Model class Category(Translatable, MPTTModel): title = models.CharField(max_length=200) slug = models.SlugField() parent = TreeForeignKey('self', on_delete=models.CASCADE, null=True, blank=True, related_name='children') class Meta: # enforcing that there can not be two categories under a parent with same slug unique_together = ('slug', 'parent',) class MPTTMeta: order_insertion_by = ['title'] class TranslatableMeta: fields = ['title', 'slug'] Form class CategoryForm(forms.ModelForm): use_required_attribute = False title = forms.CharField(max_length=200) slug = forms.SlugField(help_text=_('Will be generated automatically from the title')) def __init__(self, *args, **kwargs): self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = '.' self.helper.form_class = 'form-horizontal form-bordered' self.helper.label_class = 'col-lg-3' self.helper.field_class … -
Unable to paginate django-tables2-column-shifter
I have a table will 1000+ user records, I am unable to paginate it or add filters to it. tables.py from django_tables2_column_shifter.tables import ColumnShiftTable from .models import UserAdminTB import django_tables2 as tables class AdminData(ColumnShiftTable,tables.Table): def get_column_default_show(self): self.column_default_show = ['associate_nbr', 'first_name','last_name','last_hire_date','function','client','lob'] return super(AdminData, self).get_column_default_show() class Meta: model = UserAdminTB views.py class AdminView(SingleTableView): template_name = 'admin.html' def get(self,request,*args,**kwargs): queryset = UserDetails.objects.all() table = AdminData(queryset) return render(request,self.template_name, {'table': table}) -
Convert text file to tiff file in python
I am converting text file to tiff by using the following code but it is not working when text file content starts with special characters. I don't know why it is not working. Could you please anyone help me to do this task def main(): image = text_image('/Users/administrator/Desktop/367062657_1.text') image.show() image.save('contentok.tiff') def text_image(text_path, font_path=None): grayscale = 'L' # parse the file into lines with open(text_path) as text_file: lines = tuple(l.rstrip() for l in text_file.readlines()) large_font = 20 font_path = font_path or 'cour.ttf' try: font = PIL.ImageFont.truetype(font_path, size=large_font) except IOError: font = PIL.ImageFont.load_default() print('Could not use chosen font. Using default.') pt2px = lambda pt: int(round(pt * 96.0 / 72)) max_width_line = max(lines, key=lambda s: font.getsize(s)[0]) test_string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' max_height = pt2px(font.getsize(test_string)[1]) max_width = pt2px(font.getsize(max_width_line)[0]) height = max_height * len(lines) # perfect or a little oversized width = int(round(max_width + 5)) # a little oversized image = PIL.Image.new(grayscale, (width, height), color=PIXEL_OFF) draw = PIL.ImageDraw.Draw(image) vertical_position = 5 horizontal_position = 5 line_spacing = int(round(max_height * 1.0)) for line in lines: draw.text((horizontal_position, vertical_position), line, fill=PIXEL_ON, font=font) vertical_position += line_spacing c_box = PIL.ImageOps.invert(image).getbbox() image = image.crop(c_box)`enter code here` return image -
How to ignore a specific migration?
I have a migration like this: class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20191023_2245'), ] operations = [ migrations.AddField( model_name='agenda', name='theme', field=models.PositiveIntegerField(default=1), ), ] But it raises an error: django.db.utils.ProgrammingError: column "theme" of relation "app_agenda" already exists Not a problem, I've wrapped this error like this: from django.db import migrations, models, ProgrammingError def add_field_theme_to_agenda(apps, schema_editor): try: migrations.AddField( model_name='agenda', name='theme', field=models.PositiveIntegerField(default=1), ), except ProgrammingError as e: # sometimes it can exist if "already exists" not in str(e): raise class Migration(migrations.Migration): dependencies = [ ('app', '0020_auto_20191023_2245'), ] operations = [ migrations.RunPython(add_field_theme_to_agenda), ] This works like a charm and all the following migrations are done. My problem is that each time I run a "makemigrations" Django adds again the migration (= the one on the top of my question). I guess it's because it doesn't see it in the migrations, because my code obfuscate it. How to circumvent this using migrations (dont say answers like "this problem is on your database, correct your database")? -
How to fix Django admin encoding error when I update the user?
When I update user data through the admin panel I get the following error: IntegrityError at /admin/registration/testuser/11/change/ ������������: INSERT ������ UPDATE �� �������������� "django_admin_log" ���������������� ���������������������� ���������������� ���������� "django_admin_log_user_id_c564eba6_fk_auth_user_id" DETAIL: �������� (user_id)=(11) ���������������������� �� �������������� "auth_user". How I can fix this? P.S. I saw an old similar question, but the custom backend from there, knocked me all the authorization. -
How to start task at 0815 and run it every 15 minutes in django
I am trying to schedule a celery task on django, which would start at 0815 in the morning and run every 15 minutes. @periodic_task(run_every=crontab(minute='*/15', hour='8-23',), queue='xenia_celery_priority_queue_1', options={'queue': 'xenia_celery_periodic_queue_1'}) As I understand, I would need to set minutes=15, so the task starts at 0815, bu I am using minutes, to run the task every 15 minutes already. Is there a simple way to start the task at 0815 and run it every 15 minutes? -
Conditional Statement If-else in Jinja2
I'm building my first application in Django and I am having trouble with the conditional loop. I want to create a form where users would input their name, family size and income and it would calculate where they land on the sliding scale (A, B, C or Overqualify) based on their income. I'm expecting it to output one scale (A,B,C, or Overqualify) but it keeps looping - so what I am getting is: What I am getting If anyone can help me or point me to any resources because I just started learning python and django so I'm quite stuck. Thank you! models.py from django.db import models # Create your models here. class SlidingScale(models.Model): scale = models.CharField(max_length=1) family_size = models.IntegerField() min_annual = models.IntegerField(default = 0) max_annual = models.IntegerField() def __str__(self): return self.scale forms.py from django import forms class SlidingForm(forms.Form): name = forms.CharField(max_length = 100) household = forms.IntegerField() income = forms.IntegerField() views.py from django.shortcuts import render from django.template.response import TemplateResponse from .models import SlidingScale from .forms import SlidingForm # Create your views here. def index(request): return render(request, 'index.html', {}) def calculator(request): if request.method == "POST": #Get the posted form form = SlidingForm(request.POST) data = SlidingScale.objects.all() if form.is_valid(): name = form.cleaned_data['name'] household …