Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple inputs with same name to write to database
I have a form and with several fields with the same name, I need to get this data in django view and write to the database. For now I am just trying to get the HTML data and render in the view but only the last value of the html form is displayed. View def agenda_padrao(request): inicio = request.POST['inicio'] fim = request.POST['fim'] idempresa = request.POST['id'] if request.POST: for i in inicio: print(i) return render(request, 'core/agenda.html') agenda.html <form method="POST" action="/agenda/padrao/">{% csrf_token %} <div class="modal-body"> <div class="row "> <h3>Horários</h3><br/> <a class="btn btn-success" href="javascript:void(0)" id="addInput"> <span class="glyphicon glyphicon-plus" aria-hidden="true"></span> </a> </div> <div id="dynamicDiv"> <div class="row col-12"> <input type="time" class="form-control form-control" id="inicio" name="inicio[]" style="width: 150px; margin-right: 10px;"> <input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px;"> <input type="hidden" name="id" value="{{ user.id_empresa }}"> </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancelar</button> <button type="submit" class="btn btn-primary" >Confirmar Horário Padrão</button> </div> </form> Javascript adding the fields $(function () { var scntDiv = $('#dynamicDiv'); $(document).on('click', '#addInput', function () { $('<p>'+ '<input type="time" class="form-control form-control" id="inicio" name="inicio" style="width: 150px; margin-right: 10px;">'+ '<input type="time" class="form-control form-control" id="fim" name="fim" style="width: 150px; margin-right: 10px;">' + '<a class="btn btn-danger" href="javascript:void(0)" id="remInput">' + '<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>' + '</a><br/>'+ '</p>').appendTo(scntDiv); return false; }); … -
Loading python envvars without using `source`
I am looking for a solution to loading an envvars.sh file within a django application. I would prefer to do this within the settings module and keep a file outside of it. Here is what I currently have: SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) def source_envvars(fname='envvars.sh'): """Equivalent of `$ source {fname}` with lines in the form of `export key=value`""" envvars = os.path.join(SITE_ROOT, fname) if not os.path.exists(envvars): return with open(fname, 'r') as f: for line in f: if line.startswith('export '): line = line.strip() key = line.split('=')[0].split()[1] value = line.split('=')[1].strip('"\'') os.environ[key] = value if not os.environ.get('DB_HOST'): source_envvars() # rest of settings.py file... Are there any downsides of using this approach? I know this doesn't support complicated bash-type exports, but all I have are basic exports of the form: export DB_HOST=rds.amazon.com/12345 Does the above approach properly instantiate all the variables, or does it seem to be missing something or insecure in some way or other? -
Django/React deployment not serving static files on Heroku
I've hunted the Internet and manu SO posts but haven't found what solves my solution yet. I have a Django back end, and a React front end created with create-react-app. But all I'm getting is Django Rest Framework API Root page—from what I can tell, it's simply not serving up the static files properly. My files are located at https://github.com/acd37/lead-manager It would be a lot for me to copy and paste—but I'm hoping someone can look at this and see what the issue is, or will clone it and give it a shot. If I npm run build and then serve, I get a blank page saying that my this.props.leads.map function can't fun. If I run heroku local, I get the same API Root page. Any ideas!? New to Python——deploying NodeJS apps to Heroku is MUCH easier! -
Django group by for reverse relationship
Let's say I have the following: class A: .... class B: a = models.ForeignKey(A,....) class C: a = models.ForeignKey(A,....) b = models.ForeignKey(B,....) user = models.ForeignKey(User, ....) I want to use regroup to display all C objects grouped together by a, user in a table with fields from A and all C objects in a drop down upon clicking the row. So.... # regroup A queryset by C foreign key and user foreign key c.field1, c.field2, ...., user.email, user.first_name, .... + dropdown a.field1, a.field2, a.field3, ..... If C contains a foreign key to a with multiple users these should be distinct rows. Meaning.... First level regroup by model C... great we have C model with all related A model as drop down..... But, these can have duplicate users. So separate top level by user + C model relation. I'm lost on how to do the previous sentence. First level group by is easy. -
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