Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Find all points in the database within a particular radius in Django
I have a Django model with separate columns of latitude and longitude (not the point field). I want to select all the points in my database within a particular radius from a given point. I tried geo-django but is required me to have a Pointfield. Is there any alternative I can retrieve all points with latitude and longitude as separate columns. Also I have indexed all my data using django-elasticsearch-dsl , so if there is is any method through elasticsearch-dsl would be equally helpful. I tried the method in the following link , but it too required to have a Pointfield . https://gis.stackexchange.com/questions/141533/geodjango-find-all-points-within-radius/177292#177292?newreg=690fabeb672246d98a7d29efa5422042 -
Access data of a model linked through a OneToOneField model on a form
I want a pre-populated form with the details (e.g. first name and surname) about the profile of a logged-in user, so that they can update them. I have a custom user model with first name and surname in it, and then a profile model which is linked to the user model and extends it, containing some extra information. I've defined a constant within the profile model which theoretically should get the user's first name and surname. models.py: class User(AbstractBaseUser): email = models.EmailField(verbose_name="email", unique=True, max_length=255) first_name = models.CharField(max_length=30, blank=True, null=True) surname = models.CharField(max_length=30, blank=True, null=True) [...] objects = UserManager() views.py: @login_required def profile_edit(request): if request.method == 'POST': p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if p_form.is_valid(): p_form.save() messages.success(request, f'Your account has been updated') [...] forms.py: class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ('first_name', 'surname') template.html: {% extends "base.html" %} {% block content %} <div> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{ p_form }} <button class="button" type="submit"> User update</button> </form> </div> {% endblock content %} When accessing the template via the browser I expect to see the form already populated with the profile's (i.e. user's) first name and surname. Instead, I get a django.core.exceptions.FieldError: Unknown field(s) (surname, first_name) specified for Profile in … -
Using Kiwi's password reset through the "forgot password" link displays 500 Internal Server Error. Is this an issue with settings at common.py?
Recently I had to change another user's password due to a probable typo. Using the login page's "forgot password" displayed a 500 error. Looking through Kiwi's dashboard, documentation, and github discussions, it was said that users can only change their own passwords. While I have worked around the issue (unable to change password) by using docker exec -it kiwi_web /Kiwi/manage.py changepassword userNameHere , I want to know if the cause for the initial 500 error is due to a settings issue in Kiwi's common.py file or it is something else entirely. Tried https://docs.djangoproject.com/en/2.2/topics/auth/default/ https://kiwitcms.readthedocs.io/en/latest/configuration.html https://github.com/kiwitcms/Kiwi/issues/610 https://docs.djangoproject.com/en/2.0/topics/email/#quick-example EMAIL_BACKEND = 'django_ses.SESBackend' AWS_SES_ACCESS_KEY_ID = 'key' AWS_SES_SECRET_ACCESS_KEY = 'key' EMAIL_HOST = '' EMAIL_PORT = 25 EMAIL_FROM = 'mail' DEFAULT_FROM_EMAIL = 'kiwi@example.com' EMAIL_SUBJECT_PREFIX = '[Kiwi-TCMS] ' Expected to be able to use password reset aimed towards the user's set email address. Actual is the 500 error. New to this btw. Thanks in advance. -
django how to create a sign out link with template?
I have tried this: .sign-out { height: 21px; width: 168px; color: #0854B3; font-family: Averta, serif; font-size: 14px; line-height: 21px; text-align: center; padding-top: 17px; margin-left: 291px; } <html> ... <form method="post" action="{% url logout %}"> {% csrf_token %} <div class="sign-out" type="submit">sign out</div> </form> <html> However the sign out text isn't clickable -- how do I make it so? -
Search in XEditableDatatableView is not working
Search in XEditableDatatableView isn't working properly for the custom fields/Non-field columns. I am trying to search with both the mobile number and email address which are multiple (formset I have used). But in search_fields whatever is there in the end it searches that. If my search_fields is like this search_fields = ['full_name', 'contactnumber__number', 'emailaddress__email_id'] then my search is working for only emailaddress and not for contactnumber and full_name. If I exchange the fields then search works with the last field only. The editable thing is working but search is happening with only one field. models.py from django.db import models from phonenumber_field.modelfields import PhoneNumberField class EnquiryModel(models.Model): full_name = models.CharField(max_length=100) class ContactNumber(models.Model): number = PhoneNumberField() enquiryform = models.ForeignKey(EnquiryModel, on_delete=models.CASCADE, blank=True, null=True) class EmailAddress(models.Model): email_id = models.EmailField(blank=True, null=True) enquiryform = models.ForeignKey(EnquiryModel, on_delete=models.CASCADE, blank=True, null=True) views.py class EnquiryDatatableView(XEditableDatatableView): model = EnquiryModel template_name = 'enquiryform/enquiry_list_datatable.html' class datatable_class(Datatable): candidatename = columns.TextColumn("Name", sources=None, processor='get_full_name') contactnumber = columns.TextColumn("Contact", sources=None, processor='get_contactnumber') emailaddress = columns.TextColumn("Email ID", sources=None, processor='get_emailaddress') def get_full_name(self, instance, *args, **kwargs): return format_html("<a href='/enquiryform/" + str(instance.id) + "' target='_blank' >" + instance.full_name + "</a>") def get_contactnumber(self, instance, *args, **kwargs): cnumber = EnquiryModel.objects.get(id=instance.id) numbers = cnumber.contactnumber_set.all() return "<br>".join([str(a.number) for a in numbers]) def get_emailaddress(self, instance, *args, **kwargs): eforms = … -
Inner join using Django router
I have two models "Users" and "UserHasMachine" which are connected by primary key I wanted to create queryset with fields from both of the tables filtered by a field "machine" field in "UserHasMachine" table I tried to use select_releated but it seems to return just full "User" table without filtering by a field in "UserHasMachine" models.py class User(models.Model): id = models.BigAutoField(primary_key=True) email = models.CharField(unique=True, max_length=128) name = models.CharField(max_length=256, blank=True, null=True) pwd_hash = models.CharField(max_length=128, blank=True, null=True) pwd_salt = models.CharField(max_length=256, blank=True, null=True) is_builtin = models.IntegerField() has_account = models.IntegerField() is_verified = models.IntegerField() is_enabled = models.IntegerField() verifycode = models.CharField(max_length=128, blank=True, null=True) user_creator = models.ForeignKey('self', models.DO_NOTHING) is_deleted = models.IntegerField() deleted_at = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = False db_table = 'user' class UserHasMachine(models.Model): user = models.ForeignKey(User, models.DO_NOTHING, primary_key=True) machine = models.ForeignKey(Machine, models.DO_NOTHING) role = models.CharField(max_length=5) created_at = models.DateTimeField(blank=True, null=True, auto_now_add=True) updated_at = models.DateTimeField(blank=True, null=True, auto_now=True) class Meta: managed = False db_table = 'user_has_machine' unique_together = (('user', 'machine'),) views.py class UserMachineViewSet(ListRetrieveUpdateModelViewSet): queryset = UserHasMachine.objects.select_related('user') serializer_class = UserMachineSerializer filter_backends = (filters.DjangoFilterBackend, ) filter_fields = ('machine_id', ) permission_classes = (partial(UserInAnyGroup, { 'update': ['admin'], 'partial_update': ['admin'] }),) class UserViewSet(ListRetrieveUpdateModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer filter_backends = (filters.DjangoFilterBackend, ) … -
Pagination calling APIs data again in django
I am working on a project where I have to pass several projects ids to API calls. I am storing that in a list and on that list I am using paginator. But when I access the next page again the whole view gets called and it makes those API calls again instead of taking it from the stored list. for i in rt: t = requests.get('https://wstest2.xtm-intl.com/rest-api/projects/' + str(i['id']), headers=headers,verify=False) tt = t.json() print('yo') targetlist.append(tt) mylist=list(zip(rt,targetlist)) page=request.GET.get('page',1) paginator = Paginator(mylist, 10) pagelist=paginator.get_page(page) context={'pagelist':pagelist} return render(request,'dashboard/home.html',context) -
i am facing trouble in django fyp
What I need to do ,I want to submit my university final year project in Django .I have done my basic with Django and Django-rest-frame..what I need to do next, I also need idea for project any one help me? -
Is it possible to control data displayed on templates of multiple apps from admin?
I have a partial template that I use on multiple apps. You can imagine it like something like a footer that containst contact info. I want to be able to change that contact info from admin but since it is used by multiple apps I would probably have to make a model for this in every app that I have in my project. Is it possible to make something like a global model that would be able to do this? -
Should i annotate types everywhere?
Should i annotate types in my unit tests functions? What also with overridden django methods like save and get or post functions in generic view? -
How to get a token passed to Django allauth Signup
I am using allauth and want a user to be able to invite people via email to sign up to an account. When the new user signs up, I want to set their 'school' field to be the same as the user who invited them. In other words, they are part of the same school and I want to store that info when saving the new user. To achieve this, I have an invite button which sends an email with the original user's school passed as a token, like so: class AddUsers(TemplateView): template_name = 'schools/add-users.html' def get(self, request, *args, **kwargs): add_user_form = AddUserForm() context = { 'add_user_form': add_user_form } return render(request, self.template_name, context) def post(self, request, *args, **kwargs): if 'add_users' in request.POST: add_user_form = AddUserForm(request.POST) if add_user_form.is_valid(): to_email_address = add_user_form.cleaned_data.get('email_field') user = request.user school = request.user.school mail_subject = 'Invitation to create an account' url = request.build_absolute_uri(reverse('account_signup')) uid = urlsafe_base64_encode(force_bytes(school.pk)) token = account_activation_token.make_token(school) activation_link = "{0}?uid={1}&token{2}".format(url, uid, token) message = 'Hi,\n\nYour colleague ' + user.first_name + ' has invited you to sign up.\n\n' message += 'Click the activation link below\n\n' message += activation_link email = EmailMessage(mail_subject, message, to=[to_email_address]) email.send() return HttpResponseRedirect(reverse('schools:add-users',)) return HttpResponseRedirect(reverse('settings', )) I override the allauth Signup form like … -
How can I display all my existing records in Mysql from Django database?
I migrated the Django database model to MySQL. When I tried to access the data in MySQL, I can't seem to find my existing data. How can I fix this? Migration code: settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'sample', 'USER': '********', "PASSWORD": '********', 'HOST': '*****', 'PORT': '*****', 'OPTIONS': { 'sql_mode': 'traditional', } } } models.py from django.db import models import os from PIL import Image from datetime import date import datetime from .validators import validate_file_extension import base64 from django.utils.functional import cached_property from django.utils.html import format_html def get_directory_path(instance, filename): today = date.today() t = datetime.datetime.now() day, month, year = today.day, today.month, today.year hour, minutes, seconds = t.hour, t.minute, t.second filename = str(day) + str(month) + str(year) + str(hour) + str(minutes) + str(seconds) + '.png' dir = 'media' path = '{0}/{1}'.format(dir, filename) return path class Image(models.Model): image = models.FileField(upload_to = get_directory_path, null = True , validators=[validate_file_extension]) created_date = models.DateTimeField(auto_now = True) def __str__(self): return str(self.id) After this, I typed: python manage.py makemigrations python manage.py migrate Everything seems to work well but I'm not able to view my data. Any suggestions? -
How to show execution percentage on html template in django at realtime
How can I show the no of loop executed at the backend on html page? or a progress bar of the loop execution. -
Error creating new content types when Uwsgi kills aworker
I am Running a django application with uwsgi, I am observing a case Sometimes, when uwsgi kills it's worker and and respawns a worker. Thu Aug 8 11:02:33 2019 - worker 1 killed successfully (pid: 25499) Thu Aug 8 11:02:33 2019 - Respawned uWSGI worker 1 (new pid: 4192) And then the next request received by the django application returns 500 error with Exception: RuntimeError: Error creating new content types. Please make sure contenttypes is migrated before trying to migrate apps individually. at line content_type = ContentType.objects.get_for_model(Coupon) -
Python/Django logging: logger lets through log records below its' level?
I use Python 3.7.3 and Django 2.2.4. I wanted to extend the Django's default logging config to achieve the following: myproject emits some WARNING-s that I want to be logged to stderr using logging.StreamHandler. I want 5xx ERROR-s with stack traces also be logged to stderr the same way (but not WARNING-s about 4xx error codes!) What I tried to do first: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'myproject-console': { 'level': 'WARNING', 'class': 'logging.StreamHandler', }, }, 'loggers': { 'myproject': { 'handlers': ['myproject-console'], 'level': 'WARNING', 'propagate': False, }, '': { 'handlers': ['myproject-console'], 'level': 'ERROR', 'propagate': False, }, } } It worked. But catch-all '' logger having the level of ERROR ended up forwarding Django's propagated WARNINGs about 400s (like Unauthorized: <url> for every 401) to the stderr too! Even though the respective logger is clearly of ERROR level, it seems to let through messages of a lower WARNING level to a WARNING handler. What I ended up doing and what worked as I wanted was to create a separate ERROR-level handler and forward catch-all ERROR logger output to it: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'myproject-console': { 'level': 'WARNING', 'class': 'logging.StreamHandler', }, 'myproject-console-error': { 'level': … -
Django html how to override css
I have a button like so .btn--primary { height: 45px; width: 300px; border: none; border-radius: 100px; background-color: #00A87E; color: #FFFFFF; font-family: Averta, sans-serif; font-size: 16px; font-weight: 600; line-height: 19px; } In my django template, I want to override some attributes of this button. Specifically, I want it to be aligned to the centre I have got this so far: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" type="text/css" href="{% static "css/main.css" %}"/> <meta charset="UTF-8"> <title>My centre button</title> </head> <body> </body> </html> How do I accomplish this? :) -
Is there a way to modify downloaded / cloned github code?
I have cloned the following github app: https://github.com/tomwalker/django_quiz, however I would like to tweak it slightly by using my own base.html and modifying the models to fit the purpose of my site. The problem is that even if I make changes to the code it doesn't appear on the site. It's as if the code I'm editing doesn't have any influence to the app. I'm new to Django so I guess there are a simple answer for this problem? When I clone the project the app works as it should, but I can't make any changes. I therefore tried to copy the code from each file one by one into my project. This didn't work either, receiving errors like: "No module named 'quiz'" (which is an app that's included in the link above). The directory structure of my project is displayed below: mysite | |-app_1 |-app_2 |-django_quiz | | | |-essay | |-migrations | |-multichoice | |-quiz | |-true_false |-mysite I would obviously like to be able to modify the code. At the moment I could do any changes to the code in django_quiz and nothing changes on the site. -
Error loading MySQLdb module. Did you install mysqlclient? on MacOS
Am Trying to connect to my mysql db from django app. I get the below error during migratation: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? I've already installed mysqlclient as below: Requirement already satisfied: mysqlclient in /usr/local/lib/python3.7/site-packages (1.4.2.post1) I've also tried with pymysql and adding below code to ini.py file: import pymysql pymysql.install_as_MySQLdb() Gives me some other errors. What could be wrong? Python 3.7 , mysql 5.7 and Django 2.2 are my setup versions. -
Setup Emacs for Django development
I am trying to set up emacs for django development. I already have elpy, jedi and flycheck set up and working with my venvs, but when I go to look for extending my setup for django development, I find too many related modes that seem to be doing similar things. Specifically package-list-packages gives me the following options: django-commands django-manage django-mode djangonaught pony-mode python-django Searching the web for comparisons doesn't seem to yield much result and I can't find anything relevant or recent here. Now I can certainly try each and every one of these for a day or two and evaluate them one by one, but I was wondering if somebody can at least help me eliminate some of the options or give me some advice on the matter. Thank you. -
How to add registration record in mongodb database?
I am working on a project in django and using mongodb. I am new in this field. I have a question that how to add registration record in mongodb using django. Just like User in django admin page. I want it to save all the users who register in my website in mongodb. How to do this? -
How to add different model to ModelForm as extra field?
So I'm trying to add an extra field to a ModelForm class in the init func, so that on the Create/Update class views I could grab this model and create a new model. Since the Model doesn't have this field, how could I add it in the init func or is there some other way I could add this field? I've tried overriding init method to include this field in the ModelForm class, but this still throws me an error that the argument is unexpected class MeterInstallationForm(ModelForm): class Meta: model = MeterInstallation fields = METER_INSTALLATION_DEFAULT_FIELDS def __init__(self, *args, **kwargs): instance = kwargs.get("instance") super(MeterInstallationForm, self).__init__(*args, **kwargs) if instance: # get tariff info in the form # self.fields["tariff"] = instance.tariff self.fields["tariff"] = TariffApplication.objects.filter(meter_installation__pk=instance.meter_installation.pk).values_list("tariff", flat=True) I would love to know how to make this work, so that in my CreateView I could start creating a third model by the given Tariff -
Django email templates rendering generate invalid html | Django Authentication. user signup emails
Django 2, Python 3. Django default authentication send email containing corrupted html. contains 3D with each attribute's equal sign. style=3D" contains = with each starting new line. padd= ing-top:20px; Sample Code: <div style=3D"padding: 40px; background: #fff;"> <table style=3D"width: 100%;" cellspacing=3D"0" cellpadding= =3D"0" border=3D"0"> <tbody> <tr> <td style=3D"border-bottom:1px solid #f6f6f6;"> <h1 style=3D"font-size:14px; font-family:ar= ial; margin:0px; font-weight:bold;">Greetings!,</h1> <p style=3D"margin-top:0px; color:#bbbbbb;"= >Here are your account activation instructions.</p> </td> </tr> <tr> <td style=3D"padding:10px 0 30px 0;"> <p>Thank you for joining us.</p> <p>To activate your profile, please follow = this link:</p> <center> <a href=3D"http://localhost:8000/accoun= ts/activate/uyi90WsYyvLKmn4wwwqq/" style=3D"display: inline-block; padding:= 11px 30px; margin: 20px 0px 30px; font-size: 15px; color: #fff; background= : #4fc3f7; border-radius: 60px; text-decoration:none;">Activate Profile</a> </center> <b>- Thanks (project team)</b> </td> </tr> <tr> <td style=3D"border-top:1px solid #f6f6f6; padd= ing-top:20px; color:#777">If the button above does not work, try copying an= d pasting the URL into your browser. If you continue to have problems, plea= se feel free to contact us at info@project.com</td> </tr> </tbody> </table> </div> Please help resolve/identify the issue. -
Is it a simple conversion or a creation of a new object?
Here are my models, pretty straightforward: class Entity(BaseModel): is_physical = models.BooleanField(default=True) class Address(BaseModel): description = models.TextField(default=None, blank=False, null=False) class EntityAddress(BaseModel): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, blank=False, null=False) address_type = models.ForeignKey(AddressType, models.CASCADE, blank=False, null=False) address = models.ForeignKey(Address, on_delete=models.CASCADE, blank=False, null=False) From there I've created the model Person which is a physical entity: class PersonManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(is_physical=True) class Person(Entity): objects = PersonManager() user = models.OneToOneField(User, blank=True, null=True, on_delete=models.CASCADE) Then I generate tons of addresses, tons of Persons, it works. When I try to create a "person address" like this: EntityAddress.objects.create(entity=person, address_type=choice(address_types), address=address, comment=None))) I get "EntityAddress.entity" must be a "Entity" instance. The solution is : EntityAddress.objects.create(entity=Entity(person), address_type=choice(address_types), address=address, comment=None))) Hence my question: does Entity(person) create a new object in memory, or it just does a simple conversion? -
Search Engine in Django
When I search the files I uploaded using the upload functionality of the website, the search engine finds the files. However, when I try to search for the files that were uploaded using ftp, the search engine is unable to find the files. -
how to make a modal show using bootstrap in django
i have a modal that contains a list and on the click button it must show the problem is that once i click the button the modal doesn't show instead it display a shadow i know that by default the modal is hidden and i need jquery in order to make it show and display its content. update2.html <div class="modal fade" id="modalCart" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <!--Header--> <div class="modal-header"> <h4 class="modal-title" id="myModalLabel">Your Result</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <!--Body--> <div class="modal-body"> <table class="table table-hover"> <thead> <tr> <th>ID</th> <th>Number</th> <th>Title</th> <th>Type</th> <th>Content</th> <th>User</th> </tr> </thead> <tbody> {% for folder in FilterRecords %} <tr align="center"> <td>{{ folder.id }}</td> <td>{{ folder.FolderNum }}</td> <td>{{ folder.FolderTitle }}</td> <td>{{ folder.Type }}</td> <td>{{ folder.Content }}</td> <td>{{ folder.user}}</td> </tr> {% endfor %} </tbody> </table> </div> <!--Footer--> <div class="modal-footer"> <button type="button" class="btn btn-outline-primary" data-dismiss="modal">Close</button> <button class="btn btn-primary">Checkout</button> </div> </div> </div> </div> base.html <form class="form-inline" id = "folderSearch" method="GET" action="{% url 'search_folder' %}"> <input class="form-control mr-sm-2" type="text" placeholder="عما تبحث؟" name="searchFolder" value="{{request.GET.searchFolder}}"> {%include 'blog/update2.html' %} <a href="{% url 'update2'%}" class=" btn btn-danger confirm-search" title="Search" data-toggle="modal" data-target="#modalCart" id="searchButton">search </a> </form> <script type="text/javascript"> $(document).ready(function(){ $(document).on('click', '.confirm-search', function () { $('#modalCart').modal('show'); }); }) </script>