Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
jquery function 'is not defined' when connected from another file
I decided to store my JQuery functions in a separated file since I use them in many places in my django project. I placed the file in a static folder and load it in base template which other templates inherit from. Here is my custom.js file: var initialize_inputs = function () { var current_value = $(this).text().trim(); var input="<input type='text' class='input-data' value='"+current_value+"'>"; $(this).html(input); $(this).removeClass('text-md-center editable').addClass('text-md-center') } var process_inputs = function () { var new_value = $(this).val(); var td=$(this).parent("td"); $(this).remove(); td.html(new_value); var model_name = td.attr('data-model') var model_field = td.attr('data-field') var model_instnace_id = td.attr('value') td.removeClass('text-md-center').addClass('text-md-center editable') $.ajax({ url: "{% url 'ajax_update_static_value' %}", type: 'post', dataType: 'json', data: {'model_name': model_name, 'model_field_name': model_field, 'model_instance_id': model_instnace_id, 'new_value': new_value, 'csrfmiddlewaretoken': "{{ csrf_token }}"}, success: function (data) { if ('error' in data) { alert(data.error) } else { td.html(new_value) } } }) } But somehow it happens that one function - initialize_inputs works just fine while another - process_inputs doesn't showing error process_inputs is not defined. In my base.html: {% load static %} <script src='{% static "custom.js" %}'></script> In a template: {% block custom_js %} <script> $(document).ready(function(){ $(document).on("dblclick", ".editable", initialize_inputs); $(document).on("blur", ".input-data", process_inputs); }); </script> {% endblock custom_js %} What do I do wrong? Thank you. -
Django model unique=True not throwing any error which used in atomic transaction
Scenario: I am trying to create/insert data to Django model (POSTGRES database) employee and profile. When I insert duplicate records (i.e. with same work_email - unique and same employee_id - unique) I am expecting a database error in an atomic transaction. However, the below code doesn't throw any error, but when I see the database table no duplicate is created. Dropped a database and created a new DB and new migrations to make sure there is no problem with the sync. However, the result is the same with no error. Any help is appreciated. Thanks class Employee(models.Model): """ Employee table containing all the employee information. """ profile = models.OneToOneField(Profile, on_delete=models.CASCADE) id = models.CharField(max_length=50, unique=True, blank=False, default=uuid.uuid4, editable=False, db_index=True) employee_id = models.CharField( max_length=100, blank=False, unique=True, primary_key=True, error_messages={'employee_id': "A user with employee id already exists."} ) class Profile(AbstractUser): """ Enhancing user model with additional fields. This is in relation with a table ProfileExtras. Extras can be utilised to add any fields to further enhance Profile with key value pair. """ email = None date_of_birth = models.DateField(blank=False) work_email = models.EmailField( max_length=50, blank=False, unique=True, db_index=True, error_messages={'work_email': "A user with work email already exists."} ) def create_employee(app_context, data_dict): try: with model_transaction.atomic(): # Data insertion logic … -
Use Celery periodic tasks output in Django views set up with django_celery_beat
I am trying to use Celery to perform a rather consuming algorithm on one of my models. Currently in my home.tasks.py I have: @shared_task(bind=True) def get_hot_posts(): return Post.objects.get_hot() @shared_task(bind=True) def get_top_posts(): pass Which inside my Post object model manager I have: def get_hot(self): qs = ( self.get_queryset() .select_related("author") ) qs_list = list(qs) sorted_post = sorted(qs_list, key=lambda p: p.hot(), reverse=True) return sorted_post Which returns a list object of the hot posts. I have used django_celery_beat in order to set a periodic task. Which I have configured in my settings.py CELERY_BEAT_SCHEDULE = { 'update-hot-posts': { 'task':'get_hot_posts', 'schedule': 3600.0 }, 'update-top-posts': { 'task':'get_top_posts', 'schedule': 86400 } } I do not if I can perform any functions on my models in Celery tasks, but my intention is to compute the top posts every 1 hour, and then simply use it in one of my views. How can I achieve this, I am not able to find how I can get the output of that task and use it in my views in order to render it in my template. Thanks in advance! -
django channels websocket closes during handshake
I'm trying to integrate a simple chat room into my current website project using this tutorial from the channels readthedocs https://channels.readthedocs.io/en/latest/tutorial/index.html When I try to load the homepage for my website which should automatically connect to the global chat, I get this backend console HTTP GET / 200 [0.01, 127.0.0.1:58286] HTTP GET /static/chatroom/base.css 304 [0.00, 127.0.0.1:58286] HTTP GET /static/chatroom/images/profiles/anonymous.jpg 304 [0.00, 127.0.0.1:58288] HTTP GET /static/chatroom/images/background.jpg 304 [0.00, 127.0.0.1:58288] WebSocket HANDSHAKING /ws/chat/global/ [127.0.0.1:58290] WebSocket DISCONNECT /ws/chat/global/ [127.0.0.1:58282] javascript console Firefox can’t establish a connection to the server at ws://127.0.0.1:8000/ws/chat/global/. 127.0.0.1:8000:59:23 Socket error: [object WebSocket] 127.0.0.1:8000:69:17 Chat socket closed unexpectedly: 1006 I'm not really sure what code I should give you guys for my example, but here is the code for my consumer, and my settings consumers.py # chat/consumers.py import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(WebsocketConsumer): async def connect(self): self.room_name = 'global' self.room_group_name = 'chat_%s' % self.room_name # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data=None, bytes_data=None): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { … -
HTML pages aren't extending from other HTML files
I'm trying (for the first time on my own) to use VSCode to build a web app. Just starting with the basics, an index.html page with "Hello, world!" on it. I've also created a layout.html file with code for a navigation bar and some other stuff I got from Bootstrap's sample template as a starting point. If I open the layout.html file in my browser, the nav bar appears. But the index.html page doesn't receive this, even though I've put {% extends "layout.html" %} in Index. It also shows other HTML that's in Layout, but it shows it in plain text. I'm assuming I'm supposed to have done something to link these files or something? But I'm not sure what. Forgive the super noob question but would really appreciate the help. Including the current code for Layout and Index as well as screenshots of each. EDIT: For some additional context, I've just finished the CS50 course so my knowledge is limited to what I've learned there. In building web apps in that course, they had set up the server and I guess whatever connections are necessary, we just had to build the pages and the Python code for the app. … -
how to prevent tag movement in Django
my code is {% extends 'base.html' %} {% block content %} <h1>hello {{name}} world<h1> {% endblock %} but i save it. It become {% extends 'base.html' %} {% block content %} <h1>hello {{name}} world <h1> {% endblock %} how to I fix this problem -
Access uploaded file in Django Admin
I am trying to open the file uploaded in Django Admin, But i get an error Doesn't exist. Perhaps Deleted? error: Support_ staff with ID “1/change/Persona/SOFTECAsia2017.pdf” doesn’t exist. Perhaps it was deleted? models.py: class Support_Staff(models.Model): Name=models.CharField(max_length=20,blank=True) Persona=models.FileField(upload_to='Persona/') def __str__(self): return self.Name admin.py: class Support_Staff_admin(admin.ModelAdmin): list_display=('Name',) admin.site.register(Support_Staff, Support_Staff_admin) -
Upload to S3 from request.FILES Django
I am using Django and have a template with the following input field: <input type="file" name="file_upload"> When the form is submitted, I can access the submitted file like this: request.FILES['file_upload'] Now that I have this file, I want to upload it to my S3 bucket from the Python backend. How can I do this? Thanks! -
Django password field custom class
I would like to render the password field with a custom class, so I tried this: from django.contrib.auth import get_user_model from django.db import transaction User = get_user_model() class SignupForm(forms.ModelForm): first_name = forms.CharField(label=_(u'First name'), max_length=30) last_name = forms.CharField(label=_(u'Last name'), max_length=30) password1 = forms.CharField(widget = forms.PasswordInput(render_value = True, attrs={'class': 'form-control', 'placeholder': 'Your password'})) def __init__(self, *args, **kwargs): super(SignupForm, self).__init__(*args, **kwargs) self.fields['username'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your username'}) self.fields['first_name'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your first name'}) self.fields['last_name'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your last name'}) self.fields['email'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your email address'}) self.fields['password1'].widget.attrs.update({'class': 'form-control', 'placeholder': 'Your password'}) As you may notice, I tried to add the class on the declaration and in the initialization but none of this works. The class is still the default one. Note that for email, username, and the other fields, the class/placeholder are working fine. Am I missing something? -
How do I fix this function syntax?
Iv'e tried searching up the problem to no avail, so I chose to come on stack overflow to ask this problem. def Year(2015): ^ Syntax Right here Year = 2015 return Year Year = '2015' print(Year) -
Pandas closing django-like file, gives ValueError: I/O operation on closed file when uploading
In my process i need to upload a file to django as: newFile = request.FILES['file'] then in another big function i open it with pandas: data = pandas.read_csv(data_file, engine = 'python', header=headers_row, encoding = 'utf-8-sig') and then i need to upload it uploaded_file = Uploaded_file(file = newFile, retailer = ret, date = date) but randomly (like 50/50) i get a ValueError: I/O operation on closed file. Any solution to this? is it possible to open the file again or maybe make a copy of it and use pandas in one and upload the other? -
Where to store OAuth tokens in a Django application
I’m at the planning stage for an app I’d like to create using django. My idea for one aspect of the app is to hook in to a user’s outlook.com (or gmail.com etc...) account to create a calendar entry/event. In order to do this I plan to leverage the OAuth framework which during the process issues both an access token and refresh token. What is a method I can use to store this information safely in my app’s back-end so that it can be reused and users do not need to re-authorise every time my app interacts with the user’s account on the target server? ——————————————————————————————— I have read similar questions to this but all of the answers seem particularly vague, as if no-one is willing to advise on the issue. I thought about just storing the tokens directly in the django session framework but a lot of sources I’ve read strongly advise against storing the tokens directly. I have read about encryption-storage-decryption as an option to obfuscate the tokens but this seems pointless. If you are encrypting with the intention of scrambling the content of a database field, you are making the assumption that someone might access your database … -
KeyError in my view context when trying to dynamically call a view in Django
I try to dynamically call a view in Django with this url configuration : url(r'^niveau/(?P<niveau_id>\d+)/(?P<channel>\w+)/$', views.switcher , name='vue_niveau') Then in my view.py, i have : def switcher(request, niveau_id, channel): if channel == 'VueNiveau': return VueNiveau.as_view()(request) It works, as i get the good view call, but then when i try to get the niveau_id in my VueNiveau context : class VueNiveau(generic.TemplateView): template_name = 'cours/vue_niveau.html' context_object_name = 'liste_niveau' def get_queryset(self): return Niveau.objects.all() def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) niveau = Niveau.objects.get(id=kwargs['niveau_id']) context['niveau'] = niveau i get a KeyError, saying that niveau_id is undefined... Without the switcher function, all works perfectly and i can get the url data etc... So it seems like something is happening between the call of the switcher function and get_context_data... Does someone understand this behaviour ? -
pillow rendering image in django
Is any thing wrong with this program? @property def imageURL(self): try: url = self.image.url except: url = '' return url I used it but django does not render the images uploaded from the admin page Please anyone with idea on how to fix this issue? -
What happens when I do: queryset.anything = 'something'?
I did this thing: >>> latest.values('amount') <QuerySet [{'amount': 100}, {'amount': 100}, {'amount': 100}, {'amount': 180}]> >>> latest.values('amount').total=480 >>> latest.values('amount').total Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'QuerySet' object has no attribute 'total' >>> Is there any way to use latest.values('amount').total? Is it possible to add something in a queryset? -
Package a Django application as a desktop application
We are considering using Django for an application which can be seen mostly as a desktop application. That is, it is not to be installed on our servers, but directly on our customer's laptops (but still accessed through their browser on localhost.) Whilst it is OK to require Python to be installed, it is not to require to install Django, or other dependencies. It would probably run using the internal runserver. And most likely not use SQL (or only SQLite if necessary.) Is it possible to "package" the application with Django and all dependencies? What are the options here? Ideally, the install guide would read: install Python, if not done yet download and unzip our application archive go to that dir and execute python3 manage.py runserver Note I: The goal is NOT to package a publicly available website as an app. Note II: The only related questions I have found are several years old (10 and 7 years old resp.) -
not able to use wkhtmltopdf even after installing
I have succesfully installed wkhtmltopdf, still when i try "wkhtmltopdf --version" in cmd prompt it says " The term 'wkhtmltopdf' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again." This got default installed in program files.i thought this might be creating some error..tries reinstaling it in users..nothing helped though -
UUID' object has no attribute '_meta'
I am getting the above error message: UUID object has no attribute '_meta' when updating a model instance. I am using instance = id in my form instance. as shown in the code below: def organisationdetails(request, id): context = baseviewsuser(request) orgdetails = OrganisationDetails.objects.filter(FormFieldOrgID=id) context['orgdetails'] = orgdetails if request.method == "POST": print(id) form = OrganisationForm(request.POST, request.FILES, instance= id) if form.is_valid(): try: orgupdate = form.save(commit=False) orgupdate.save() return redirect(request, 'administration/organisation/list.html', context) except Exception as e: context['execption'] = e print(e) return render(request, 'administration/organisation/details.html', context) else: context['formerrors'] = form.errors print(form.errors) return render(request, 'administration/organisation/details.html', context) else: return render(request, 'administration/organisation/details.html', context) The model itself has a UUID as a PK. eg class OrganisationDetails(models.Model): FormFieldOrgID = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) FormFieldOrgCode = models.CharField(max_length=10, verbose_name='Organisation Code', help_text='Enter organisation identifier', default='NULL', ) FormFieldOrgName = models.CharField(max_length=75, help_text='Enter Organisation Name', verbose_name="Organisation Name") # The debug is showing the line form = OrganisationForm(request.POST, request.FILES, instance= id) has the problem - e.g. it is showing that the value being passed is : NONE??? yet the local vars in debug show the following: context {'department': <QuerySet [<DepartmentDetails: Accounts_Payable>]>, 'globalalert': <QuerySet [<GlobalAlerts: GlobalAlerts object (35073f13-d028-4822-9460-1c670e2b18a3)>]>, 'globalmessage': <QuerySet [<GlobalMessages: GlobalMessages object (83144b34-278f-458d-a00f-d8662770375f)>, <GlobalMessages: GlobalMessages object (c68ceb61-63b4-4661-acc1-dcea28ddd240)>, <GlobalMessages: GlobalMessages object (db8deab8-3752-41c4-8512-5b1a52c6c44b)>]>, 'organisation': <QuerySet [<OrganisationDetails: Quasi Consultants Ltd>]>, 'orgdetails': <QuerySet … -
Django templating error: Could not parse the remainder
I cannot figure out the problem with my templating. When. I tell it to render the dictionary, it does so successfully, but when I try taking out information from its keys, it returns this error: Could not parse the remainder. Here is the HTML: {% extends 'template.html' %} {% block title %}Cart{% endblock %} {% block head %} <script type="text/javascript"> <!-- Script for product div styling --> </script> {% endblock %} {% block body %} <div class="shop"> <h1 class="header">Cart</h1> <table> <tr> <th>Product Name</th> <th>Topping 1</th> <th>Topping 2</th> <th>Topping 3</th> <th>Price</th> </tr> {% for item in productlist %} <tr> {% if item["product_name"] == True %} <td>Large {{item["product_name"]}}</td> {% else %} <td>{{item["product_name"]}}</td> {% endif %} <td>{{item["topping1"]}}</td> <td>{{item["topping2"]}}</td> <td>{{item["topping3"]}}</td> <td>{{item["price"]}}</td> </tr> {% empty %} <h3>Your cart is empty</h3> Add products to the cart through the <a href="{% url 'mainindex' %}">menu</a> page. {% endfor %} </table> </div> {% endblock %} If you need me to add the backend, I'd be happy to do so. Thanks -
Can I pass a variable in for a related model in getattr()?
So this works: price = getattr(mymodel.related_model, 'msrp') But I'd like to pass in a variable for the 'related_model', something like: x = related_model_name price = getattr(mymodel.x, 'msrp') Clearly that does not work, but it shows what I'd like to accomplish. Is there a way to pass in a variable as the placeholder for the related model name in some manner? -
how to use pagination nested object django rest framework
I also want to give the pagination in array named list here. Our UserPublicSrtilizer relationship to cat_modelSrtilizer Let's look at the data in the list from here - I want to use pagination in that array named list? How can someone help a little? class UserPublicSrtilizer(serializers.ModelSerializer): class Meta: model = postmodel fields = [ 'id', 'title', 'blog_slug', 'decribe_post', 'post_img', 'post_views', 'created_at' ] class cat_modelSrtilizer(serializers.HyperlinkedModelSerializer): List = serializers.SerializerMethodField(read_only=True) class Meta: model = cat_model fields = [ 'id', 'cat_name', 'cat_description', 'cat_full_data', 'cat_icon', 'cat_slug', 'List' ] def get_List(self,obj): qs = obj.postmodel_set.all()[:3] return UserPublicSrtilizer(qs,many=True).data { "id": 2, "cat_name": "Coronavirus Explained", "cat_description": "Understand the impact of the outbreak on your trav", "cat_icon": "http://cdn.resultonlinebd.com/media/Blog_cat_icon/fdgd.jpg", "cat_slug": "Coronavirus_Explained", "List": [ { "id": 4, "title": "We have decorated it in natural ways", "blog_slug": "wedwdf", "decribe_post": "efefe", "post_img": "/media/media_blog/billgets.png", "post_views": 0, "created_at": "2020-07-02T11:06:11.299722" }, { "id": 12, "title": "We have decorated it in natural ways", "blog_slug": "wedwa", "decribe_post": "scsc", "post_img": "/media/media_blog/DlGrb_OpA_fTaWILx.jpeg", "post_views": 0, "created_at": "2020-07-04T16:42:54.623464" }, { "id": 13, "title": "Sojib New video | 2019", "blog_slug": "wedwf", "decribe_post": "sds", "post_img": "/media/media_blog/DSC_9355.jpg", "post_views": 0, "created_at": "2020-07-04T16:43:29.146703" } ] }, -
djcelery fopr Django 3.0 and Celery 4.4
I am trying to install djcelery for Celery 4.4 and Django 3. However, whenever I install django-celery it downgrades to celery 3.3. And after that I get: from kombu.utils.objects import cached_property ModuleNotFoundError: No module named 'kombu.utils' Should I use the django_celery_beat package for this purpose or should I install django-celery and fix that error? -
Django python manage.py createsuperuser - I can not write any word for the password
I hope you're well :) After using Wagtail, I've decided to launch Django on my website (other domain). I'm using O2switch and cpannel. Python 3.7 is installed and Django 3.0.8 too. Each steps work except manage.py createsuperuser I can write my login / email but I can not do anything when it's time to write my password. It's totally blocked. Do you have any tips? I can not write anything. The only one thing I can do is enter or write this caracter ¨. If i do enter: Password: Traceback (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 "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib/python3.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 146, in handle password = getpass.getpass() File "/opt/alt/python37/lib64/python3.7/getpass.py", line 77, in unix_getpass passwd = _raw_input(prompt, stream, input=input) File "/opt/alt/python37/lib64/python3.7/getpass.py", line 146, in _raw_input line = input.readline() File "/home/dulo0814/virtualenv/monProjetDjango/3.7/lib64/python3.7/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 12: ordinal not in … -
Bootstrap set color of badge dynamically
I'm using Django and Bootstrap 4.5 to build a simple web app. One of my models has a color attribute and I want to visualize it using bootstrap's badge by setting the badge's color to the color of the object. In the documentation it seems like I can only choose from the predefined colors for primary, secondary, etc. Online, I mostly found tips how to overwrite and change the primary color for all badges. Or setting a specific color in a new CSS class. What I want is to dynamically set the color of the badge according to the Django object's color attribute using Django's HTML templates. This is what I currently have: {% block content %} <h1>{{ tag.name }}</h1> <p>Description: {{ tag.description }}</p> <p>Color: <span class="badge badge-secondary">{{ tag.color }}</span></p> {% endblock %} Now, the badge always has the "secondary" color, but I want it to have {{ tag.color }} as color. -
How to check existence of an object using pk in django template?
I tried this if condition to show previous and next posts only if it exists in database. {% if blog.pk|add:-1 %} <a href="{% url 'blog:blogdetail' blog.pk|add:-1 %}">Previous Post</a> {% endif %} {% if blog.pk|add:1 %} <a href="{% url 'blog:blogdetail' blog.pk|add:1 %}">Next Post</a> {% endif %} but, it kinda ignores the condition and always show next and previous posts buttons owing to the fact that this condition is wrong. How do I fix this?