Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error by install libspatiallite for geodjango
i want to install libspatiality for use in geodjango. I use ubuntu 18.04. I have now downloaded various versions of libspatialite. Every time i execute the command ./configure the script stops with the following message: checking proj_api.h usability... no checking proj_api.h presence... no checking for proj_api.h... no configure: error: cannot find proj_api.h, bailing out proj_api.h is available in the "usr / include" folder and I can also open it. I've tried older versions of the libspatiallite with the same error. Also the commands: ./configure --with-projdir=/opt/local ./configure --with-projdir=/usr/local ./configure --with-projdir=/opt/local/include ./configure --with-projdir=/usr/local/include brought no success. -
Running setup.py install for tesserocr ... error
When ever I enter for command - pip3 install tesserocr - It gives error - Collecting tesserocr Using cached https://files.pythonhosted.org/packages/e3/77/fb26b321c3b9ce4a47af12b19e85ddbf4d0629adb6552d85276e824e6e51/tesserocr-2.5.0.tar.gz Building wheels for collected packages: tesserocr Building wheel for tesserocr (setup.py) ... error tesserocr.cpp:8586:43: error: ‘class tesseract::ResultIterator’ has no member named ‘GetBestLSTMSymbolChoices’ __pyx_v_output = (__pyx_v_self->_riter->GetBestLSTMSymbolChoices()[0]); ^~~~~~~~~~~~~~~~~~~~~~~~ error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for tesserocr Running setup.py clean for tesserocr Failed to build tesserocr Installing collected packages: tesserocr Running setup.py install for tesserocr ... error ERROR: Command errored out with exit status 1: command: /home/hostbooks/django1/myproject/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-7nxw40tx/tesserocr/setup.py'"'"'; __file__='"'"'/tmp/pip-install-7nxw40tx/tesserocr/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record /tmp/pip-record-p51ckvh8/install-record.txt --single-version-externally-managed --compile --install-headers /home/hostbooks/django1/myproject/include/site/python3.6/tesserocr cwd: /tmp/pip-install-7nxw40tx/tesserocr/ Complete output (14 lines): Supporting tesseract v4.0.0 Building with configs: {'libraries': ['tesseract', 'lept'], 'cython_compile_time_env': {'TESSERACT_VERSION': 67108864}} running install running build running build_ext building 'tesserocr' extension creating build creating build/temp.linux-x86_64-3.6 x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -I/usr/include/python3.6m -I/home/hostbooks/django1/myproject/include/python3.6m -c tesserocr.cpp -o build/temp.linux-x86_64-3.6/tesserocr.o -std=c++11 -DUSE_STD_NAMESPACE tesserocr.cpp: In function ‘PyObject* __pyx_pf_9tesserocr_16PyResultIterator_8GetBestLSTMSymbolChoices(__pyx_obj_9tesserocr_PyResultIterator*)’: tesserocr.cpp:8586:43: error: ‘class tesseract::ResultIterator’ has no member named ‘GetBestLSTMSymbolChoices’ __pyx_v_output = (__pyx_v_self->_riter->GetBestLSTMSymbolChoices()[0]); ^~~~~~~~~~~~~~~~~~~~~~~~ error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Command errored out with exit status … -
Queries are too slow; prefetch_related not solving the problem
We are using Django 2.1 for Speedy Net. I have pages which display about 96 users per page, and for each user I want to display how many friends he has on Speedy Match, with an active email address. The query checks for each user if (self.email_addresses.filter(is_confirmed=True).exists()) is true. For each user of 96 users, it checks all his friends and run this query - more than hundreds of times per page. The query for fetching the users is User.objects.all().order_by(<...>), and then for each user it checks this query: qs = self.friends.all().prefetch_related("from_user", "from_user__{}".format(SpeedyNetSiteProfile.RELATED_NAME), "from_user__{}".format(SpeedyMatchSiteProfile.RELATED_NAME), "from_user__email_addresses").distinct().order_by('-from_user__{}__last_visit'.format(SiteProfile.RELATED_NAME)) I added prefetch_related in the User's manager model: def get_queryset(self): from speedy.net.accounts.models import SiteProfile as SpeedyNetSiteProfile from speedy.match.accounts.models import SiteProfile as SpeedyMatchSiteProfile return super().get_queryset().prefetch_related(SpeedyNetSiteProfile.RELATED_NAME, SpeedyMatchSiteProfile.RELATED_NAME, "email_addresses").distinct() But adding "email_addresses" and "from_user__email_addresses" to prefetch_related doesn't make the page load faster - it takes about 16 seconds to load the page. When loading the page without checking if each friend has a confirmed email address it takes about 3 seconds to load the page. Is there a way I can load all the email addresses of the users once and not each time a user is checked? Actually I would also like the friends query to be … -
How to populate complex django model using json data and Django ORM?
I have data as JSON format, and a Django model to populate with that data. JSON file contains around 4000+ objects where each has 30+ properties. To make this work done, i wrote a function which iterate through the JSON objects and create model object. Model.objects.create ( json data ... ) But this gives me many errors as there are multiple models each connected with another through ForeignKey field and ManyToMany field. For example: { "about":"", "academic-medium":"", "address":"",, "college_academic_bg":{ "end_year":"2015", "identification_document_picture":" ", "medium":"example_version", "name_of_degree":"A Level", "name_of_institution":"Example primary school" }, "complete_signup":true, "data_of_birth":831232800, "date_till_premium_account_valid":"2019-12-11 00:00:00", "display_picture":"dsp-url-example-exm.jpeg", "education_higher":"A Level", "education_higher_other":null, "education_secondary":"O Level", "education_secondary_other":null, "email":"example.bit@gmail.com", "evening":"[0,1,2,3,4]", "gender":"Female", "government_id_number":"ARANDOM234", "government_id_picture":null, "government_id_type":"Passport", "grade":1, "graduation_status":1, "graduation_year":null, "graduation_year_started":"2016", "group_higher":"Science", "group_secondary":"Science", "higher_version":1, "home_area":11, "hsc_copy":null, "hsc_verified":0, "id":1, "image_status":1, "institution_higher":"example school and college", "institution_major":"example major", "institution_secondary":"example school and college", "institution_type":2, "is_phone_number_verified":true, "is_premium":1, "is_suspended":0, "is_verified":true, "last_active_at":"2019-12-30 16:14:53", "masters_status":null, "medium_preference":"[1,2]", "morning":"null", "name":"example name", "nid_verified":0, "notes":"example note", "number_of_public_profile_views":85, "offline_preferred_teaching_areas":"[2,18,22,11]", "offline_preferred_teaching_subjects":"[5,10,13,15,16,18,19,21,30,31,33,186,192,194,197,198,206,207,349,211,213,346,222,223,228,230,240,242,243]", "old_slug":"example-slug", "passing_higher":"2015", "passing_secondary":"2012", "phone":"+000000000", "referral_count":0, "referral_tutor_id":null, "result_higher":null, "result_secondary":null, "salary_range_end":15000.0, "salary_range_start":8000.0, "schedule":[ false,true,true,false,true,true,false,true,true,false,true,true,false,true,true,false, false,false,false,false,false ], "schedule_is_flexible":true, "school_academic_bg":{ "end_year":"2012", "identification_document_picture":" ", "medium":"example-version", "name_of_degree":"O Level", "name_of_institution":"example school" }, "sign_up_channel":"activation", "sign_up_date":"2018-12-05 09:48:01", "ssc_copy":null, "ssc_verified":0, "status":0, "steps":4, "subject_query":"", "teaching_days":4, "teaching_preference":"[1,2,3]", "teaching_version":0, "undergraduate_university":6, "undergraduate_university_academic_bg":{ "end_year":" ", "identification_document_picture":" ", "name_of_degree":"example & Microbiology", "name_of_institution":6, "start_year":"2016" }, "undergraduate_university_id":"000235434", "uni_copy":null, "uni_verified":1, "updated_at":"2019-12-17 11:03:01", "user_id":2, … -
django development of data over time
I have a web application where user gets experience for finishing particular tasks. I´m using Django-REST and REACT for frontend. I would like to show statistics, where the user can see the graph how much exeperience he has gained each month. What is the best aprroach to save data. I was thinking about creating a model, which will store information about a month and user experience. Then on the end of the month i would run a script which will collect all these information for each user. I would like to know if there is something, that could go wrong or if there is better way, how to achieve same result, please let me know. Thanks for every advice! -
Editing profile in django
I am trying to figure out how to edit and update a profile from a custom html form. I have watched tutorials on how to use UserChangeForm to potentially inherit fields from Django's inbuilt change form and change a profile using this. But I would rather use the html page that comes with the template I am using. This is the html file of the profilepage: ... <li><a href={% url editprofile %}>Edit Profile</a></li> ... the html of the template to edit the profile page <form class="form-horizontal"> <div class="form-group"> <label for="inputEmail3" class="col-sm-2 control-label">Avatar</label> <div class="col-md-6"> <div class="media v-middle"> <div class="media-left"> <div class="icon-block width-100 bg-grey-100"> <i class="fa fa-photo text-light"></i> </div> </div> <div class="media-body"> <a href="#" class="btn btn-white btn-sm paper-shadow relative" data-z="0.5" data-hover-z="1" data-animated> Add Image<i class="fa fa-upl"></i></a> </div> </div> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-md-2 control-label">Full Name</label> <div class="col-md-8"> <div class="row"> <div class="col-md-6"> <div class="form-control-material"> <input type="email" class="form-control" id="exampleInputFirstName" placeholder= {{ user.username }}> <label for="exampleInputFirstName">First name</label> </div> </div> <div class="col-md-6"> <div class="form-control-material"> <input type="email" class="form-control" id="exampleInputLastName" placeholder="Your last name"> <label for="exampleInputLastName">Last name</label> </div> </div> </div> </div> </div> <div class="form-group"> <label for="inputEmail3" class="col-md-2 control-label">Email</label> <div class="col-md-6"> <div class="form-control-material"> <div class="input-group"> <span class="input-group-addon"><i class="fa fa-envelope"></i></span> <input type="email" class="form-control" id="inputEmail3" placeholder="Email"> <label for="inputEmail3">Email address</label> … -
py manage.py dumpdata withoutrest.employee --indent 4 in django Rest framework
Django Rest Framework When ever I am creating a new resource, the id/pk increments by 1. Suppose I have created a resource with id no. 7 and I delete it and if again I want to create another resource, it's automatically assigning to the next id no. Check the id no.s in my code; "pk": 1, "pk": 2, "pk": 3, "pk": 19 [ { "model": "withoutrest.employee", "pk": 1, "fields": { "eno": 100, "ename": "a", "esal": 20000.0, "eaddr": "hyd" } }, { "model": "withoutrest.employee", "pk": 2, "fields": { "eno": 2, "ename": "b", "esal": 30000.0, "eaddr": "bangalore" } }, { "model": "withoutrest.employee", "pk": 3, "fields": { "eno": 3, "ename": "c", "esal": 40000.0, "eaddr": "delhi" } }, { "model": "withoutrest.employee", "pk": 19, "fields": { "eno": 700, "ename": "Minnie", "esal": 10000.0, "eaddr": "Cuttack" } } ] -
What's the correct syntax for multiple ValidationError functions?
I have a model on which I want to raise 2 conditional validation errors: def clean(self): if self.personal_id_type == 0 and self.personal_id is None: raise ValidationError( { 'personal_id_type': [ "ID type can not be 'None' if you have set a value.", ] } ) if self.personal_phone_mobile is None and self.personal_phone_direct is None: raise ValidationError( { 'personal_phone_mobile': [ 'Please enter at least one personal phone number', ], 'personal_phone_direct': [ 'Please enter at least one personal phone number', ], } ) This displays the errors in isolation fine, so the logic is sound, however when both errors exist only the first exception is raised. Have I got the syntax wrong? -
Как отобразить на сайте галлерею фотографий в django? Пожалуйста помогите
Это класс модели галлереи class Gallery(models.Model): image = models.ImageField('Изображения', upload_to='uploads/') product = models.ForeignKey(Article, on_delete=models.CASCADE) К этой модели она относится class Article(models.Model): art_title = models.CharField('Название', max_length = 200) art_text = models.TextField('Описание') art_type = models.CharField("Класс" , max_length = 20, choices = TYPE, default = TYPE[0]) pub_date = models.DateTimeField('Дата публикации') def was_published_recently(self): return self.pub_date >= (timezone.now() - datetime.timedelta(days = 7)) def __str__(self): return self.art_title class Meta: verbose_name = 'Товар' verbose_name_plural = 'Товары' А вот куда я хочу вывести одну фотографию из галереи div class="card mb-3"> div class="row no-gutters"> div class="col-md-4"> img src="{{**Вот сюда надо вставить картинку**}}" class="card-img" alt="..."> /div> div class="col-md-8"> div class="card-body"> h5 class="card-title"><a href="{% url 'articles:detail' a.art_title %}"> {{a.art_title}}/a>/h5> p class="size card-text">{{a.art_text}}...</p> p class="card-text"><small class="text-muted">Last updated 3 mins ago</small></p> /div> /div> /div> /div> Пожалуйста помогите мне вставить туда одну фотографию из галереи привязанной к статье, которую я создал. -
Django FormView: form_valid() takes 2 positional arguments but 3 were given
I have the following views to display a page where you see a detail view of a book and post a comment/review below: class BookDetailView(DetailView): model = Book def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = BookReviewForm() return context class BookComment(SingleObjectMixin, FormView): template_name = 'book/book_detail.html' form_class = BookReviewForm model = Book def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('book_detail', args=[str(self.object.id)]) class BookDetail(View): def get(self, request, *args, **kwargs): view = BookDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = BookComment.as_view() return view(request, *args, **kwargs) The review class: class Review(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='reviews', ) review = models.CharField(max_length=5000) score = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(10)]) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) class Meta: unique_together = ('book', 'author') def __str__(self): return self.review The form: class BookReviewForm(forms.ModelForm): class Meta: model = Review fields = ('review', 'score',) I want to use the information given in the form to create a new review in which the currently logged in user is author and book is the book from the DetailView we are in, but I can't figure out how to validate and save. I tried adding this to BookComment … -
Django extra_views, ModelFormSetView doesn't save the data
I have two problems, i have a flat table with settings in my db, structure is: setting: char value: char It shows the form just fine, but: First Problem: It shows an empty field combination at the end. Second problem: It doesn't save the data, no error, no redirect to the success page, nothing. my views.py: class UpdateSettings(ModelFormSetView): model = Settings fields = ['setting', 'value'] template_name = 'settings.html' success_url = '/shows' my settings.html: {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <form method="post"> {% csrf_token %} {{ formset.management_form }} {% for form in formset %} <div class="row"> <div class="col-6"> {{ form.setting|as_crispy_field }} </div> <div class="col-6"> {{ form.value|as_crispy_field }} </div> </div> {% endfor %} <div class="form-group form-actions"> <button class="btn btn-success">Change</button> </div> </form> {% endblock %} -
Call javascript function when selected value in radio buttons changes using django forms
I have a Google Map that displays the directions between a point A and B. Using a radio button, the user should be able to select which transport he wants to use: walking, bike, car or public transport. I am using Django forms. My forms.py looks like this: from django import forms class Transport(forms.Form): CHOICHES = [('walking','Walking'), ('bike','Biking'), ('transit','Public'), ('driving','Car')] transport = forms.ChoiceField(choices=CHOICHES, widget=forms.RadioSelect) my template is: [...] {% include 'maps/map.html' %} <form action="/your-name" method="post"> {% csrf_token %} {{ form}} </form> [...] maps/map.html is: {% load static %} {% block content %} <div id="map"> </div> <script> var map; function initMap(position) { var directionsService = new google.maps.DirectionsService; map = new google.maps.Map(document.getElementById('map'), { center: {lat: -34.397, lng: 150.644}, zoom: 8 }); function calculateRoute(mapOrigin, mapDestination,transport) { var directionsDisplay = new google.maps.DirectionsRenderer({ map: map }); var request = { origin: mapOrigin, destination: mapDestination, travelMode: transport }; directionsService.route(request, function (result, status) { if (status === "OK") { directionsDisplay.setDirections(result); } else { window.alert('Directions request failed due to ' + status); } }); } {% for address in address_list %} calculateRoute({{address.A}},'{{ address.B }}','WALKING'); {% endfor %} } </script> <script src={{ LINK_API_GOOGLE_KEY }} async defer></script> {% endblock content %} at the moment "WALKING" is hardcoded. I need to … -
How to do Resultset unpacking in a template for loop in django
I'm trying to query a cassandra table and display the results to the user. In my views.py file after I query, I'll get a cassandra.cluster.ResultSet object. When i print the result using plain old python like > table_rows = session.execute(query) > > print("table_rows: ",table_rows) > for row in table_rows: > print(row) I get proper output like this: table_rows: <cassandra.cluster.ResultSet object at 0x7f341a861f98> Row(a=23, b=15, c=10) Row(a=10, b=17, c=15) Row(a=12, b=16, c=20) But I use the templates then It wont display anything <table> {% for row in table_rows %} <tr> {% for val in rows %} <td>{{ val }}</td> {% endfor %} </tr> {% endfor %} </table> Please suggest any solution to this. -
Django: Issue with SSL certificate ("SSL connection error: The message received was unexpected or badly formatted")
I'm using Windows 10, Python 3.7.6. Using the following packages: # Name Version Build Channel mysql-connector-c 6.1.11 he025d50_1002 conda-forge mysqlclient 1.4.6 pypi_0 pypi sqlalchemy 1.3.12 py37hfa6e2cd_0 conda-forge sqlite 3.30.1 hfa6e2cd_0 conda-forge sqlparse 0.3.0 py_0 conda-forge django 3.0.2 py37_0 conda-forge django-classy-settings 2.1.1 pypi_0 pypi django-debug-toolbar 2.1 py_0 conda-forge django 3.0.2 py37_0 conda-forge django-classy-settings 2.1.1 pypi_0 pypi django-debug-toolbar 2.1 py_0 conda-forge I am using an MySQL database with the following settings. This DB was created using an IT cloud data service within my company. I downloaded the SSL certificates and placed them within my django project. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'MyTestTVPVDb', 'USER': 'MyTestTVPVDb_so', 'PASSWORD': 'YYYYYYYYYYYYYYYYYYY', 'HOST': 'XXXXXXXXXXXXXXXXXXXXXXX', 'PORT': '3307', 'OPTIONS': { 'ssl': { 'ssl-ca': os.path.join(SSL_CERT_ROOT, 'ca_cert.pem'), } } } } Now when I type python manage.py dbshell, I am able to connect to the DB OK and everything looks OK. I can see that the DB support SSL. Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 476212 Server version: 5.5.5-10.0.20-MariaDB-wsrep-log MariaDB Server, wsrep_25.10.r4144 Copyright (c) 2000, 2019, Oracle and/or its affiliates. All rights reserved. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks … -
How to fix UnicodeDecodeError in Django REST Framework?
I want to show ProductImageSerializer in the browsable API. But I got this error: UnicodeDecodeError at /api/product_images/ 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte Unicode error hint The string that could not be encoded/decoded was: ����� Here's my models.py: class ProductImage(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) image = models.ImageField(upload_to='product_images', width_field=None, height_field=None, max_length=250) default = models.BooleanField(verbose_name='Default Picture', default=False) def __str__(self): return '%s - %s' % (self.product.product_id, self.default) Here's my serializers.py: class ProductImageSerializer(serializers.ModelSerializer): product = serializers.PrimaryKeyRelatedField(many=False, queryset=Product.objects.all()) class Meta: model = ProductImage fields = ['id', 'product', 'image', 'default'] def to_representation(self, instance): if self.context['request'].method == 'GET': product = ProductSerializer(instance.product, many=False, context=self.context).data data = { 'id': instance.id, 'product': product, 'image': instance.image, 'default': instance.default, } return data return Serializer.to_representation(self, instance) I think from what I've searched on several StackOverflow posts is that the problem occurs because of the image field. Here's my views.py: class ProductImageView(viewsets.ModelViewSet): queryset = ProductImage.objects.all() serializer_class = ProductImageSerializer -
Django-Filter: Filtering upon an already previous filtered result
Using Django-Filter in conjunction with Django-Tables2 to display a paginated set of objects, that have been filtered once. class ResultFilter(django_filters.FilterSet): description = django_filters.CharFilter(lookup_expr='icontains') class Meta: model = models.Legislation fields = "sector", "country", "act" class ResultTable(django_tables2.Table): class Meta: template_name = "django_tables2/bootstrap4.html" model = models.Legislation exclude = "id", class HomeView(django_tables2.SingleTableMixin, FilterView): template_name = "home.html" filterset_class = tables.ResultFilter table_class = tables.ResultTable paginate_by = 5 I'm struggling to figure out how to build something like a "filter-inception" where an already filtered result can be filtered again. Concept of Filtering I tried things like encoding the queryset.query raw sql string into the url as query_param, so if the user filters again - the backend knows which query has been executed before and can adapt. I really do not like this attempt. I am pretty sure there is a much better way to do this. -
Continuously update database Django
I am building a web application using the Django framework where I want to track certain vessels around the globe. To do this I will be getting data from the website AIShub.net. I want my web application to extract the data from Aishub.net every 6 hours and save it into the SQLite database. Does anybody have a suggestion on what the best method for doing this would be? -
How to prevent csv injection in django application
I am having a Django application with file upload feature. I am using Clamav to scan the file for viruses. I want to prevent CSV injection in my application too. I found this stackoverflow link related to it, but is of no help. Please suggest me how to do that. -
Filtering through Django models
I am new to Django and I'm having a problem with QuerySet while filtering through Django models. Filtering works just fine when I'm in python shell, but when generating a url, it shows all records instead. This is the model I work on: class Tabela(models.Model): block_id = models.CharField(max_length=64) timestamp = models.DateTimeField() type = models.CharField(max_length=32) link = models.CharField(max_length=64) link_as_account = models.CharField(max_length=100) account = models.CharField(max_length=100) amount = models.CharField(max_length=64) def __str__(self): return '%s %s %s %s %s %s %s' % (self.block_id, self.timestamp, self.type, self.link, self.link_as_account, self.account, self.amount) This is my results.html: <body> <div class="table-responsive"> <table class="table"> <thead class="thead-dark"> {% for head in field_names %} <th scope="col">{{ head }}</th> {% endfor %} </thead> <tbody> {% for row in data %} <tr scope="row"> {% for cell in row %} <td>{{ cell }}</td> {% endfor %} </tr> {% endfor %} </tbody> </table> </div> And this are parts of my views.py: def results(request): model = Tabela field_names = [f.name for f in model._meta.get_fields()] data = [[getattr(ins, name) for name in field_names] for ins in Tabela.objects.prefetch_related().all()[:10]] return render(request, 'nanosite/results.html', {'field_names': field_names, 'data': data}) def results_by_addresse(request): model = Tabela field_names = [f.name for f in model._meta.get_fields()] data = [[getattr(ins, name) for name in field_names] for ins in Tabela.objects.filter(block_id=1)] return … -
href Not Workink in Django HTML template
I creating a option to delet a DB register in django. However my href in HTML is not working. Onde i inspect i can seee the correct URL ref in the button but when i click not happens. This is mu URL: URL: url(r'^pessoa-delete/(?P<id>\d+)/$', pessoa_delete, name='core_pessoa_delete'), My View: def pessoa_delete(request, id): pessoa = Pessoa.objects.get(id=id) if request.method == 'POST': pessoa.delete() return redirect('core_lista_pessoas') else: return render(request, 'core/delete_pessoa_confirm.html', {'pessoa': pessoa}) My template to update register: <h2>Atualizando Pessoa: {{ pessoa }}</h2> <form action="{% url 'core_pessoa_update' pessoa.id%}" method="POST"> {% csrf_token %} {{ p_form.as_p }} <button type="submit"> Atualizar </button> </form> <button action="{% url 'core_pessoa_delete' pessoa.id %}"> Deletar </button> My template to confirm delete: <h2>Certeza que deseja deletar a pessoa {{ pessoa }}</h2> <form method="POST" action="{% url 'core_pessoa_delete' pessoa.id %}"> {% csrf_token %} <button type="submit" > Deletar </button> </form> The href of update template is not redirect to delete confirmations, could you please you take i look in my code and provide some guide? -
getting value from Mysql and passing to Django
am new in MySql and begginer in Django. I have created a web for school where a teacher enters a studnet name and gets results for certain subjects. I created form to get a student name. Django is linked already to MySql. I want to get for entered student grade for Math subject? To make the process automatic. How can do it? The database file name is profile. It contains ids for each student, its name and subjects and grades for math subject. forms.py from django import forms from .models import Student class StudentForm(forms.ModelForm): students= forms.CharField(max_length=150, label='',widget= forms.TextInput) class Meta: model = Student fields = ('students',) models.py from django.db import models class Student(models.Model): students = models.CharField(max_length=150) class Prof(models.Model): id = models.IntegerField(primary_key=True) tick = models.CharField(max_length=150) class Meta: managed = False db_table = 'profile' views.py from django.shortcuts import render from django.views.generic import TemplateView from .forms import StudentlForm def home(request): form = StudentlForm() if request.method == "POST": form = StudentlForm(request.POST) if form.is_valid(): data = form.save(commit=True) students = data.students context={ 'students':students,'} else: form = StudentlForm() return render(request,'school/search.html',{'form':form}) return render(request,'school/analysis.html',context) return render(request,'school/search.html',{'form':form}) I will appreciate any help and tips, directions to get solution as i am struggling with it several days. I have watched tutorials … -
Delete model instance button
I have a for loop that lists all the testimony instances in my model. I'd like to have the button in the code below delete the related instance when clicked. html {% block content %} {% for testimony in testimonies %} <a href="{% url "main:update_testimony_view" slug=testimony.slug %}"> <h3>{{testimony.name}}</h3> <button type="button" class="btn btn-danger">Delete</button> </a> {% endfor %} **** {% endblock content %} Thanks for any help -
Django: Correct way of passing data object from view to template to view?
From a template users can upload a csv file which gets parsed in def parseCSV(request): magic happens here (conforming date formats and all such fun things) return column names to template This view returns a list of columns and the user is asked to pick x columns to save. The users choice is posted to def saveCSV(request): logic for saving Now my question is, how do I most correctly handle the csv data object between view 1 and 2? Do i save it as a temperary file or do i send it back and forth view1->template->view2 as a data object? Or maybe something third? -
image uploading trouble in django
i have uploaded image but it is not showing up in page... Uploaded image is also not showing up in media folder. Used django forms for uploading image. have a look at my code snippets: my models.py: class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() published_date = models.DateTimeField(blank=True, null=True) blog_img = models.ImageField(upload_to='images/',null=True, blank=True) @property def img(self): if self.blog_img and hasattr(self.blog_img, 'url'): return self.blog_img.url else: return "#" my views.py: def post_new(request): if request.method =="POST": form = PostForm(request.POST , request.FILES) if form.is_valid(): post = form.save(commit=False) post.author= request.user post.save() return redirect('post_detail',pk=post.pk) else: form=PostForm() return render(request, 'blog/post_edit.html',{'form':form}) def post_edit(request,pk ): post = get_object_or_404(Post, pk=pk) if request.method == "POST": form = PostForm(request.POST,request.FILES, instance=post) if form.is_valid(): post = form.save(commit=False) post.author= request.user post.save() return redirect('post_detail',pk=post.pk) else: form = PostForm(instance=post) return render(request, 'blog/post_edit.html', {'form': form}) i have added this in settings.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') my post_list.html: {% extends 'blog/base.html' %} {% block content %} <div class="h2"> <h2>Recent Posts</h2> </div> {% for post in posts %} <div class=""> <div class="post"> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <a href="{% url 'post_detail' pk=post.pk %}">Comments: {{ post.approved_comments.count }}</a> <img src=" {{ post.img }} " width="200px" alt="images"> <p>{{ post.text|linebreaksbr }}</p> <div class="date"> <p>published: … -
Form doesn't appear when mixing DetailView and FormView in single view
I am following this https://docs.djangoproject.com/en/3.0/topics/class-based-views/mixins/#an-alternative-better-solution so that for ever Book detail view users can post reviews below. class BookDetailView(DetailView): model = Book def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = BookReviewForm() return context class BookComment(SingleObjectMixin, FormView): template_name = 'book/book_detail.html' form_class = BookReviewForm model = Book def post(self, request, *args, **kwargs): if not request.user.is_authenticated: return HttpResponseForbidden() self.object = self.get_object() return super().post(request, *args, **kwargs) def get_success_url(self): return reverse('book_detail', args=[str(self.object.id)]) class BookDetail(View): def get(self, request, *args, **kwargs): view = BookDetailView.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = BookComment.as_view() return view(request, *args, **kwargs) The form used is: class BookReviewForm(forms.Form): class Meta: model = Review fields = ('review', 'score',) The Review model: class Review(models.Model): book = models.ForeignKey( Book, on_delete=models.CASCADE, related_name='reviews', ) review = models.CharField(max_length=5000) score = models.PositiveSmallIntegerField(null=True, blank=True, validators=[MinValueValidator(0), MaxValueValidator(10)]) author = models.ForeignKey( get_user_model(), on_delete=models.CASCADE, ) class Meta: unique_together = ('book', 'author') def __str__(self): return self.review Yet when I add the form to the template: <div> <form method="POST">{% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> </div> it doesn't appear, only the submit button. If I click the button, I get redirected correctly. How can I make the form appear?