Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reset password view without using FormViews in django
I am trying to set a reset password view without using the reset FormViews that Django uses by default. This means that I don't really use the auth application, more than for the tokens and some other small stuff. What I did now is a normal view that displays an email/username form, and send an email to the user with a token: password_reset_token = PasswordResetTokenGenerator() def sendPasswordResetEmail(user, current_site): mail_subject = 'Password reset' message = render_to_string('myapp/password_reset_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': password_reset_token.make_token(user), }) to_email = user.email email = EmailMessage(mail_subject, message, from_email='testing@testing.com', to=[to_email]) email.send() After this, the user should be displayed with a view that asks for the user to fill a SetPasswordForm if the token is correct and it's a GET request. Or it should check for the token and check if the form is valid. If the form and token are valid then the password should be changed. I am trying to replicate a bit Django's PasswordResetConfirmView, but I'm not really sure if I'm doing it right. This is how I would do it, but I can't tell if there's any way to exploit the view somehow: def passwordResetConfirm(request, uidb64, token): if request.user.is_authenticated: return redirect("decks:index") try: uid … -
How to render results from groupby query in html - Django
I'm trying to render results of a group by query from a view to an HTML table but it is returning nothing. I originally had success in listing all results, but after applying the sum aggregation I can't get it to appear. Django View - with Group By def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.filter(user_id=request.user.id).values('symbol') obj = obj.aggregate(total_units=Sum('units'), total_cost=Sum('cost'))\ .annotate(total_units=Sum('units'), total_cost=Sum('cost'))\ .order_by('symbol') # Returns list of dictionaries context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) HTML <style> table, th, td { border: 1px solid black; } </style> <div class="container"> <h1>My Dashboard</h1> <table> <tr> <th>Symbol</th> <th>Total Units</th> <th>Total Cost</th> </tr> {% for row in object.obj %} <tr> <td>{{ row.symbol }}</td> <td>{{ row.units }}</td> <td>{{ row.cost }}</td> </tr> {% endfor %} </table> </div> {% endblock %} I'll provide the view below that worked without the group by. Django View - No group by def get_asset_price(request): # CryptoAssets is the model obj = CryptoAssets.objects.all().filter(user_id=request.user.id) # Returns list of objects context = { 'object': obj } return render(request, 'coinprices/my-dashboard.html', context) -
django-filter fieldset dependent on related field polymorphic ctype
class RelatedPoly(PolymorphicModel): common_field = ... class QweRelatedPoly(RelatedPoly): qwe = ... class RtyRelatedPoly(RelatedPoly): rty = ... class A(Model): related_poly = OneToOneField(RelatedPoly, ...) I also have a ViewSet for A model, and I need to implement a filterset_class which should be able to filter by both qwe and rty fields of RelatedPoly subclasses. In which ways could I achieve this? -
Django Nested Group By Data in template
here I explain my model, data, table structure, and expected result. My models are given below: class Buyer(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=20 class Merchand(models.Model): name = models.CharField(max_length=100) code = models.CharField(max_length=20 class Order(models.Model): code = models.CharField(max_length=20) buyer = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='br_order') merchand = models.ForeignKey(CustomUser, on_delete=SET_NULL, related_name='mr_order') value = models.FloatField(null=True, blank=True) qty = models.FloatField(null=True, blank=True) this is my model structure and my order model data is like this: {'code': 'C-001', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '100'} {'code': 'C-002', 'buyer': 1, 'merchand': '1', 'qty': 100, 'value': '300'} {'code': 'C-003', 'buyer': 2, 'merchand': '2', 'qty': 100, 'value': '400'} {'code': 'C-004', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'} {'code': 'C-005', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'} {'code': 'C-006', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'} {'code': 'C-007', 'buyer': 3, 'merchand': '2', 'qty': 700, 'value': '400'} {'code': 'C-008', 'buyer': 2, 'merchand': '2', 'qty': 900, 'value': '4500'} {'code': 'C-009', 'buyer': 2, 'merchand': '3', 'qty': 200, 'value': '2000'} I want to generate a table like this: = Buyer: 1, qty: 200, value: 400 - code: C-001, qty: 100, value: 100 - code: C-002, qty: 100, value: 300 = Buyer: 2, qty: 200, value: 13400 - code: C-003, qty: 100, value: … -
Python: sys.modules key points to diffenent module then the one it should originally point to
Running django-4.0.3, python-3.8.10; Python 3.8.10 (default, Nov 26 2021, 20:14:08) Type 'copyright', 'credits' or 'license' for more information IPython 7.27.0 -- An enhanced Interactive Python. Type '?' for help. In [1]: import sys In [2]: keys = sorted([key for key in sys.modules if 'lino_medico.lib.courses' in key]) ...: modules = tuple( ...: m ...: for m in map(sys.modules.__getitem__, keys) ...: ) In [3]: keys Out[3]: ['lino_medico.lib.courses', 'lino_medico.lib.courses.desktop', 'lino_medico.lib.courses.models'] In [4]: sys.modules[keys[-1]] Out[4]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [5]: sys.modules['lino_medico.lib.courses.models'] Out[5]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [6]: from importlib import import_module In [7]: import_module(keys[-1]) Out[7]: <module 'lino_medico.lib.courses.desktop' from '/home/blurry/lino/env/repositories/medico/lino_medico/lib/courses/desktop.py'> In [8]: keys[-1] Out[8]: 'lino_medico.lib.courses.models' In [9]: import weakref In [10]: isinstance(import_module(keys[-1]), weakref.ProxyTypes) Out[10]: False If you look at the keys in Out[3]: the last module name is 'lino_medico.lib.courses.models' but in Out[4]: as well as in Out[5]: and Out[7]: the key points to the file .../lino_medico/lib/courses/desktop.py instead of .../lino_medico/lib/courses/models.py. I am feeling out of my league here. Any help would be appreciated on explaining how this can happen. -
Django formset error: multiple values added are not saved, only the last value is saved
I'm using Django's formset to add the function to add multiple forms on one page. I want to receive all the Model fields from the form and save several objects through the '+' button only for the hour field. Currently, the code below accepts only the hour field in the form. In order to receive input of all fields from the form, is it necessary to input all fields in forms.py? With the code below, 'save' function works, but assuming that 5 'hours' field are entered, only the last value is added to DB. [models.py] class Supporting(models.Model): date = models.DateTimeField(blank=True, null=True) student = models.ForeignKey(Student, on_delete=models.CASCADE, blank=False, null=True) hour = models.CharField(max_length=2, blank=True, null=True) teacher = models.CharField(max_length=50, blank=True, null=True) comment = models.TextField(blank=True, null=True) technician = models.CharField(max_length=50, blank=True, null=True) [forms.py] from django import forms from django.forms import modelformset_factory from .models import Supporting SupportingModelFormset = modelformset_factory( Supporting, fields=('hour', ), extra=1, widgets={'name': forms.TextInput(attrs={ 'class': 'form-control', }) } ) [views.py] def add_supporting(request): if request.method == 'GET': formset = SupportingModelFormset(queryset=Supporting.objects.none()) elif request.method == 'POST': formset = SupportingModelFormset(request.POST) if formset.is_valid(): for form in formset: if form.cleaned_data.get('hour'): form.save() return HttpResponseRedirect('/supporting/') return render(request, 'supporting/add.html', {'formset': formset}) [supporting/add.html] {% block content %} <form class="form-horizontal" method="POST" action=""> {% csrf_token %} {{ formset.management_form … -
Handle many models using graphene in django
In my django project i have many different models which i want to query using GraphQL. For instance: class Country(): name = CharField(max_length) class Competition(): name = CharField(max_length) class Season(): name = CharField(max_length) class Team(): name = CharField(max_length) ... etc In my schema.py I need to create the GraphQL Types: class CountryType(): class Meta: model = models.Country fields = '__all__' class CompetitionType(): class Meta: model = models.Competition fields = '__all__' class SeasonType(): class Meta: model = models.Season fields = '__all__' class TeamType(): class Meta: model = models.Team fields = '__all__') ... etc And last but not least I have to create the Query class in the schema.py: class Query(graphene.ObjectType): country = graphene.relay.Node.Field(CountryType) competition = graphene.relay.Node.Field(CompetitionType) season = graphene.relay.Node.Field(SeasonType) team = graphene.relay.Node.Field(TeamType) all_country = graphene.List(CountryType) all_competition = graphene.List(CompetitionType) all_season = graphene.List(SeasonType) all_team = graphene.List(TeamType) def resolve_all_countries(root, info): return models.Country.objects.all() def resolve_all_competitions(root, info): return models.Competition.objects.all() def resolve_all_seasons(root, info): return models.Season.objects.all() def resolve_all_teams(root, info): return models.Team.objects.all() def resolve_country_by_name(root, info, name): try: return Country.objects.get(name = name) except Country.DoesNotExist: return None ... etc This all seems like much boilerplate code which adds unnecessary complexity and overhead. Of course for sophisticated queries you would need to write your own functions, but is this really "the way … -
Using Apache XAMPP on Windows 10 to create 1 Django website and one normal website
I have created a Django protect that works perfectly fine on windows Apache with Xampp. However, if I try to create a virtual host for a non-Django website, it doesn't work. If I then put my Django website into a virtual host it doesn't work, but then my non-Django website does work. By doesn't work I mean it takes me to this https://i.stack.imgur.com/DS0a5.png Here is all my code for my Django website inside a virtual host and my other non-project in a virtual host. #Django Wensote <VirtualHost *:443 _default_:443 neostorm.us.to:443> ServerName neostorm.us.to ServerAlias neostorm.us.to Alias /static "C:/xampp/htdocs/neostorm/static" <Directory "C:/xampp/htdocs/neostorm/static"> Require all granted </Directory> WSGIScriptAlias / "C:/xampp/htdocs/neostorm/neostorm/wsgi_windows.py" application-group=neostorm <Directory "C:/xampp/htdocs/neostorm/neostorm"> <Files wsgi_windows.py> Require all granted </Files> </Directory> ErrorLog "C:\xampp\apache\logs\neostorm_error.log" CustomLog "C:\xampp\apache\logs\neostorm_custom.log" common </VirtualHost> #Non Django Website <VirtualHost *:443 mail.neostorm.us.to:443> ServerName mail.neostorm.us.to DocumentRoot "C:/xampp/htdocs/webmail" <Directory "C:/xampp/htdocs/webmail"> Require all granted </Directory> </VirtualHost> Any help would be appreciated. -
Is it possible to get the selected date of DateRangeFilter in django admin.py?
I am trying to export the admin data into CSV file. For that i have to use start range and end range. So, i need to give the start date and end date manually the date is not fixed here. If i allow the user to select the date from DateRangefilter my job will be easy. After selecting the date i will allow them to export as CSV within two date ranges. Is it possible? example: Mymodel.objects.filter(created_at__range=(start_date, end_date)) Note: I have to do this functionality within the admin.py file. Not in frontend using javascript things. Please help me. Image link below https://i.stack.imgur.com/nWYNj.png -
Make a new model but no migrations are found
I currently have 1 model in my admin database called "Users" I was able to do a migration for this. But when I created another model, and when I try to migrate, there are no changes. class RegisterForm(models.Model): name = models.CharField(max_length=10) email = models.EmailField() password1 = models.CharField(max_length=20) password2 = models.CharField(max_length=20) admin.py: admin.site.register(RegisterForm) In my settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users', ] Ive tried doing python manage.py makemigrations users and python manage.py makemigrations Ive tried removing past migrations and editing the init file, but no luck. Could anyone provide me some guidance? Thanks! -
Is there a way to concatenate non related django models?
I have like 20 django apps in one project with their similar own models each represent a branch of a chain, the will simultaneously be doing CRUD operations? first of all, is this a good design? will it be too much on any online database? the second part is how to combine all the models for data representation? the models go something like this class App1(models.Model): serial = models.IntegerField() date_entry = models.DateField(default=datetime.date.today) company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING) product = models.ForeignKey(to=Product, on_delete=models.DO_NOTHING) weight = models.DecimalField(max_digits=10, decimal_places=2) country = models.ForeignKey(to=Country, on_delete=models.DO_NOTHING) cert_no = models.CharField(max_length=40) custom_cert_date = models.DateField() model 2 class App2(models.Model): serial = models.IntegerField() date_entry = models.DateField(default=datetime.date.today) company = models.ForeignKey(to=Company, on_delete=models.DO_NOTHING) product = models.ForeignKey(to=Product, on_delete=models.DO_NOTHING) weight = models.DecimalField(max_digits=10, decimal_places=2) country = models.ForeignKey(to=Country, on_delete=models.DO_NOTHING) custom_cert_no = models.CharField(max_length=40) custom_cert_date = models.DateField() and so on for each app I want to combine the weights of all models grouped by country, date_entry, and product one group by at a time?? I've tried this but it just concat them, doesn't add the weights, however the columns are the same? app1_data = App1.objects.filter(date_entry__gte=year1, date_entry__lte=year2).values('product__type').annotate( Sum('weight')).order_by('product__type') app2_data = App2.objects.filter(date_entry__gte=year1, date_entry__lte=year2).values('product__type').annotate( Sum('weight')).order_by('product__type') combined_data = list(chain(app1_data, app2_data)) will pandas help ? any help will be appreciated -
Type warning on pandas to_csv method path_or_buf variable given an HTTP response
I'm passing a pandas dataframe as csv file to the HTTP response and the code is working well. BUT I have here a warning on type hint on pandas' method to_csv on path_or_buf variable, Pycharm warns with : Expected type 'Union[str, PathLike[str], WriteBuffer[bytes], WriteBuffer[str], None]', got 'HttpResponse' instead This is the code used : def get_dataframe_response(request: Request) -> HttpResponse: my_dataframe: DataFrame = pd.DataFrame(<my_data_here>) get_dataframe_response: HttpResponse = HttpResponse(content_type="text/csv") get_dataframe_response["Content-Disposition" = "attachment; my_filename.csv" my_dataframe.to_csv(path_or_buf=get_dataframe_response, index=False, header=True) return get_dataframe_response -> Do you know what's causing this error or what should I use instead ? I tried get_dataframe_response.content but had issues and code stopped working. I saw pandas had issues even 6 months ago with type hints on path_or_buf variable already. But I want to make sure I use the right types. -
How does the Now() class works?
So I found a way to get the database timestamp and I tried to implement it for the first time def __str__(self): is_exp = 'EXPIRED' if self.date_created > Now() - datetime.timedelta(minutes=10) else 'AVAIL' return '{} {}'.format(self.code, is_exp) the code is used to see if a token is expired. I ran this code an it gave me this errpr '>' not supported between instances of 'datetime.datetime' and 'CombinedExpression' Now I've found some solution I've not tried yet but my main goal here is to understand what's going on. -
How to restrict access for personal profile page in django?
For example, I have a user: testuser. His personal page is users/account/testuser. How can I restrict access for his personal profile page, so only he can visit this page and for others it will be 403? I suggest I should use UserPassesTestMixin for it, but I don't know what to write in test_func. Actually I want to compare username from url, and user's username, and if it be equal, django will allow access to page. Or maybe there is another way to do it? View: class AccountInformationView(UserPassesTestMixin, DetailView): model = Profile template_name = 'users/account.html' def get_object(self, queryset=None): return get_object_or_404(User, username=self.kwargs.get('username')) def test_func(self): pass url: path('account/<str:username>', AccountInformationView.as_view(), name='account') -
How to show different column in select field django admin?
I've a model Customer: class Customer(models.Model): customer_name = models.CharField(max_length=128, null=True) contact_name = models.CharField(max_length=64) def __str__(self) -> str: return self.customer_name Customer Model is related with Event and CustomerEvent Model by ForiegnKey. In Django Admin panel we like to show customer_name in dropdown with Event which is working fine as Customer object str representation is self.customer_name. But In CustomerEvent we'd like show contact_name in admin panel dropdown which is not in __str__ representation. Here is my sample code: def render_change_form(self, request, context, *args, **kwargs): context['adminform'].form.fields['customer'].queryset = Customer.objects.filter(customer_type__iexact='I') return super(CustomerEventAdmin, self).render_change_form(request, context, *args, **kwargs) Please give me some idea to make it. -
How to execute a command using Python script on a terminal from html page in Django
I have a command which I want to run on a terminal in Django using a python script and not going on a terminal so how should I write the python script for it. Python command:- python ./ConfigManagement.py device_init -hn hostname -nr where device_init,-hn, hostname and -nr are arguments for the command. -
Need to return the value of a foreign key ID in a different model using django rest framework
models.py class Project(models.Model): project_name = models.CharField(max_length=20) client= models.ForeignKey(Client,on_delete=CASCADE,related_name="Client1",default=None) user=models.ManyToManyField(Default_User,related_name='users',default=None) description=models.TextField() type=models.TextField() class Meta: db_table ='Project' def __str__(self): return self.project_name class Job(models.Model): job_name=models.CharField(max_length=50) user= models.ForeignKey(Default_User,on_delete=CASCADE) project = ChainedForeignKey(Project,chained_field="user", chained_model_field="user",related_name='projects',show_all=False, auto_choose=True, sort=True) date = models.DateField(max_length=10,default=None) class Meta: db_table ='Job' def __str__(self): return '{}'.format(self.job_name) Serializers class ProjectSerializers(serializers.ModelSerializer): class Meta: model= Project fields= '__all__' class Job_Serializers(serializers.ModelSerializer): class Meta: model= Job fields = '__all__' viewsets class ProjectViewSet(viewsets.ModelViewSet): authentication_classes =[JWTAuthentication] permission_classes=(permissions.IsAdminUser,) queryset=models.Project.objects.all() serializer_class=serializers.ProjectSerializers filter_backends = [filters.SearchFilter] search_fields = ['project_name'] class Job_Viewset(viewsets.ModelViewSet): renderer_classes = (CustomRenderer, ) authentication_classes =[JWTAuthentication] permission_classes=(permissions.IsAdminUser,) queryset=models.Job.objects.all().order_by('-id') serializer_class=serializers.Job_Serializers Actually I need to get the project name from the Project model in the Job model. As now as project is a foreign key in Job model it is returning the project_id in the Job model but i need to get the project name along with the id in the job model response. I have tried with the queryset but i couldn't able to get the results which i expected. Need to get ike below results while using get call function. Result expected: { "id": 1, "job_name": "API for Timesheet", "date": "2022-03-08", "user": 2, "project": 1, "project_name": timesheet #need to get like this } -
How to select multiple posts through django checkboxes for comparison on a seperate page but pagination not allowing it
I'm a beginner in Django. Thanks for your help and patience. I have a model which I use to show a list of posts. I am using django pagination as there are many posts. I want the visitor to be able to select some posts through checkboxes. The selected posts are then used for comparison on a seperate page. In the html template, I have all the posts inside a form - each post is associated with a checkbox (checkbox is not part of the model). When a visitor selects some posts and clicks a submit button, then a view function returns a page with the selected posts for comparison. It all works fine, but the problem is with the pagination - i.e., when the visitor selects posts from different pages. For example, when selecting posts from the second page, those that were selected in the first page are not considered (no longer checked ?). I have looked at using sessions, form wizard, etc. But I still can't figure out how they can help or what is the appropriate approach for me to investigate more. Any guidance would be appreciated. -
Django ORM QuerySet Takes Too Much Time in Docker
I have a simple query in my django. values = ['profile_url', 'name','profit'] home = Home.objects.get(homename='Valley Homes') user_filters = {"name":"san agustin", "age":21} user_excludes = {} users = (User.objects.annotate(distinct_user=ArrayAgg(*values, distinct=True)).filter(home=home, **user_filters).select_related(*user_filters.keys()).exclude(**user_excludes).values(*values)) On local ec2 instance it takes up to 4 seconds to query On docker it takes up to 84 seconds which is horrible. I thought using select_related would shorten time but still it doesnt. Really need help in improving performance on docker. How can i make it faster like in local? -
I want to show User Groups along with user details in ListView in Django
I am trying to add User Groups in List View along with User Info but...... I know how to do in it DRF, In DRF I add groups fields class meta in serailizers.py, and then it works fine. But here I can not do it. Here is my code class UserListView(LoginRequiredMixin, ListView): login_url = '/' redirect_field_name = 'redirect_to' model = User template_name = 'user/list.html' context_object_name = 'user_list' paginate_by = 10 def get_queryset(self): comp_id=User.objects.filter(email=self.request.user).values_list('company_id', flat=True).first() if comp_id != None: return User.objects.filter(company_id=comp_id) else: return User.objects.all() def get_context_data(self, **kwargs): context = super(UserListView, self).get_context_data(**kwargs) user = self.get_queryset() page = self.request.GET.get('page') paginator = Paginator(user, self.paginate_by) try: user = paginator.page(page) except PageNotAnInteger: user = paginator.page(1) except EmptyPage: user = paginator.page(paginator.num_pages) context['user'] = user return context -
django rewrite many to many add method
I am new to django, I have a Profile object and trying to write subscriptions. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # follow subscribe follower = models.ManyToManyField(User, blank=1, related_name='prof_follower_set') followed = models.ManyToManyField(User, blank=1, related_name='prof_followed_set') the thing is, I need to forbidden a user to subscript to himself, therefore, I want to rewrite the add method of many to many field. I had a look on Manager and did not work out a way. I will be very grateful for your help. -
Update a model field when another modal field is updated
Having two models: class A(models.Model): project_code = models.CharField(max_length=250, null=False, blank=False) reference_code = models.CharField(max_length=250, null=False, blank=False, unique=True) quantity = models.CharField( max_length=250, null=True, blank=True, ) class B(models.Model): project_id = models.IntegerField( null=False, blank=False, default=0, ) quantity = models.CharField( max_length=250, null=True, blank=True, ) I would like to update B.quantity when A.quantity changes. How could I synchronize the two fields? When creating a B object, B.quantity always gets the value from existing A.quantity. I am newbie using Django ORM. I have been researching and found this in the official documentation, but it is not clear to me how to 'synchronize' Many-to-one relationships with a single field since it seems to synchronize the entire table. -
Partial model match in django?
I have a table in my db and I am connecting it to a Django model using "managed=False". The thing is I don't want all 300 columns on that table. I only need two or three column, can I create a model with db_table pointing to that table but not defining all columns? Appreciate your time in advance. -
Django many-to-many attribute with "through" model displayed on parent form
I'm new to Django and have been banging my head against the desk for a few days now trying to figure this one out. I apologize in advance if it's been asked/answered already. I'm building a basic restaurant inventory tracking app that allows the user to create ingredient inventory, create menus, and create items on those menus. When creating an item, the user should be able to define the ingredients that go into making that item AND the quantity of each ingredient required. When creating a menu item, I am trying to generate a form that allows the user to name the item, give it a price, then add ingredients one by one, with a given ingredient's quantity being selected as an ingredient is added. So something like this: Name: _______ Price: _______ Ingredient: ______ Quantity: _______ Ingredient: ______ Quantity: _______ Ingredient: ______ Quantity: _______ [Add another ingredient button] Here is my current code: # models.py class Ingredient(models.Model): GRAM = 'GR' OUNCE = 'OZ' ITEM = 'IT' UNIT_CHOICES = [ ('GR', 'Grams'), ('OZ', 'Ounces'), ('IT', 'Item') ] name = models.CharField(max_length=200) unitType = models.CharField(max_length=2, choices=UNIT_CHOICES, default=ITEM) unitCost = models.DecimalField(max_digits=10, decimal_places=2) inventoryQuantity = models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return self.name class Menu(models.Model): name … -
'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte '
how solve this error? "'utf-8' codec can't decode byte 0x89 in position 0: invalid start byte ' . while uplaoding csv file in django. Here view function def upload_csv(request): template = "upload_csv.html" if request.method == "GET": return render(request,template) csv_file=request.FILES['file'] if not csv_file.name.endswith('.csv'): messages.error(request,'This is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string =io.StringIO(data_set) next(io_string) for row in csv.reader(io_string,delimiter=',',quotechar="|"): _, created = Company.objects.update_or_create( name = row[0], hr_name =row[1], hr_email=row[2], hr_verified=row[3], user_id=row[4], primary_phone=row[5], comments=row[6], ) context={} return render(request, template,context)