Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use inlineformset_factory when multiple Foreign key
I have four models of the shop, customer, product, an order. I am showing the relation of models shop user = models.OneToOneField(User, null=True, related_name='shop', blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=70, null=True, default='shop', ) address = models.CharField(max_length=70, null=True) Shop_category = models.CharField(max_length=200, null=True, ) customer user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=100, null=True, default='customer') Phone = models.PositiveIntegerField(blank=True, null=True) product shop = models.ForeignKey(Shop, models.CASCADE, null=True, blank=True) name = models.CharField(max_length=100, blank=True) Brand = models.CharField(max_length=200, blank=True) description = models.TextField(null=True, blank=True) order shop = models.ForeignKey(Shop, models.CASCADE, null=True) customer = models.ForeignKey(Customer, models.CASCADE, null=True) product = models.ForeignKey(Product, models.CASCADE, null=True) quantity = models.CharField(max_length=30) date_created = models.DateTimeField(auto_now_add=True) status = models.CharField(max_length=200, choices=STATUS, default='Pending') note = models.CharField(max_length=1000, null=True) when customers login then the shop will print on the screen and a button on shop to show the products by the shop in the form card. On the product card, there is an order button that adds the product in order after submitting the selected product will print with the remaining filled of order that show in the image how I can create an order so that the customer in order is the instance and the shop in order is that shop which is selected to show the products, and products which are … -
Can I create an AbstractBaseUser like this?
class Staff(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="Date Joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="Last Login", auto_now_add=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) first_name = models.CharField(max_length=60) last_name = models.CharField(max_length=60) position = models.CharField(max_length=45) department_fk = models.ForeignKey( Department, models.CASCADE, db_column='department_fk') <----- This is what im worried about I dont know if it will accept a foreign key in django. Can anyone give me an advice how to properly do this? -
AWS deployment of django application
I have a django application which has been deployed in aws. The URL in ec2 instance is loading fine too. My application has a modal where I should enter my team name and username. Whenever I try in [ec2instanceurl]:8000/ (when i start gunicorn)iam not facing any alert error. But when i start the nginx and access the url without port(8000) the page is loading and whenever i enter the details in modal and click confirm button it shows an alert says '[ec2instanceurl] says error' I will attach the error snap here I want to know whether it is my django app error or any aws settings error. The thing is that its working fine in local,and in gunicorn port. Though Iam new to aws deployment iam expecting advices.. Thanks in advance -
OperationalError at /admin/products/product/add/ no such table: main.auth_user__old
I was editing a project on Django, so I deleted my pychache, migrations, and db.sqlite3 and created a new superuser to log into the admin page. After I created a product and pressed 'Save' on the admin page an error saying "OperationalError at /admin/products/product/add/ no such table: main.auth_user__old" appeared. I have tried solving this issue with solutions such as doing makemigrations and migrate again, but none of the solutions I have tried have worked so far. Does anyone know of a possible solution to this? -
Django datetime format changes
I have datetime stored in sql database. When Django renders the page along with data, on html the date is displayed as June 11, 2020, 5:56 p.m. This is render directly from the django backend. But when I retrieve data using jquery ajax, the data is displayed with format 2020-06-11T17:57:12.188 How do I convert to the other type? -
How to change the host in next key in a paginated URL in django rest framework?
I have a ModelSerializer in Django Rest Framework with paginated responses. So I have deployed it with gunicorn in a docker container. gunicorn -c gunicorn_config.py app.wsgi --bind 0.0.0.0:5000 Now the problem is in the paginated responses. The next key is something like. next: "http://0.0.0.0:5000/admin/users/?page=2&per_page=10" In my client-side where I am consuming these APIs, I just check the next key and fetch the next response. But since the next key has the host as 0.0.0.0:5000 hence it will cause API call failure. And the purpose is not served for the next key. So at the moment, my API server is running in a separate docker container. Which is set up via the reverse proxy in nginx. -
How to get entries of two related models in a single view?
Basically I am working on an inventory management system. The models "Purchase_Bill" and "Purchase_Item" are the ones I wish to get entry for. Here is a snippet of them, class Purchase_Bill(models.Model): status_choices = ( ('Paid','Paid'), ('Unpaid','Unpaid'), ) category_choices = ( ('Product','Product'), ('Packaging','Packaging'), ) Bill_Num = models.CharField(max_length=30,null=True,blank=True) Supplier = models.ForeignKey(Supplier,on_delete=models.CASCADE) Cheque_No = models.IntegerField(null=True,blank=True) Cheque_due = models.DateField(default=date.today,null=True,blank=True) Status = models.CharField(max_length=10,choices=status_choices,default="Update") Bill_Date = models.DateField(default=date.today,blank=True,null=True) Category = models.CharField(max_length=20,choices=category_choices,default="Update") def __str__(self): return self.Bill_Num class Purchase_Item(models.Model): purchase_bill = models.ForeignKey(Purchase_Bill,null=True,on_delete=models.SET_NULL,verbose_name = "Bill ID") product = models.ForeignKey(Product,null=True,on_delete=models.SET_NULL,verbose_name = "Product") #batch yet to be created with an other model called Inventory #expiry yet to be created with an other model called Inventory p_qty = models.IntegerField(verbose_name = "QTY") p_cost = models.IntegerField(verbose_name = "Cost") p_gst = models.IntegerField(verbose_name = "GST") def __str__(self): return self.purchase_bill.__str__() Our system requires the entry of Purchase_Bill Attributes at first, and then we gotta add the products (ForeignKey attribute from the model Purchase containing the list of products and their details) in the Purchase_Item model one by one. (1 or more entries for the Purchase_Item with the same "purchase_bill" (points to Bill_Number in the parent model) Such that, Bill_Number is automatically set to instance of the Purchase_Bill which they have just entered (inline formsets). How to get the … -
Aparecendo a Time_Zone (DJANGO)
Boa noite. Meu código está exibindo a time zone completamente errada e confesso que não faço ideia de como fazer ela desaparecer ou ficar em horário normal. Estou usando Charts.js No views: def notaEntradaList(request): nota_entrada = NotasEntradas.objects.all().order_by('criado') template_name = 'notaEntradaList.html' listagem_produto=[] listagem_quantidade=[] listagem_data=[] listagem_valor_total=[] for produto in nota_entrada: listagem_produto.append(produto.produto) listagem_quantidade.append(produto.quantidade) listagem_data.append(str(produto.criado)) listagem_valor_total.append(float(produto.precoQuantidade())) print(listagem_produto, listagem_quantidade, listagem_data) context = { 'nota_entrada': nota_entrada, 'listagem_produto': listagem_produto, 'listagem_quantidade': listagem_quantidade, 'listagem_data':listagem_data, 'listagem_valor_total':listagem_valor_total, } return render(request, template_name, context) No notaEntradaList: <canvas id="myChart" width="400" height="100"></canvas> <script> var ctx = document.getElementById('myChart').getContext('2d'); var myChart = new Chart(ctx, { type: 'line', data: { labels: {{listagem_data |safe }}, datasets: [{ label: 'Acrescentados', data: {{listagem_quantidade|safe }}, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } }, }); </script> Como eu poderia solucionar isso exibindo a data certinha com a hora, se possívelmente? -
The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256 with Django Angular
I am using Django as backend to return API's at front end Angular side. I used AWS S3 for media storage. URL is generating using the s3 url and able to upload the files on S3 bucket. Problem is on web the Image content getting the 400 Bad Request. following is my code: AWS_ACCESS_KEY_ID = "XXXXXXXXXXXXXXXXXX" AWS_SECRET_ACCESS_KEY = "XXXXXXXXXXXXXXXXXXX" AWS_STORAGE_BUCKET_NAME = "app" AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' #AWS_QUERYSTRING_AUTH=False when I am uncommenting the #AWS_QUERYSTRING_AUTH=False and making all the s3 Images as public then able to access the image on web, need to make image explicitly public, which I don't want this. after commention getting the url like - https://famesta-app.s3.ap-south-1.amazonaws.com/user_30/profile/download.png?AWSAccessKeyId=XXXXXXXXXXXXXXXX&Signature=XXXXXXXXXXXXXXXXXXXx%3D&Expires=1592369615 Error: <Error> <Code>InvalidRequest</Code> <Message>The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.</Message> <RequestId>20DF944878611</RequestId> <HostId>sZPyWKvGHSRt7ANyDlOUh71/xUV14H0avAjaERfkoQxiq0=</HostId> </Error> My region is Asia Pacific (Mumbai) AWS Configuration- CORS Configuration <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedHeader>*</AllowedHeader> </CORSRule> </CORSConfiguration> And In S3 Permission I have allow the Public access. If I will make whole bucket as public and AWS_QUERYSTRING_AUTH=False then able to upload image get access on web everything that I wanted, but I don't think so it is safe to make bucket itself public. … -
Django Simple History - Tracking M2M field changes (with "through")
I am using django-simple-history to track changes to my fields, and from what I see, it seems like django-simple-history does not track changes to M2M fields. I tried introducing an intermediate model for the M2M fields, and then attaching a HistoricalRecords() field within that intermediate model, but it seems like there is no use for that, unless I am using the django-simple-history wrongly. It seems like whenever I add a new relation in the M2M field (with "through"), a new instance is created within the intermediate model referencing foreign key relations to the two models with M2M relations, and whenever a relation is removed, that corresponding instance in the intermediate model would be deleted. If that is the case, how can I track the changes of the M2M fields through the intermediate model? Since the instance would be deleted whenever it is removed as a relation, which would lead to the tracking to not exist, since that instance no longer exists. I am new to django-simple-history, so do guide me along if I missed out or misunderstood anything, thanks all! Here is my code: models.py class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100) history = HistoricalRecords() class SalesProject(models.Model): sales_project_id = … -
How to remove change password link from django admin site?
I am using active directory login authentication for my django web application. So there is no need of change password link in admin site. I have searched lot of article, but I haven't found any thing to hide change password link. So what is the way of hiding change password link from admin? -
Unable to use ShowInLegend Property along with drawTable in highcharts Piechart
I was successful in rendering a dataTable within the pie chart div for my Django application. It can be found here: http://jsfiddle.net/6vqzLo7h/ $(function () { Highcharts.setOptions({ colors: [ '#1cc88a', '#008a59', '#6adfb6' ] }); Highcharts.drawTable = function() { // user options var tableTop = 200, colWidth = 60, tableLeft = 50, rowHeight = 20, cellPadding = 2.5, valueDecimals = 1, valueSuffix = ''; // internal variables var chart = this, series = chart.series, renderer = chart.renderer, cellLeft = tableLeft; // draw category labels $.each(series, function(serie_index, serie) { renderer.text( serie.name, cellLeft + cellPadding, tableTop + (serie_index + 1) * rowHeight - cellPadding ) .css({ fontWeight: 'bold' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( series[0].data[i].name, cellLeft + colWidth - cellPadding, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'right' }) .add(); }); $.each(series[0].data, function(i) { renderer.text( Highcharts.numberFormat(series[0].data[i].y, valueDecimals) + valueSuffix, 150, tableTop + (i + 2) * rowHeight - cellPadding ) .attr({ align: 'left' }) .add(); }); } $('#container').highcharts({ chart: { plotBackgroundColor: null, plotBorderWidth: null, plotShadow: false, events: { load: Highcharts.drawTable }, height: 600, width: 800, marginBottom: 250 }, title: { text: undefined }, credits: { enabled: false }, tooltip: { pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>' }, plotOptions: { pie: { … -
Admin can view all orders
@login_required(login_url='/') def order_list(request): order = Order.objects.filter(user=request.user) context = { 'order': order } return render(request, "order_list.html", context) So this is my view function, right now a logged-in user can only view his/her own order. I have two users an admin and a customer. I want the customers to view their own orders which is working fine, but I want the admin to view all the orders created by customers. -
Django doesn't accept image submission, method and enctype included in form tag but browser console claims it is missing
I'm following along with a tutorial to build a Django project. Part of the project is being able to upload an image to the test cdn directory. This is what my form looks like currently: <form method='POST' action="." enctype='multipart/form-data'> {% csrf_token %} {{ form.as_p }} <button type="submit">Send</button> </form> The method and enctype are very clearly defined. I've also set up my settings.py STATIC_URL = '/static/' LOCAL_STATIC_CDN_PATH = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn_test') STATIC_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'static') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'staticfiles') ] MEDIA_ROOT = os.path.join(LOCAL_STATIC_CDN_PATH, 'media') MEDIA_URL = '/media/' set up the files to be received in the view: form = BlogPostModelForm(request.POST or None, request.FILES or None) set up the model use ImageField: image = models.ImageField(upload_to='image/', blank=True, null=True) and the url patterns: if settings.DEBUG: # test mode from django.conf.urls.static import static # display images/files saved in the test cdn urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) But even with all this, the console informs me: Form contains a file input, but is missing method=POST and enctype=multipart/form-data on the form. The file will not be sent. This is the tutorial in case it helps https://www.youtube.com/watch?v=-oQvMHpKkms&list=PLM39hJgCef42hVok8ZRRE4LpLD-5bOxBh&index=20&t=13385s the part in question starts at 3:48:00. -
Display template before running certain code in the view with Django
I have a Django site. One of my pages loads just some HTML and it is very quick at loading. I am adding some code that will send me a email when this page loads but the code takes a few seconds to execute. Instead of holding the entire page back waiting on this code to execute is it possible to display the template and then run this code? This is what I am running: msg = EmailMessage('Request Callback', 'Here is the message.', to=['email@yahoo.com']) msg.send() -
doesn't an epxlicit app_label
When i starting a new app, every time i getting this error. "RuntimeError: Model class JabaGames.apps.mainsite.models.games doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS." My other apps is renamed to short version 'appname' and i had same problem, but i fixed it, i don't know how. This error shows when i create a new app named "comments" my settings.py INSTALLED_APPS = [ 'users', 'comments', 'crispy_forms', 'blog', 'mainsite', 'grappelli', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] my comments/models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings import JabaGames.apps.mainsite.models class Comment(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) post = models.ForeignKey('article', on_delete=models.CASCADE) (trying to make a foreign key to other app, when i got an error (if you guys will tip me how to correctly import other model, i will be so happy) ) content = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.user.username) def __str__(self): return str(self.user.username) apps.py from django.apps import AppConfig class CommentsConfig(AppConfig): name = 'comments' every single app has a same code as comments/apps.py (is it a bad practice) -
How to implement QR code cross login from mobile app as authentication method for website or webapp in a vendor agnostic way?
I am using Django 2.2 for my webapp. And I have been looking for tutorials that cater for QR code cross login to webapp using mobile app. Basically the workflow is like this: expected workflow User arrives at website on desktop Given a choice of username/password or QR code login (We assume user is registered) User chooses QR code to login User is prompted to install mobile app (can be android or iOS) User installs mobile app and logins using username/password. On mobile app, user then agrees to future login using QR code as alternative (this is done once) After this, in future logins, when User chooses QR code to login as per step 3. They use the mobile app to scan QR code generated on the website login page. The mobile app then uses FaceID or FingerPrint ID (assuming iOS) to then allow login. The user presses a Yes button on the mobile app to confirm login. Somehow the webapp is notified dynamically and allows login on the desktop browser. I don't quite get how the mobile and the web app at the backend all work with one another to achieve this seamlessly. What I did find I did … -
Set ID to a field value
I have a form that a user can submit but I want the ID of the form to be the value of a certain field. For example, if a user submits a Recipe form for "pasta", I want the form ID to be "pasta". Then the user can access the recipe by entering the URL http://127.0.0.1:8000/recipe/pasta. I feel like this needs to be done in the view and urls file. views.py class CreateRecipeView(CreateView): form_class = RecipeForm(auto_id=recipe_name) # This would be the value of the recipe_name def get_success_url(self): return reverse("recipe_update/{}/".format(recipe_name)) urls.py path('recipe_update/<str:pk>/', views.UpdateRecipeView.as_view(), name='recipe_update') -
Django _set.add() method doesn't do what I hope it would, but does not give me any errors either
So, I am working on a Django-based website (Django 3) and I am trying to use a file to add certain elements into the database. While reading the file and its data works smoothly, the script seems to stop abruptly on this line: studentClass.student_set.add(student) Right before that, I have lines like these being executed with no problem: school = get_object_or_404(School, pk=form.cleaned_data['school'].pk) studentClass, created = StudentClass.objects.get_or_create( school=school, name=form.cleaned_data['name'], grade=form.cleaned_data['grade'] ) . . . print("\nSUCCESS!\n") print("\nAttempting to add {} to {}".format( student, studentClass)) studentClass.student_set.add(student) <---- SUSPECTED CULPRIT! The output from the print statement to the console: Attempting to add (<Student: 1 - Jessica>, False) to 1 - HenMei The second print("SUCCESS!") statement is not executed, thus I am quite sure that studentClass.student_set.add(student) is the line that's causing some trouble. Since I am a beginner, I may very well be wrong. Models are defined as follows: class StudentClass(models.Model): school = models.ForeignKey(School, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=25) grade = models.PositiveSmallIntegerField(default=1) class Meta: ordering = ['grade', 'name'] def __str__(self): return "{} - {}".format(self.grade, self.name) class Student(models.Model): studentClass = models.ManyToManyField(StudentClass) student_number = models.PositiveSmallIntegerField() first_name = models.CharField(max_length=50) gender = models.CharField(max_length=6, default='Female') class Meta: ordering = [F('student_number').asc(nulls_last=True)] def __str__(self): return "{} - {}".format(self.student_number, self.first_name) Last but not least, … -
Iterate in django views
I have problem with iteration all over the list in django views.py file from django.shortcuts import render, redirect, HttpResponse from django.views.decorators.http import condition import time import roundrobin STATES = [ "hello", "world" ] get_roundrobin = roundrobin.basic(STATES) def test(request): for i in get_roundrobin(): return HttpResponse(i) Django answers me only first symbol of the each element of the STATES list, I mean django return "h" then "w" instead "hello" then "world", how to fix it? -
Create object and child objects in DRF
I have 2 Serializers, Order and OrderDetail: class OrderSerializer(serializers.ModelSerializer): detail = serializers.SerializerMethodField() class Meta: model = Order fields = ['pk', 'user', 'date', 'status', 'detail '] def create(self, validated_data): order= Order.objects.create(**validated_data) detail_data = validated_data.pop('detail') if detail_data : for detail in detail_data : OrderDetail.objects.create(order=order, **detail) return order def get_detail(self, obj): """obj is an order instance. Return list of dicts""" queryset = OrderDetail.objects.filter(order= obj) return [OrderDetailSerializer(m).data for m in queryset] and class OrderDetailSerializer(serializers.ModelSerializer): """ Just in case if its needed for create for multiple instances """ def __init__(self, *args, **kwargs): many = kwargs.pop('many', True) super(OrderDetailSerializer, self).__init__(many=many, *args, **kwargs) order = serializers.PrimaryKeyRelatedField(queryset=Order.objects.all()) product = serializers.PrimaryKeyRelatedField(queryset=Product.objects.all()) class Meta: model = OrderDetail fields = ['pk', 'order', 'product', 'quantity','individual_price'] In postman I send: { "user": 1, "date": "2020-06-02", "status": "Approved", "detail": [ { "product": 2, "quantity": "3", "individual_price": "15.00" }, { "product": 1, "quantity": "1", "individual_price": "10.00" } ] } And it throws the following error: KeyError at /api/v1/order/ 'detail' Request Method: POST Request URL: http://localhost:8000/api/v1/order/ Django Version: 3.0.3 When I print the data its showing this: {'user': <User: test>, 'date': datetime.date(2020, 6, 3), 'status': 'Approved'} Seems like detail its a read only field, dont know if its for the SerializerMethodField. About that, I need detail with … -
Django Require Particular Version of Python to be Used
I edited my settings.py file to have the following at the very bottom: [requires] python_version="3.7" When I run python manage.py runserver, I get the following error message: NameError: name 'requires' is not defined what am I doing wrong? -
Not able to add message when a search is not met in the database
I am trying to add a message to the template when a search is not yet in the DB. So, there is an view from tour_store app which retrieves the data from the db and loads into the destination.html template: tour_store/destinations function: def destinations(request): destinations = Destinations.objects.all() return render(request, 'destinations.html', {'destinations': destinations}) and search/do_search function: def do_search(request): if request.method == "GET": # 'q' is the name in the search form // tour_title is the name that will be searched from Destination model destinations = Destinations.objects.filter(location__icontains=request.GET['q']) return render(request, 'destinations.html', {'destinations': destinations}) the place the search form is main.html: <form action="{% url 'search' %}" method="GET" class="header__search"> <div class="input-group search-input"> <!-- Change the search input phrase here --> <input type="text" name="q" placeholder="Search for `Thailand`." class="form-control"> <div class="input-group-append"> <button class="btn btn-warning" type="submit" name="button"><i class="fas fa-search"></i></button></div> </div> </form> destination.html {% for destination in destinations %} {% if destination in destinations %} <div class="row" data-aos="fade-up" data-aos-anchor-placement="top-bottom" data-aos-duration="1000"> <div class="col-md-7"> <a href="{% url 'destinationDetails' id=destination.id %}"> <img class=" embed-responsive img-fluid rounded mb-3 mb-md-0" src="{{ destination.image.url}}" alt=""> </a> </div> <div class="col-md-5 "> <h3>{{destination.tour_title}}</h3> <h6>{{destination.location}}</h6> <p >{{destination.description|safe|slice:":150"}}...</p> <p class="text-secondary"><i class="text-info far fa-calendar-check"></i> <strong>{{destination.booking_start_date}} - {{destination.booking_end_date}}</strong></p> <h3>€ {{destination.price}}</h3> <a class="btn btn-info rounded py-2 btn-block" href="{% url 'destinationDetails' id=destination.id %}"> View … -
How do I hash a file name when saving file to model django?
How does hashing work with models? I want to hash the name of video files that upload to my model. models.py class VideoUpload(models.Model): name= models.CharField(max_length=500) videofile= models.FileField(upload_to='videos/', null=True) -
Preserve user input after submitting in Django form
I am trying to create a website using Django. I am not familiar with Django and I have a problem. I would like to create a form that has file selection for video uploading and two different buttons which are “Upload” and “Save”. I don't want to save video directly to the database using one button. Because of that, I need two buttons. When a user selects a file and clicks the “Upload” button, the video should be uploaded. Then, if the user clicks the “Save” button, the video should be saved into the database(model). There is no problem in the video selection and uploading process. However, when I click the “Save” button, the video cannot be saved since the video vanishes after clicking the “Upload” button. HTML file: <form method="post" enctype="multipart/form-data" id="form1"> <div class="form-group" > <label for="exampleFormControlFile1">Upload your video: </label> {% csrf_token %} {{ form.as_p }} </div> <button class="btn btn-primary btn-lg" name="upload_bttn" id="bttn1" type="submit" >Upload</button> <button class="btn btn-primary btn-lg" name="save_bttn" type="submit" >Save</button> <p>Uploaded file: <a href="{{url}}" target="_blank">{{url}}</a></p> views.py def video_upload(request): context = {} if request.method == 'POST' and 'upload_bttn' in request.POST: uploaded_file = request.FILES['videofile'] task_name = request.POST['task'] env_name = request.POST['environment'] light_name = request.POST['lightcondition'] fs = FileSystemStorage() file_name = fs.save(uploaded_file.name, …