Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flask/Django modules of converting files [duplicate]
I'm trying to build a little converter website. pdf to docx, images to pdf, csv to excel etc... I really want to use node as my static files host server. But as I know node doesn't have that cool modules to handle such convertations. I think of using another server of python, e.g flask or django frameworks. So what are the best modules for python for converting files? Is there anything you could suggest me for solving this problem? -
Submit form with other modal forms Django
I'm trying to create an HTML page with a form, I have a button that open a modal with another form. The form within the modal is being submitted correctly but when I try to submit the other form the button doesn't send any request but I don't know why. I'm not very skilled using Django and HTML/JS so I could be missing something but I didn't have this problem on other pages. I'm also using crispy-bootstrap-forms. This is my HTML code: {% extends 'scenarios/home.html' %} {% load crispy_forms_tags %} {%block subtitle%} <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script> <h1 style="text-align:center"> Create your scenario </h1> {%endblock%} {% block body %} <div class="container"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{scenario_form|crispy}} <h1> VM List </h1> {%if vm_list%} <ul> {% for vm in vm_list %} <h3>{{vm.nome}}</h3> <span></span> <button> Edit Machine</button> {% endfor %} </ul> {% else %} <h2>No VMs at the moment</h2> {% endif %} <div class="container"> <!-- Trigger/Open The Modal --> <button type="button" class="btn btn-default btn-lg" id="myBtn">Add VM</button> <!-- Modal --> <div class="modal fade" id="myModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> </div> <div class="modal-body"> <form method="POST" enctype="multipart/form-data"> {% csrf_token %} … -
How can i use Uniqueconstraint for asymmetrical purposes?
How can i customize UniqueConstraint for this purpose: -user1 can follow user2. -user2 can follow user1. The problem right now is when user1 follows user2,user2 can't follow user1 because of unique constraint. Is there anyway to do it? class FollowUserModel(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) user1 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='followers') user2 = models.ForeignKey(User,on_delete=models.CASCADE,related_name='following') timestamp = models.DateTimeField(auto_now_add=True) class Meta: constraints = [models.UniqueConstraint(fields=['user1','user2'],name='unique_followuser')] -
How to include a variable in api call in python?
I am trying to implement a searchbar in django. I am getting the search input as movie_title from the html form. Now, how do i include it in my api call ? I tried with curly braces. Here's is the code def searchbar(request): if request.method == 'GET': movie_title = request.GET.get('movie_title') searched_movie = requests.get( 'http://www.omdbapi.com/?apikey=9a63b7fd&t={movie_title}') -
Flask/Django converting files
I'm trying to build a little converter website. pdf to docx, images to pdf, csv to excel etc... I really want to use node as my static files host server. But as I know node doesn't have that cool modules to handle such convertations. I think of using another server of y, e.g flask or django frameworks. So what are the best modules for converting files? -
django export to PDF using WeasyPrint working in development server whereas not working in production with "https"
I am trying to do Django export HTML containing image to PDF with WeasyPrint. IT is working fine in development server. whereas in production server, It is not showing image. it is showing TEXT content properly. I am using "https" . @login_required def html_to_pdf_view(request,bogId): bog = Brideorgroom.objects.get(bogId='bogId') html_string = render_to_string('brideorgroom/bogdetail_pdf.html', {'bog': bog}) base_url = request.build_absolute_uri() html = HTML(string=html_string, base_url=base_url) pdf_file = html.write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'attachment;filename="profile.pdf"' return response -
Tempus Dominus, Moments JS, Strftime and Timepicker in boot-strip modal forms
I have model called workshift with the fields work_shift , start, end, shift_hours and location. l want to use time picker for the fields start and end and calculate the shift_hours. Now instead of time picker only l get datetimepicker when l run the app. How do l get only time picker in the start and end forms fields? How do l calculated and display the results in the shift_hours forms fields anytime start and end time is picked? Below is my codes class WorkShift(BaseModel): work_shift = models.CharField(max_length=50, verbose_name='Work Shift', unique=True) start = models.TimeField(verbose_name='Start Time') end = models.TimeField(verbose_name='Closing Time') shift_hours = models.IntegerField(default=0, verbose_name='Shift Hours') location = models.ForeignKey(Location, on_delete=models.CASCADE, verbose_name='Shift Location') def __str__(self): return self.work_shift def save(self, force_insert=False, force_update=False, using=None, update_fields=None): user = get_current_user() if user is not None: if not self.pk: self.user_creation = user else: self.user_updated = user super(WorkShift, self).save() def toJSON(self): item = model_to_dict(self) item['start'] = self.start.strftime('%%H:%M:%S') item['end'] = self.end.strftime("%H:%M:%S") item['location'] = self.location.toJSON() return item class Meta: verbose_name = 'Wor kShift' verbose_name_plural = 'Work Shifts' ordering = ['id'] form.py class WorkShiftForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) class Meta: model = WorkShift fields = '__all__' widgets = { 'work_shift': TextInput(attrs={ 'class': 'form-control', }), 'start': TimeInput( format='%I:%M %p', attrs={ 'value': … -
django: Pass additional data to context in FormView
I’m new to this forum and this is my first question, so please be kind Before I state my question, here is the code to the regarding model, form, view and template class Medium(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) dateiname = models.CharField(max_length=100) dateipfad = models.CharField(max_length=100) MEDIEN_TYP = ( ('f', 'Foto'), ('v', 'Video'), ('d', 'Dokument'), ) typ = models.CharField( max_length=20, choices=MEDIEN_TYP, blank=True, default='Foto') URHEBER_NAME = ( ('a', 'Person A'), ('b', 'Person B'), ) urheber = models.CharField( max_length=20, choices=URHEBER_NAME, blank=True, default='Person A') datum_erstellung = models.DateField( null=True, blank=True, verbose_name='Erstelldatum') personen = models.CharField( max_length=100, null=True, blank=True, verbose_name='Person(en)') ort = models.CharField(max_length=20) inhalt = models.CharField( max_length=100, null=True, blank=True, verbose_name='Inhalt/Anlass') kommentar = models.TextField(max_length=1000, null=True, blank=True) rating = models.DecimalField( max_digits=3, decimal_places=2, null=True, blank=True) def get_absolute_url(self): return reverse('medium-detail-view', args=[str(self.id)]) def __str__(self): return self.dateiname class AbfrageForm(forms.Form): medien_typen = ( ("f", "Foto"), ("v", "Video"), ("d", "Dokument"), ) medien_typ = forms.ChoiceField(choices=medien_typen) personen = ( ("Person X", "13: Person X"), ("Person Y", "14: Person Y"), ("Person Z", "14: Person Z"), ) vorname = forms.ChoiceField(choices=personen) orte = ( ("Place A", "Place A"), ("Place B", "Place B"), ) ort = forms.ChoiceField(choices=orte) class AbfrageView(LoginRequiredMixin, FormView): template_name = 'abfrage.html' form_class = AbfrageForm success_url = '.' def get_context_data(self, **kwargs): context = super(AbfrageView, self).get_context_data(**kwargs) #context['auswahl'] = self.auswahl return context … -
Is there any possible way to deploy Django app without "setup python app" feature in Cpanel?
I was trying to deploy my Django app on a Hostgator Cpanel. But there is no "set up python app" feature present on my Cpanel. I have come to know that I have to buy the CloudLinux feature to get that. Is there any way to set the application root, startup file, and other things provided by that(including starting and stopping my app anytime) to run my Django app? -
accessing context data in a class
I want to use DeleteView for different cases instead of rewritting a new function for every case. So I thougt I pass the model as an argument in the url and then select wich delete to use by overiding the get_context_data function. My problem is how to access the context variable: views.py: class PDelete(DeleteView): template_name='kammem/delete.html' if context['model']=='Person': model=Person success_url=reverse_lazy('personer') elif context['model']=='Concert': model=Concert success_url=reverse_lazy('concert') def get_context_data(self,**kwargs): context=super().get_context_data(**kwargs) context['model']=self.kwargs['model'] return context urls.py path('pdelete/<int:pk>/<str:model>',PDelete.as_view(),name='pdelete'), the problem is that the context variable is undefined in the class. Any suggestions? -
attribute Error using django Model Forms choicefield
I am trying to use ChoiceField in ModelForms follow is my code in forms.py Format_Choices=[('Line Numbering','Line Numbering'),('Header Numbering','Header Numbering')] class EstimateForm(forms.ModelForm): class Meta: model=Estimate estimateFormat=forms.ChoiceField(choices=Format_Choices,widget=forms.RadioSelect()) this form is link with following estimate model in models.py class Estimate(models.Model): estimateFormat=models.CharField(max_length=25,default='Line Numbering') in the template when I use {{form.estimateFormat| as_crispy_field}} it generate following error |as_crispy_field got passed an invalid or inexistent field which field should I use in models.py to make ChoiceField compliant with models.py -
What event.target will contain if I added submit event listener on the form
I have a lot of forms on the page and when one of them is submitted I want to send request via ajax to the view and have an id of the article and other info. So I need to check if form that has been clicked is the same as event.target. I did something like this but don't know if it is correct(first console.log works but second not): <div id = "list"> {% for article in news %} <a href="{{ article.resource }}"><h1>{{ article.title }}</h1></a> <p>{{ article.published }}</p> <img src = "{{ article.url }}"> <p> <button><a href="#" class="vote" id="{{ article.id }}" action = "upvote">Upvote</a></button> <button><a href="#" class="vote" id="{{ article.id }}" action = "downvote">Downvote</a></button> </p> <div id="span"> {% with article.upvotes.count as total_upvotes and article.downvotes.count as total_downvotes %} <span upvote-id = "{{ article.id }}">{{ total_upvotes }}</span><span> upvote{{ total_votes|pluralize}}</span> <span downvote-id = "{{ article.id }}">{{ total_downvotes }}</span><span> downvote{{ total_votes|pluralize}}</span> {% endwith %} </div> <form method = 'post' action = '{% url "news:news_list" %}' form-id = '{{ article.id }}' class="form"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value = "post"> </form> {% endfor %} </div> {% endblock %} {% block domready %} const list = document.getElementById('list'), items = document.getElementsByClassName('vote'); forms = … -
How to "add another row" in Django on change input
I am using TabularInline formset in admin view with extra=1 to have only a row of formset. I wish to automatically add a row (like when I click on "add another row") when a row is filled, that means using "on change". To do that I tried to intercepet onChange input overwriting change_form.html in this way: $(document).on('change', '#myform_set-group .field-mymodel select', function () { // test console.log("changed!"); // I tried this $('#myform_set-group tbody tr.add-row').formset(); // and this $('#myform_set-group tbody tr.add-row').click(); // and this $("#myform_set-group .tabular.inline-related tbody tr").click(); // and this $("#myform_set-group .tabular.inline-related tbody tr").formset(); }); but don't work -
Dots and boxes solving algorithm/heuristic
I'm currently working on a "dots and boxes" program and I can't make good algorithm(heuristic). Can anyone help me or does anyone have a code in python? -
python manage.py runserver: TypeError: argument 1 must be str not WindowsPath
I am following up a django tutorial and I have just installed django using 'pip install django=2.1' and it was successfully install and then created a project using 'django-admin startproject pyshop .' after that I am trying to runserver using 'python manage.py runserver' and I am getting a 'TypeError: argument 1 must be str not WindowsPath'. Am i missing something. Please help! -
( Python ) { MCQ } What advice would you give to this company about the user interface for this appliction?
{ Python } (MCQ) A company uses an offline system order for selling products. The company wants to build a new online site. The data trends of current order shows that customers typically buy once or twice a year. The company has the following requirement for the site. Should have ability to shop quickly from application Should have ability for the web designers to modify the user interface to provide a new user experience There should be ability to browse the catalog and find the product with 3 clicks What advice would you give this company about the user interface for this application? -
Multiple Choice with django
Im working on a quiz application with Django. Im struggling with making a form that can act as the multiple choice. I have to pull the questions and answers from the database so, i then display them on the page. I was going to just put booleanfield checkboxes beside the displayed choices, is there a better way to do this? I recently became aware of the multiple choice field, but i believe it aids in displaying the choice as well. I just want there to be 'boxes' i can customize with css. Is there anyway to have the field pull from the database or can i use the multiple choice field to display the wanted boxes by the answer choices already displayed. -
Compare last_modified to date.today() in Django
In models.py class PapaAbb(models.Model): last_modified = models.DateTimeFilel(auto_now=True, blank=True, null=True) def is_new(self): if self.last_modified == date.today(): return True return False and call this in HTML template as {% if papaabb.is_new %}new{% endif %} I expected showing 'new' text on html page but nothing happened. Any advice would be welcome. thx in advance... -
(Python){MCQ} Select which is not true about python web development?
More then 1 option can be correct! Select the statement which is not true about python web development? Need to configure your web server to announce its version access-control-allow-origin header value should be set to "*" firewall address the vulnerability issue such as sql injection, xss,etc. So,i its not required to handle in python code Python code needs to address only the vulnerability that are not addressed by firewall -
Django: ValidationError ['ManagementForm data is missing or has been tampered with']
Django: ValidationError ['ManagementForm data is missing or has been tampered with'] i have been getting this error when i use the forminline factory module, im sorry if my question isnt placed properly, this is my first time here. my form template is this: {% extends 'accounts/main-form.html'%} {% load static %} {% block title %} <title>CRM | Form</title> {% endblock %} {% block link %} <link rel="stylesheet" type="text/css" href="{% static 'css/style1.css'%}"> {% endblock %} {% block content %} <div class="container"> <form action="" method="POST"> {{formset.management_form}} {% for i in formset %} {{i}} {% endfor %} <input type="submit" class="btn" value="submit"> </form> </div> {% endblock%} this is the form code in views.py def order_form(request, pk): customers = Customer.objects.get(id=pk) OrderFormSet = inlineformset_factory(Customer, Order, fields=('product', 'status',)) formset = OrderFormSet(request.POST) if request.method == 'POST': formset = OrderFormSet(request.POST, instance=customers) if formset.is_valid(): formset.save() return redirect('/') context = {'formset': formset} return render(request, 'accounts/order_form.html', context) my models from django.db import models # Create your models here. class Customer(models.Model): name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=200, null=True) def __str__(self): return self.name class Product(models.Model): CATEGORY = ( ('Indoor', 'Indoor'), ('OutDoor', 'Outdoor') ) name = models.CharField(max_length=200, null=True) … -
How to write URL For multiple Slug
here is my path path('<slug:category_slug>/<slug:city_slug>/<slug:slug_text>/', views.category_view_detail, name='post_detail'), how to write URL for this example {% url 'post_delete' posts.slug %} but i want to add all three slug inside the URL how to do something like this... ({% url 'post_detail' posts.category posts.city posts.slug %}) but this not work.. -
Django error by adding Channels to settings.py INSTALLED_APPS
I'm trying to learn Django channels, so for the beginning, I simply installed and added "channels" to the Django project, INSTALLED_APPS in the settings.py, as showing below. Installed channels with pip: pip install channels Installed versions: channels 3.0.3 daphne 3.0.1 Django 2.2.13 settings.py > INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', ... 'django_ace', 'channels', # added this ] I just installed one package and added one line to the settings.py so this shouldn't be an error, but when I try to run the server python .\source\manage.py runserver I got an error as showing below. > python .\source\manage.py runserver --noreload Traceback (most recent call last): File ".\source\manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute django.setup() File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\pg\django\win\simple-django-login-and-register\venv\lib\site-packages\django\apps\config.py", line 116, in create mod = import_module(mod_path) File "c:\python37\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File … -
Cannot assign "OrderedDict()...: "..." must be a "..." instance
Im using Django Rest & React to make a web app. models.py RegoNumber = models.CharField(max_length=10) RegoExpiry = models.DateField(auto_now=False,auto_now_add=False) LastRentedDate = models.DateField(auto_now=False,auto_now_add=False) def __str__(self): return self.RegoNumber class Hire(models.Model): # StartRentDate = models.DateField(auto_now=False,auto_now_add=False,null=True) # EndRentDate = models.DateField(auto_now=False,auto_now_add=False,null=True) KMsLastShown = models.IntegerField() KMsToLastService = models.IntegerField() # ServiceHistory = models.FileField() LastService = models.IntegerField() RentalPrice = models.FloatField() Bike = models.OneToOneField(Bike,on_delete=models.CASCADE,null=True,related_name='Bike') def __str__(self): return f'Bikes hire data' serializers.py from rest_framework import serializers, fields from drf_writable_nested.serializers import WritableNestedModelSerializer from .models import Hire, Bike class BikeSerializer(serializers.ModelSerializer): class Meta: model = Bike fields = '__all__' class HireSerializer(WritableNestedModelSerializer): Bike = BikeSerializer(required=False) class Meta: model = Hire fields = '__all__' index.js (react) import ReactDOM from 'react-dom' import {useReducer} from 'react' import Cookies from 'js-cookie' ReactDOM.render( <React.StrictMode> <App/> </React.StrictMode>, document.getElementById('root') ) function App(){ function sendData(e) { e.preventDefault() const csrftoken = Cookies.get('csrftoken'); const dataToSend = { method: 'POST', headers: {'Content-Type':'application/json', 'Accept': 'application/json', 'X-CSRFToken': csrftoken }, body: JSON.stringify({ KMsLastShown: 0, KMsToLastService: 50, LastService: 50, RentalPrice: 40, Bike: { RegoNumber: 'Hello', RegoExpiry: '2020-05-11', LastRentedDate: '2020-07-07' } }) } console.log('Working') fetch('/api/hire/',dataToSend) .then(response => response.json()) .then(json => console.log(json)) } return ( <> <button onClick={function(e){sendData(e)}}></button> </> ) } When I try making a Post request in my index.js of the Bike, it returns an error Cannot assign "OrderedDict([('RegoNumber', 'Hello'), … -
Django on Heroku. See all GET requests of a path
I have a Django 2.0 project hosted on Heroku. In the logs, this is what a GET request looks like: timestamp source[dyno]: message 2021-02-14T05:23:35.513467+00:00 heroku[router]: at=info method=GET path="/static/tag.gif"... I'd like to be able to access the full GET request message with python in the Django project. I'd preferably like to get this through the django-heroku library. If that's not possible, then I'd like some way to scrape the Heroku logs. I know they can be filtered by source and dyno via CLI, but I haven't seen anything about filtering by message. Maybe there's a way to add a listener of sorts? -
django.db.utils.ProgrammingError in Cpanel
when i migrate in Cpanel get this error : django.db.utils.ProgrammingError: (1146, "Table 'morvari2_morvarid_store_db.store_setting_setting' doesn't exist")