Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why doesnt work edit model by list_filter with custom model manager?
For Post model I created a custom manager: #models.py class ObjectsOnManager(models.Manager): def get_queryset(self): return super(ObjectsOnManager, self).get_queryset().filter(status='on') class OnOffStatusModel(models.Model): ON = 'on' OFF = 'off' STATUS_CHOICES = ( (ON, 'Показывать'), (OFF, 'Не показывать'), ) status = models.CharField("Статус", max_length=15, choices=STATUS_CHOICES, default=ON) objects_on = ObjectsOnManager() objects = models.Manager() class Meta: abstract = True class Post(OnOffStatusModel): # fields ...... Then changed get_queryset in modelAdmin #admin.py class PostAdmin(admin.ModelAdmin): form = PostImageControlForm fields = ('count', 'status', 'image', 'title', 'descript', 'body', 'main_post', ) list_display = ('title', 'main_post', 'count',) list_editable = ('main_post', 'status') list_filter = ('category', 'main_post', 'status') def get_queryset(self, request): return Post.objects.all() So if I edit model on the change model page it is ok, but if i tried to edit on the change list page I have got the error enter image description here -
I import the module TinyMCE and the django isnt working
I think I have a outdated verison of TinyMCE and i was wondering how to fix the ImportError: cannot import name 'TinyMCE' from 'tinymce'. It was working before i form.py from django import forms from tinymce import TinyMCE from .models import Post, Comment class TinyMCEWidget(TinyMCE): def use_required_attribute(self, *args): return False class PostForm(forms.ModelForm): content = forms.CharField( widget=TinyMCEWidget( attrs={'required': False, 'cols': 30, 'rows': 10} ) ) class Meta: model = Post fields = ('title', 'overview', 'content', 'thumbnail', 'categories', 'featured', 'previous_post', 'next_post') class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ('content', ) -
DJANGO - please guys need help in signals pre_save
when i try to make a slugfield , and when i write the pre_save code it doesn't reconize my model i don't know why , please help this is my model : from django.db import models from post.utils import unique_slug_generator from django.db.models import signals from django.db.models.signals import pre_save class product(models.Model): title=models.CharField(max_length=50) slug=models.SlugField(max_length=50,unique=True) photo=models.ImageField(upload_to='img') price=models.PositiveIntegerField(default=0) discription=models.TextField(max_length=255) def __str__(self): return self.title def slug_save(sender,instance,*args,**kwargs): if not instance.slug: instance.slug=unique_slug_generator(instance,instance.title,instance.slug) pre_save.connect(slug_save, sender =product) utils.py: from django.utils.text import slugify def unique_slug_generator(model_instance,title,slug_field): slug=slugify(title) model_class=model_istance.__clas__ while model_class._default_manager.filter(slug=slug).exists(): object_pk=model_class._default_manager.latest(pk) object_pk=object_pk.pk + 1 slug=f'{slug}-{object_pk}' return slug the error message : class product(models.Model): File "C:\Users\Madara\Desktop\khkh\sluger\post\models.py", line 28, in product pre_save.connect(slug_save, sender =product) NameError: name 'product' is not defined -
Django pass argument to view from html form
I have an html page that contains a dropdown selector. I have this encased in a form and I essentially want to just reload the same page with a different value passed in when Update is clicked. Here is the html: <form action="{% url 'analyze:plot' %}"> <select> {% for name in x_keys %} <option name="x_key_name" id="{{ name }}" value="{{ name }}">{{ name }}</option> {% endfor %} </select> <input type="submit" value="Update"> </form> Here is the view def plot(request, x_key='test_key'): svg_dict = { 'svg': get_fig(x_key=x_key), 'x_keys': ScatterKeysXAxis.objects.all(), } # set the plot data plt.cla() # clean up plt so it can be re-used return render(request, 'analyze/plot.html', svg_dict) How do I set the x_key within the view from the html form? Is there a better way to do what I am describing? -
Redirecting to wrong URL Django
I've been working on a Django project that has multiple types of users. Hence, I'm creating more than one signup page, one for each type of user. I created one page for users to chose if they want to sign up as a mentor or a student so they can later be given a right form. However, my urls don't work properly and both 'register' and 'register_student' urls take me to the view I created for register. What am I doing wrong? My register/urls.py : urlpatterns = [ path('', views.register, name='register'), path('', views.student_register, name='student_register'), ] My register/templates/register/register.html {% block content %} <h2>Sign up</h2> <p class="lead">Select below the type of account you want to create</p> <a href="{% url 'student_register' %}" class="btn btn-student btn-lg" role="button">I'm a student</a> {% endblock %} My register/views.py def register(request): return render(request, "register/register.html") def student_register(request): if request.method == "POST": student_form = StudentRegisterForm(request.POST) if student_form.is_valid(): user = student_form.save(commit=False) user.is_student = True user.save() else: student_form = StudentRegisterForm() return render(request, "register/student_register.html", {"student_form": student_form}) And my app's ursl: mentorapp/mentorapp/urls: urlpatterns = [ path('', include("django.contrib.auth.urls")), # gives access to django log-in/out pages path('mainpage/', include('mainpage.urls')), path('register/', include('register.urls')), path('student_register/', include('register.urls')), ] localhost:8000/register shows the 'register.html' page and when I click on 'I'm a student' url … -
How to resolve 'no pg_hba.conf entry for host' error for django app?
I am building a web app using django. I am trying to connect the app to the Azure Database for PostgreSQL. I get this error when I use the "python manage.py makemigrations" command in the powershell. -
Django filter by a specific day
I have an application that I need to pick one day and it returns me the total number of events as well as the list of active events that day. Each event has a duration. I can filter for today, but how do I do if I want to filter for any other day? model class Event(models.Model): name = models.CharField(max_length=50, null=True, blank=True, verbose_name='Name') start_date = models.DateTimeField(null=True, blank=False, verbose_name='Start') end_date = models.DateTimeField(null=True, blank=False, verbose_name='End') def __str__(self): return '{}'.format(self.name) view def total_events(request): events = Event.objects.filter(Q(start_date__lte=timezone.now()) & Q(end_date__gte=timezone.now())) total_events = events.count() context = { 'events': events, 'total_events': total_events, } return render(request, 'list.html', context) template <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Event Search</title> </head> <body> <br> <br> DAY: <input type="text"> <button>Filter</button> <br> <br> <b>Total of active events in filtered day:</b> {{ total_events }} <br> <b>List of active events in filtered day:</b> <table> <tr> {% for event in events %} <td> {{ event.name }} </td> {% endfor %} </tr> </table> </body> </html> The output is like this: Can some one give me a direction to follow? thanks! -
Nested Models when API Endpoint differs in field names from model with Django Rest Framework
Let's say I receive the following json: { "id": 1234, "created_at": "2019-10-22T14:18:09-04:00", "person": { "id": 7234, "name": "John Smith" }, "ticket": { "id": 5432, "person_id": 7234, "name": "How to fix this function?" } } And I want to serialize and then save to a db with the following tables: Event, Person, and Ticket where Ticket is described as follows: class Ticket(models.Model): id = models.PositiveIntegerField(primary_key=True) person = models.ForeignKey('Person') name = models.CharField(max_length=100) What ought the Ticket Serializer to look like? Currently, I have what doesn't work: class TicketSerializer(serializers.ModelSerializer): person_id = serializers.IntegerField() class Meta: model = models.Ticket def to_internal_value(self, data): try: data['person'] = data['person_id'] except KeyError: pass return super().to_internal_value(data) class EventSerializer(UniqueFieldsMixin, NestedCreateMixin, serializers.ModelSerializer): person = PersonSerializer() ticket = TicketSerializer() class Meta: model = models.Event The error I get reads: rest_framework.exceptions.ValidationError: {'ticket': {'person': [ErrorDetail(string='Invalid pk "7234" - object does not exist.', code='does_not_exist')]}} -
How to PATCH a column in table according to an id from another table in django
I am building a django application. I have a question here. This is my models.py class Device(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_name = models.CharField(max_length=200, null=True, blank=True ) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.id) class StatusActivity(models.Model): OFFLINE = 1 ONLINE = 2 STATUS = ( (OFFLINE, ('Offline')), (ONLINE, ('Online')), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) device_id = models.ForeignKey(Device, related_name='status_activity', on_delete=models.CASCADE) changed_to = models.PositiveSmallIntegerField(choices=STATUS) modified_at = models.DateTimeField(auto_now_add=True) I want to write an api that takes id of Device and change its relational data(changed_to field) in StatusActivity table. How should my views.py should be ? from rest_framework import generics, status from rest_framework.response import Response from .models import Device, StatusActivity from .serializers import DeviceSerializer, StatusActivitySerializer class DeviceListView(generics.ListAPIView): queryset = Device.objects.all() serializer_class = DeviceSerializer class DeviceListByIdView(generics.UpdateAPIView): queryset = Device.objects.filter(id=self.request.id) serializer_class = StatusActivitySerializer def patch(self, request, *args, **kwargs): super(DeviceListByIdView, self).patch(request, args, kwargs) instance = self.get_object() serializer = self.get_serializer(instance) data = serializer.data response = {"status_code": status.HTTP_200_OK, "message": "Successfully updated", "result": data} return Response(response) -
Show the count of inline items in the admin view
I want to show the count of a related item in the parent items listing in django. But I keep getting an error. models.py class TblHoldings(models.Model): item_code = models.CharField(unique=True, max_length=5) product_name = models.CharField(max_length=45) service_provider = models.ForeignKey(TblHoldingsServiceProviders,on_delete=models.CASCADE, related_name='service_provider',db_column='service_provider') account_details = models.CharField(max_length=100) purchase_cost = models.IntegerField() current_value = models.IntegerField() power_of = models.CharField(max_length=45, blank=True, null=True) purchase_date = models.DateTimeField(blank=True, null=True) goal_term = models.CharField(max_length=40, default="M",choices=FIN_GOAL_TERM) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.product_name + ' at ' + self.service_provider.provider_name class Meta: verbose_name = 'Holding' verbose_name_plural = 'Holdings' managed = True db_table = 'tbl_holdings' class TblHoldingsSubProducts(models.Model): item_code = models.CharField(max_length=5, blank=True, null=True) holding_id = models.ForeignKey(TblHoldings, default= 1,on_delete = models.CASCADE,related_name='holding_id', db_column='holding_id' ) product_name = models.CharField(max_length=45) account_details = models.CharField(max_length=100) purchase_cost = models.IntegerField() current_value = models.IntegerField() power_of = models.CharField(max_length=45) purchase_date = models.DateTimeField(blank=True, null=True) maturity_date = models.DateTimeField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True, null=True, blank=True) updated_at = models.DateTimeField(auto_now=True, null=True, blank=True) def __str__(self): return self.product_name class Meta: verbose_name = 'Holdings Sub Product' verbose_name_plural = 'Holdings Sub Products' managed = True db_table = 'tbl_holdings_sub_products' admin.py class HoldingsSubProductsInline(admin.TabularInline): model = TblHoldingsSubProducts @admin.register(TblHoldings) class HoldingsAdmin(admin.ModelAdmin): list_display = ('item_code', 'product_name', 'service_provider', 'power_of','current_value', 'purchase_date', 'subproduct_count') list_filter = ('goal_term', 'power_of', 'product_name', 'service_provider') ordering = ('purchase_date',) search_fields = ('product_name',) inlines = [ HoldingsSubProductsInline, ] def subproduct_count(self, … -
Django returns a error of circular import
enter image description hereWhen I wrote urlpatterns I got such error: django.core.exceptions.ImproperlyConfigured: The included URLconf '' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably ca used by a circular import. -
How to Create a Scheduled Post in Django?
I would like to publish the shipment according to the specified date and time. For example, when I send the article today, I want it to be published automatically when the time comes tomorrow. (or at any date and time) How can I do it? Relevant part of the model: With this model, date and time are determined for post. models.py published = models.DateTimeField(default=timezone.now, verbose_name="Yayımlanma Tarihi",) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) views.py def post_index(request): post_list = Post.objects.all() query = request.GET.get('q') if query: post_list = post_list.filter( Q(title__icontains=query) | Q(content__icontains=query) | Q(author__first_name__icontains=query) | Q(author__last_name__icontains=query) ).distinct() paginator = Paginator(post_list, 5) # Show 25 contacts per page page = request.GET.get('sayfa') posts = paginator.get_page(page) return render(request, 'post/index.html', {'posts': posts}) -
heroku limit with django analyzing files without model?
i created an app using django and heroku to upload pdf files and get some specific data out of them. After deploying I found few things. 1: There is a limit in the http response which i believe is around 30 to 40 secs, however some of these files are super big and it may require a bit more time. Is there a way to increase the time response? if not, any other server you may recommend? 2: Because I am not using a db to storage the files, cannot find anywhere is django or heroku has a limit for handling files without saving them in a db. any specific limits? -
Bootstrap Modal submit button not working with DeleteView in Django 2.2
I am learning Django 2.2 and using a little bit of Bootstrap to help with the front end. I have a Model created which stores some user information like first name and last name. I have created a DeleteView class which is supposed to delete entries from the database using the ID. Everything works fine as is. But if I try to implement the DeleteView class using a Bootstrap modal window, nothing seems to happen even if I click the submit button. I am not sure what I am doing wrong. I read in another thread here in Stackoverflow that we need to include the button inside a form which I have done too. But it still doesn't delete the entry. Below is all the code required. Note - I have placed the Delete button inside the contacts_view.html file. The contacts_delete.html file is exactly the same. My idea is to provide the user to not just view the details but also update or even delete the specific entry. When I click on the Delete button, the modal pop up window appears. But when I click on the 'Confirm' button, the entry does not get deleted as required. Please let me … -
how to change the filename stored on disk - django, s3
I am trying to change the name of a file that a user uploads. I can get it to change the filename, but it is still stored in the S3 server as the original filename. Django says that -- "The file is saved as part of saving the model in the database, so the actual file name used on disk cannot be relied on until after the model has been saved." You guys know of any tips on where do put a function in either my view, form or model to allow for me to change the filename on the disk? from forms.py: class AddAttachmentForm(forms.ModelForm): class Meta: model = Attachment fields = ('attachment',) labels = { 'attachment': '' } widgets = { 'attachment': forms.FileInput(attrs={'style':'display:none;'}) } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.error_messages = { 'required': '{fieldname} is required'.format(fieldname=field.label), } from models.py class Attachment(models.Model): def rand_str(n): return ''.join([random.choice(string.ascii_letters + string.digits) for i in range(n)]) random_folder = rand_str(75) user = models.ForeignKey('User', on_delete=models.CASCADE, null=True) competency = models.ForeignKey('Competency', related_name="attachments", on_delete=models.CASCADE) attachment = models.FileField(upload_to=random_folder, blank=True) attacher = models.ForeignKey('User', related_name='attacher', on_delete=models.SET_NULL, null=True) filename = models.CharField(max_length=255) file_type = models.CharField(max_length=255, null=True, blank=True) date_attached = models.DateTimeField(null=True, blank=True) from views.py form = AddAttachmentForm(request.POST, request.FILES) if form.is_valid(): … -
Mysqlclient not installing
MySQL Version : mysql Ver 14.14 Distrib 5.7.28, for Linux (x86_64) using EditLine wrapper OS: Ubuntu 18.04 Command: pip install mysqlclient I want to connect MySQL and python vertualenv version: 16.7.8 The response I got. Collecting mysqlclient Using cached `enter code here`https://files.pythonhosted.org/packages/d0/97/7326248ac8d5049968bf4ec708a5d3d4806e412a42e74160d7f266a3e03a/mysqlclient-1.4.6.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Command errored out with exit status 1: command: /var/www/venv/bin/python3 -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-zcjzm7gs/mysqlclient/setup.py'"'"'; __file__='"'"'/tmp/pip-install-zcjzm7gs/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-rhjvnuzr --python-tag cp36 cwd: /tmp/pip-install-zcjzm7gs/mysqlclient/ Complete output (31 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.6 creating build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.linux-x86_64-3.6/MySQLdb copying MySQLdb/times.py -> build/lib.linux-x86_64-3.6/MySQLdb creating build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/__init__.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.linux-x86_64-3.6/MySQLdb/constants running build_ext building 'MySQLdb._mysql' extension creating build/temp.linux-x86_64-3.6 creating build/temp.linux-x86_64-3.6/MySQLdb 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 -Dversion_info=(1,4,6,'final',0) -D__version__=1.4.6 -I/usr/include/mysql -I/usr/include/python3.6m -I/var/www/venv/include/python3.6m -c MySQLdb/_mysql.c -o build/temp.linux-x86_64-3.6/MySQLdb/_mysql.o x86_64-linux-gnu-gcc -pthread -shared -Wl,-O1 -Wl,-Bsymbolic-functions -Wl,-Bsymbolic-functions -Wl,-z,relro … -
implementing following and followers doesn't work properly
I have a user model that has a slug field for lookup. I am trying to implement a user following and followers as its own model in my rest API, so I can save more info about the following and followers, and since I am trying to build a big project, I gathered it was a better practice. The problem is that the code doesn't work and the user when he tries to follow does not follow the user. I want to be able to follow the user if the user, and the user not able to follow himself and to follow once models.py class UserFollowing(models.Model): following = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="follows", null=False, blank=False, on_delete=models.DO_NOTHING) followers = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="followed_by", null=False, blank=False, on_delete=models.DO_NOTHING) followed_on = models.DateTimeField(auto_now_add=True) serializers.py class UserFollowingSerializer(serializers.ModelSerializer): following_count = serializers.SerializerMethodField(read_only=True) followers_count = serializers.SerializerMethodField(read_only=True) user_is_following = serializers.SerializerMethodField(read_only=True) followed_on = serializers.SerializerMethodField(read_only=True) class Meta: model = UserFollowing fields = "__all__" def get_followed_on(self, instance): return instance.followed_on.strftime("%d %B, %Y") def get_following_count(self, instance): return instance.following.count() def get_followers_count(self, instance): return instance.followers.count() def get_user_is_following(self, instance): request = self.context.get("request") return instance.following.filter(slug=request.user.slug).exists() views.py class UserFollowAPIView(APIView): serializer_class = UserFollowingSerializer permission_classes = [IsAuthenticated] def delete(self, request, pk): user = get_user_model().objects.get("slug") UserFollowing.objects.delete(user_id=user, following_user_id=user) def post(self, request, pk): user = get_user_model().objects.get("slug") UserFollowing.objects.create(user_id=user, following_user_id=user) urls.py path("<slug:slug>/follow/", … -
How to pre select value in a django forms.Select field
I am new to django. I am creating a simple CRUD application using django 2.2, I have a simple addstudent.html page where i can add data in some fields including a dropdown where I can select the class of student and database is updated. Below is my code: forms.py class StudentForm(forms.ModelForm): class_list= [ ('Class IIX', 'Class IIX'), ('Class IX', 'Class IX'), ('Class X', 'Class X'), ('Class XI', 'Class XI'), ('Class XII', 'Class XII') ] student_class= forms.CharField(label='Class', widget=forms.Select(choices=class_list,attrs={'style': 'width:175px'})) class Meta: model=Student fields='__all__' models.py class Student(models.Model): student_id=models.CharField(max_length=20) student_name=models.CharField(max_length=100) student_email=models.EmailField() student_contact=models.CharField(max_length=100) student_class=models.CharField(max_length=100) class Meta: db_table='student' snippet of addstudent.html template where dropdown is shown correctly <div class="form-group row"> <label for="sname" class="col-sm-4 col-form-label">Student Class:</label> <div class="col-sm-8"> {{form.student_class}} </div> </div> Problem: I am not able to figure out how to preselect the dropdown when I edit a student, I get the value as 'Class X' from the database but how do i use this database value to select correct option in dropdown? Please Note: This project is for school kids and I can't use JQUERY/JAVASCRIPT here. -
best languge to design a social network [closed]
what's the best programming language should I use to design social network like facebook Instagram twitter... ruby on rail or python with Django or JavaScript or php or what so please give me the best I should use also I just want to say that I like Django the most but I want my website be the best -
'OneHotEncoder' object has no attribute 'categories_'
I'm trying to run a python3 project of predicting the outcome of cricket matches using Random Forest Algo for the training of the machine. I'm currently getting this error **Traceback: File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/core/handlers/base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/fourth_umpire/views.py" in prematch 107. probab = pre_match_predict("2016",team1,team2,venue) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/fourth_umpire/predictions/pred.py" in pre_match_predict 17. X_test = enc.transform(X_test).toarray() File "/Users/kyvinay/cfd_apriori/4th_umpire/web/scikit-learn/sklearn/preprocessing/_encoders.py" in transform 390. X_int, X_mask = self._transform(X, handle_unknown=self.handle_unknown) File "/Users/kyvinay/cfd_apriori/4th_umpire/web/scikit-learn/sklearn/preprocessing/_encoders.py" in _transform 107. if n_features != len(self.categories_): Exception Type: AttributeError at /pre_pred/ Exception Value: 'OneHotEncoder' object has no attribute 'categories_'** The corresponding code is import numpy as np from scipy import sparse from ..base import BaseEstimator, TransformerMixin from ..utils import check_array from ..utils.fixes import _argmax from ..utils.validation import check_is_fitted from ._label import _encode, _encode_check_unknown __all__ = [ 'OneHotEncoder', 'OrdinalEncoder' ] class _BaseEncoder(TransformerMixin, BaseEstimator): """ Base class for encoders that includes the code to categorize and transform the input features. """ def _check_X(self, X): """ Perform custom check_array: - convert list of strings to object dtype - check for missing values for object dtype data (check_array does not do that) - return list of features (arrays): … -
Is there a way to use the python modele "webbrowser" with Heroku?
I am working on deploying a django app to heroku and I am having trouble with the webbrowser module. The function initially creates a pdf from html using pdfkit (this part works fine). Afterwards, I use '''webbrowser.open_new_tab''' to render the pdf in a new tab. This works perfectly locally, but not when I deploy to Heroku :( I checked the Heroku log, and it indicates that the pdf is being properly compiled and that the webbrowser command is successfully called, but alas, a new tab is not opened... Are there any suggestions on how best to tackle this issue? Perhaps I am missing an important environment variable that allows me to open new pages on the user's browser? Thank you, -- Carter -
Django - Check If form field contains a whitespace
In my project, I have a forms.py that contains the following field: fullName = forms.CharField(min_length=3, max_length=255, widget=forms.TextInput(attrs={'placeholder': 'Full Name', 'class': 'fullNameField'})) In my views.py, I check if the field does not contains a whitespace: if not ' ' in form.cleaned_data.get('fullName'): context ['fullNameError'] = "Please enter a valid full name" When I submit the form and add a space, the context ['fullNameError'] is called when it shouldn't be. Does anybody know why? Thank you. -
How do I use the AdagradDAOptimizer Optimizer by using tf.compat.v1.train?
I tried using the AdagradDAOptimizer for my model but I got an error while I did the same thing to the ProximalAdaGrad Optimizer class. I did not get an error for that one so I am confused as to what I am doing wrong. My code: import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt import numpy as np import time start_time = time.time() data = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = data.load_data() class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot'] train_images = train_images/255.0 test_images = test_images/255.0 optimizer1 = tf.compat.v1.train.AdagradDAOptimizer(0.001) model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(100, activation="softsign"), keras.layers.Dense(10, activation="softmax") ]) model.compile(optimizer=optimizer1, loss="sparse_categorical_crossentropy", metrics=["accuracy"]) model.fit(train_images, train_labels, epochs=5) test_loss, test_acc1 = model.evaluate(test_images, test_labels) print("Test acc is:", test_acc1) print("--- %s seconds ---" % (time.time() - start_time)) Error Message: ERROR:root:Internal Python error in the inspect module. Below is the traceback from this internal error. Traceback (most recent call last): File "/usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py", line 2882, in run_code exec(code_obj, self.user_global_ns, self.user_ns) File "<ipython-input-4-bdc36910ec8c>", line 11, in <module> data = tf.keras.datasets.fashion_mnist File "/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/util/module_wrapper.py", line 193, in __getattr__ attr = getattr(self._tfmw_wrapped_module, name) AttributeError: module 'tensorflow' has no attribute 'keras' During handling of the above exception, another exception occurred: Traceback (most recent … -
Django how to get id from the database and show in the html
this is my views.py: def gradescales(request): grade = list(gradeScalesSetting.objects.all()) # < DB hit once gradeScalesSettings = gradeScalesSetting.objects.all() rounding = [] configuration = [] for i in grade: if i.Rounding not in rounding: rounding.append(i.Rounding) if i.Configuration not in configuration: configuration.append(i.Configuration) return render(request, 'Homepage/gradescale.html', {"rounding": rounding, "configuration": configuration,"gradeScalesSetting":gradeScalesSettings}) i use this code because i dont want to use distinct(), but im getting trouble in getting their id. this my template <select name="gradescale" id="gradescale" onchange="summary(this.value)" required="required" > {% for r in configuration %} <option value="{{r}}">{{r}}</option> {% endfor %} </select> this is the result: i just want that in my the value is the id of what list i selected this is my database -
Django 2.2: How to redirect a user from a view to a specific page with a context?
Our website is listing properties ads. When a user publish an ad, I would like to redirect him to a "thank you" page. But inside this thank you page I would like to put a button with the link to the detailed view of the created ad. I don't want to use "messages" framework because I need a dedicated page for tracking purpose. How can I send the context (in this case the absolute url of the created object) to the "thank you" page? It doesn't matter if the solution requires the use of a class based view or a function view. Many thanks in advance !