Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django get subobjects in view
My two models: class BusinessType(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) description = models.CharField(max_length=200) class Business(models.Model): def __str__(self): return self.name name = models.CharField(max_length=200) description = models.CharField(max_length=200) bus_type = models.ForeignKey(BusinessType, on_delete=models.CASCADE, name="type") class Appointment(models.Model): from datetime import datetime business = models.ForeignKey(Business, on_delete=models.CASCADE, name="appointments") done = False created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Now I add this context to my view: 'business':Business.objects.order_by('name'), My template: {{business|length}}<hr /> {%for business_entry in business%} {{business_entry.appointments.all|length}} {%endfor%} Now the business length outputs "2" and that's right, I have two business objects. But for the appointments I get the value "0" which is not true. What am I doing wrong? -
Django change ordering of items in a Postgres ArrayField
dm_scripts = ArrayField(models.TextField(blank=True, null=True), default=list) I have a Django model, and I wanted to use the ArrayField to store a list of TextFiles. The order matters, and I've been asked to allow a user to reorder these. How would you do that? I've googled and searched here, but found nothing. Even Django's official documentation doesn't mention this. -
Linking ManytoMany relationship with Modelform
I'm pretty new to Django and I am working on a project that currently requires the following: I have two basic structures: a Project model and a TeamMember model- both related to each other through a ManytoMany relationship. Then I have an TMAssigned 'through' class. The team member will have many projects assigned to it over time. I have a ModelFrom which creates a Project model through the creation of the form. My question is, How do I link the team member to the newly created project upon the submission of the form? Here is a bit of my model & form code: TeamMember class TeamMember(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") fullname = models.CharField(max_length=100, default= "Full Name") projects = models.ManyToManyField(Project, blank=True, through="TMAssigned") email = models.EmailField(max_length=254) cellphone = PhoneNumberField(null=False, blank=False, unique=True) numberofcases = models.IntegerField(max_length=10000, default=0) @property def fullnamefunc(self): fullname = "{} {}".format(self.firstname, self.lastname) return fullname def __str__(self): return self.fullname TMAssigned class TMAssigned(models.Model): teammember = models.ForeignKey(TeamMember, on_delete=models.CASCADE) project = models.ForeignKey(Project, on_delete=models.CASCADE) Project class Project(models.Model): pursuitname = models.CharField(max_length=500) datecreated = models.DateTimeField(auto_now=True) bdmember = models.CharField(max_length=200, default="None") Form.py class bdForm(forms.ModelForm): bdmemberlist = TeamMember.objects.all().order_by('lastname') pursuitname = forms.CharField() bdmember = forms.ModelChoiceField(queryset= bdmemberlist) addbdteam = forms.ModelMultipleChoiceField( queryset=TeamMember.objects.all().order_by('lastname'), widget=Select2MultipleWidget, required=False) #this class … -
Fetching https content via api on client site but browsers raising mixed content http errors
I'm trying to build an external API in a Django app to serve some content over to a production client Wordpress site. The client is on https and the javascript uses fetch to get https api url but browsers are claiming http mixed content. What gives? I've tried both Chrome and Firefox and both are returning similar errors fetch('https://mysite.pythonanywhere.com/apit?param1=100000&param2=1000',{ method: 'GET', }) .then(function(response) { if (response.status !== 200) { console.log(response); console.log('Looks like there was a problem. Status Code: ' + response.status); return; } }); my view for this in Django has: response = JsonResponse(the_content_dict,safe=False) return response I can visit the URL directly in my browser and view the json response as expected but when I place the code above on the client WP site, I see in the Firefox console: Blocked loading mixed active content “http://mysite.pythonanywhere.com/apit?param1=100000&param2=1000” TypeError: NetworkError when attempting to fetch resource. rank:154:3 Response { type: "cors", url: "https://mysite.pythonanywhere.com/apit?param1=100000&param2=1000", redirected: false, status: 500, ok: false, statusText: "Internal Server Error", headers: Headers, body: ReadableStream, bodyUsed: false } Looks like there was a problem. Status Code: 500 Similarly, in Chrome: (index):154 Mixed Content: The page at 'https://clientsite.com' was loaded over HTTPS, but requested an insecure resource 'http://mysite.pythonanywhere.com/apit?param1=100000&param2=1000'. This request has been … -
How to select from drop down in django
I have a bunch of tuples that I get from an API and I am displaying them as : |User1 ID| User1 Name | User1 Status | "Choose Button" |User2 ID| User2 Name | User2 Status | "Choose Button" |User3 ID| User3 Name | User3 Status | "Choose Button" I want the user to click on the choose button, and get the information back in the views.py wherein I can use the user. id to change its status. I'm new to Django and I am not understanding how to proceed with it. I am only being able to display it as shown above (without the choose button) PS: Sorry, I cant provide with any code as I dont even know how to do it. -
is there a way to save Data on another page in django?
I'm building a simple tool that will allow users to save contact information on another page and redirect back to the index page. I try many things and I still can't figure it out, thanks in advance. code below url.py url(r'^lead/$', views.lead, name='lead'), view.py def lead(request): new_item=Blogger.email new_item.save() return HttpResponseRedirect('/app') index.html <a href="/app/lead" title="add lead" >Add lead</a> models.py class Blogger(models.Model): email=models.EmailField() -
How to Form Submit after Server Side Changes Django
I have a Javascript function to get the id in a Select, and then send it to my Views so I can change the value of an attribute based on the id I got. Javascript: $('#venta_form').submit( function(event) { event.preventDefault(); //Detiene el submit del form para que se ejecute esta funcion var _this = $(this); //Obtengo el id del submit form pedido_id = $("#id_pedido").val(); var url = '/control/estado/'+pedido_id; console.log(pedido_id); $.ajax({ type: "POST", url: url, data: { 'pedido': pedido_id }, success: function () { console.log('Funciono!'); _this.unbind('submit').submit(); //Continua el submit del form si la funcion se realiza }, error: function() { alert('Ha ocurrido un error, intentalo de nuevo'); console.log("error"); } }); }); My View: def estado_pedido(request, pk): if request.method == 'POST': obj = Pedido.objects.get(pk=pk) obj.estado = "Finalizado" obj.save() return render(request, 'control/venta_list.html') But when I change that value, my form doesn´t work and doesn´t save the values. This my CreateView for the form: class VentaCreate(CreateView): model = Venta # fields = '__all__' form_class = VentaForm success_url = reverse_lazy('control:ventas') template_name_suffix = '_crear' @method_decorator(permission_required('control.add_venta',reverse_lazy('control:ventas'))) def dispatch(self, *args, **kwargs): return super(VentaCreate, self).dispatch(*args, **kwargs) What could be the problem that is causing the form to not work after I change the value in my View? -
How to handle Django Pagination with Nested tabs
I want to add pagination to my template,My template have Nested Tab(see code), all My inner tabs contain a table and i want to add pagination to all my tables in my inner tabs. I have so far added pagination to one of my table and it works but the problem is whenever page refresh it goes my to first tab <!-- overview--> , not the one that made the request, although pagination is working. This is the structure of my tabs.I am not using custom JS or CSS, only BS4 class <div class="tab-content" id="nav-tabContent"> <!--OVERVIEW TAB--> <!--STATIC TAB--> <!--TAB 1--> <!--TAB 2--> <!-- FILES TAB--> <!--TAB 1 --> <!--TAB 2 --> <!--TAB 3 --> <!--Registry TAB --> <!--TAB 1 --> <!--TAB 2 --> <!--Network TAB--> <!--TAB 1 --> <!--TAB 2 --> <!--TAB 3 --> </div> TEMPLATE.html <nav aria-label="Page navigation"> {% if strings.has_other_pages %} <ul class="pagination justify-content-center pagination-lg"> {% if strings.has_previous %} <li class="page-item"><a class="page-link" href="?page=1">First</a> </li> {% endif %} {% for i in strings.paginator.page_range %} {% if strings.number == i %} <li class="page-item active"><a class="page-link" href="{{ i }}">{{ i }}</a></li> {% elif i > strings.number|add:'-3' and i < strings.number|add:'3' %} <li><a class="page-link" href="?page={{ i }}">{{ i }}</a></li> {% endif … -
Call source envvars from within python
In my django settings.py file, I would like to call an envvars.sh file to import things like DB_CREDENTIALS. I'm trying to do something like this: if not os.environ.get('DB_PASSWORD'): subprocess.call(['source', 'envvars.sh']) DB_PASSWORD = os.environ.get('DB_PASSWORD', '') It works from the terminal, doing $ source envvars.sh but not from within python. Is there another way to do this? -
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!!