Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not able to connect to postgresql in production, using AWS RDS
my django app, when I ran it locally(localhost + sqlite3) or in production(public Postgres RDS) on port 8000, it works perfectly. As ports below 1024 are not accessible without root permissions, hence to run on port 80 I used: sudo python3 manage.py runserver and got the following error : OperationalError at / could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? I am using it from the same region EC2 instance. I was able to make migrations and migrate it over the same RDS Postgres database. I also tried running on port 80 with gunicorn and root privileges but the same error. Here is my production settings.py file : import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get('SKEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_skeleton', 'storages' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', … -
Can't Import psycopg2._psycopg Inside a docker
I am trying to build a docker image with the following requirement.txt file but when I call my python function, there is a part that calls to a redshift database to perform query and ectract data, then I get an error : ImportError: /usr/local/lib/python2.7/site-packages/psycopg2/.libs/libresolv-2-c4c53def.5.so: symbol __res_maybe_init version GLIBC_PRIVATE not defined in file libc.so.6 with link time reference python-dateutil==2.6.0 numpy==1.12.0 jsonschema==2.6.0 pandas==0.20.3 python-consul==0.7.2 boto==2.49.0 datadog==0.15.0 invoke==1.4.1 SQLAlchemy==1.1.5 graypy==0.2.14 llvmlite==0.31.0 fastparquet==0.2.1 simple-salesforce==0.74.2 pytz==2019.1 psycopg2==2.7.1 My docker file is : FROM python:2.7 ENV COLLECTION aa ENV TASK_PARAMS aa RUN apt-get update -y && \ apt-get install -y python-pip python-dev WORKDIR /opt/airflow_repository ADD analytics ./analytics ADD FrameworkPY ./FrameworkPY COPY requirements.txt requirements.txt ENV PYTHONPATH ${PYTHONPATH}:/opt/airflow_repository/similarweb_analytics ENV INI_ENVIRONMENT_SETTINGS_PATH=/etc/ RUN pip install -r requirements.txt CMD invoke -c $COLLECTION mainrun $TASK_PARAMS after building the docker image I am trying to run a python script that read data from my redshift : Using the following cmd : docker run -it -e COLLECTION=/opt/airflow_repository/ods/sf/sf_to_ods -e TASK_PARAMS="--job-type /opt/airflow_repository/ods/sf/configs/sf_contact_delta.json" airflow_bidev i get the following error traceback : pid 6 - 2020-04-29 20:34:27,083 - INFO - sf_to_ods.py - run - line 60 - starting sf_to_ods Setting value pid 6 - 2020-04-29 20:34:27,087 - INFO - consul_connections.py - get_connection_settings - line 15 - retreving general_settings … -
Django: How to Make Decision Based on Tuple Choices
Please I want to know how to show another input based on someone's choice. Take the Django form code below for instance. Staff_or_Student = forms.ChoiceField(choices=(('Staff','Staff'), ('Student', 'Student')), widget=forms.Select(attrs={'class':'form-control'}), required=True ) With this, I expect when a user picks Staff, then s/he should see a form to input staff_id i.e Staff_ID = forms.CharField( label='Staff ID', max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter ID'}), required=True, ) but matriculation number if the student is chosen. Matriculation_Number = forms.CharField( label='Matriculation Number', max_length=100, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'Enter Matric Number'}), required=True, ) Please how can I achieve this? -
Django. I need data in my "first" model from my "third" model. Does it mean that I made a mistake or it is doable?
I would like to kindly ask you for your help. I need data from my third model in my first model. And I am struggling right now with it. Can I fix it as it is or I will have to rebuild my code ? Maybe first I will show you what I got. models.py: from django.db import models from django.contrib.auth.models import User class Question(models.Model): question = models.CharField(max_length=300) answered = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) datecompleted = models.DateTimeField(null=True, blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.question class Answer(models.Model): question_id = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) answer = models.TextField(max_length=1000) created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.answer class VoteQuestion(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE, blank=False, null=True) votesubmitted = models.DateTimeField(null=True, blank=True) votesscore = models.IntegerField(default='0') amountofvotes = models.IntegerField(default='0') class Meta: unique_together = ['user', 'question'] And in my views.py I am doing this: def home(request): allquestionswithanswers = Question.objects.filter(datecompleted__isnull=False) allquestionswithoutanswers = Question.objects.filter(datecompleted__isnull=True) return render(request, 'main/home.html', {'allquestionswithanswers': allquestionswithanswers, 'allquestionswithoutanswers': allquestionswithoutanswers}) And that's because in home.html I want to call this: <ul> {% for question in allquestionswithanswers %} <li> {{ question }} Score: {{ question.votesscore }} {{ question.user }}<br><br> <form class='my-ajax-form' method='POST' action='' data-url="{% url 'questionvoteup' question.id %}" > {% csrf_token %} … -
is it possible for a fileField t save a url in django
I am working and using dj-rest-auth and Django-allauth on a project where the user has a profile photo field in his user model. This field has a one to one relationship with another model that has a file field. It is a file field because the user should be able to add images and gifs as his profile photo. The problem is that when the user signs up using google the profile photo is gotten from google, which is a URL. How can I go around this? my photo model class Photo(models.Model): ''' This model will be a general model for files upload to amazon ''' url = models.FileField() def __str__(self): return self.url class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=254, unique=True) name = models.CharField(max_length=250) display_picture = models.OneToOneField(Photo, on_delete=models.CASCADE, related_name='dp', blank=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(null=True, blank=True) date_joined = models.DateTimeField(auto_now_add=True) slug = models.SlugField(max_length=255, unique=True, blank=True) -
Not able to install the latest django in virtualenv
Hello I am trying to install latest version of django in my virtualenv through the following command. pip install Django==3.0.5 for which I got an output as below ERROR: Could not find a version that satisfies the requirement Django==3.0.5 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1,1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3,1.3.4, 1.3.5, 1.3.6,1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, 1.11.11, 1.11.12, 1.11.13, 1.11.14, 1.11.15, 1.11.16, 1.11.17, 1.11.18, 1.11.20, 1.11.21, 1.11.22, 1.11.23, 1.11.24, 1.11.25, 1.11.26, 1.11.27, … -
Node (npx one time run) and Django talking to each other
How can this be done? Use case is say I have some assets to be generated from an image upload. Note I don't mean compressed - like django-compressor etc does. I literally mean new assets from an uploaded one. Typically, you could run a process offload it to celery ping task status for progress and have a display if it was all Django / data stuff. But, for this I have no idea. You have to get django + npx command talking to each other, need progress, a preview of the image returned once done, etc. There's subprocesses where I can do subprocess.run(my npm command). But, this is still missing the "talking" portion and watching the generated assets / progress status. If I can figure this out can do the rest. Just not sure where to start. No resources I could find on this. At a high level: Django request posts -> subprocess is called -> 200 returned -> subprocess calls npx one-off task in background -> ??? <-> django watches for this / displays. -
Autocomplete off in django crispy form
I am new in crispy form configuration. I have a django form and want to setup autocomplete = off thoughout the form. I found this attribute can be set within field widget. But instead of individual input , how can we apply whole form in a single line? -
React Django state lost in continuous refresh of page
I'm developing a web app with Django and React, I build the structure of the page on a react component and it looks like it works. I have a to do list component, I have a state that holds title and items of the to do list. then when the list is completed I wanted to post the to do list to the database. The issue that I'm facing is the following: - Load http://localhost:8000/ - click on add item - react renders the new empty field for the new item. it last a second, the page refreshes, the link becomes http://localhost:8000/?title=&dateCreation=&toDoItem=&when=&note=&toDoItem=&when=&note= and the page loses the state and everything is like at the beginning of the state state = { toDoList:{ title:"", dateCreation:"", toDoItems:[ {itemName:"",when: "", note:""}, ] } } addItemHandler = () => { const toDoList = {...this.state.toDoList} const toDoItems = [...this.state.toDoList.toDoItems] toDoItems.push({itemName:"",when: "", note:""}) toDoList.toDoItems = toDoItems return this.setState({toDoList: toDoList}) } -
Django - Get live output of subprocess command
I'm currently developping a small WebApp in Django and I need to run a shell command at some point. The command is gonna actually take a lot of time to run (6-10 minutes) so I would like to get live stdout from the command in my Django View ... (In order to live track the command) I'm not a beginner in python so I now how to run the command and get live output with subprocess but I total new with Django so I have no clues of how to pass the live output to the views ... I was not able to find an answer that fit my needs on the net ... Thanks for helping me and sorry for the english ... -
Open New View in Bootstrap Modal in Django
My situation is that I have several modals (4 to be exact) which should be accessible in every single view in my app. I will use just one as an example. Let's take a look at how I am displaying this on the home screen view: base.html ...abbreviated... <a data-toggle="modal" href="#exampleModal">Shipment</buton> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Create Shipment</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form method="POST"> {% csrf_token %} <div class="modal-body"> {{shipmentForm|crispy}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" name="shipment" class="btn btn-primary">Save changes</button> </form> </div> </div> </div> </div> And here is the view which passes shipmentForm to that template views.py def HomeView(request): if request.method == 'POST': shipment_form = CreateShipmentForm(request.POST) if shipment_form.is_valid(): new_shipment = shipment_form.save()the user to the success page return redirect('ShipmentListView') shipmentForm = CreateShipmentForm() context = { 'shipmentForm': shipmentForm, } return render(request, 'home.html', context) This works perfectly fine, but the problem is, I would need to include this code from HomeView in every single view in my app. That would be a lot of repeating myself. I have included the html for the modal in my base.html so that … -
Adding more fields to send_mail
I see people using the send_mail function like this: send_mail(subject, message, from_email, ['admin@example.com']) My form have more fields such as 'name' and 'phone_number'. How can I pass those extra fields to the send_mail function? forms.py class ContactForm(forms.Form): name = forms.CharField(required=True) phone_number = forms.CharField(required=True) from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) views.py def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "email.html", {'form': form}) -
Django: Redirecting to previous, specific page
Good evening, inside my Django-Table there is a button that redirects to another page to edit the entry inside a row. So - let's say - in my url: ".../coworker/3/" I press a random button inside my table and it leads me to the next side (url: "../coworker/3/...something.../"). My Question is: is it possible to press another button to abort and redirect to the previous page? Right now I'm having trouble with the inside my url! Error message: "NoReverseMatch at ..." The button that leads me from one page to another (the one that's working): <td>{{ item.id }}</td> <td>{{ item.customer }}</td> <td><a class="btn btn-sm btn-warning" href="{% url '...something...' item.id %}">Edit</a></td> Thanks and a good night to all of you! -
incorrect email recieved from contact form django
HI i've got small issue with my contact form it wokes it sends emails but for some reason those emails are not correct i've got field in the form that asks uder email and no matter what i type there the mail comes like from me .. the email i type in the form is in the subject.. i'm not sure if this is correct view def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): from_email = form.cleaned_data['from_email'] subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] try: send_mail([from_email], subject, message, [EMAIL_HOST_USER]) except BadHeaderError: return HttpResponse('Invalid header found.') return redirect('success') return render(request, "blog/contact.html", {'form': form}) def successView(request): return HttpResponse('Success! Thank you for your message.') form class ContactForm(forms.Form): from_email = forms.EmailField(required=True) subject = forms.CharField(required=True) message = forms.CharField(widget=forms.Textarea, required=True) -
403 error with Django-Rest-Framework and Django-Oauth-Toolkit in client_credentials mode
I am trying to us the Django-Oauth-Toolkit authentication with the client_credentials mode, and I can: create successfully create my client_id and client_secret register my token But after, any api call using this token yields a 403 error with the message: { "detail": "You do not have permission to perform this action." } My settings.py is: INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "oauth2_provider", "rest_framework", "drf_yasg", "users", ] MIDDLEWARE = [ "oauth2_provider.middleware.OAuth2TokenMiddleware", "django.middleware.security.SecurityMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "django.middleware.clickjacking.XFrameOptionsMiddleware", ] AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",}, ] REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "oauth2_provider.contrib.rest_framework.OAuth2Authentication", "rest_framework.authentication.SessionAuthentication", # To keep the Browsable API ), "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", "oauth2_provider.contrib.rest_framework.TokenHasReadWriteScope", ), } AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", # To keep the Browsable API "oauth2_provider.backends.OAuth2Backend", ) -
Django thousands and decimal separation
I have the following code in my html files: {% load humanize %} <table > ..... <td> {{e.giacenza_euro|floatformat:'2' |intcomma}} € </td> But it shows me ad example 1,000,00 €, but I wanto to obtain the following result: 1.000,00 €. How can I obtain it? -
How to restart Django development server without clearing cache?
Anyone know how I can restart Django's development server without clearing the cache? I thought maybe using a filesystem cache would do the trick, but it does not seem to. It appears that Django invalidates the previous cache keys when the development server is restarted. Or rather, Django probably looks for cache keys with a new prefix that is dependent upon the timestamp of the time when the server started. How do I prevent this behavior? -
Django - display and saving in a simple form
This is a very beginner-orientated question but I've been stuck on this issue all day. I would like to load the data for a specific record and be able to save it (Submit button in a template) but i'm still trying to understand instances and the save method. models.py class model_essays(models.Model): user = models.ForeignKey(User, default='1', on_delete=models.CASCADE) title = models.CharField(max_length=100, default='') date_added = models.models.DateTimeField(auto_now_add=True) body = models.TextField() def __str__(self): return self.title I understand the id is created automatically forms.py class frm_essays (forms.ModelForm): class Meta: model = model_essays fields = ['title', 'date_added', 'body'] urls.py urlpatterns = [ path('essay/<int:pk>', views.views_essay), ] views.py {stuck here} @login_required def views_essay(request, pk): if request.method == 'POST': updatedForm = essay_detail(request.POST, instance=request.? {I want the ID of the essay}) if u_form.is_valid(): updatedForm.save() messages.success(request, f'this essay has been updated') return redirect('essay_detail') else: updatedForm = frm_core_concept(instance=request.{as above}) context = { 'updatedForm': updatedForm } return render(request, 'essay_detail.html', context) On the decorator - I haven't gotten around to only allowing the users to view their own created essays, this would be the next large hurdle but not the issue I'm asking about. -
displaying a list of lists in django template
i have the following list of lists : [[ "task1","task2"],["task3","task4", "task5"]] and I'm trying to display each list on the x axis of a graph ( so in total I have 2 graphs) in the HTML template using a script as follow: {% for j in range %} <script> var x = "id"+{{j}}; var myChart = document.getElementById(x).getContext('2d'); Chart.defaults.global.defaultFontFamily = 'Arial'; Chart.defaults.global.defaultFontSize = 14; Chart.defaults.global.defaultFontColor = 'Darkblue'; var massPopChart = new Chart(myChart, { type: 'line', //bar horizontalbar, pie, line, doughnut, radar, polarArea data:{ labels:[ {% for t in tas %} {% for s in t %} '{{s}}', {% endfor %} {% endfor %} ], datasets:[{ label: 'Points', data:[{% for foo in pend %} '{{foo.pending_task.points_upon_completion}}' ,{% endfor %} ], backgroundColor:"grey", borderWidth:2, borderColor:'black' }] }, options:{ title:{ display: true, text:"Productivity", fontSize:20 }, legend:{ display: false // show or not show //position:'', // change position maybe left right }, layout:{ padding:{ left:0, right:0, top:0, botton:0 }, } } }); </script> {% endfor %} but it's not working, I'm not able to separate the two lists -
Django - substracting time
Welcome I have a problem. What field should be in model to substract times. I mean for example: 1st car made 500h 28 mins, 2nd car made 350h 15 min and i need a column substract where I'll have substraction from this two times. I made currently working model but only on integer field. When i tried time field and add something like 500:28 it gave me an error " incorrect time". Current model: class Aircraft (models.Model): id = models.AutoField(primary_key=True) registration = models.CharField(max_length=7) #hours to maintenance hours_to_maintenance = models.IntegerField(help_text = "test", null = True) #current hours ch = models.IntegerField(help_text = "test", null = True) #rm = models.IntegerField(help_text = "test", null = True) added_by = models.ForeignKey('auth.User', on_delete = models.CASCADE,) def __str__(self): return self.registration Really thanks for help -
make length in integerfield django model
my model.py is : from django.core.validators import MinLengthValidator,MaxLengthValidator class clients(models.Model): client_identity_id = models.IntegerField(validators=[MaxLengthValidator(11),MinLengthValidator(11)], unique=True) ' ' my serializers.py is : class UserSerializer(serializers.ModelSerializer): #money = serializers.IntegerField(required=False) class Meta: model = clients fields = ('client_identity_id','client_id','client_firstname','client_middlename','client_lastname','client_country','money','client_num') read_only_fields = ('money','client_id') def create(self, validated_data, **kwargs): validated_data['client_id'] = ''.join(secrets.choice(string.ascii_uppercase + string.digits) for i in range(8)) return clients.objects.create(**validated_data) my views.py is : def post(self,request): data=request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) but when i make a post request with client_identity_id=12345678910 it keep telling me "object of type 'int' has no len()" how can i fix that please ? -
ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. Django
I'm developing to do lists app , and have some issues , I tried some options , but it didn't help Here is my code: models class Lists(models.Model): date = models.DateTimeField(default=datetime.now,blank=True) title = models.CharField(max_length=200) class ListsItem(models.Model): date = models.DateTimeField(default=datetime.now,blank=True) title = models.CharField(max_length=200) main_list=models.ForeignKey(Lists, on_delete=models.PROTECT, null=True) views lists = Lists.objects.order_by('-date') listitem = ListsItem.objects.order_by('-date').filter(main_list=lists) Here what I tried listitem = ListsItem.objects.order_by('-date').filter(main_list=lists[0]) listitem = ListsItem.objects.order_by('-date').filter(main_list=lists).count() Is there any solutions ? -
Django project pdfkit.from_url not render image
I have used PDFkit to render my HTML file into a PDF. However, the image is not being displayed. I tried the solution for a similar problem posted here and rewrote my code as so: def get_pdf_for(request, slug): invoice = get_object_or_404(Invoice, slug=slug) data = dict() data["object"] = invoice data["DOB"] = "Jan 10, 2015" template = get_template('invoice/invoice_detail.html') html = template.render(data) pdf = pdfkit.from_string(html, False) filename = "sample_pdf.pdf" response = HttpResponse(pdf, content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="' + filename + '"' return response -
Split issues in django html template drop-down list
Actual Data Save in the table field: Active Network Tasks,Network Security,DC facilities Html Template: {% for subcat in all_subcats_keys %} <option value="{{subcat.subcategory }}">{{subcat.subcategory }}</option> {% endfor %} </select> Data's are displaying the drop-down list but it is not splitting by comma. It is displaying in a single data but I need to display as a list. So user select anyone value from the list. Means e.g. Active Network Tasks Network Security DC facilities Please help how to resolve this issues and I was trying to split the data but unable to do it. -
My django server app stops working everytime I insert code described bellow [closed]
Python 3.8.2 Django 3.0.5 When I insert this code: SETTINGS_DIR = os.path.dirname(__file__) PROJECT_PATH = os.path.join(SETTINGS_DIR, os.pardir) PROJECT_ROOT = os.path.abspath(PROJECT_PATH) TEMPLATE_DIRS = ( os.path.join(PROJECT_ROOT, 'templates'), into my Django web app, it stops working. Terminal says SyntaxError: unexpected EOF while parsing Browser says Error connection refused But without that code it works without any problem. Please help. I appreciate your help.