Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Convert from dash html to regular html string
I've been using plotly to generate a few charts and used dash to render them on a simple heroku server. Now I am moving the dash component to Django, I have a very nice html layout generated with dash function, which is composed of some charts and some styling with it. I am trying to read it as html so that I can use a function in view to call the page. When I checked the layout data type, it is dash.html.Div.Div rather than html, or string of "html". I am wondering if I can convert it directly into HTML, so that I can render it like normal html code. Thanks -
{% block contents %} conditional on a variable Django template inheritance
I am using Django's template inheritance from a base file called base.html. All of my apps, except one, require that {% block contents %} {% endblock %} is present in that file, which is problematic. I am trying to find away to make the inclusion {% block contents %} {% endblock %} conditional on a variable. What I have so far tried in base.html: {% if some_variable %} {% block contents %} {% endblock %} {% endif %} But that doesn't seem to work. I have also tried: {% if some_variable %} {% with 'base_block_content.html' as path %} {% include path %} {% endwith %} {% endif %} base_block_content.html being simply: ''' {% block contents %} {% endblock %} ''' But that doesn't work either. My only other option is to write a completely separate base.html for the one app, which doesn't quite fit in with the 'DRY' concept. -
How to pass tuple with one element as param in sql query Python?
How can I pass tuple with only one element as param in sql query Python? I have tried this solution suggested here: imploding a list for use in a python MySQLDB IN clause ids = [(UUID('1232a4df-5849-46c2-8c76-74fe74168d82'),)] # list of ids cursor.execute(''' SELECT ... WHERE id IN %(ids)s AND created_at > %(start_dt)s ''', { 'ids': tuple(ids), 'start_dt': '2019-10-31 00:00:00' }) but this solution does not work in python 3 and mysql-connector-python 8.0.21. I get this error: An error "Python tuple cannot be converted to MySQL type" is returned. -
Django celery page is giving 404
I'm trying to acces https://docs.celeryproject.org/en/stable/django/first-steps-with-django.html but getting 404. Is celery not officially available? -
Unable to add a placeholder in django-ckeditor?
I have integrated django-ckeditor in my blog, i have added placeholder with the help of widget in my forms.py like this from blog.models import Contact from ckeditor.widgets import CKEditorWidget class ContactFrom(forms.ModelForm): content = forms.CharField(widget=CKEditorWidget(attrs={'placeholder':"Type.."})) class Meta: model = Contact fields = ("content",) Even i can see placeholder in my textarea through inspect but not showing in my ckeditor what should i do? -
send email on model create - django
I want to send an email automatically when I create an invoice. Is that possible? What I'm after. I have a invoice model and I put send_email code in it "def save(self):", I'm making perfex CRM invoice system, so I'm using the foregin key in invoice model to get a customer, but whenever I create new invoice it says "The invoices “INV-b066” was added successfully." but in invoice model it shows nothing like it's empty model I even tried to open invoice using index number and restarted the server and migrations stuff and it didn't worked but if I remove def save(self): function it works perfectly fine I'm trying to send an email automatically on model create Customer model class Customers(models.Model): Your_Name = models.CharField(max_length=220) Email_Address = models.EmailField(max_length=220) Profession = models.CharField(max_length=220) phone = PhoneNumberField(unique=True) No_of_Persons = models.IntegerField() Packages = models.CharField(choices=PAKAGES, max_length=100) Address = models.CharField(max_length=220) City = models.CharField(choices=CITIES, max_length=10) Time = models.CharField(choices=TIME, max_length=10) Date = models.DateTimeField() Message = models.TextField() def __str__(self): return f'{self.Your_Name}' Invoice model class Invoice(models.Model): Customer = models.ForeignKey(Customers, on_delete=models.CASCADE) Invoice_Number = models.CharField(default=inv_num, max_length=10) Recurring = models.CharField(choices=Recurrings, max_length=12) Invoice_date = models.DateField() Due_date = models.DateField() Packages = models.CharField(choices=PAKAGES, max_length=100) Package_name = models.CharField(max_length=50) Package_description = models.TextField() Package_Quantity = models.IntegerField() Package_Price = models.IntegerField() def … -
How to filter queryset using item inside a list in a JSON file in Django?
I have JSON files that are structured like this in my database: } "user" : { "contacts" : [ { "type" : "email", "data" : "aaa@foo.com" }, { "type" : "phone_number", "data" : "4444-4444" }, { "type" : "email", "data" : "bbb@foo.com" }, ... ], "name" : "Bob" } } What I want is to filter the queryset so I end up only having users that have an account with an email registered. Anyone knows how to make this work? I am aware of user__contacts__0__type=email but the list doesn't have a fixed size. -
How do I configure my media files to upload on AWS S3 Bucket in Django?
I've created a Blogging App using Django and Heroku-Postgres as Database. The user uploaded images gets removed in Heroku-Postgres after redeployment I think and it just disappears from the website. I tried fixing this using AWS S3 Bucket but I'm not able to configure the settings in my Django App, the user uploaded files are uploaded to media/images/ according to my models.py models.py class Post(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) article_image = models.ImageField(null=True, blank=True, upload_to="images/") settings.py AWS_STORAGE_BUCKET_NAME = '#####' AWS_S3_REGION_NAME = 'us-east-1' AWS_ACCESS_KEY_ID = '####' AWS_SECRET_ACCESS_KEY = '####' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME MEDIAFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] DISABLE_COLLECTSTATIC=1 MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Now, what am I supposed to remove/keep from these so that the user uploaded images which are now stored in media/images/ are stored in AWS S3 Bucket? -
Javascript infinite scroll that updates new divs when reached to the bottom of screen not working
I am trying out a web app using Django from the edX course CS50 Web Programming. Below is the javascript for an infinite scroll that updates 20 posts every time reaching the bottom of the screen but it just stopped after reaching 20th post. <script> // Start with first post let counter = 1; // Load posts 20 at a time const quantity = 20; // When DOM loads, render the first 20 posts document.addEventListener('DOMContentLoaded', load); window.onscroll = function(ev) { if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) { load(); } }; // Load next set of posts function load() { // Set start and end post numbers, and update counter const start = counter; const end = start + quantity - 1; counter = end + 1; // Get new posts and add posts fetch(`/users/home/posts?start=${start}&end=${end}`) .then(response => response.json()) .then(data => { data.posts.forEach(add_post); }) }; // Add a new post with given contents to DOM function add_post(contents) { // Create new post const post = document.createElement('div'); post.className = 'post'; post.innerHTML = contents; // Add post to DOM document.querySelector('#posts').append(post); }; </script> Below is posts function in python from views.py def posts(request): if not request.user.is_authenticated: return HttpResponseRedirect(reverse("users:login")) # Get start and end points start … -
Bootstrap button doesn't display properly in django form
EDIT: Just realized how bloated this question is and how poorly formated my html. Sorry I didn't catch it before posting. Working on fixing it now So, as you can probably see in the images, I'm having trouble getting a bootstrap button to display in my Django template properly. It's meant to submit a user registration form but as you can see I've tried putting it in a few places to see if a container is affecting it:Bootstrap buttons as they appear in my project and, of course, it should look like this: enter image description here Here's the relevant template, with the button repeated in a few places: <!-- my base template --> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <title>Short Thoughts Posted Publicly Online</title> </head> <body> <!-- I've got a navbar here, but I can't imagine that's relevant --> <div class="container"> <div class="columns"> {% block content %} {% endblock content %} </div> </div> <script src="{% static 'js/bootstrap.bundle.js' %}"></script> </body> </html> <!-- my registration template --> {% extends 'base.html' %} {% block content %} <button type="button" class="btn btn-default">Register</button> <div class="row"> <div class="shadow-none p-3 mb-5 … -
How to register with django on template?
I have a small project. There is a ready registration form in the project. I want to register on this registration form. I don't want to create inputs with python codes in forms.py. I want to record with imputs in existing HTML codes. I hope I was able to explain what I wanted. I will be glad if you help me. register.html {% extends 'partials/_base.html' %} {% load static %} {% block content %} <!-- BREADCRUMB --> <div id="breadcrumb"> <div class="container"> <ul class="breadcrumb"> <li><a href="#">Home</a></li> <li class="active">Register</li> </ul> </div> </div> <!-- /BREADCRUMB --> <!--REGISTER FORM--> <div style="width: 500px;" class="container"> <form class="form-horizontal" role="form" method="post"> {% csrf_token %} <br> <div class="form-group"> <label for="firstName" class="col-sm-3 control-label">Ad</label> <div class="col-sm-9"> <input type="text" id="firstName" placeholder="First Name" class="form- control" autofocus> </div> </div> <div class="form-group"> <label for="firstName" class="col-sm-3 control-label">Soyad</label> <div class="col-sm-9"> <input type="text" id="lastName" placeholder="Last Name" class="form- control" autofocus> </div> </div> <div class="form-group"> <label for="email" class="col-sm-3 control-label">Email</label> <div class="col-sm-9"> <input type="email" id="email" placeholder="Email" class="form-control"> </div> </div> <div class="form-group"> <label for="email" class="col-sm-3 control-label">Nömrə</label> <div class="col-sm-9"> <input type="text" id="phone" placeholder="Phone" class="form-control"> </div> </div> <div class="form-group"> <label for="password" class="col-sm-3 control-label">Şifrə</label> <div class="col-sm-9"> <input type="password" id="password" placeholder="Password" class="form- control"> </div> </div> <div class="form-group"> <label for="birthDate" class="col-sm-3 control-label">Doğum tarixi</label> <div class="col-sm-9"> <input type="date" … -
Why is only some context data available in django template?
I'm having trouble accessing some of the context data in a django template, probably due to a basic misunderstanding on my part. Please see abbreviated code below. My view is: class UserCourseListView(LoginRequiredMixin, generic.ListView): model = CustomUser template_name = 'account/course/list.html' context_object_name = 'puser_course_list' def get_queryset(self): return CustomUser.objects.filter(username=self.request.user.username) My model is: class CustomUser(AbstractUser): email = models.EmailField(max_length=254, blank=False,) course = models.ManyToManyField(Course, related_name="course", blank=True) firstname = models.TextField(max_length=254, blank=True ) surname = models.TextField(max_length=254, blank=True ) nickname = models.TextField(max_length=254, blank=True ) def __str__(self): return str(self.id) def get_absolute_url(self): return reverse('patient_user_detail', args=[str(self.id)]) And template is: {% for pcourse in puser_course_list %} <dt>{{ pcourse.courses_joined.all }}</dt> <dt>{{ pcourse.id }}</dt> <dt>{{ pcourse.username }}</dt> <dt>{{ pcourse.firstname }}</dt> <dt>{{ pcourse.surname }}</dt> {% endfor %} I am able to acces the user id, username and retrieve a queryset from a related model (using related name 'courses_joined'), but can't retrieve the firstname and surname? Any thoughts or help would be most appreciated. I'm assuming a context processor isn't required in this scenario as all of the data should be in the context_object? -
How to limit the number of threads to one
How can this function be changed so that it only executes on one thread? Is it possible? Should I have a separate function for this? I tried to create a dictionary and count each loop, but it doesn't make sense because after using import pdb;pdb set_trace () I can see that more threads are used "<Thread(Thread-4 (eventFunc), initial daemon)>" Code: def event(codeName=None, context=None, attachments=None, is_thread=True, **kwarks): if settings.IS_EVENT_ACTIVE: #print(u"Event [{}]".format(codeName)) # logger.debug(u"Event [{}] {}".format(codeName,traceback.print_exc())) logger.debug(u"Event [{}]".format(codeName)) if portalSetting.EVENT_THREAD and is_thread: x = threading.Thread(target=eventFunc, args=(codeName, context, attachments, ), kwargs=kwarks) # import pdb;pdb.set_trace() x.start() else: eventFunc(codeName=codeName, context=context, attachments=attachments, **kwarks) -
AttributeError: 'NoneType' object has no attribute 'as_sql'
that's ok to makemigrations, but it's error when I migrate. Please give me some advise, I didn't find the same case "as_sql" in Google. Thank you. This is my models class ClinicInfo(models.Model): name_cn = models.CharField(max_length=100, verbose_name=_('Chinese Name')) name_en = models.CharField(max_length=100, verbose_name=_('English Name')) short_name = models.CharField(max_length=10, unique=True, verbose_name=_('Short Name')) address_cn = models.CharField(max_length=200, verbose_name=_('Chinese Address')) address_en = models.CharField(max_length=200, verbose_name=_('English Address')) telnum_1 = models.CharField(max_length=20, verbose_name=_('1st Tel No.')) telnum_2 = models.CharField(max_length=20, blank=True, verbose_name=_('2nd Tel No.')) email = models.EmailField(max_length=254, blank=True, verbose_name=_('Email')) fax = models.CharField(max_length=20, blank=True, verbose_name=_('Fax')) class meta: verbose_name = _('Clinic Information') verbose_name_plural = _('Clinic Information') def __str__(self): return self.name_cn class DoctorArg(models.Model): weekday_list = ( (0, _('Monday')), (1, _('Tuesday')), (2, _('Wednesday')), (3, _('Thursday')), (4, _('Friday')), (5, _('Saturday')), (6, _('Sunday')) ) period_list = ( ('full', _('Full Day')), ('am', _('AM')), ('pm', _('PM')) ) clinic = models.ForeignKey(ClinicInfo, on_delete=models.CASCADE, verbose_name=_('Clinic')) weekday = models.IntegerField( choices=weekday_list, verbose_name=_('Weekday')) period = models.CharField(max_length=4, choices=period_list, default='full', verbose_name=_('Period')) ''' doctor = models.ForeignKey( MyUser, limit_choices_to={'role': 'Doctor'}, on_delete=models.CASCADE, verbose_name=_('Doctor')) ''' class Meta: verbose_name = _('Doctor Arrangement') verbose_name_plural = _('Doctor Arrangements') # unique_together = [['weekday', 'period', 'doctor']] def __str__(self): return 'Doctor arrangements' I didn't find the same case "as_sql" in Google. I tried to trace this error according to this way link, but didn't get debug print. -
What 'namespace' is used for in Django urls?
I have namespace parameter in the urls.py of project, like this: path('blog/', include('blog.urls', namespace='blog')), And then I have app_name = blog in the urls.py of the blog application. I do that because that's what I've learned to do without actually understanding what namespace is doing when app_name is defined? -
What form action should i use to solve error 405 on post?
##html <form id="schedule-form" action="#" method="POST"> {% csrf_token %} .... <input type="submit" id="submit-horario" value="Confirmar" class="btn button-raised btn-green text-white text-uppercase fw-600 me-md-1 mt-3" onclick="gtag_confirmar_horario('S_{{ prestadorservicos.prestadorservicoid }}', '{{ servicoregioes.as_string|escapejs }}', '{{ menor_desconto.get_tipo_de_desconto_display|escapejs }}', '{{ menor_desconto.preco_desconto }}', '{{ prestadorunidade.as_string|escapejs }}', '{{ prestador.parceiro }}', '{{ prestadorservicos.preco }}')"/> </div> </form> ##urls from django.conf.urls import url from django.urls import path from . views import BuscaHorarios, AgendaHorario app_name = "agendamento" urlpatterns = [ url(r'^(?P<prestadorservicosid>[0-9]+)(?:/(?P<unidadeid>[0-9]+))/$', BuscaHorarios.as_view(), name='horarios', ), url('/', AgendaHorario.as_view(), name="agenda_horario"), ] When i submit this form i get 405 http error on console. There is no problem loading (get) this page [25/Mar/2022 11:55:38] "GET /agendamento/11749/1341/ HTTP/1.1" 200 19435 only to submit (post) [25/Mar/2022 11:56:51] "POST /agendamento/11749/1341/ HTTP/1.1" 405 0 -
Using HTML if statements to return results
I am trying to print a list of courses that a user has uploaded onto their account but am having trouble figuring out how to do that. I have tried to print {{ course.student_course }} and {{user.username}} and they both appear to print the same thing. But when I do the comparison in the if statement, nothing returns. Here is the html snippet <div class="container h-100"> <div class="row justify-content-center"> {% if courses_list %} {% for course in courses_list %} {% if course.student_course == user.username %} <button type="button" class="btn btn-outline-primary">{{ subject }} </button> <p>{{ subject }}</p> {% endif %} {% endfor %} {% else %} <p>No courses have been uploaded.</p> {% endif %} </div> </div> And here is the fields of my model that I am trying to access. class Course(models.Model): subject = models.CharField(max_length=4) course_number = models.CharField(max_length=4, default='') course_name = models.CharField(max_length=100, default='') course_section = models.CharField(max_length=3, default='') student_course = models.OneToOneField(User, on_delete=models.CASCADE, default='') def __str__(self): return self.subject + " " + self.course_number Like I said, I tried to print each field being compared and they both turned the same thing but when I try to do the comparison it returns nothing. -
Please critique my Django app (for entry level resume)
Link: https://coleabell05.pythonanywhere.com/home/ Entry level Python/Django oriented programmer here and I just finished a sort of first draft of a simple inventory app linked above I'm planning to use on my resume, launched on pythonanywhere. If anyone has some time, would you mind giving it a look? Hoping for advice on what additional functionality I could work on adding and how I could make it more appealing to recruiters? Also if its structure is confusing at all and what I could change to clarify it's function. As it stands now, it's intended to be a functioning register and inventory manager for a pizzeria. The user makes an account and then has the power to add or delete entrees and ingredients to the kitchen as well as close the register for the day and make purchases. Thanks for any help! -
django create an api
Issue hi there, my application are almost frontend, what I meant by that, apps such as json formatter, codePen, jsFiddle and some online graphers, I wrote a lot of javascript to achieve a frontend interactive application. to be more focused, I have specific views, let's say, a markdown editor, that you can type from left, and outlook appearance render to right. here, it's a bit intricate, some user cases, when in a form, that the user can input raw text into a textarea, and it's markdown supported, therefore, I need to write a button, see in editor, which takes all user's current input text, and open a new tab with the markdown editor. The difficulty of this, is that those raw text do not need to be saved, the user only need to see the rendered effect, but django only works with model. I thought of many ways: rest framework api view Ajax POST view abstract model but I failed to make it work. Code template <!-- some code above --> {% comment %} form.content returns a string {% endcomment %} {{ form.content }} <button>see in editor</button> <!-- some code below --> javascript const content = document.querySelector('#id_content'); const button = … -
Django: How separate the data inside the model based on the user
I want to make an attendance system that prevents each user to see the attendance that some users have taken. But in my case, the attendance that the other users take can be shown by every user. How can I prevent this part? These are my codes: Models.py class ClassAttendance(models.Model):Faculty_Name = models.CharField(max_length=200, null=True, blank=True)Student_ID = models.CharField(max_length=200, null=True, blank=True)firstname = models.CharField(max_length=200, null=True, blank=True)lastname = models.CharField(max_length=200, null=True, blank=True)date = models.DateField(auto_now_add = True, null = True)time = models.TimeField(auto_now_add=True, null = True)college = models.CharField(max_length=200, null=True, blank=True)course = models.CharField(max_length=200, null=True, blank=True)year = models.CharField(max_length=200, null = True)section = models.CharField(max_length=200, null = True)subject = models.CharField(max_length=200, null = True)status = models.CharField(max_length=200, null = True, default='Absent')def __str__(self): return str(self.Student_ID + "_" + str(self.lastname) + "_" + str(self.date)+ "_" + str(self.subject)) class Faculty(models.Model): user = models.OneToOneField(User, null = True, blank = True, on_delete= models.CASCADE) firstname = models.CharField(max_length=200, null=True, blank=True) lastname = models.CharField(max_length=200, null=True, blank=True) college = models.CharField(max_length=200, null=True, choices=COLLEGE) course = models.CharField(max_length=200, null=True, choices=COURSE) year = models.CharField(max_length=200, null=True, choices=YEAR) section = models.CharField(max_length=200, null=True, choices=SECTION) subject = models.CharField(max_length=200, null=True, choices=SUBJECT) def str(self):return str(self.firstname + " " + self.lastname) class Meta:verbose_name_plural = "Faculties" I expected that after the users take attendance, they are the ones that can see that information -
Django UpdateView with reverse foreign key
I am using UpdateView, which is very cool abstraction and makes it very easy to update existing Models. I however want to include into this reverse foreign keys (kinda similar to inline admins). There is also inlineformset_factory, which helps creating this kind of reverse foreign key formsets. Of course I can handle all this manually (modelform and then each formset). But I'd like to put all those forms together and abstract this functionality into a view so that I then only specify the model, fields (same as in UpdateView), but also those reverse foreign keys. Is there a view for this or do I have to create my own? Any kind of experience with this would be appreciated. -
How to parse the "src" of image tag in Django textfield?
So I have code in my HTML template like this <div class="blog-content"> {{post.text|safe|linebreaks}} <p><img src="{{ image_dict.1.url }}" alt=""></p> </div> This above renders the image fine in HTML. My view is like this def post_detail(request, slug): post = BlogPost.objects.get(slug=slug) images = post.images.all() image_dict = {} for image in images: image_dict[image.image_order] = image.image print(image.image) return render(request, 'blog/post_detail.html', { 'post': post, 'images': images, 'image_dict': image_dict, }) Basically I'm setting it up so that I can render the images via {{image_dict.image_order.url}} But I wanna render the images as per following to associate them with each paragraph of text like so Text in Django TextField However, while the code within the template evaluates to the image url, for example say for an image with order '1' <p><img src="{{ image_dict.1.url }}" alt=""></p> becomes <p><img src="/media/images/codewithlewis.png" alt=""></p> The exact same code I typed in django's textfield (as attached in above image) remains like <p><img src="{{ image_dict.1.url }}" alt=""></p> within HTML and nothing gets rendered of course. A screen shot of this: I'm fairly new to Django but I feel like I have tried everything. How might I go about fixing this? Thank you. -
I'm getting the following error and I don't know what to do about it [closed]
since i'm new to django i don't know what to do next it'll really be helpful if somebody helped me i tried to inherit a template named 'basic.html' but at {% block css %}{% endblock %} i'm getting this error "{ expected css(css-lcurlyexpected)" -
Django testing HttpResponse
I've seen tutorials and guides about testing views which are rendering some templates, but I don't know how to use Django's testing module in case if I have views which are returning Jsons in HttpResponse? Any help will be appreciated. Thank You -
Refresh html DIv in Django
i am trying to refresh an {%extends%} page since my base.html is getting message information from whatever is happening in the python backend, it only shows the message after i refresh my page and i want to refresh it every x seconds so the alerts will show without needing to refresh my entire page. <div id="Mydiv"> {% extends 'crodlUSDT/base.html'%} </div> <script> $(document).ready(function() { function refresh() { var div = $('#Mydiv'), divHtml = div.html(); div.html(divHtml); } setInterval(function() { refresh() }, 3000); //300000 is 5minutes in ms }) </script> this is what i've found online but tested a lot of different things but none are working, is this possible ? thanks