Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django.db.utils.OperationalError: unable to open database file f
I have this kind of error File"C:\Users\ComputerPC\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\ LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py", line 205, in get_new_connection conn = Database.connect(**conn_params) django.db.utils.OperationalError: unable to open database file while this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': 'myapp', 'USER' : 'postgres', 'PASSWORD': 'er1234', 'HOST': 'localhost' } } -
DJANGO ADMIN TabularInline in TabularInline
I have 3 models models.py class TestObj(models.Model): name = models.CharField('Название', max_length=30) description = models.TextField('Описание теста') topic = models.ManyToManyField(Topic, verbose_name='Тема теста') class Question(models.Model): text = models.TextField('Вопрос') testobj = models.ForeignKey(TestObj, on_delete=models.CASCADE, verbose_name='Тест') many = models.BooleanField('Много ответов', default=False) class Answer(models.Model): text = models.TextField('Ответ') status = models.BooleanField('Верный?', default=False) question = models.ForeignKey(Question, on_delete=models.CASCADE, verbose_name='Вопрос') I want to create tests through the admin panel. I want to create quiz questions and answers for each question on the quiz page class AnswerInline(admin.TabularInline): model = Answer class QuestionInline(admin.TabularInline): model = Question @admin.register(TestObj) class TestObjAdmin(admin.ModelAdmin): inlines = (QuestionInline,) how do i add AnswerInline in QuestionInline? -
No file was submitted error when trying to do an axios POST between react and django rest frame work
I am trying to simply upload a file in my react front-end and send it to my Django rest framework back-end API but keep getting no file was submitted. I have tried setting the filefield to require=false however this just posts null. I am not sure what I am doing wrong if anyone can help. model.py class Upload(models.Model): file_uploaded = models.FileField(upload_to='Apps') def __str__(self): return f"{self.file_uploaded}" serializer.py class UploadSerializer(ModelSerializer): class Meta: model = Upload fields = ('file_uploaded',) views.py class UploadViewSet(viewsets.ModelViewSet): queryset = Upload.objects.all() serializer_class = UploadSerializer parser_classes = (MultiPartParser, FormParser,) print(Upload.objects.all()) def post(self, request, *args, **kwargs): fileSerializer = UploadSerializer(data=request.data) if fileSerializer.is_valid(): fileSerializer.save() return Response(fileSerializer.data, status=status.HTTP_201_CREATED) else: return Response(fileSerializer.errors, status=status.HTTP_400_BAD_REQUEST) react upload and submit functions handleUpload = (files) =>{ var file = new FormData(); file.append(files.target.files[0].name, files.target.files[0]) this.setState({mfile_JsonFile: file}); } createApp = e => { e.preventDefault(); axios.post( "http://127.0.0.1/api/upload/", this.state.mfile_JsonFile).then(() => {alert("posted")}); }; -
How to apply timezones to Django Model DateTimeFields
When a Django model contains a DateTimeField the date is always saved in UTC timezone. If you add a date that had a time zone the information is translated and will be retrieved differently. This happens even if the TIME_ZONE has been set in settings.py and the date was created using timezone.localtime(timezone.now()). The same issue happens when the date is added dynamically, like with models.DateTimeField(auto_now_add=True) or models.DateTimeField(auto_now=True). How can I retrieve or save date times in the correct timezone? -
drf - how to access field of parent serializer in child serializer
I have 3 models models.py class First(models.Model): is_available = models.BooleanField(default=False) class Second(models.Model): some_field = models.BooleanField(default=False) class Third(models.Model): first = models.ForeignKey(First, null=True, blank=True, on_delete=models.CASCADE) second = models.ForeignKey(Second, null=True, blank=True, on_delete=models.CASCADE) serializers.py class SecondSerializer(serializers.Serializer): some_field = serializers.BooleanField() is_available = serializers.BooleanField() # field from models.First class ThirdSerializer(serializers.Serializer): second = SecondSerializer() views.py class ThirdViewSet(mixins.ListModelMixin, GenericViewSet): ......... def get_queryset(self): return Third.objects.select_related('first', 'second') I have to send the response through ThirdSerializer but First.is_available should be sent in SecondSerializer. How can I achieve that? -
I am trying to use Django paginator with HTML, What am I doing wrong?
I am trying to use pagination in one of my learning projects which is an Ecommerce website. I am trying to load products on the Products page. I followed the django docs tutorial and some youtube. The paginator works like the page 1,2 etc but on all the pages it show every product while I specified in views.py on three. views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] products = Product.objects.all() paginator = Paginator(products, 3) page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = {'products': products, 'cartItems': cartItems, 'paginator': page_obj} return render(request, 'store/products.html', context) products.html: <!--Pagination--> <div class="container p-4"> <div class="pagination justify-content-center"> <span class="step-links"> {% if paginator.has_previous %} <a href="?page=1">&laquo; first</a> <a href="?page={{ paginator.previous_page_number }}">previous</a> {% endif %} <span class="current"> Page {{ paginator.number }} of {{ paginator.paginator.num_pages }} </span> {% if paginator.has_next %} <a href="?page={{ paginator.next_page_number }}">next</a> <a href="?page={{ paginator.paginator.num_pages }}">last &raquo;</a> {% endif %} </span> </div> </div> <!--end of Pagination--> -
how to install redis 6 on centos 7
Whenenver I install redis on centos it installs version 3.2 which is not compatible with my django channels-redis. I have used commands- sudo yum install redis sudo yum install redis -y Now How do I install my desired version of redis? And I have uninstalled redis as advised( removed the files before uninstall). Thank you. -
Django:Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class DomainUserAdmin
I want to add a phone number field on the admin site when i want to create a new user manually from the admin page, i have proceed doing this by this code: in admin.py from django.contrib.auth.admin import UserAdmin class DomainUserAdmin(UserAdmin): form = DomainUserChangeForm add_fieldsets = ( (None, {'fields': ('email','first_name', 'last_name', 'phone', )}), ) + UserAdmin.add_fieldsets forms.py class DomainUserChangeForm(UserChangeForm): phone = forms.CharField(label='phone') class Meta(UserChangeForm.Meta): model = DomainUser help_texts = { 'username': _('Required. 150 characters or fewer. Letters, digits and \/@/./+/-/_ only.'), # NOQA } models.py: class DomainUser(User): class Meta: proxy = True def __init__(self, *args, **kwargs): self._meta.get_field( 'username' ).validators[0] = DomainUnicodeUsernameValidator() super().__init__(*args, **kwargs) --->it gives me an error: Unknown field(s) (phone) specified for User. Check fields/fieldsets/exclude attributes of class DomainUserAdmin. HELP PLEASE, How i can add a field phone number when i want to signup(create a new user) from the admin page. -
Bootstrap collapsible card not collapsing within a for loop
I am having trouble getting the collapsible cards to collapse when clicked. When a card is clicked, the card does not collapse like it suppose to. I have already linked the Jquery and bootstrap as well. What am I missing? My current methods is from https://www.bootstrapdash.com/bootstrap-4-tutorial/collapse/ <div class="container-fluid p-5"> {% for section in sections %} <div id="accordion" role="tablist" aria-multiselectable="true"> <div class="card"> <div class="card-header" role="tab" id="heading{{section.id}}"> <h5 class="mb-0"> <a data-toggle="collapse" data-parent="#accordion" href="#collapse{{section.id}}" aria-expanded="true" aria-controls="collapseOne"> Section {{forloop.counter}} </a> </h5> </div> <div id="collapse{{section.id}}" class="collapse show" role="tabpanel" aria-labelledby="heading{{section.id}}"> <div class="card-body"> {% for i in section.coursematerial_set.all %} <p>{{i.lecture_name}}</p> {% endfor %} </div> </div> </div> </div> {% endfor %} </div> -
Exception in thread django-main-thread, SECRET_KEY already installed
I cloned my own repository in GitHub and after installing the necessary dependencies I tried to run my project with: python3 manage.py runserver But when I do that, I get this exception in the thread and I can't see any particular error Exception in thread django-main-thread: Traceback (most recent call last): File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/workspace/.pip-modules/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/workspace/.pip-modules/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/home/gitpod/.pyenv/versions/3.8.11/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 843, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/workspace/.pip-modules/lib/python3.8/site-packages/django/contrib/auth/admin.py", line 6, in … -
How can i refactor this to remove DRY
I have two serializers implemented here with same methods that is to validate the files 1 and 2 how can i refactor my code here so that i take care of DRY serializers.py class FilecreateSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ( 'file', ) def create(self, data): user = self.context['request'].user if not user.is_anonymous: validated_data.update({'uploaded_by': user.person}) return super().create(data) def file_checking(self, file): ca = pd.read_excel(file, dtype=str) if not something(): raise ValidationError() return file class FileUpdateSerializer(serializers.ModelSerializer): class Meta: model = Mymodel fields = ('file_2',) def file_2_checking(self, file): ca = pd.read_excel(file, dtype=str) if not something(): raise ValidationError() return file -
Get the error "List object has no attribute error" while creating a virtual environment [closed]
When creating a virtual environment in some folder, I get the error, Error: 'list' object has no attribute 'read', but despite this, the environment is created like in the image. But when I want to activate it gives an error "Scripts\activate" is not internal or external command, executable program, or batch file. -
Django - difference in time between big serializer and small
I'm creating a music rating app and I'm using REST Framework to create API in Django. It's super easy but I'm wondering if there is any big difference in loading time when using big serializers model and small. By big and small I mean like in getting more data. For instance I have a album page where I need to use this serializer. "id": 2, "title": "OK Computer", "slug": "ok-computer", "created_at": "2022-02-22T21:51:52.528148Z", "artist": { "id": 13, "name": "Radiohead", "slug": "radiohead", "image": "http://127.0.0.1:8000/media/artist/images/radiohead.jpg", "background_image": "http://127.0.0.1:8000/media/artist/bg_images/radiohead.jpg", "created_at": "2022-02-22T00:00:00Z" }, "art_cover": "http://127.0.0.1:8000/media/album/art_covers/ok-computer_cd5Vv6U.jpg", "genres": [ "Alternative Rock", "Art Rock" ], "overall_score": null, "number_of_ratings": 0, "release_date": "1997-05-28", "release_type": "LP", "tracks": [ { "position": 1, "title": "Airbag", "duration": "00:04:47" }, { "position": 2, "title": "Paranoid Android", "duration": "00:06:27" } ], "links": [ { "service_name": "spotify", "url": "https://open.spotify.com/album/6dVIqQ8qmQ5GBnJ9shOYGE?si=L_VNH3HeSMmGBqfiqKiGWA" } ], "aoty": null This serializer is rather massive and I only need this data for Albums details page. I also pull this data in Albums list page where I list all my albums and almost all of this data is not used. If I make another serializer, little less complex and use it in albums list page, will there be a drastic difference in load speed? And if … -
Render a Table in Template with "far" foreign key in Django
I have the need to render a Table in a ListView template in a Django app, but the information to render comes from diferent tables, so far I have the next logic built: model.py class Plan(models.Model): name = models.CharField(...) description = models.CharField(...) type = models.ForeignKey('Type', on_delete=models.CASCADE, null=False) def get_absolute_url(self): return reverse('plans:plans_detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Type(models.Model): client = models.ForeignKey('clients.Client', on_delete=models.CASCADE, null=False) name = models.CharField() levels = models.IntegerField() def get_absolute_url(self): return reverse('plans:type_detail', kwargs={'pk': self.pk}) def __str__(self): return self.name class Levelname(models.Model): plan_type = models.ForeignKey(Type, on_delete=models.CASCADE) level = models.IntegerField() name = models.CharField() strategy_name = models.CharField() class Meta: unique_together = ('plan_type', 'level',) def __str__(self): return self.name class Node(models.Model): parent = models.ForeignKey('self', null=True, blank=True, on_delete=models.CASCADE) plan = models.ForeignKey(Plan, on_delete=models.CASCADE, related_name='nodes') name = models.CharField(max_length=100, null=False) level = models.ForeignKey(LevelName, on_delete=models.CASCADE, related_name='nodes') description = models.CharField(max_length=500, null = True, blank = True) def __str__(self): return self.name For this tables, y created a view that for a created Plan render the associated Node with the next view: class NodeCreateStructure(LoginRequiredMixin, ListView): model = Node def get_queryset(self): ## Prefetch hace el join en el return return Node.objects.filter(plan_id= self.kwargs['plan_pk']).prefetch_related('plan__type') I want to print a Table that shows the Node Structure like this example: I hope it's understandable, thanks so many … -
Django removes my custom html attributes from option tag
I am trying to add custom data-* attributes to the option tag in a select element. I have my custom template (widget) which is used by Django, but it seems like Django removes my custom attributes. somewhere in further steps My custom option template: widgets/tree_option_template.html <option value="{{ widget.attrs.lft|stringformat:'s' }}" data-test="test" >{{ widget.label }} - {{ widget.attrs.rght|stringformat:'s' }}</option> Custom widget: class MultiChoiceFilterWidget(forms.SelectMultiple): """ TODO. Based on FilteredSelectMultiple """ option_inherits_attrs = True option_template_name = "widgets/tree_option_template.html" ... Usage in admin.py: class UserAdminForm(forms.ModelForm): class Meta: model = User fields = "__all__" read_projects = CustomTreeNodeMultipleChoiceField( queryset=Project.objects.filter(disabled=False), required=False, widget=MultiChoiceFilterWidget(verbose_name="Projects", is_stacked=False), ) When I am changing e.g. value attribute then it changes in DOM as well but my custom attributes are not available in HTML: As we can see there is no data-test attribute... Any idea why my custom tags are not visible in HTML? Thanks! -
django - resize images with pil
In my app In the save method I am compressing uploaded images. Now I want to also resize the images if they are very large. I played around with PIL in a test environment and came up with this code that works as expected. from PIL import Image image = Image.open('img.jpg') (w,h) = image.size if (w > 2000): i = image.size # current size (height,width) i = i[0]//2, i[1]//2 # new size image = image.resize(i, Image.ANTIALIAS) image.save('halfresizesssd.jpg') However when I try to merge it into my django project I get this error 'int' object is not subscriptable - i = i[0]//2, i[1]//2 # new size If i understand the error correctly it is because i am passing an int as an array, I dont really understand that because if i try and pass say 2 instead of i i get the same error. I tried to just resize the image and skip the compression but I was still getting the same error def compress(image): im = Image.open(image) # create a BytesIO object im_io = BytesIO() #resize image im = im.convert("RGB") im = im.save(im_io,'JPEG', quality=70, optimize=True) # create a django-friendly Files object new_image = File(im_io, name=image.name) w = new_image.size if (w … -
How to POST image of nasted serializer using postman django APIVIEW
I know how to post image for normal field (using form-data in postman) but I'm stack when I need to post nested serializer contain an image field. Serializer.py looks like: class ProgramSerializer(serializers.ModelSerializer): image=ImageSerializer() class Meta: model = Program exclude = ('create_date') class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image field= ('image','name') views.py : class program_apiView(APIView): def post(self, request): parser_classes = [MultiPartParser,FormParser] serializer = programSerializer(data= request.data) if serializer.is_valid(): serializer.save() return Response( serializer.data, status = status.HTTP_201_CREATED ) -
Chart with date selector in a Django project
I want to create a Javascript chart with a date selector in my Django project like this example: https://plotlydash.com/pie-chart-with-drop-down-list-and-date-picker-range-in-plotly-dash/ I created a date selector input in my chart.html file. This will allow me to append the input date value to URL when I click "generate report". For example: it will append: ?start=2022-02-02&end=2022-02-24 in the URL link. <div class="d-sm-flex align-items-center justify-content-between mb-4"> <form method="get" action="chart/"> <div class="form-row"> <label for="start">Start Date:</label> <div class="col"> <input type="date" class="form-control" name="start_date" min="2020-01-03" required> </div> <label for="end">End Date:</label> <div class="col"> <input type="date" class="form-control" name="start_date" min="2020-01-03" required> </div> <button type="submit" class="btn btn-primary"><i class="fas fa-download fa-sm text-white-50"></i> Generate Report</button> </div> </form> The output of this date selector on my chart.HTML page is: My chart data is based on a list of dictionaries. It's a Django project, so my data is defined in views.py: I count the number of records with Mike, Jane and Jack. mylist= [{'Date': '2021-10-02', 'ID': 11773, 'Receiver': Mike}, {'Date': '2021-10-02', 'ID': 15673, 'Receiver': Jane}, {'Date': '2021-10-03', 'ID': 11773, 'Receiver': Mike}, ... {'Date': '2021-12-25', 'ID': 34653, 'Receiver': Jack}] mike=len(tuple(d for d in mylist if d['Receiver'] == 'Mike')) jane=len(tuple(d for d in mylist if d['Receiver'] == 'Jane')) jack=len(tuple(d for d in mylist if d['Receiver'] == 'Jack')) count = … -
what does [0] mean in django query?
for example when I want to filter a query, why should I write [0] at the end? order_item = OrderItem.objects.filter( item=product, user=self.request.user, ordered=False )[0] when I don't add [0] at the end it raises an error something like that: Field 'id' expected a number but got <QuerySet [<OrderItem: OrderItem object (5)>]>. or in another situation when I don't add [0] at the end, it raises this error: 'QuerySet' object has no attribute 'items' -
Visual Studio Code autoimport extension
I am looking for a solution on a problem I am having in VSCode. In fact, I was using an extension which was making auto - import between models and so on in Django Projects. The thing is, I had to reset my Mac and I forgot which extension that was. It was something that was also able to make all the used imports let's say with a more vivid color on VSCode and also was making all the "unused" variables (the one that were not used in the context in django or other variables) with less vivid colors. This extension also changed the color of the models in Django too, giving all the type of DB entries (like Charfield or Foreign Key) a different color. I know it's a little bit tricky to understand but I tried to find out which extension that was but I really don't remember. Thank you very much for any help -
Connecting to a remote db through a jump server in Django
I'm trying to tunnel my db connection in a django application through a jump server but can't seem to get it working because django manage.py handles & process the connections. here's that I have in the settings.py #process ssh_key first ssh_key= os.getenv('SSH_KEY', '').encode('utf8').decode('unicode_escape') server ={} with sshtunnel.open_tunnel( (os.environ.get('SSH_HOST'),int(os.getenv('SSH_PORT'))), ssh_pkey=paramiko.RSAKey.from_private_key(io.StringIO(ssh_key)), ssh_username= os.environ.get('SSH_USERNAME'), remote_bind_address=(os.environ.get('DB_HOST'), int(os.getenv('DB_PORT'))), ) as ssh_proxy_host: server={ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': os.environ.get('DB_HOST'), 'PORT': ssh_proxy_host.local_bind_port, 'NAME': os.environ.get('DB_NAME'), 'USER': os.environ.get('DB_USER'), 'PASSWORD': os.environ.get('DB_PASS'), } # here's where I should have the connection function to db, but don't know if django has that option available -
How do I write logs to docker container in a Django project?
I am trying to configure my local logger to write the logs to docker container, so I can see the logs in the list displayed by the command docker[-compose] logs <container> --tail 100 In settings.py, I configured LOGGING variable like this: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'default': { 'format': '[DJANGO] %(levelname)s %(asctime)s %(module)s ' '%(name)s.%(funcName)s:%(lineno)s: %(message)s' }, }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'default', } }, 'loggers': { '': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': True, } }, } In the files where I need the loggers, at the beginning, I am writing: import logging logger = logging.getLogger(__name__) Then, in my code where I need it I write: ....... logger.error('something happened') ....... As I configured my logger, the log will be displayed in the console. But my problem is: How can I display it in docker container when I call the aforementioned command ? Example like desired output: ........ web_1 | [2022-02-23 17:37:10 +0200] [9] [INFO] ASGI 'lifespan' protocol appears unsupported. web_1 | [2022-02-23 17:37:10 +0200] [9] [INFO] Application startup complete. web_1 | [2022-02-23 17:37:10 +0200] [10] [INFO] Application startup complete. web_1 | My log somewhere here.. ........ Thank you very much … -
How can I pass True into form if one field is selected and False if another
I have select field in my html <select class="form-select" name="is_recurrent" id="payment"> <option value="False" class="option" selected>One-time fee</option> <option value="True" class="option">Subscription</option> </select> I have model Donate in models.py class Donate(BaseModel): is_recurrent = models.BooleanField(default=False) ... I have form in forms.py class DonateForm(forms.Form): is_recurrent = fields.BooleanField(???) ... How can I pass True into form if subscription is selected and false if one-time fee is selected -
Django + React as ecommerce shop
I have been learning Django and React for some time now. As part of my learning, I've decided to work on building my own store so I don't use Shopper anymore. Can you recommend any ready-made ecommerce framework where I can add React as frontend? -
drf - remove miliseconds from serializers.DateTimeField when sending response
I have to write a serializer that returns datetime in the following formats: 2012-01-01T13:00:00+00:00 (utc_with_timezone) 2020-01-01T09:00:00 (with_out_timezone)but the response that is sent contains miliseconds: 2022-01-01T18:14:05.378897+05:00 class SomeResponse(serializers.Serializer): utc_with_timezone = DateTimeField() with_out_timezone = DateTimeField() How can I manipulate the output format without changing the settings for the whole project?