Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgres+django on kubernetes: django.db.utils.OperationalError: could not connect to server: Connection timed out
My Django app can't connect to the Postgres server on Kubernetes. All other pods are able to connect to this Postgres server and creds are valid as well, any idea why not this Django app django.db.utils.OperationalError: could not connect to server: Connection timed out Is the server running on host "postgres-postgresql" (10.245.56.118) and accepting TCP/IP connections on port 5342? -
No function matches the given name and argument types. You might need to add explicit type casts. Django Postgresql
I am trying to get the average of a field in my model but I keep getting this error: Exception Type: ProgrammingError Exception Value: function avg(character varying) does not exist LINE 1: SELECT AVG("home_course"."course_difficulty") AS "course_dif... ^ HINT: No function matches the given name and argument types. You might need to add explicit type casts. This is my model field I am getting an average on: class Difficulty(models.TextChoices): EASY = '1', 'Easy' MEDIUM = '2', 'Medium' HARD = '3', 'Hard' FAILED = '4', 'Failed' course_difficulty = models.CharField( max_length=2, choices=Difficulty.choices, default=Difficulty.MEDIUM ) And I am using this query: avg = Course.objects.filter(course_code=self.course_code,course_university=self.course_university).aggregate(Avg('course_difficulty')) (course_code and course_university are both CharFields) Now after searching I came to realize that it's possibly because course_difficuly is a CharField, how can I convert it to integer without losing my text choices? Can I simply change it to IntegerField? -
Django allauth error for missing argument?
Erros appear when I tried to submit register form, the problem is that I don't know how to debug code, which is not mine, like packages (allauth in this case): AttributeError at /users/signup/ 'bool' object has no attribute 'get' Request Method: POST Request URL: http://localhost:8000/users/signup/ Django Version: 2.2.4 Exception Type: AttributeError Exception Value: 'bool' object has no attribute 'get' signup.html: {% extends 'index.html' %} {% block 'head-title' %} <title>Вход</title> {% endblock %} {% block 'body' %} {% load i18n %} {% block content %} <div id="dialog_signin_part" class="zoom-anim-dialog"> <div class="small_dialog_header"> <h3>Регистрирай се</h3> </div> <p>{% blocktrans %}Вече имаш акаунт? <a href="{{ login_url }}">Логни се тук</a>.{% endblocktrans %}</p> <div class="utf_signin_form style_one"> <div class="tab_container alt"> <div class="tab_content" id="tab1" style=""> <p>test</p> <form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}"> {% csrf_token %} {{ form.as_p }} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <button type="submit">{% trans "Sign Up" %} &raquo;</button> </form> </div> </div> </div> </div> {% endblock %} {% endblock %} Any advice how to debug it is welcome. I'm open to provide more information, files etc. -
How to display signup errors so they are not in a list django
Hello i am doing a school project in django. I want to display signup errors. I have tried with {{form.errors}} but it shows a list with where it went wrong and what went wrong. How can i get only the thing that went wrong? I have tried with a foor loop on {{form.erros}} but it only shows where it went wrong and not what went wrong. How do i get the sub list ? def register(request): #form za registracijo form = CreateUserForm() #če je gumb pritisjen oz post if request.method == 'POST': #vnesemo podatke v form form = CreateUserForm(request.POST) #če so podatki pravilni if form.is_valid(): #form shranimo form.save() #dobimo ime uporabnika user = form.cleaned_data.get('username') #izpišemo da je uspešno narejen račun messages.success(request, 'Account was created for %s' %(user)) #vas vrnemo na prijavo return redirect('login') #context za vnos forma v template context = {'form': form} #naložimo stran ob zahtevi return render(request, 'accounts/register.html', context) -
How to get class name from custom_exception_handler in django
I m implementing custom_exception_handler in django here is the code.. from rest_framework.views import exception_handler def custom_exception_handler(exc, context): response = exception_handler(exc, context) ... ... return response_set I get a function name by implementing this context['view'].__class__.__name__ Similarly i want a class name, from which class this exception are occur/trigger. I tried various way but didn't work, I didn't get class name! If you know, Then please write your solution in comment section. -
Application error: hosting django blog app
error detail o I'm seeing Application error enter image description here -
Why javascript doesn't detect the elements that are added after a django for loop?
So it's all in the title, I'll put my code right here: {% extends "list/base.html" %} {% block content %} <main class="site-main" style="background-color: black;"> <!--Banner Area--> <section class="site-banner pb-5" style="background-color: black; overflow: hidden; position: relative; color: white;"> <div class="container"> <h3>Liste</h3> <p class="total" style="color: black; display: none;">{{ total }}</p> {% for movie in movies %} <div class="c"> <img src="https://via.placeholder.com/1000x1481" alt="Avatar" class="image"> <div class="overlay"> <a data-modal-target="#cont" class="icon" title="User Profile" style="display: block;"> <i class="fa fa-play" aria-hidden="true"></i> </a> </div> </div> <div class="cont{{movie.id}}" id="cont{{movie.id}}"> <div class="row"> <div class="col-lg-4"> <img src="https://via.placeholder.com/1000x1481" alt="Avatar" class="image"> </div> <div class="col-lg-8"> <div class="modal-header"> <div class="title">{{ movie.title }}</div> <a data-close-button class="close-button">&times;</a> </div> <span>Sorti en {{ movie.date_released|date:"Y" }}</span> <span>avec {{ movie.author}}</span> <span class="id">{{movie.id}}</span> <p>{{movie.synopsis}}</p> </div> </div> </div> {% endfor %} <div id="ov"></div> </div> </section> </main> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> <script> const openModalButtons = document.querySelectorAll('[data-modal-target]'); const closeModalButtons = document.querySelectorAll('[data-close-button]'); const overlay = document.getElementById('ov'); var d = document.querySelector('.total').innerText; function popup() { for (i=1, c = d; i<c; i++) { const cont = addEventListener(document.querySelector(".cont"+i)); console.log(cont); cont.style.background = "red"; cont.style.color = "white"; cont.style.width = "75%"; cont.style.transform = "translate(-50%, -50%) scale(0)"; cont.style.position = "fixed"; cont.style.top = "50%"; cont.style.left = "50%"; cont.style.padding = "20px"; cont.style.zindex = "10"; cont.style.overflow = "hidden"; cont.style.maxWidth = "80%"; cont.style.borderRadius = "30px"; const contAct = document.querySelectorAll(".cont"+i+".active"); contAct.style.transform … -
Vectorizing Function using Pandas Dataframe result in KeyError
I am still new to Pandas dataframe and I'm trying to vectorize the following loop functions because while it gets the job done, iterating a 30,000 rows dataframe using iterrows() is not viable at all header = data_reader.columns.values.tolist()[1:] series_list = [] # New row in Timeseries table for datetime_index, row in data_reader.iterrows(): for i in range(0, len(row)-1): metrics = Metrics.objects.get(name=header[i]) print(metrics) try: val = float(row[i]) series_list.append(Timeseries(timestamp=datetime_index, parameter=metrics, float_val=val, status=None, device_id=metadata)) except ValueError: series_list.append(Timeseries(timestamp=datetime_index, parameter=metrics, float_val=None, status=row[i], device_id=metadata)) Timeseries.objects.bulk_create(series_list) Thus I've looked up on Pandas/NumPy Array Vectorization and how it can shorten the time complexity of a function. I am trying to convert the above function into the vectorized version and this is what I've got so far header = data_reader.columns.values.tolist()[1:] series_list = [] data_reader = data_reader.reset_index() for i in range(1, len(header)): series_list.append(insertion(header, series_list, data_reader['datetime'].values, data_reader[i].values, metadata)) Timeseries.objects.bulk_create(series_list) def insertion(header, series_list, datetime, df_col, metadata): metrics = Metrics.objects.get(name=header[i]) print(metrics) try: val = df_col series_list.append(Timeseries(timestamp=datetime, Parameter=metrics, value=val, status=None, device_id=metadata)) except ValueError: series_list.append(Timeseries(timestamp=datetime_index, Parameter=metrics, value=None, status=val, device_id=metadata)) return series_list However when I try to run the code I always get KeyError: 1 error message. Any idea on how I can vectorize my function and the cause of the error message? -
Django custom context processor passes incorrect data to home template only
I'm working on a project which I require to show category menu on every page. So I decided to use a context processor for that as shown below: import logging logger = logging.getLogger(__name__) def product_categories(request): from shopadmin.models import ProductCategory categories = ProductCategory.objects.all() logger.info(f'CATEGORIES ARE: {categories}') return {'product_categories': categories} And I show the categories with following code in base.html {% if product_categories %} <div class="categories_menu_toggle"> <ul> {% for category in product_categories %} {% if category.is_root_category %} <li class="menu_item_children categorie_list"><a href="#"><span><i class="zmdi zmdi-desktop-mac"></i></span>{{ category.title }}<i class="fa fa-angle-right"></i></a> {% if category.sub_categories.all %} <ul class="categories_mega_menu"> {% for sub_category in category.sub_categories.all %} <li class="menu_item_children"><a href="#">{{ sub_category.title }}</a> {% if sub_category.sub_categories %} <ul class="categorie_sub_menu"> {% for child_category in sub_category.sub_categories.all %} <li><a href="">{{ child_category.title }}</a></li> {% endfor %} </ul> {% endif %} </li> {% endfor %} </ul> {% endif %} </li> {% endif %} {% endfor %} <li id="cat_toggle" class="has-sub"><a href="#"> {% trans 'More Categories' %}</a> <ul class="categorie_sub"> <li><a href="#"><span><i class="zmdi zmdi-gamepad"></i></span> {% trans 'Hide Categories' %}</a></li> </ul> </li> </ul> </div> {% endif %} home.html, products.html, product.html, invoice.html and almost all other templates extend base.html template. But something happens here that I can not understand. When I open the homepage (index), the result of the logger.info(...) from … -
Django Admin Models. Foreign Key Pop Up Window Full Screen
There is a foreign key in one of my models. In the add model page, when I click on the + button next to foreign key a pop up window appears. I want this window to be Full screen. -
Django Views has an issue not allowing all Context Variables to appear in template
I have made a Slider Model which contains 3 images and Texts related to it to slide in a Carousel My issue is that I want these images to be shown as per the order assigned as per the model but only one appears. If I remove the {% if sliders %} {% for slider in sliders %} the latest image only appears because in the views it is filtered by .latest('timestamp') I have also tried to replace .latest('timestamp') in the views with .all() it still didn't work This is the model: class Slider(models.Model): title = models.CharField(max_length=60) image = models.ImageField(blank=False, upload_to='Marketing') order = models.IntegerField(default=0) header_text = models.CharField(max_length=120, null=True, blank=True) middle_text = models.CharField(max_length=120, null=True, blank=True) footer_text = models.CharField(max_length=120, null=True, blank=True) button_text = models.CharField(max_length=120, null=True, blank=True) active = models.BooleanField(default=False) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) class Meta: ordering = ['order'] def __str__(self): return self.title def get_image_url(self): return "%s/%s" % (settings.MEDIA_URL, self.image) This is the view: class HomeView(ListView): model = Item paginate_by = 10 template_name = "home.html" def get_context_data(self, **kwargs): context = super(HomeView, self).get_context_data(**kwargs) try: context['marketing_message'] = MarketingMessage.objects.filter( active=True).latest('timestamp') except MarketingMessage.DoesNotExist: context['marketing_message'] = None try: context['slider'] = Slider.objects.filter( active=True).latest('timestamp') except Slider.DoesNotExist: context['slider'] = None return context This is the template: {% if sliders %} {% … -
Cannot connect to localhost:8000/admin page, Django
I'm a Django newbie. I'd created a superuser for my site, but when I start the server and try to connect to localhost:8000/admin page, the site refuses to connect and I get a ERR_CONNECTION_REFUSED (site cannot be reached) error. -
Flask-Admin page not found on production
I have built a flask app and deployed it to production using Vercel(formerly zeit now). Everything works except the flask admin. It returns url not found when accessing example.com/admin . Some suggested this move admin.Admin() initialization block away from the main function . But I don't know what that means can somebody help me ? Everything works perfect on local machine -
Reverse Foreign Key in filter of QuerySet in Django
Let's say I have two models: class Human(models.Model): name= models.CharField(#... class Jacket(models.Model): owner = models.ForeignKey(Human, #... So, thanks to this Question I was able to figure out that I could get all Jackets of a Human by doing: human_object.jacket_set Now I want to get a Queryset with all Humans that own a jacket. Inspired by this Question, I tried something like this, Human.objects.exclude(jacket__set=None) but I wouldn't be here if that had worked. Thx for helping and stay healty! -
Can not create media folder in Django Project
Media folder is not getting created when I run the server. I am working in localhost. You can see the urls.py and settings.py code below. I added 'django.template.context_processors.media' to the templates. My Django Version is 2.0.3 and I am using Python 3.6.8. When I run the code, media folder should be created automatically. How can I fix that issue? MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') #settings.py urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name = "index"), path('about/', views.about, name = "about"), path('articles/', include("article.urls")), path('user/', include("user.urls")), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) #urls.py -
How to use same django app for multiple sites like example.com, company.com and subdomains?
I would like to use django sites framework to get access with different URL´s to same application but it would be interesting to use the subdomains also, i do not know if django hosts will work with the sites framework. Would you mind to clarify my doubts, I haven´t found anything clear. -
User uploads and amazon ec2 instance
Not sure if this is the right place to ask this question but I would love to get an answer to this specific question. I have a Django SaaS that requires a user to upload a 5mb-15mb file per connection. I am expecting to scale up to 100 users. Most likely the app will be used daily by users. I am using nginx and gunicorn. In this scenario, what ec2 instance make sense to use and how many server should configurate to handle the uploads? I know that tests are necessary to exactly figure it out but in general, what kind of resource are required for this type of setup? -
Django Organizations with Django REST?
I wish to create several instances of several models in a "wizard" (think https://django-formtools.readthedocs.io/en/latest/) I decided not to use django-formtools because it just gave me a headache trying to customize it. Instead, I'll try to rely on DRF to create a rest api based wizard. My concern is - how can "translate" an existing ModelForm to work with DRF? I'm using Django Organizations, and one of the modelforms is for creating an organization through the provided ModelForm: class OrganizationAddForm(forms.ModelForm): """ Form class for creating a new organization, complete with new owner, including a User instance, OrganizationUser instance, and OrganizationOwner instance. """ email = forms.EmailField(max_length=75, help_text=_("The email address for the team owner (defaults to yours)")) def __init__(self, request, *args, **kwargs): self.request = request super(OrganizationAddForm, self).__init__(*args, **kwargs) class Meta: model = Organization exclude = ('users', 'is_active') def save(self, **kwargs): """ Create the organization, then get the user, then make the owner. """ is_active = True try: user = get_user_model().objects.get(email=self.cleaned_data['email']) except get_user_model().DoesNotExist: user = invitation_backend().invite_by_email( self.cleaned_data['email'], **{'domain': get_current_site(self.request), 'organization': self.cleaned_data['name'], 'sender': self.request.user, 'created': True}) is_active = False return create_organization(user, self.cleaned_data['name'], is_active=is_active) Can I somehow just pop this into a APIView and call the form_class above in a post method? Or would I need … -
Generate chart data based on withdrawals and deposit infos with python django
I have date and amount informations about withdrawals and deposits of an employees balance. Exactly I have these models in django: class Withdraw(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) amount = models.PositiveIntegerField(default=0) date = models.DateTimeField(default=timezone.now) class Deposit(models.Model): employee = models.ForeignKey(Employee, on_delete=models.CASCADE) amount = models.PositiveIntegerField(default=0) date = models.DateTimeField(default=timezone.now) So I have an array containing all dates of withdraws and deposits, and another array with the cumulative sums, so the actual balance: eg: days = [3,7,9] balance = [40,20,60] What I want is to display the whole month's balance with a line chart. I use chart.js, where I have to add the X and Y axes exactly the values I would like to show. So to have a full month's view I should pass to chart js these data. days = [1...30] #in case of a 30 day long month balance = [ 0, 0, 40, 40, 40, 40, 20, 20, 60, ..........#until end of the month.......] Do you know a better approach for this? Are there any function in python to create the balance array with data for all days in a month? Thx! -
Unpack error after running compilemessages in django
I have a Django project, and it was working fine. after some merges from my teammates, now when I try to run the server, AFTER using these manage.py makemessages and manage.py compilemessage I get this error: magic = unpack('<I', buf[:4])[0] struct.error: unpack requires a buffer of 4 bytes Can anyone help ? -
{{form}} fields not populating in modal
I'm experiencing an odd behaviour. I'm calling a foundation modal dialog from a parent page (parent.html) via a <a> element. This dialog contains a form which. I have another modal and calling a similar form (for another model) on the same page which is working fine (and before you ask: I've made a test and took it out completely and still have the issue with this one). This is my code. Users/models.py class Profile(models.Model): first_name = models.CharField(max_length=120, null=True, blank=True) forms.py: from users.models import Profile class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['first_name'] views.py: def venue_add_view(request): form_venue = VenueForm(request.POST or None) if form_venue.is_valid(): form_venue.save() context = { 'form_venue': form_venue, } return render(request, "venue-add.html", context) profile-add.html <div class="reveal" id="addProfile" data-reveal> <form id="addProfileForm" action='/profile-add/' onsubmit="mysubitfunction();" method='POST'> {% csrf_token %} <div class="grid-container"> <div class="grid-x grid-padding-x"> <h4>Add a new profile</h4> <div> {{form_profile.non_field_errors}} <p>Form should be here: </p> {{ form_profile }} </div> </div> <input class="button" type='submit' value='Save' /> </div> </form> parent.html: {% extends 'base.html' %} {% load static %} {% block content %} {% include '../profile-add.html' %} <a href="javascript:void(0)" data-open="addProfile">Add a new profile</a> {% endblock %} urls.py: from myapp.views import ( parent_view, profile_add_view) urlpatterns = [ path('parent_view/', parent_view, name='parent-view'), path('profile-add/', profile_add_view, name='profile-add') ] Now, … -
django/wagtail sendmail function not loading
it works perfectly in development environment but does not work for production. I am using apache2 as my server. The send mail functionality is called when a user fills in a feedback form , and the entry is saved into my database. contact/models.py/contactpage def send_mail(self, form): # `self` is the FormPage, `form` is the form's POST data on submit # Email addresses are parsed from the FormPage's addresses field addresses = [x.strip() for x in self.to_address.split(',')] print(addresses) # Subject can be adjusted, be sure to include the form's defined subject field submitted_date_str = date.today().strftime('%x') subject = self.subject + " - " + submitted_date_str # add date to email subject print(subject) content = [] # Add a title (not part of original method) content.append('{}: {}'.format('Form', self.title)) for field in form: # add the value of each field as a new line value = field.value() if isinstance(value, list): value = ', '.join(value) content.append('{}: {}'.format(field.label, value)) # Add a link to the form page content.append('{}: {}'.format('Submitted Via', self.full_url)) # Add the date the form was submitted content.append('{}: {}'.format('Submitted on', submitted_date_str)) # Content is joined with a new line to separate each text line content = '\n'.join(content) print(content) # wagtail.admin.mail - send_mail function is … -
Form creation for custom Inherited custom model
I'm very new to django. I'm working on simple login system. I have created a custom model named UserProfile which is inheriting User model by django. I have learnt to create forms that helps the user to change his profile details using the UserChangeFrom by django. But It allows changes to fields in the User model alone. But I want the form with my UserProfile model's fields too, So I created a form class inheriting this UserchangeForm. I don't know how to get the UserProfile object of current user,I tried getting it with the User objects primary key -1. but I don't think it will work for all the cases. form.py class EditUserProfileForm(UserChangeForm): website=forms.URLField(required=True) class Meta: model=UserProfile fields=( 'description', 'website', 'city', 'phone', ) def save(self, commit=True): user = get_object_or_404(UserProfile,pk=super(EditUserProfileForm, self).save(commit=False).pk-1) user.description=self.cleaned_data['description'] user.website=self.cleaned_data['website'] user.city=self.cleaned_data['city'] user.phone=self.cleaned_data['phone'] if commit: user.save() return user views.py def edit_profile(request): #print('primary:', request.user.pk-1) if request.method == 'POST': form = EditProfileForm(request.POST,instance=request.user) UserProfileForm= EditUserProfileForm(request.POST,instance=request.user) if form.is_valid() and UserProfileForm.is_valid(): form.save() UserProfileForm.save() return redirect(reverse('accounts:profile')) else: form = EditProfileForm(instance=request.user) UserProfileForm=EditUserProfileForm() args={'form':form,'UserProfile':UserProfileForm} return render(request,'accounts/edit-profile.html',args) -
webpack hot reload uses incorrect url
I'm using webpack's hot reload feature, along with Django. When I open the webpack dev server to http://127.0.0.1:3000/some/page/. I modify some Javascript to make the page hot reload. But the hot reload URL that gets fetched ends up being http://127.0.0.1:3000/some/page/bc6434656229f08c1681.hot-update.json http://127.0.0.1:3000/some/page/bc6434656229f08c1681.hot-update.js This is incorrect. The correct URL is always on based on http://127.0.0.1:3000/static. This is because /some/page/ is done through react-router, and is not an actual path on the server. Does webpack have an option to set the hot reload base URL? At the moment I'm just telling Django to redirect it, which works but isn't ideal. Ideally I would not want to write extra code in Django just for webpack's hot reload to work. P.S. My webpack config is: The way I integrate it with Django is through: devServer: { // For Webpack dev server. We use Django's static path since our index redirects to Django's index. publicPath: 'http://localhost:8000/static/', port: 3000, hot: true, inline: true, historyApiFallback: true, headers: { 'Access-Control-Allow-Origin': '*' }, proxy: { '/': { target: 'http://localhost:8000', // Redirect everything that we don't build to Django changeOrigin: true, }, }, }, -
Django, how to add 2 or more django custom filters
I am having difficulty adding 2 or more filters in jinga. <strong class="btn btn-block rounded-0 btn-outline-primary disabled" > {{ order.get_cart_total| add:500, floatformat:2 }} </strong>