Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I determine if two values would be the same on the same field in a Django model?
I'd like to determine whether two values would end up being the same if stored in the same Django model field. model_values_equal(MyModel, my_date_field, "2019-01-02", date(2019, 01, 2) -> True model_values_equal(MyModel, my_date_field, "2019-01-02", date(2019, 01, 3) -> False Basically, if two values would store the same value for a field on a model, I'd like to return True (in the above example, the string would be converted to date internally by the DateField) -
Error occurring when generating random string, and using when sending an email
I am writing an endpoint in my api where users can reset their passwords. I use the python library smtp to send an email to the user with a code. This code is a simple string. I randomly generate this string, and send it as the content for the email. However when I send a request to the endpoint, The error: AttributeError: 'NoneType' object has no attribute 'encode' occurs. Here is my endpoint code: code = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(8)) content = 'Subject: {}\n\n{}'.format('Your code to reset your password:', code) mail = smtplib.SMTP('smtp.gmail.com', 587) mail.ehlo() mail.starttls() mail.login(os.environ.get('email'), os.environ.get('password')) mail.sendmail(os.environ.get('email'), user.email, content) mail.close() hashedReset = make_password(code) user.resetCode = hashedReset user.save() return JsonResponse({'message': 'An email has successfully been sent to the email paired with this account.'}, status=200) When I print the code variable, a random string is displayed, therefore that isn't the issue. Anyone know what the issue is? Thank you. -
Django site won't load after a few months of resting
My django server won't load. When I run python manage.py runserver it will show the first message about packages and then crash my computer in 10 seconds. Nothing won't work including a mouse cursor. It was a working project a few months ago but now when I need to change a couple of things there it won't let me do it. I've already reinstalled python and all the packages. Also my app uses postres db but I can access it via PGAdmin, so what is the issue? It work fine though on a remote computer on Linux but I need it to work locally also. -
i'm getting this error while installing msqlclient. even i installed visual c++ but the same issue is coming
i'm getting this error while installing ms q l c l i en t. even i installed visual c++ but the same issue is coming. i have searched for this type of error but i did not found it. i tried by installing p y my sq l, i updated setup too ls, in command prompt also it's displaying the same error. Building wheels for collected packages: my sq l cl i e n t Building wheel for my sq l c l i en t (setup. p y) ... error ERROR: Command error e d out with exit status 1: c building 'MySQL db._mys q l' extension error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": ht t p s://visual studio. micro soft. com/downloads/ ---------------------------------------- ERROR: Failed building wheel for mys q l cl i e n t Running setup.p y clean for mys q l c l i e n t Failed to build mys q l client Installing collected packages: mys q l client Running setup.p y install for mys q l client ... error ERROR: Command err o red out with exit status 1: command: ' i tried in many … -
Django crispy forms add API to crispy field
I am not well versed in javascript so I am having trouble adding API functionality to a Django form. This is the API I want to use: https://clinicaltables.nlm.nih.gov/apidoc/icd10cm/v3/doc.html I want to add that functionality to a crispy field within my HTML: {{ form.diagnosis_codes|as_crispy_field }} What is the best way to accomplish this? -
What is the reason for moving logic out of Django views?
I am wondering why we would move logic out of the views.py file if it seems to work best there? Take for example this view: class MemoCreateView(LoginRequiredMixin, CreateView): model = Memo form_class = MemoForm def form_valid(self, form): form.instance.sender = self.request.user # set form sender as user form.save() casino = self.request.user.casino form.instance.casino.add(casino) # set form sender as user groups = form.cleaned_data['receiver'] # data from forms title = form.cleaned_data['title'] content = form.cleaned_data['content'] for group in groups: # send notification to receiver groups username = User.objects.filter(groups__name=group) for user in username: form.instance.unread.add(user) user_obj = User.objects.get(username=user) user_phone = user_obj.phone user_email = user_obj.email if user_obj.sms_notifications: send_memo_sms(user_phone) if user_obj.email_notifications: send_memo_email(user, user_email) notify.send(sender=form.instance.sender, recipient=group, verb=title, description=content) form.save() return super(MemoCreateView, self).form_valid(form) It is a long form_valid method but seems to all belong in the view, correct? I was trying to shift some of the logic to the Memo model but with having to use the request object that logic would have to move into the ModelAdmin's save_model method. This seems to be a confusing way of structuring the code. I know this is slightly opinionated but, does this logic work better in the view's form_valid method or elsewhere? Why? My goal here is to make my views thinner as … -
Heroku (django/react) CORS request did not succeed
I'm deploying my django/react app to heroku. Basically all frontend and react routing works but I am not getting data from API requests. I have already set CORS settings: INSTALLED_APPS = [ 'whitenoise.runserver_nostatic', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'corsheaders', ] MIDDLEWARE = [ # 'django.middleware.security.SecurityMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.Csr# CORS SETTINGSfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware' ] # CORS SETTINGS CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) I'm using axios for API requests. Sample request (/api/posts/ endpoint): (also I don't know how to set URLS properly) let url = 'https://<<MYPAGENAME>>.herokuapp.com/api/posts/' axios.get(url).then({ DOES SOMETHING }) Actually I'm getting 200 OK status code but response payload is empty. When I visit https://<>.herokuapp.com/api/posts/ in browser I can see API viewset but it's also empty. -
Signals in Django. Please break down the code
@receiver(post_save,sender=User) def create_profile(sender,instance,created,**kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save,sender=User) def create_profile(sender,instance,**kwargs): instance.profile.save() Can someone please explain the code in simple words. I understand that post_save is signal which is send by User and create_profile receives the signal. and if the user is created,it saves the profile. but can someone break down the code so I understand and use it elsewhere rather than just copy paste it. and what is instance and why do we use it ? -
Unable to install uwsgi - Django
setup.py from setuptools import setup, find_packages setup ( name = "todobackend", version = "0.1.0", description = "Todobackend Django REST service", packages = find_packages(), include_package_data = True, scripts = ["manage.py"], install_requires = ["Django>=1.9, <2.0", "django-cors-headers>=1.1.0", "djangorestframework>=3.3.0", "MySQL-python>=1.2.5", "uwsgi>=2.0"], extras_require = { "test": [ "colorama>=0.4.1", "coverage>=4.5.4", "django-nose>=1.4.2", "nose>=1.3.7", "pinocchio>=0.4.2" ] } ) requirements.txt . requirements_test.txt -e .[test] Logs does not show uwsgi getting downloaded in /build, $ docker-compose up test Creating dev_db_1 ... done Creating dev_cache_1 ... done Creating dev_test_1 ... done Attaching to dev_test_1 test_1 | DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support test_1 | Looking in links: /wheelhouse test_1 | Collecting Django==1.9 (from -r requirements.txt (line 1)) test_1 | /appenv/local/lib/python2.7/site-packages/pip/_vendor/urllib3/util/ssl_.py:365: SNIMissingWarning: An HTTPS request has been made, but the SNI (Server Name Indication) extension to TLS is not available on this platform. This may cause the server to present an incorrect TLS certificate, which can cause validation failures. You can upgrade to a newer version of … -
How to add custom css class to wagtail dashboard buttons
How can we add custom classes to wagtail dashboard buttons like 'View Live', 'Edit' Buttons for contents created. When I browse through the core files I noticed core wagtail hooks for admin page like below (I know we are not supposed to edit the core files) if page.live and page.url: yield PageListingButton( _('View live'), page.url, attrs={'target': "_blank", 'rel': 'noopener noreferrer', 'title': _("View live version of '{title}'").format(title=page.get_admin_display_title())}, priority=30 ) If I add 'class':'custom-class' to attrs value then the default class disappears and custom-class appears What is the right way to do this -
required = True attribute not working in Django's MultipleChoiceField
I have services field in my MainForm class. It looks like this: services = forms.MultipleChoiceField( choices=services, widget=forms.widgets.CheckboxSelectMultiple({"id": "services"}), label="Here you can choose one or more services", required=True ) But, when I sumbit my MainForm, it passes validation even with empty services field. As I saw, anyone who want MultipleChoiceField to be required, sets it to True. But, in my case, it doesn't work. -
Dash datatable not support in django. not find solution
Im tired to checking dash datable document and also dash django but not find away to shown dash-datatable in django -
Ajax and Python - How to deal with request timeout
I have a little django project that creates a XLSX report using XlsxWriter getting records from a database using the following "pseudo" python code: global myWorkbook myWorkbook = Workbook("my_report.xlsx", {'constant_memory':true}) db_conn = databases.getDbConnection() table1_thread = threading.Thread(target=generate_sheet, args=("table1", db_conn)) table1_thread.start() table2_thread = threading.Thread(target=generate_sheet, args=("table2", db_conn)) table2_thread.start() table3_thread = threading.Thread(target=generate_sheet, args=("table3", db_conn)) table3_thread.start() table4_thread = threading.Thread(target=generate_sheet, args=("table4", db_conn)) table4_thread.start() #Threads joining here... db_conn.close() return myWorkbook These tables that I'm doing the SELECT's are really huge (about 50 thousand rows) and takes a long time to generate the report (from 2 to 8 minutes). In my front end I want to use an ajax request to start the report generation and to show a "Download button" when the report is done in ajax success function. But I'm facing a timeout issue after the click on "Generate Report" button. I searched the Internet and I figure out that I can't change this ajax timeout. So, I would like to now: What should I do to accomplish this objective? I don't have the possibility to save the reports in the server because they are heavy (about 40~60MB) and it's generated every day. -
Django Qeryset order by a not directly related model's field
I have the following model design: class Boat(models.Model): name = models.CharField(max_length=30, null=False) harbour = models.ForeignKey(Harbour, null=True, on_delete=models.SET_NULL) class Harbour(models.Model): name = models.CharField(max_length=60) city = models.ForeignKey(City, null=True, related_name='city_harbours', on_delete=models.SET_NULL) class City(models.Model): name = models.CharField(max_length=80) county = models.CharField(max_length=30, null=True) class NearestCity(models.Model): city = models.ForeignKey(City, related_name='city', null=False, on_delete=models.CASCADE) near_city = models.ForeignKey(City, related_name='near_city', null=False, on_delete=models.CASCADE) weight = models.DecimalField(null=False, max_digits=25, decimal_places=20) Brief explanation: A Boat belongs to a Harbour and a Harbour belongs to a City. Not all Cities have a harbour related. NearestCity is a table where is stored how close is a city the rest of the cities: The weight is a decimal value that indicates how far is city from _near_city_ . The more smaller is the 'weight' value, the more close is city to near_city. For example: city near_city weight ---- --------- ------ London Rome 2.210103 London Manchester 0.113134 It means that Manchester is closer to Lonon than Rome. Problem to solve: Given a name of a city without any harbour related, for instance Berlin, a want to return all the boats of those closest cities that do have at least one harbour related. This Boat's queryset must be ordered by weight DESC. -
Using Django Templates to send an email
I have a Django template that I'm using to send emails. I'm using Sorl thumbnail to generate a thumbnail to be used in the email. {% thumbnail event.image '90x100' crop=True as im %} <img class="float-center" src="{{ im.url }}" alt=""> {% endthumbnail %} The issue is the src is an absolute path on the filesystem. I would like to prepend the im.url with my server's web address. I tried a few ways of concatenating strings but nothing seemed to stick. -
Django - How to call a @classmethod from a View as a result of form POST
I'm fairly new to Django and I'm not sure this is the best way to do this. To summarize- what I am trying to accomplish is: Call a @classmethod located within a ModelForm from the POST method within the TemplateView. Please see below for the pertinent code: form.py class bdForm(forms.ModelForm): addbdteam = forms.ModelMultipleChoiceField(queryset=TeamMember.objects.all().order_by('lastname'), widget=Select2MultipleWidget, required=False) @classmethod def assign_team(cls, addbdteam): for b in addbdteam: assignee = Broker.objects.filter(fullname=b) assignee.projects.add(cls) print('Added project to {}.').format(assignee) views.py class bdFormView(TemplateView): def post(self, request): form = bdForm(request.POST) if form.is_valid(): print("form is valid") project = form.save(commit=False) form.assign_team(form.cleaned_data['addbdteam']) # project.save() text = form.cleaned_data['briefcard'] brokername = form.cleaned_data['sourcingbroker'] brokerobj = Broker.objects.all().filter(fullname=brokername) print(brokerobj) Thanks for your help!! -
Django template not found although it it exists in templates folder
Django version 2.2.6 I have the following folder structure and was expecting Django to find index.html based as it is placed in the default location under templates. Am I doing something wrong here? Did Django stop looking up the template paths by default? -app | settings.py urls.py ... templates | base.html index.html views.py from django.shortcuts import render # Create your views here. def home_view(request): return render(request, 'index.html') urls.py from django.contrib import admin from django.urls import path from .views import home_view urlpatterns = [ path('', home_view, name='index'), path('admin/', admin.site.urls), ] -
Content Duplication when Extending CKAN with a custom theme
So I am trying to extend CKAN using our theme and I keep encountering issues due to plugin order (I believe) and content duplication. For example in 2 instances, I am trying to fix a missing font-awesome ICON in the Issues tab and rename Groups to Collections. The template file is ckan/templates/package/read_base.html and I am trying to override in dmt_theme/templates/package/read_base.html The following Screenshots and code output: {% ckan_extends %} {% block package_organization %} {% endblock %} {% block content_primary_nav %} {{ super() }} {% if h.issues_enabled(pkg) %} {{ h.build_nav_icon('issues_dataset', _('Issues'), dataset_id=pkg.name) }} {% endif %} {% endblock %} Produces this: And when I try to copy the content from CKAN's read_base.html file to just rewrite and control the whole block of content... And regardless of where I put the plugins in my development.ini file it seems to have the same effect. The plugin order is another issue I been battling for the better part of a year now. -
Django admin sites request
I am serving my webpage with nginx and waitress using https. When I go to my domain, I see the admin page, but when I try to login the following message appears: Forbidden (403) CSRF verification failed. Request aborted. Help Reason given for failure: Referer checking failed - https://example.com/admin/login/?next=/admin/ does not match any trusted origins. There are other threads around this topic, but all of them seem to address custom forms. This is the django default admin login page. How am I supposed to change the provided forms so that the CSRF tokens are sent? And why is this not happening automatically by default? My MIDDLEWARE list in settings.py contains django.middleware.csrf.CsrfViewMiddleware. -
Django, display part of table items in droplist in UpdateView class
I'm new to django. So I got two model class: 1. Order model, dealing with order details, including a "status_id" as FK related with Status table 2. Status model, storing order status, the scheme is something like below: id name 1 submitted 2 cancelled 3 pending 4 confirmed 5 completed The scenario is when customer created a order, status_id=1 (submitted) by default, who can also change the status to cancelled to cancel the order. Then only system admin can change the status to "pending", "confirmed" or "completed" depending on situations. So, on the page that admin manage orders, I want the dropdown list of status only show id=3,4,5 in Status table. How can I make that happen? By the way, I'm using generic class-basd view. Check the code below. Views.py class UpdateByAdminView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Order fields = ['title', 'content', 'status'] def form_valid(self, form): return super().form_valid(form) def test_func(self): if self.request.user.is_staff: return True return False -
Django ModelForm Not Saving - Tried 3 methods of interacting with the Model
The Goal I have a list of calls, the callqueue, loading into a form based on the Current Custom User's Extension. I need to load the first instance and then cycle through the calls when the form is saved. I have a variable called follow_up that's a datefield and if set to later than todays date, that client won't pull in the query listed below and should accomplish the goal of moving the queue along. Thing is, I can't seem to get the form to save. Query referenced earlier Client.objects.filter(follow_up__lte=date.today(), csr__extension=request.user.extension).order_by('-hot') The thing is, I can't get the form to save. I've been troubleshooting this problem for a couple of days at this point and I feel my face and keyboard becoming friends soon. What I've tried so far Using a ModelForm with a Class Based View Using a ModelForm with an UpdateView Using a manually defined ClientForm(forms.Form) Making sure null= True, blank = True for testing purposes Using Pagination on a formset with one form limiting and specifying one form as found here def client_view(request): def wait_days(num): return timezone.now() + timezone.timedelta(days=num) wait_time = wait_days(2) FormSet = modelformset_factory(Client, form=ClientSheet, extra=0) if request.method == 'POST': formset = FormSet(request.POST) if formset.is_valid(): if … -
Make multiple POST requests to a URL concurrently in Python
I'm using Django and Django Rest Framework. Inside my urls.py, I've defined the following endpoint /payments/. It supports POST requests. Background info: Not long ago, we had a user send multiple requests to this server concurrently triggering a race condition and therefore stealing money. Question: How can I write a test to send 100-1000 requests to this URL API endpoint? This is how I currently send POST "test" requests in my test file: class PaymentViewTestCase(BaseTestCase): def setUp(self): super(PaymentViewTestCase, self).setUp() self.client = APIClient() self.client.force_authenticate(user=self.profile) def test_post_create_payment(self): amount = 1000 request_data = { 'amount': amount, } res = self.client.post( '/v2/instant/transfer/', ujson.dumps(request_data), content_type='application/json', secure=True ) However, I would like to trigger this POST request 1000, exactly at the same time. -
Save data into mysql with Django
I'm beginner with Django and I'm trying implement a app to save some data into Mysql 1st Step: I'm Check If "mag_no" field exist in mysql db, if yes: bring model_code and line_nm After that, I want create a form to include the other fields: CN1,CN2,CN3,CN4 and reuse the previous already get from first check. CN_form.html <form action="{% url 'CnCreateListMag' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Mag No:</label> <input id="mag_no" type="text" name="mag_no" value="{{ mag_no }}"> <label>Model Code:</label> <input id="model_code" type="text" name="model_code" value="{{ model_code }}"> <label>Line:</label> <input id="line_nm" type="text" name="line_nm" value="{{ line_nm }}"> <label>Result:</label> {% if result == 'OK' %} <a STYLE="background-color:DodgerBlue;">{{ result }}</a> <br><br> <form action="{% url 'magazine_new_add' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <label>Mag No:</label> <input id="mag_no1" type="text" name="mag_no1" value="{{ mag_no }}"> <label>Model Code:</label> <input id="model_code1" type="text" name="model_code1" value="{{ model_code }}"> <label>Line:</label> <input id="line_nm1" type="text" name="line_nm1" value="{{ line_nm }}"> <label>CN1:</label> <input id="cn1" type="text" name="cn1" value=""> <label>CN2:</label> <input id="cn2" type="text" name="cn2" value=""> <label>CN3:</label> <input id="cn3" type="text" name="cn3" value=""> <label>CN4:</label> <input id="cn4" type="text" name="cn4" value=""> <button type="submit" class="btn btn-info my-4 btn-block">Save</button> </form> {% else %} <a STYLE="background-color:Salmon;">{{ result }}</a> {% endif %} <button type="submit" class="btn btn-info my-4 btn-block">Search</button> </form> My Views: @login_required def CnCreateListMag(request): form = CNForm(request.POST or None) if request.method … -
should I use Instagram postgressql id generator techniques for my project
If my epoch time is the 2019-11-11. For how many years can I generate unique I'd using Instagram technique. Can someone explain how this algorithm works. https://instagram-engineering.com/sharding-ids-at-instagram-1cf5a71e5a5c?gi=a23b1b9c6107 -
Django: Limit the number of selections in the UI using the FilteredSelectMultiple Widget
I am using the FilteredSelectMultiple widget from Django Admin. My form currently looks something like this (I have changes some names for SO but it is functional): class SelectExampleForm(forms.Form): class Media: css = {'all': ('/static/widgets.css',), } js = ('/static/jsi18n.js',) def __init__(self, *args, **kwargs): group_name = kwargs.pop('group_name') location = kwargs.pop('location') r = super(SelectExampleForm, self).__init__( *args, **kwargs) # total pool of choices qs = Employee.objects.filter( group__name=group_name, town=location ) # Currently selected choices current = Employee.objects.filter( group__name=group_name, town=location, attendance__isnull=False ) # populating the widget ... self.fields['personnel'] = \ forms.ModelMultipleChoiceField( queryset=qs, widget=FilteredSelectMultiple( 'Employee', is_stacked=False), label='', initial=current, show_hidden_initial=True ) return r Although the details of the models aren't important it may help give some context: I have a current set of choices. There is a pool of potential choices that a user can select from. A quota of total selections allowed. This number is less than the number of potential choices. I would like to limit the number of choices one can select in the UI, so that only a certain number of choices n can be selected and appear on the right hand side of the widget. I am currently validating this on submission of the form, which I will continue to do, but …