Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display only days on django template
I'm trying to display the difference between 2 giving dates on django, and i've managed to make it, but now i'm strugling to display only the days, without the time, is there any filter that i can use? My html template: <a href="{% url 'edit_contract' contract.id %}"> {% if contract.status == 'PN' %} {{ today |sub:contract.starting_date }} {% else %} TODO {% endif %} </a> My view: @login_required def contract_list(request): contracts = Contract.objects.filter(user=request.user) total_contracts_value = Contract.objects.filter(user=request.user).aggregate(sum=Sum('value'))['sum'] or 0 contracts_count = Contract.objects.filter(user=request.user).count() today = date.today() return render(request, 'list_contract.html', {'contracts': contracts, 'total_contracts_value': total_contracts_value, 'contracts_count': contracts_count, 'today':today}) My output: -
how to pass multiple optional parameter in Django views.py
I want to know how to write code efficiently when there are multiple if statements in one function in Django views.py. This function is about the stats, there is a table of 6 stats vertically in card format. five and six variable have different values depending on the parameter. def statistic(requests): one = Student.objects.filter(...) two = Teacher.objects.filter(...) three = Subject.objects.filter(...) four = Assignment.objects.filter(...) team_parameter = request.GET.get('team') if team_parameter == 'ALL': five = Student.objects.filter(...) else: five = Student.objects.filter(team=team_parameter, ...) option = request.GET.get('option') from = request.GET.get('from_date') to = request.GET.get('to_date') if option == 'total': six = Subject.objects.filter(...) else: six = Subject.objects.filter(register_date__gte=from, register_date__lte=to, ...) return render(request, 'stats.html', {'one': one, 'two': two, 'three': three, 'four': four, 'five': five, 'six': six}) When entering the statistics page, there is no value of request.GET, and parameters can be set in the drop down list from the 5 or 6 tables. And 'ALL' for table 5 and 'total' for table 6 are set as default values. And when I select another option in table 5 or 6, if the data of the table is changed, the contents of tables 1, 2, 3, and 4 do not disappear and the values should be continuously output. I don't know how to … -
Django with django_plotly_dash register admin panel
In my project django using dash, in panel admin is registered DJANGO PLOTLY DASH(image attachment),but I want to remove this. I don't have idea how do this. enter image description here -
django.db.utils.OperationalError: (1045, 'Plugin caching_sha2_password could not be
I'm trying to containerize my Django app with mysql and I get the following error when I try to run docker-compose up --build. Successfully tagged drosmokers_web:latest [+] Running 3/2 ⠿ Network drosmokers_default Created 0.1s ⠿ Container drosmokers-db-1 Created 0.3s ⠿ Container drosmokers-web-1 Created 0.1s Attaching to drosmokers-db-1, drosmokers-web-1 drosmokers-db-1 | 2022-05-19 02:09:40+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started. drosmokers-db-1 | 2022-05-19 02:09:40+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' drosmokers-db-1 | 2022-05-19 02:09:40+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.28-1debian10 started. drosmokers-db-1 | 2022-05-19T02:09:40.450429Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.28) starting as process 1 drosmokers-db-1 | 2022-05-19T02:09:40.459416Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. drosmokers-db-1 | 2022-05-19T02:09:40.971548Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. drosmokers-db-1 | 2022-05-19T02:09:41.218218Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. drosmokers-db-1 | 2022-05-19T02:09:41.218279Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. drosmokers-db-1 | 2022-05-19T02:09:41.229850Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. drosmokers-db-1 | 2022-05-19T02:09:41.261835Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.28' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL … -
highlight.js not working on django website
I have a django website where I'd like to display blocks of code w/ syntax highlighting. I've installed highlight.js and per their instructions am injecting style and js into html, in this case in base.html: ... <link rel="stylesheet" href="{% static 'highlight/styles/default.min.css' %}"> <script src="{% static 'highlight/highlight.min.js' %}"></script> <script>hljs.highlightAll();</script> I then add code to some view using dash html components: ... html.Div([html.H3(title), html.Pre(html.Code(code, className=f'language-{lang}'))]) The code isnt't syntax highlighted. Not sure how to troubleshoot this. -
ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed
Does anyone know how to solve this error? ValueError: The field socialaccount.SocialAccount.user was declared with a lazy reference to 'auth.user', but app 'auth' isn't installed. -
Error making mutations for a many to many relation with graphene-django
I'm trying to make something with graphene-django but I'm having some issues with the many to many relations, I'm trying to create a relation between roles and permissions, according the documentation and some tutorials everything is "OK" with the code but when I open the graphql console to make a mutation for the intermediate table there's an error so, it's not completely "OK". This is how my code looks like Models: class Roles(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=500) def __str__(self): return self.name class Permissions(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=500) def __str__(self): return self.name class RolePermissions(models.Model): role = models.ForeignKey(Roles, on_delete=models.DO_NOTHING) permission = models.ForeignKey(Permissions, on_delete=models.DO_NOTHING) def __str__(self): return True Types: class RolesInput(graphene.InputObjectType): id = graphene.ID() name = graphene.String() description = graphene.String() class PermissionsInput(graphene.InputObjectType): id = graphene.ID() name = graphene.String() description = graphene.String() class Role_PermissionsInput(graphene.InputObjectType): id = graphene.ID() roleId = graphene.ID() permissionId = graphene.ID() Mutation class CreateRolePermission(graphene.Mutation): class Arguments: role_permission_data = Role_PermissionsInput(required=True) role_permission = graphene.Field(RolePermissionsType) @staticmethod def mutate(root, info, role_permission_data=None): role_permission_instance = RolePermissions( role =role_permission_data.roleId, permission=role_permission_data.permissionId, ) role_permission_instance.save() return CreateRolePermission(role_permission=role_permission_instance) I already have data into the DB to test the querys and everything is good and I can create both roles and permissions individually, but the relation between is having a … -
Django model rendering number instead of string
I'm creating a blog site with authors posting blogs, etc. The issue is with rendering the author's name, instead django is returning a number. My blog model: class Blog(models.Model): title=models.CharField(max_length=255) author=models.ForeignKey(User, on_delete=models.CASCADE) date_posted=models.DateTimeField(auto_now_add=True) body=models.TextField() def __str__(self): return self.title And my serializer: class Meta: model=Blog fields=('title', 'author', 'body', 'date_posted') However, in django rest framework it's rendering a number, when it should be the 'admin' user: [ { "title": "First Blog", "author": 1, "body": "Example blog text", "date_posted": "2022-05-18T23:55:21.529755Z" } ] A bit confused, since there's no error, it just isn't rendering 'admin'. Any help would help thanks. -
Doble initialization on django-bootstrap-modal-forms
I currently using this library on django https://github.com/trco/django-bootstrap-modal-forms I got this on my js script: function initializeBSModal(modalId) { const Modal = $(modalId); Modal.modalForm({ modalID: '#bs-modal', modalContent: '#bs-modal-content', modalForm: '#bs-modal-content form', formURL: Modal.data('form-url'), }); } Each time it is used it initialized correctly, but if in any instance it is called twice (e.g draw event on table), it initialized a second time, executing twice or more times on requesting GET to the View (only GET not on POST) Code example: {% block content %} <div id="bs-modal-create" class="" data-form-url="{% url 'create_item' %}"> CREATE </div> {% endblock %} {% block scripts %} <script> initializeBSModal('#bs-modal-create'); initializeBSModal('#bs-modal-create'); -> This causes 2 initialization, 2nd GET </script> {% endblock %} How may i only initialize not initialized modals?? -
how can I make python work in pycharm again
I was using Pycharm properly before, So I needed to install anaconda. Whilst trying to install anaconda, I had to delete all files or traces of my python for anaconda to be installed properly. Please how to get back to using Pycharm properly as I was before including continuing my Django project. because everywhere is just messed up. I don't know what to do or start from -
MDN Django TypeError: 'NoneType' object is not callable
In the code below, I have a book model, and I am trying to register that model along with the List Display with a decorator. Unfortunately, I am getting an error listed below, saying there is a TypeError with my Model List Display Class, where NonType object is not callable. I have looked into solutions, but haven't found any, so it would be nice to get some help. I am following MDN tutorial BTW, https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Admin_site. Thank you for helping! Book Model class Book(models.Model): title = models.CharField(max_length=200) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) summary = models.TextField(max_length=1000, help_text='Enter a brief description of the book') isbn = models.CharField('ISBN', max_length=13, unique=True, help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn' '">ISBN number</a>') genre = models.ManyToManyField(Genre, help_text='Select a genre for this book') def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' Book Model in Admin with List Display @admin.site.register(Book) class BookAdmin(admin.ModelAdmin): list_display = ('title', 'author', 'display_genre') Error class BookAdmin(admin.ModelAdmin): TypeError: 'NoneType' object is not callable -
Why am I getting a type error between two integers
I am trying to make the shopping cart of an e-commerce store and I've modelled the database and everything but I keep on getting a type error. Storefront/Models.py/Product from django.db import models class Product(models.Model): name = models.CharField(max_length=200) slug = models.SlugField(max_length=200) price = models.DecimalFiled(max_digits=10, decimal_places=2) quantity= models.IntegerField(default=1) def __str__(self): return self.name Now I'm working on the shopping cart view to take quantity from users and to check if it is more than available goods. Cart/views.py (jumping some codes) from Storefront.models import Product try: quantity=int(request.data['quantity']) if quantity > Product.quantity: raise NotAcceptable('quantity more than available in stock') The error code I'm getting is: TypeError: '>' not supported between instances of 'int' and 'DeferredAttribute' The quantity being inputed is being converted to an integer and Product.quantity is an integerfield so what am I doing wrong? -
Overriding .update() and getting "... fields with this <name> already exists" after adding lookup_field
I'm having to override .create() and .update() in my serializer due to having a nested relationship crmfields. I'm extending the User model and adding some fields in from our CRM system that sync over via Webhooks. Basically if a user is created/updated there, it syncs them over to the web application. My POST looks like the following: { "username": "test@test.com", "first_name": "Test First", "last_name": "Test Last", "email": "test@test.com", "is_active": true, "crmfields": { "guid": "00000000-0000-0000-0000-000000000001" } } This creates the user and corresponding crmfields record at roughly the same time. The issue I'm running into is with PUT and doing something like the following: { "username": "test@test3.com", "first_name": "Test First1", "last_name": "Test Last2", "email": "test@test1.com", "is_active": true, "crmfields": { "guid": "00000000-0000-0000-0000-000000000001" } } This returns a response of: { "crmfields": { "guid": [ "crm fields with this guid already exists." ] } } It doesn't look like it gets to my custom .update() method in the serializer before this error triggered. I had this working several months ago. Since then I've added lookup_field to the views.py because we decided we wanted to use the guid in the crmfields as the lookup (e.g. /api/users/00000000-0000-0000-0000-000000000001/)and not the pk in the Users model. There … -
Static CSS files not updating/loading in Django project
Problem: None of the changes I'm making to my CSS files are being applied to my HTML pages. So I tried to clear the cache and now my site says it can't find my static files. Exact error when I inspect my page in developer mode "GET http://127.0.0.1:8000/static/css/style.css%3F net::ERR_ABORTED 404 (Not Found)" Background: I'm creating a basic image editing site using django, html/css, and injecting JS to apply some filters to images. Previously I was able to make changes and they were reflected, but now whenver I try and make any html/css files none of the css gets linked nor are changes being applied. Things I've tried: Gone into settings cleared browser cache Disabled caching in developer mode appended the version of css file ?v1.1 to force a rest (caused the 404 error from above) Run collectstatic in terminal Cleared cache opened site in private window Watched several youtube vids on setting up static file dir and I think its correct. At some point in time my css was loading and updating as I made changes. Directory Layout These are my settings Settings.py BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Image_API', 'rest_framework', … -
How to delete an object using javascript in django
I want to do the delete operation by javascript with a confirmation window. How to do it? <div class="card-footer"> <a href="{% url 'course_delete' student.slug %}"><button>Delete</button></a> </div> -
How to specify uvicorn workers in gunicorn conf file
I run Django app with gunicorn using: gunicorn -c gunicorn.conf.py config.wsgi ## gunicorn.conf.py: from os import environ bind = '0.0.0.0:' + environ.get('PORT', '8000') workers = environ.get('WORKERS', 8) loglevel = 'info' graceful_timeout = 300 Now I run it with gunicorn + uvicorn gunicorn -c gunicorn.conf.py config.asgi -k uvicorn.workers.UvicornWorker and I want the add the -k uvicorn.workers.UvicornWorker to the gunicorn.conf.py -
Django: populating many to many field using modelformset_factory
I try to populate a many-to-many field. The Relationship exists between the Menus and Course Model. I added some custom fields to the M2M Table, so I can store the order of the courses and their type (i.e. Starter, Appetizer, etc.). To get a dynamic webform, I use modelformset_factory with the python-formset-js-improved pip package (https://pypi.org/project/django-formset-js-improved/). following the logic in my views.py, explained here Populate a ManyToManyField, I run into the following error. This error applies to all keyword arguments. menu.menu_item.add(course_position=position, course_type=menu_item_form['course_type'], course=course) TypeError: add() got an unexpected keyword argument 'course_position' What did I get wrong? below are extracts from models.py, forms.py, views.py and the html file models.py class Course(models.Model): # Individual name of a course (i.e. "Natschis Spezial Fondue") creator = models.ForeignKey(User, related_name='creator_id_course', on_delete=models.PROTECT) course_name = models.CharField(max_length=100) course_description = models.CharField(max_length=1000) course_price = models.DecimalField(max_digits=7, decimal_places=2, null=True) course_tags = models.ManyToManyField(CourseTag) private = models.BooleanField(default=False, verbose_name=_('private item')) active = models.BooleanField(default=True) deleted = models.BooleanField(default=False) objects = CourseManager() def __str__(self): return self.course_name class Menu(models.Model): class Status(models.TextChoices): ACTIVE = 'a', _('active') SUSPENDED = 's', _('suspended') DELETED = 'd', _('deleted') # assemble a menu from different courses --> "Movie" creator = models.ForeignKey(User, related_name='creator_id_menu', on_delete=models.PROTECT) menu_name = models.CharField(max_length=100, default='', verbose_name=_('Menu Name'), help_text=_('i.e. saturday night fajita night')) menu_description = models.TextField(max_length=1000, … -
add remember me option in login page in django
I have a piece of code in which I defined (remember me) in, but it does not work properly. Where do you think my problem could be? def login(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') remember_me = request.POST.get('remeber_me') user = auth.authenticate(username=username, password=password) if user: auth.login(request, user) if not remember_me: request.session.set_expiry(0) else: request.session.set_expiry(1209600) return redirect('/') messages.info(request, 'Credentials invalid') return redirect('login') return render(request, 'login.html') -
Django: Redirect from FormView to DetailsView upon submitting the form
Relevant FormView: class addrecipe(FormView): form_class = AddRecipeForm model = Recipe template_name = 'recipebook/addrecipe.html' fields = '__all__' extra_context = { 'recipe_list': Recipe.objects.all() } Relevant Form: class AddRecipeForm(forms.ModelForm): name = forms.CharField(max_length="50", label="Recipe Name") description = forms.Textarea(attrs={'class': 'desc-text-area'}) servings = forms.IntegerField() tools = forms.ModelMultipleChoiceField(queryset=Tool.objects.all(), widget=forms.CheckboxSelectMultiple, required = True, help_text="Select all relevant tools") class Meta: model = Recipe fields = ("__all__") URL pattern for the details view page: path('<int:pk>/recipedetails', views.recipedetails.as_view(), name='recipe_details'), I want to have the user submit the form, then be taken to the details page of the entry they just made into the database. I've tried doing this using reverse/reverse_lazy with a success url but that hasn't been successful. I also tried adding the following to my form view class: def form_valid(self, form): test_recipe = Recipe.save() return redirect('recipe_details', pk=test_recipe.pk) -
Which is the best way on AWS to set up a CI/CD of a Django app from GitHub?
I have a Django Web Application which is not too large and uses the default database that comes with Django. It doesn't have a large volume of requests either. Just may not be more than 100 requests per second. I wanted to figure out a method of continuous deployment on AWS from my source code residing in GitHub. I don't want to use EBCLI to deploy to Elastic Beanstalk coz it needs commands in the command line and is not automated deployment. I had tried setting up workflows for my app in GitHub Actions and had set up a web server environment in EB too. But it ddn't seem to work. Also, I couldn't figure out the final url to see my app from that EB environment. I am working on a Windows machine. Please suggest the least expensive way of doing this or share any videos/ articles you may hae which will get me to my app being finally visible on the browser after deployment. Thank you in advance! -
am new with django ckeditor the embed plugin failed to fetch given a url
this is my ckeditor cofigs CKEDITOR_CONFIGS = { 'special': { 'toolbar': 'Special', 'width': 'auto', 'toolbar_Special': [ ["Format", "Bold", "Italic", "Underline", "Strike", "SpellChecker"], ['NumberedList', 'BulletedList', "Indent", "Outdent", 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock'], ["Image", "Table", "Link", "Unlink", "Anchor", "SectionLink", "Embed"], ['Undo', 'Redo'], ["CodeSnippet"], ["Maximize"] ], # Remove these dialog tabs (semicolon separated dialog:tab) 'removeDialogTabs': ';'.join([ 'image:advanced', 'image:Link', 'link:upload', 'table:advanced', #'tableProperties:advanced', ]), # Extra plugins to be used in the editor 'extraPlugins': ','.join([ 'mathjax', # Used to render mathematical formulae 'codesnippet', # Used to add code snippets 'image2', # Loads new and better image dialog 'embed', # Used for embedding media (YouTube/Slideshare etc) 'tableresize', # Used to allow resizing of columns in tables ]), } } the error message is there anything am missing -
Djangochannelsrestframework doesn't work like in documentation
I'm trying to create websocket connection with djangochannelsrestframework. I tried all like in documentation and I got this error "django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet." https://djangochannelsrestframework.readthedocs.io/ This is my github repository to chek code https://github.com/muradoff101/igroteka/tree/master -
Saving a file from FileResponse in Django
How to save file in FileField from FileResponse in Django. I have the simplest PDF function to create PDF file in Django (according to the documentation). import io from django.http import FileResponse from reportlab.pdfgen import canvas def some_view(request): # Create a file-like buffer to receive PDF data. buffer = io.BytesIO() # Create the PDF object, using the buffer as its "file." p = canvas.Canvas(buffer) # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. p.drawString(100, 100, "Hello world.") # Close the PDF object cleanly, and we're done. p.showPage() p.save() # FileResponse sets the Content-Disposition header so that browsers # present the option to save the file. buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename='hello.pdf') It returns PDF. But how to save this PDF in FileField? I need something like this: Models.py class FileModel(models.Model): file = models.FileField() Views.py def some_view(request): [...same code as above to line buffer.seek(0)...] obj = FileModel() obj.file = FileResponse(buffer, as_attachment=True, filename='hello.pdf') obj.save() -
Django can't set attribute while changing media file url
I'm creating a function where I want the directory of the file changes if the image_type changes, for example if the image_type is aerial_view it should be in 1 folder and it if it is detailed_view it should move to another. The file is able to move succesfully, however I'm facing can't set attribute while changing url of the image. I'm not sure if this is the best way to change folder of a MEDIA file, I'd like suggestions if there's a better way. def post(self, request): image_ids = dict((request.data).lists())['image_id'] image_types = dict((request.data).lists())['image_type'] arr = [] for img_id, img_type in zip(image_ids, image_types): image_qs = RoofImages.objects.get(id=img_id) image_qs.image_type = img_type print(BASE_DIR) try: if image_qs.image_type == 'detailed_view': full_image_url = f'{BASE_DIR}{image_qs.image.url}' full_new_image_url = full_image_url.replace('aerial_view', 'detailed_view') shutil.move(full_image_url, full_new_image_url) image_qs.image.url = str(image_qs.image.url).replace('aerial_view', 'detailed_view') except Exception as e: print(e) try: if image_qs.image_type == 'aerial_view': full_image_url = f'{BASE_DIR}{image_qs.image.url}' full_new_image_url = full_image_url.replace('detailed_view', 'aerial_view') shutil.move(full_image_url, full_new_image_url) image_qs.image.url = str(image_qs.image.url).replace('detailed_view', 'aerial_view') except Exception as e: print(e) arr.append({img_id: img_type}) image_qs.save() response_content = { 'status': True, 'message': 'Images type change successfully.', 'result': arr } return Response(response_content, status=status.HTTP_201_CREATED) -
Did not create model for user table. is it mandatory for order table?
I'm a newbie in django and doing my very first food delivery website. I've not created any model for user auth table but created model for my menu table. now i want to create a model for order table where i want to keep both menu id and user id as foreign key.. is it possible any way or i must create a model for user table also?