Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter and count in template tag
im trying to filter and count a specific queryset in the template with Django templete enginge. Cant get it to work. The film_list is the context and film is the table and language is a field. Any tips on how to use filter and count at the same time in the template engine? Or should i solve it in another way? {% if filmlist.film.language == "danish" %} {{ film_list.all.count }} {% endif %} -
django-rest-framework: how do I update a nested foreign key? My update method is not even called
I have something like this (I only included the relevant parts): class ImageSerializer(serializers.ModelSerializer): telescopes = TelescopeSerializer(many=True) def update(self, instance, validated_data): # In this method I would perform the update of the telescopes if needed. # The following line is not executed. return super().update(instance, validated_data) class Meta: model = Image fields = ('title', 'telescopes',) When I perform a GET, I get nested data just as I want, e.g.: { 'title': 'Some image', 'telescopes': [ 'id': 1, 'name': 'Foo' ] } Now, if I want to update this image, by changing the name but not the telescopes, I would PUT the following: { 'title': 'A new title', 'telescopes': [ 'id': 1, 'name': 'Foo' ] } It seems that django-rest-framework is not even calling my update method because the model validation fails (Telescope.name has a unique constraint), and django-rest-framework is validating it as if it wanted to create it? Things worked fine when I wasn't using a nested serializer, but just a PrimaryKeyRelatedField, but I do need the nested serializer for performance reason (to avoid too many API calls). Does anybody know what I'm missing? Thanks! -
Room matching query does not exist. django rest framework, Django retsframework
I am new to django. im my project I want to post a photo to a hotel an d aphoto to the room of the hotel: but I am getting the following problem:Room matching query does not exist. django rest framework. Room id does not exist although it does exist in the database In my serializer.py class RoomPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = RoomPicture fields = ['id', 'room', 'location'] class RoomSerializer(serializers.ModelSerializer): roompicture = RoomPictureSerializer(many=True) class Meta: model = Room fields = ['id', 'roompicture'] class HotelPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = HotelPicture fields = ['id', 'hotel', 'location'] class ComplexSerializer(serializers.ModelSerializer): hotelpicture = HotelPictureSerializer(many=True) roompicture = RoomSerializer(many=True) class Meta: model = Hotel fields = ['id', 'hotelpicture', 'roompicture'] def create(self, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') roompictures_data = validated_data.pop('roompicture') hotel = Complex.objects.create(**validated_data) for hotelpicture in hotelpictures_data: HotelPicture.objects.create(hotel=hotel, **hotelpicture) for roompicture_data in roompictures_data: room = Room.objects.create(hotel=hotel, **roompicture_data) room_pictures_data = room_data.pop('roompicture') for room_picture_data in room_pictures_data: RoomPicture.objects.create(room=room, **room_picture_data) return hotel def update(self, instance, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') roompictures_data = validated_data.pop('roompicture') # Updates for hotel pictures for hoteltpicture_data in hotelpictures_data: hotelpicture_id = hotelpicture_data.get('id', None) if hotelpicture_id: hp = hotelPicture.objects.get(id=hotelpicture_id, hotel=instance) hp.location = hotelpicture_data.get('location', cp.location) hp.save() else: HotelPicture.objects.create(hotel=instance, **hotelpicture_data) # update for residence for room_data … -
django-channels identify client on reconnect
I connect several (anonymous, not logged in) clients via websocket / django-channels (routing.py, consumers.py). When a client reloads the page or reconnects, for whatever reason, he gets a new channel_name. Is there a nice way to identify the reconnecting client as the same client he was on first connect? Is there some kind of identifier? -
How to inject HTML file into another HTML file in Django?
I want to inject(or import html file) into another HTML file in Django. Of course, I tried to do it, but I am getting errors below. http://prntscr.com/23pkqwf TemplateDoesNotExist at / fanduel.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.10 Exception Type: TemplateDoesNotExist Exception Value: fanduel.html Exception Location: C:\Users\j\Desktop\Project\Python\p\website\webenv\lib\site-packages\django\template\backends\django.py, line 84, in reraise Python Executable: C:\Users\j\Desktop\Project\Python\p\website\webenv\Scripts\python.exe Python Version: 3.8.0 I built the code like this. <div class="section-title"> <h2>FanDuel</h2> </div> <div class="row"> <!-- start row--> <div class="col-lg-6 col-md-6 text-center"> {% include 'fanduel.html' %} </div> <!-- end row --> </div> Of course, there is a fanduel.html file in the same level directory. I am not sure what I am wrong. I hope anyone knows what my issue is. Thank you in advice. -
django reverse relation query from ForeignKey
Let's say I have a couple of simple models defined: class Pizza(models.Model): name = models.CharField() # Get the name of topping here ... class Topping(models.Model): pizza = models.ForeignKey(Pizza) One thing I can do is a query on Topping, but and access that Pizza. But that is not what I want. I want to do a reverse-relation query. I want to get the Topping inside Pizza, if such Topping exists, There may and will be some Pizza without Topping. Using django and drf How can I achieve this? we don't like pineapple pizza -
If statement in Django Model Fields
I want to add these fields to my Store Model, but i wanna include logic that if Let's say WooCoomerce was chosen as a StoreType, i want Access_Token not to be Required. Also when i Choose either Shopify/Shopper i want Consumer_key and Consumer_secret not to be required. Do you have any idea how to get around that? StoreType = models.CharField(blank=True, choices=Storetypes.choices, max_length=12) Api_Url = models.CharField(blank=True) Access_Key = models.CharField(blank=True, max_length=100) Consumer_Key = models.CharField(blank=True, max_length=100) Consumer_Secret = models.CharField(blank=True, max_length=100) -
Django Forms not working. Does not display anything. Any helps?
I was doing some How-To tutorials about Django Forms. But it will not display anything for me. Any ideas why? Picture below illustrates my problem. This is my Login -> index.html <body> <div class="gradient-border" id="box"> <h2>Log In</h2> <form action = "" method = "post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </div> </body> this is forms.py class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) password = forms.CharField(widget = forms.PasswordInput()) Login Page -
Reverse for 'account' not found. 'account' is not a valid view function or pattern name.121
enter image description here enter image description here enter image description here Hello, can you help me? Django gives me this error. Reverse for 'account' not found. 'account' is not a valid view function or pattern name. Inside the photo is a complete explanation -
validate user shift and then show data in Django
I have developed two API "ShiftstartAPI" and "tickettableAPI" when user start the shift only he can able to view the tables in Django. I have tried below approach but its not working as expected all it hides the table even after shiftstart views.py: shift start API # startshift @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UserShiftStartSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) once user click on the shift start the ticket tables needs to populate. Here,I have tried checking the requested user in the "shiftstartAPI" # tickets table @api_view(['GET', 'POST']) def ClaimReferenceView(request, userid): try: userID = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if request.user in UserStartShift(): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= {}'.format(userid,)) result_set = cursor.fetchall() print(type(result_set)) response_data = [] for row in result_set: response_data.append( { "Number": row[0], "Opened": row[1], "Contacttype": row[2], "Category1": row[3], "State": row[4], "Assignmentgroup": row[5], "Country_Location": row[6], "Openedfor": row[7], "Employeenumber": row[8], "Shortdescription": row[9], "AllocatedDate": row[10] } ) return Response(response_data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Django - Product Details in XML file
I have a task to export all product details such as name, price etc. from db to XML file. Since now i'm exporting most of the fields and save them to an XML file. However i'm a bit confused on how to export images. I have 2 models one for Product and one for ProductImages, see below: models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=50) slug = models.SlugField(max_length=500, null=True, unique=True) sku = models.CharField(max_length=100, unique=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/') created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True) Also according to requirements there are two fields where images should be exported. If there is one image (product table) should be exported to item_image_link which i exporting it with no problem. And if there are more than one (ProductImage table) to item_additional_image_link and here is where i have issue. I iterate over products table like below and then trying to find all images for specific product id like: products = Product.objects.filter(product_status=True) images = ProductImage.objects.filter(product__id__in=products) for products in products: item = ET.SubElement(channel, "item") g_item_id = ET.SubElement(item, ("{http://base.google.com/ns/1.0}id")).text = products.sku g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")).text = 'http://127.0.0.1:8000'+products.image.url for image in … -
Django admin create new entry in a different table from an existing entry
New to Django, and I am creating an API using the Django rest_framework. Mainly because I need the preconfigured admin panel. My problem is as follows. I have products and some are active on a site. Those products get inserted into a second table when they are rendered to the final user. So as soon as a product is available the admin inserts that new row to products_live table. My questions is as follows. Is it possible using the admin panel to tick a box in the products admin view and trigger the insert of the product from the product table to the products_live table while keeping the instance of the product in the product table? Hope I made my query clear. -
How to use your own domain www.youddomain.com to serve Google Cloud Storage content
I have been using Google Cloud Storage succesfully to serve the videos and images for the webservice. However, the links for the images must include the following prefix : GS_HTTPS_URL = 'https://storage.googleapis.com/' + GS_BUCKET_NAME + "/" How can I serve the content directy from my service name ? ( for instance "www.mydomain.com/content/" rather than "https://storage.googleapis.com/". -
Hello ! how can i do about solving this problem?
?: (mysql.W002) MariaDB Strict Mode is not set for database connection 'default' HINT: MariaDB's Strict Mode fixes many data integrity problems in MariaDB, such as data truncation upon insertion, by escalating warnings into errors. It is strongly recommended you activate it. See: https://docs.djangoproject.com/en/3.2/ref/databases/#mysql-sql-mode -
Upload to S3 closes server with no error ( after changing external IP or hostname in Ubuntu)
I'm facing error while uploading image to S3 bucket. Actually, Earlier it was working fine but I'm facing this issue after one developer (now, I'm not in contact with him) changed the external IP or hostname. Same Code working fine in Localhost and Production server but facing issue in staging server. I not able to found any specific issue. Its crashing on this storage.save(file_path, case_study_img) line. I have mentioned code and screenshot for same thing File01.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings class PublicMediaStorage(S3Boto3Storage): file_overwrite = False default_acl = 'public-read' File02.py from File01 import PublicMediaStorage #its dummy according to mention file name here. Import is working fine in code # save thumbnail image print(" LINE 01 WORKS") file_name = "case-study-image-" + str(case_study_id) + case_study_img.name print(" LINE 02 WORKS") file_path = os.path.join(file_directory, file_name) print(" LINE 03 WORKS") storage.save(file_path, case_study_img) print(" LINE 04 WORKS") case_study_img_url = storage.url(file_path) print(" LINE 05 WORKS") CaseStudy.objects.filter(id=case_study_id).update( image=case_study_img_url ) DJANGO TERMINAL Last Few Lines of boto3 logger ( boto3.set_stream_logger('') ): 2021-12-20 11:28:56,830 DEBUG [urllib3.connectionpool:396] connectionpool 15908 140026478388992 https://server-name.s3.ap-south-1.amazonaws.com:443 "PUT /Server-Images-Images/case-study-image-34zomoto%20transparent%2002.png HTTP/1.1" 200 0 2021-12-20 11:28:56,830 urllib3.connectionpool [DEBUG] https://server-name.s3.ap-south-1.amazonaws.com:443 "PUT /Server-Images-Images/case-study-image-34zomoto%20transparent%2002.png HTTP/1.1" 200 0 2021-12-20 11:28:56,831 DEBUG [botocore.parsers:234] parsers 15908 140026478388992 Response headers: {'x-amz-id-2': '0+VU+4OgOlPa8E+nD93kTWkp2wqqn1W0YYim4dy72ZWRQBtCM4fpWr7ywPF+Hb4uPYd/BbMGV3k=', 'x-amz-request-id': … -
Project in Django: I can't create superuser in terminal to manipulate data in Postgresql
I am doing a project with Django in which I try to change the database from SQLITE to Postqresql. When I try to create the super user I get this error. Traceback File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 163, in create_superuser return self._create_user(username, email, password, **extra_fields) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\models.py", line 146, in _create_user user.save(using=self._db) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\base.py", line 774, in save_base post_save.send( File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 180, in send return [ File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\dispatch\dispatcher.py", line 181, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "C:\Users\l\Desktop\django-course\Django(02-09-21)\crm1\accounts\signals.py", line 7, in customer_profile group = Group.objects.get(name='customer') File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\l\anaconda3\envs\myenv\lib\site-packages\django\db\models\query.py", line 435, in get raise self.model.DoesNotExist( django.contrib.auth.models.DoesNotExist: Group matching query does not exist. Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'DEMO_TEST', 'USER' : 'postgres', … -
Django Rest Framework, How to update nested values in serializer
In DRF, I would like to post bulk transactions to my rest endpoint. On the following Serializer what would be the correct way to create a nested field of values for transactions in DFR? Do you call create for each transaction on TransactionItemSerializer OR Call save() on the Transaction model inside MasterSerializer create myself> For example: class MasterSerializer(serializers.Serializer): transactions = TransactionItemSerializer(many=True) # A nested list of 'transaction' items. 1 . Update transactions on MasterSerializer. def create(self, validated_data): transactions = validated_data.pop('transactions') # for each transaction do Transaction Save() 2 . Somehow call the create mthoud of the TransactionItemSerializer within MasterSerializer create mthoud for each transaction i.e class TransactionsSerializer(serializers.Serializer): transactions = TransactionItemSerializer(many=True) class Meta: fields = ['transactions'] def create(self, validated_data): transactions = validated_data.pop('transactions') # call create on for each transaction TransactionItemSerializer.create() here -
Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name
Im Created 2 Models. Account UserProfil First Of All, User Register email, fullname, password1, password2. The data Sending To Database in table Account. Second, User Will Login, if success, he will go to dashboard. in dashboard have a profil Form. In The Profil Form, He Will input data profil, likes number phone, birth date. etc. and will store in table UserProfil All of data in UserProfil relationship with Account. Im Try to create 'Profil Form'. Like This. my Question is How To Put the data Full_Name in this form ? i got Error Cannot resolve keyword 'user' into field. Choices are: create_account, email, full_name ... authentication/models.py class Account(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) full_name = models.CharField(max_length=150) create_account = models.DateTimeField(default=timezone.now) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_reviewer = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = CustomAccountManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['full_name'] def __str__(self): return self.full_name dashboard/models.py class UserProfil(models.Model): jenis_kelamin_choice = ( ('Pria', 'Pria'), ('Wanita', 'Wanita' ), ) user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,) nik = models.CharField(max_length=11, null=True, unique=True) nidn = models.CharField(max_length=11, null=True, unique=True) def __str__(self): return str(self.user) dashboard/views.py class UserProfilFormView(CreateView): template_name = 'dashboard/profil.html' form_class = UserProfilForm def form_valid(self, form): userPofil = form.save(commit=False) userPofil.user = Account.objects.get(user__full_name=self.request.user) userPofil.save() messages.success(self.request, 'Data Profil Berhasil Disimpan.') print(self.request.user) … -
addChild() missing 1 required positional argument: 'pk
I have to two models, namely Parent and Child. I have managed to make a model form for registering a Parent. Now I want to be able to add a child to the parent. Expected Outcome: Each parent should have a link that will pull up a child registration form. The Parent Name Field should have initial value of the parent. I'm currently getting this error, addChild() missing 1 required positional argument: 'pk models.py class Parent(models.Model): surname = models.CharField(max_length=150, null=False, blank=False) first_name = models.CharField(max_length=150, null=False, blank=False) class Child(models.Model): parent = models.ForeignKey(Parent, null=True, blank=True, on_delete=SET_NULL) first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) views.py (What am I missing on my addChild view?) def addParent(request): form = ParentForm() if request.method == 'POST': form = ParentForm(request.POST, request.FILES) if form.is_valid(): form.save() def addChild(request, pk): parent = Parent.objects.get(id=pk) form = ChildForm(initial={'parent' :parent}) if request.method == 'POST': form = ChildForm(request.POST) if form.is_valid(): form.save() -
How to store data on database after user login using social API, like facebook
I'm working on a react-native app using django as backend. The backend has a User table that extends AbstractBaseUser, and I want to store the data of social logged users inside this table. Now let's say I'm using facebook and google as social-auth API, when I get the data on the fronted, profile_id and email (for instance in the facebook case), what field do I have to use as password? I mean you'll say it's not necessary because the authentication occurs through the facebook server, but the "social_login/" endpoint is accessible without any permissions so anyone can make a request using facebook user email and its profile_id, as I saw it's possible to get it thought html inspector. So what do I have to use as unique and secure identifier when the user login-in using social API for the second time? Do I have to create a token/hash based on profile_id and email? Please don't suggest me django-social-auth or something similar, they don't fit my needs because of the high levels of customization I need. Thank you -
How can i open file with ogr from bytes or url
I'm trying to open .gml file with ogt.Open(path, False) but on production project hosted on Heroku i can read/write from filesystem. gml_parser.py: from osgeo import ogr reader = ogr.Open(file, False) Could i will open it from bytes or url ? Thanks in advance. -
Broken pipe while parsing CSV file multiple times using pandas
I have a search bar which takes city name as input. A GET API is build on django, which takes the user input and search for the input in the CSV file. For example: If user types "mum". The API takes this "mum" as input and searches for all city names starting with "mum" in the available CSV file. The search is performed everytime user enters a character. But after some time I get an error, as the API is called on every character input by the user: Broken pipe from ('127.0.0.1', 63842) I am using pandas for performing city search ### check for cities list from csv file def checkForCities(request): cities_list = [] cnt = 0 for index, row in city_dataFrame.iterrows(): if cnt >= 6: break if row["cityName"].startswith(request): print(row["cityName"]) cities_list.append({"city_name":row["cityName"], "city_code":row["id"]}) cnt += 1 return cities_list -
Django Rest Framework, nested serializers, inner serializer not visible in outer serializer
I am trying to use nested serializers in my app. I followed documentation seen on DRF website but it seems there is a problem with inner serializer visibility. The error message: Exception Type: AttributeError Exception Value: Got AttributeError when attempting to get a value for field `produkty` on serializer `ZamowieniaSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `Zamowienie` instance. Original exception text was: 'Zamowienie' object has no attribute 'produkty'. models.py class Zamowienie(models.Model): kontrahent = models.ForeignKey(Kontrahent, on_delete=models.PROTECT) my_id = models.CharField(max_length=60, unique=True) data_zal = models.DateTimeField() data_realizacji = models.DateField() timestamp = models.DateTimeField(auto_now=True) status = models.CharField(max_length=50, choices=STATUS_CHOICES, default="0") komentarz = models.CharField(max_length=100, unique=False, default="") uwagi = models.CharField(max_length=150, unique=False, default="") zam_knt_id = models.CharField(max_length=50, unique=False) class Meta: ordering = ['-data_zal'] verbose_name_plural = 'Zamowienia' objects = models.Manager() def __str__(self): return str(self.my_id) def save(self, *args, **kwargs): licznik = Zamowienie.objects.filter(Q(kontrahent=self.kontrahent) & Q(timestamp__year=timezone.now().year)).count() + 1 self.my_id = str(licznik) + "/" + self.kontrahent.nazwa + "/" + str(timezone.now().year) self.zam_knt_id = self.kontrahent.zam_knt_id super(Zamowienie, self).save(*args, **kwargs) class Produkt(models.Model): zamowienie = models.ForeignKey(Zamowienie, on_delete=models.CASCADE) ean = models.CharField(max_length=13, unique=False, blank=True) model = models.CharField(max_length=50, unique=False) kolor_frontu = models.CharField(max_length=50, unique=False, blank=True) kolor_korpusu = models.CharField(max_length=50, unique=False, blank=True) kolor_blatu = models.CharField(max_length=50, unique=False, blank=True) symbol = models.CharField(max_length=50, unique=False) zam_twrid = models.CharField(max_length=10, unique=False, blank=True) ilosc … -
how can call function inside class view in django
i have function that return some information about user device and i have one class for show my html and form_class how can i use function in class this is my views.py : from django.http import request from django.shortcuts import render, redirect from .forms import CustomUserCreationForm from django.contrib.auth.forms import UserCreationForm from django.urls import reverse_lazy from django.views import generic def a(request): device= request.META['HTTP_USER_AGENT'] return device class RegisterView(generic.CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy("register") template_name = "man/man.html" this is my urls.py : from django.urls import path from . import views urlpatterns = [ path('',views.RegisterView.as_view(), name="register"), ] -
Django: How to extract text from doc and docx files and then pass it to template to display it in a separate div that can be later on styled?
I am working on a Final Project for CS50W and I want a small app that allows users to upload their 'scripts' - files that are either .doc or .docx. These files are then saved in a separate folder and its url is saved in a models field. I want to create a separate view for displaying the contents of these files, that I can then later on style separately (changing background and text colors, size, etc.), so I want to extract the text from these files and pass it on to my template. But when I do that with open file function, I get FileNotFoundError - which I presume is because this file is not .txt file. What would be the best way to achieve this? Here's the relevant part of my code: class Script(models.Model): ... upload = models.FileField("Select your script", upload_to="scripts/%Y/%m/%D/", validators=[FileExtensionValidator(allowed_extensions=['doc', 'docx'])]) ... def read(request, script_id): script = Script.objects.get(pk=script_id) file = open(script.upload.url, 'r') content = file.read() file.close() return render(request, 'astator/read.html', { 'script':script, 'content':content, }) Maybe there's also a better way to achieve this with JS? Anyhow, thanks in advance for your help!