Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Materialize css sidenav not working in django
I am trying to create a navbar and sidenav from materialize css in django. Created three main html files with the name of mbase.html, navbar.html and sidenav.html. below are the codes respectively. mbase.html: {%load materializecss %} {% load static %} <!DOCTYPE html> <html> <head> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!-- Compiled and minified CSS --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css"> <!--custom css for materialize--> <link rel="stylesheet" type="text/css" href= {% static 'css/style.css' %}> <!--Let browser know website is optimized for mobile--> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <!--Title of the page goes here--> <title>{% block title %}Hello World {% endblock title %}</title> </head> <body> {% include 'navbar.html' %} {% block body %} {% endblock body %} <!--Jquery optional--> <script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script> <!-- Compiled and minified JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script> <script type="text/javascript" src={% static 'js/main.js' %}></script> </body> </html> navbar.html: {% load static %} <nav> <div class="nav-wrapper"> <a href="#" data-target="slide-out" class="sidenav-trigger left show-on-large"><i class="material-icons">menu</i></a> <a href="{% url 'index' %}" class="brand-logo center">CMMS</a> <ul class="right hide-on-med-and-down"> <!-- Dropdown Trigger for userprofile --> {% if request.user.is_authenticated %} <li><a id="userdropdown" class="dropdown-trigger" href="#!" data-target="dropdown2" >Hello, {{ request.user.email }}<i class="material-icons right">arrow_drop_down</i></a></li> {% else %} <li><a href="{% url 'login' %}">Login</a></li> | <li><a href="{% url 'registration' %}">Registration</a></li> {% endif %} <li><a … -
ValueError: Unable to configure handler 'errors_file': [Errno 2] No such file or directory: '/log/ErrorLoggers.log'
I'm trying to deploy django project in AWS EC2. When I run my apache server error.log file contains this. I don't know what I'm missing. Can't find file log/ErrorLogger.log. [Wed Sep 02 08:50:20.751531 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] mod_wsgi (pid=18839): Target WSGI script '/home/ubuntu/django/pims/pims/wsgi.py' cannot be loaded as Python module. [Wed Sep 02 08:50:20.751588 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] mod_wsgi (pid=18839): Exception occurred processing WSGI script '/home/ubuntu/django/pims/pims/wsgi.py'. [Wed Sep 02 08:50:20.751761 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] Traceback (most recent call last): [Wed Sep 02 08:50:20.751802 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/config.py", line 565, in configure [Wed Sep 02 08:50:20.751808 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] handler = self.configure_handler(handlers[name]) [Wed Sep 02 08:50:20.751815 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/config.py", line 738, in configure_handler [Wed Sep 02 08:50:20.751819 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] result = factory(**kwargs) [Wed Sep 02 08:50:20.751826 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/handlers.py", line 202, in __init__ [Wed Sep 02 08:50:20.751830 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] BaseRotatingHandler.__init__(self, filename, 'a', encoding, delay) [Wed Sep 02 08:50:20.751843 2020] [wsgi:error] [pid 18839:tid 140404483544832] [remote 122.176.187.97:54622] File "/usr/lib/python3.6/logging/handlers.py", line 57, in __init__ [Wed … -
How to upload multiple files in django Generic Model
I've two models, one is normal model and one is generic model as below. class Gallery(models.Model): name = models.CharField(max_length=255) slug = models.SlugField() and the another one is class GenericImage(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') image = models.ImageField(upload_to="category_images", null=True, blank=True) Now how can i upload multiple image. i tried this one https://xn--w5d.cc/2019/09/18/minimalistic-multiupload-in-django-admin.html but this is only valid for foreign table. I know i can use foreign table to store images. But i did'n't to create multiple table to store photo for multiple tables. -
Is there a way to "link" external domains to my django app?
I'm developing a Django webapp in wich I want to let my users to link an external domain, for example https://mywebstore1.com so whenever someone introduces that url in the browser, what it shows is the content that I show in for example: https://myapp.com/user-store. My knowledge in the hole domains thing is very limited so any help is much appreciated. -
can FormMixin be used in TemplateView?
Hi i've used FormMixin in DetailView but I would also like to implement it in TemplateView if that isn't possible how can I implement a form in TemplateView -
Is there a way to serialize multiple objects in Django?
In a Django Project I would like to implement a simple chat-box. Version Django version 3.0.8 Models.py class DirectMessageClass(models.Model): sender = models.ForeignKey(User, on_delete=models.CASCADE, related_name='from_this') receiver = models.ForeignKey(User, on_delete=models.CASCADE, related_name='to_this') timestamp = models.DateTimeField(auto_now=True) content = models.CharField(max_length=200) read = models.BooleanField(default=False) def serialize(self): return { "id": self.id, "sender": self.sender.username, "sendername":self.sender.profile.firstname, "senderimage":self.sender.profile.image.url, "receiver": self.receiver.username, "content": self.content, "timestamp":self.timestamp.strftime("%m/%d/%Y, %H:%M:%S"), # to format date "read":self.read, } Views.py def loadbox(request): user = request.user # Return messages in reverse chronologial order messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all() return JsonResponse([message.serialize() for message in messages], safe=False) I successfully get messages and turn it into a JSON object in the /loadbox path with this method. Later on, I fetch this data to display messages and it works. Example of my /loadbox path [{"id": 1, "sender": "ekvatorcizgisi", "sendername": "Asli", "receiver": "bilge", "content": "hi", "timestamp": "09/02/2020, 08:22:26", "read": true}] However, because I want it to display as a dialog. I need to add also the reply messages in this JSON object. In views.py I try def loadbox(request): user = request.user # Return messages in reverse chronologial order messages = DirectMessageClass.objects.filter(receiver=user).order_by("-timestamp").all() # return replies sent by the current user replies = DirectMessageClass.objects.filter(sender=user).order_by("-timestamp").all() return JsonResponse([message.serialize() for message in messages], safe=False) I am not sure how to return multiple … -
Django Python - Variable seems to be getting cached?
Within my Django app I obtain a list of projects within our Google Cloud Organisation with the following: try: global projectdicts projectdicts = cloudresmanv1.projects().list().execute() projectdicts = projectdicts.get('projects') except Exception as e: logging.error(e) The above is taken from a Django form called ProjectForm. However, after I've created a GCP project and browse within my Django app to the ProjectForm page again, the list doesn't update to show the newly-created project. My understanding is that it should run the above again, regardless. If I run through the script manually, the projectdicts variable of course updates. So, this leads me to believe for some reason the Django app or Python is caching the variable and not bothering to run the above again. Is this a likely problem? And if so, how do I force Django/Python to re-run this part of the script again to ensure the list of GCP projects is updated whenever I browse to the ProjectForm page? -
how to import modules in python/django correctly?
Started learning Python recently and had a problem importing a model into django. I am trying to import a product model into Telegram bot handler but an error occurs. Below is how my directory structure looks like: structure.png Code: from jangoMiniShop.products.models import Product Error: ModuleNotFoundError: No module named 'jangoMiniShop' Code: from ..products.models import Product Error: ImportError: attempted relative import with no known parent package -
Error Running WSGI application - client_secrets.json
I´m making a web app with django, but when I run the application, I´m getting this error: I have uploaded my client_secrets.json file in the project path and I´m sure I have no typos Settings.py GOOGLE_OAUTH2_CLIENT_SECRETS_JSON = 'client_secrets.json' WSGI.py # This file contains the WSGI configuration required to serve up your # web application at http://bohosul02.pythonanywhere.com/ # It works by setting the variable 'application' to a WSGI handler of some # description. # # The below has been auto-generated for your Django project import os import sys # add your project directory to the sys.path project_home = '/home/bohosul02/misitio' if project_home not in sys.path: sys.path.insert(0, project_home) # set environment variable to tell django where your settings.py is os.environ['DJANGO_SETTINGS_MODULE'] = 'gfglogin.settings' # serve django via WSGI from django.core.wsgi import get_wsgi_application application = get_wsgi_application() -
Why is the JQuery not working? (Djangoapp)
I have a html file that displays a weekly calendar, which works fine in my app. {% extends 'blockit/base.html' %} {% load static %} {% block head %} <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="shortcut icon" href="{% static 'img/favicon.png' %}"/> <link rel="stylesheet" type="text/css" media="screen" href="{% static "css/main.css" %}" /> <title>BlockIt - My Calendar</title> {% endblock %} {% block content %} <div class="row"> <div class="row"> <button id="back" class="col-md-3" align="left" onclick=location.href='?n={{ way.0 }}'>Last Week</span> </button> <div align="center"> <strong class="col-md-6" id="year">{{ week.0 }} - {{ week.6 }} - {{ year }}</strong> </div> <button class="col-md-3" align="left" onclick=location.href='?n={{ way.1 }}'>Next Week</span> </button> </div> {% load filters %} <div class="table-responsive" align="center"> <div class="col-md-12"> <table id="calendar" class="table"> <tr> <th></th> {% for day in week %} <th>{{day}}</th> {% endfor %} </tr> {% for i in range24 %} <tr> <th>{{i}}:00</th> {% for j in range7 %} {# id is time-day for example 8-17 it means 17th day of month and time is 8 #} <td id={{i}}-{{week|lookup:j|slice:"0:2"}}></td> {% endfor %} </tr> {% endfor %} </table> </div> </div> </div> {% endblock content %} {% block script %} <script type="text/javascript"> String.prototype.format = function() { var str = this; for (var i = 0; i < arguments.length; i++) { var reg … -
How to set validation for password in django admin Interface
In my Django admin interface when i click on change password. then i have 3 fields old password, new password and new password confirmation. So when i type old password and also type the new password same as old password it is being changed. But instead it should give error whenever in the new password field i write old password that "Create a new password that isn't your current password". Please let me know how to fix this. Forms.py from django.contrib.auth.password_validation import validate_password class ClientUserForm(forms.ModelForm): email = forms.EmailField(max_length=100, required=False) username = forms.CharField(max_length=100, required=True) password = forms.CharField( required=True, widget=forms.PasswordInput(), validators=[validate_password]) permissions = forms.MultipleChoiceField(choices=CLIENT_USER_PER_CHOICES) client = forms.ModelChoiceField(queryset=get_user_model().objects.filter( is_superuser=False, is_staff=True, client__isnull=True)) # permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all()) -
needs to fetch data from two tables. with one view function in django
def index(request): jobvacancylist = User.objects.all() return render(request, 'index.html', {"User":jobvacancylist}) candidatelist = applyjobsUser.objects.all() return render(request, 'index.html', {"applyjobsUser":candidatelist}) -
django prefetch_related for list of instances
I was wondering if it is possible to prefetch related fields for already instantiated django objects. for example let's say I have a group of instance of MyModel which I got from different sources (so I couldn't prefetch related the queryset at the first place) and I want to access related fields. I want to prefetch the fields for my list of objects in only 1 DB call. Is there an elegant way to populate my instance prefetch cache? I was imagining something like prefetch_related(list_of_instances, [field1, field2, field3]) -
Call simple function with Route Python Django
Its a simple question, but I want to understand it. I have a simple api rest in django rest framework router = routers.DefaultRouter() router.register(r'productos', ChelaViewSet) That gives me my data json from my model, it's working fine. Class ChelaViewSet: class ChelaViewSet(viewsets.ModelViewSet): serializer_class = ChelaSerializer queryset = Chela.objects.all() I just want to call a class with simple function like "hello world" from my route, when I put the URL print "Hello world" in console, no more, without queryset etc... What can I do? Ty -
Django DIRS issue
I am learning Django doc. It says , that i have to fill DIRS in INSTALLED_APP: 'DIRS': [BASE_DIR / 'templates'] That templates located in project/templates as they say. And now i somehow getting an error: ...File "D:\KoronaTime\DjangoPython\FirstProject\mysite\mysite\settings.py", line 58, in <module> 'DIRS': [BASE_DIR/ 'templates'], TypeError: unsupported operand type(s) for /: 'str' and 'str' Am I missing something? -
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 223: ordinal not in range(128)
I am trying to execute a read file command from command line inside a container in k8s for a django app but i get this error. I am able to execute the same command locally but not inside k8s. My complete error stack is as follows: raceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/code/setup/management/commands/load.py", line 40, in handle raw = file.read() File "/usr/lib/python3.6/encodings/ascii.py", line 26, in decode return codecs.ascii_decode(input, self.errors)[0] UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 223: ordinal not in range(128) -
how to conditionally validate Django
how can you check the correctness of data entry through the validation method Let's say I want to register a person to the master, you cannot register if he already has a person for this time. How can this be done via def validate_work_on (self, value): serializer class SerializerCreateServiceCreate(serializers.ModelSerializer): work_on = serializers.models.CharField(choices=Service.worked_hours) time_to_work = {} class Meta: model = Service fields = '__all__' read_only_fields = ('client_to_job',) def create(self, validated_data): return Service.objects.create( name_master=validated_data.get('name_master'), client_to_job=self.context['request'].user, work_on=validated_data.get('work_on') ) **def validate_work_on(self, value): if value in Service.worked_hours: raise serializers.ValidationError("выберите другое время") return value** class SerializerServiceCreate(SerializerCreateServiceCreate): name_master = SerializerMasters() client_to_job = UserSerializerView() model Service class Service(models.Model): worked_hours = ( ('1', '10:00'), ('2', '11:00'), ('3', '12:00'), ('4', '13:00'), ('5', '14:00'), ('6', '15:00'), ('7', '16:00'), ('8', '17:00'), ('9', '18:00'), ('10', '19:00'), ('11', '20:00'), ) name_master = models.ForeignKey(Masters, verbose_name='Мастер', on_delete=models.CASCADE) client_to_job = models.ForeignKey(User, verbose_name='Клиент', on_delete=models.CASCADE) work_on = models.CharField(verbose_name='Рабочие часы', choices=worked_hours, max_length=30) class Meta: verbose_name = 'Сервис' verbose_name_plural = 'Сервисы' and class api view class ServiceCreateView(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = SerializerCreateServiceCreate def get_object(self): return self.request.user how one can validate against this condition, I don’t understand -
Django - Add Status 'Read' to messages
I have a django model Message which has sender, recipient, sent_at and a M2MField read. In the template when user Bob clicks on user Jane, their messages are loaded in and a view with the recipient's name (Jane) gets called to filters down Bob's messages and add Bob to Jane's message' read field. It works for the first 2 messages: Bob sends a message, Jane clicks on user Bob, Jane gets added to Bob's message' read field. Jane sends a message, Bob clicks on user Jane, Bob gets added to Jane's message' read field. But after the first message from Bob and the first from Jane it stops working. Here is the view: class ReadMXApiView(APIView): def get(self, request, format=None, *args, **kwargs): sender_ = self.kwargs['username'] myself = request.user my_mex = Message.objects.filter(recipient__username=request.user).filter(sender__username=sender_) if my_mex.exists(): if myself in my_mex.latest('sent_at').read.all(): return Response('No new messages from '+sender_) else: for m in my_mex: m.read.add(myself) return Response('I read the messages') return Response('No messages from '+sender_) Thank you for any suggestions -
How to add plain text to show up in my template using css?
I want to add plain text inbetween my CharFields or TextAreas that I created using Django and Css. I do not want to add the code in my template file but in my forms.py file. The final result should be like this: "I would pay _____ for this". Here, I can either include the first part of the sentence in the "label" of my CharField or I can include it in my FieldSet using "<h5..."etc. However, if I want to include the second part of the sentence which is "for this", it doesnt show up when I use the same structure with "<h5 .."etc. And I cant include another label. Does someone have an idea how to just simply add plain text (coded in my forms.py) inbetween my survey? Thanks a lot! Example how it looks now and should look forms.py class SurveyPolicy(forms.Form): policy6a = forms.CharField( # required=False, label='', widget = forms.Textarea(attrs={'rows':1}) ) policy6b = forms.IntegerField( # required=False, label='', widget=forms.NumberInput() ) def __init__(self, *args, **kwargs): super(SurveyPolicy, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_id = 'survey-form' self.helper.label_class = 'col-lg-12' self.helper.field_class = 'col-lg-12' self.helper.layout = Layout( Fieldset( "<hr><h5 style='color: #2D2D2D; text-align: center; font-family: Roboto;'>I would pay ...</h5>", Div('policy6a', css_class='form-group row-ml-0 mb-0'), Div('policy6b', css_class='form-group … -
Django Serializing of ValueQuerySet
So I got the following ValueQuerySet records = Maintenance.objects.values('failure').annotate(fcount=Count('failure')) Out[13]: <QuerySet [{'failure': 'Bend Pin', 'fcount': 2}, {'failure': 'Winding Failure', 'fcount': 2}, {'failure': 'Degraded Capacitor', 'fcount': 2}]> I tried serializing this with Django's serializer; from django.core import serializers serializers.serialize('json', records, fields('failure', 'fcount')) AttributeError: 'dict' object has no attribute '_meta' I know I can serialize the records with json.dumps, but I want to understand why Django's serializer gives me this error. I'm running on Python 3.8.2. and Django 3.0.5. -
How to make a `INSERT INTO` sql query for django postgres JSONField?
Consider a model: from django.db import models from django.contrib.postgres.fields import JSONField class A(models.Model): field_A = JSONField(null=True) I want to write a INSERT INTO query for this table to add values rather than using the django ORM wrapper. I tried the following: from django.db import connection cur=connection.cursor() query = "INSERT INTO A VALUES ({'a':1,'b':2})" cur.execute(query) The above line throws me an error saying invalid while pointing at the start of the json object. Looking for the help of someone who can suggest me the best way to do this using SQL? -
python - django upgrade. rest_framework.response.Response not serializing data
I am upgrading my project from django 1.8.18 to 1.11.29. After changing dependencies in requirements.txt file below piece of code is not working as expected. I have tried to debug this but couldn't get any further. Issue I am facing is that Response(serializer.data) is not converting ReturnList to dict as was doing earlier. Is there anything else that needs to be updated? Output with django 1.8.18: {"msg": "Batty1",} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "st data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} {"msg": "r data"} {"count": 1, "previous": null, "results": [{"session_id": "16a635d0-0f7a-4366-b648-a907ea4f4692"}]} {"msg": "t data"} {"msg": "<type 'dict'>"} Output with django 1.11.29: {"msg": "Batty1",} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "st data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} {"msg": "r data"} {"msg": "[OrderedDict([('session_id', '16a635d0-0f7a-4366-b648-a907ea4f4692')])]"} {"msg": "t data"} {"msg": "<class 'rest_framework.utils.serializer_helpers.ReturnList'>"} Versions changed are: -
How to disable autofocus from username field in Django's UserCreationForm?
I am using the UserCreationForm class to create a signup page in my Django app. Here is my code that defines the form: class SignUpForm(UserCreationForm): email = ... username = forms.CharField(label="Username", widget=forms.TextInput(attrs={ ... "autofocus": False, ... })) password1 = ... password2 = ... Despite the autofocus attribute being set to False, when I open the form in my browser the focus is still on the username field. How can I disable it? -
How to indicate to a specific version of database? [Django] [PostgreSQL]
I using django version 3.0.2. I'd like to use postgreSQL as my instance db. And there are two version postgreSQL in server. After config setting.py DATABASES parameter, and runserver. It showed error. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dj_web_console', 'USER': 'django', 'PASSWORD': 'django', 'HOST': 'localhost', 'PORT': '', } } psycopg2.OperationalError: FATAL: password authentication failed for user "django" I'm sure that the username and password are correct. How to config pg_path in Django as odoo: In this case, I can use the specific version of pgsql. And run smoothly. -
URL pattern in django to match limited set of words
I have a URL pattern in Django where there is a variable (called name) that should only take one of a select list of words. Something like this: path("profile/<marta|jose|felipe|manuela:name>/", views.profile), So basically only these paths are valid: profile/marta/ profile/jose/ profile/felipe/ profile/manuela/ How exactly can I configure this in the Django url patterns? The above syntax tries to illustrate the idea but doesn't work. I've seen this ten year old question but that uses the previous format in the url patterns file so I imagine it should be done differently now...?