Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to Save all models changes in one query on Django
I try to modify many instance of some model (like User model), and this changes is different (I don't want to use update QuerySet method and not works for my scenario), For example some user need to change first_name and some user need to change last_name. and get users like : all_user = User.objects.all() I think if I use save method for each instance after change, Django sent one query for save that! How can I save all changes to database in one query insteadof use foreach on models and save that one by one? -
Django local http://127.0.0.1:8000/ Is Not Connecting
I am currently trying out a Django Tutorial(link below), and after I type in "python manage.py runserver" , and click on the link provided, I recieve this error: ERR_CONNECTION_REFUSED Error I disabled all of my firewalls and antivirus programs, and am extremely confused as I know nothing about Django. Tutorial link:https://realpython.com/get-started-with-django-1/ I have tried other tutorials, and recieved the exact same error. -
How to create instance of model during user registration process? Django
I am writing a simple event app in django. I have register and login process. I have two models. Model creator has one OneToOneField with attribute User. Event model has attribute "creator" as foreignKey which contain specific user. What is my problem? When I create new user, I want to create new instance of Creator model at the same time and when i log in as that user and create new event, I want to set value of creator in Event as this user. How can I do it? models.py and views.py below: models.py class Event(models.Model): SPORT = ( ('Football', 'Football'), ('Volleyball', 'Volleyball'), ('Basketball', 'Basketball'), ('Futsal', 'Futsal'), ('Tennis', 'Tennis'), ('Handball', 'Handball'), ('Ice Hockey', 'Ice Hockey'), ('Paintball', 'Paintball') ) creator = models.ForeignKey(Creator, null=True, on_delete=models.SET_NULL) sport = models.CharField(max_length=20, null=True, choices=SPORT) event_name = models.CharField(max_length=30) event_date = models.DateTimeField(default=date.today()) end_event_date = models.DateTimeField(default=date.today()) current_members = models.IntegerField(default=1) total_members = models.IntegerField(default=0) event_location = models.CharField(max_length=50) cost = models.FloatField(default=0, max_length=5) description = models.CharField(max_length=300, blank=True) def __str__(self): return self.event_name class Creator(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) views.py @unauthenticated_user def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Account created successfully!') return redirect('login') context = {'form': form} return render(request, 'events/register.html', context) -
Django validation steps process
So, I would like to create a validation process of a post between multiple users. Let say for example that a user creates a post and click on validate or "ask for review". I would like to be able to send the new post to a specific user in order to allow him to check the post and its content before validate and publish it. I would like to let multiple users of the same app to send the post to this specific "team leader" user. So I think that I need to : Create a model for the post Create a specific view and render it into an html page for the creation part When user click on "ask for notice" button, I want the post to appear in the posts_notice.html page where the "team leader" user would be able to see all the current posts asking for notice and validation. Of course, this team leader user will have the possibility to edit each post. To filter all the posts I was thinking about using a boolean field called "is_noticed". If yes the post is not rendered. If False it is rendered. Once all the posts are edited, the … -
Guidence on buliding a Django model
I am trying to build a job tracker, I have a Job model where the admin can create a job, then here's where it gets tricky for me. The employee can go to the jobs sections, check out the job, then record the start time and end time. Then display the total time worked on the job. Each time the employee works on the job it will update the total time. My initial model looks like this but not sure how to handle the start, end, and total times. I would appreciate any guidance. class TaskModel(models.Model): """ Using many to many field because incase a user checks out more than one job. Maybe a better solution? """ PROGRESS_STATUS = [ ('IN PROGRESS', 'In Progress'), ('COMPLETE', 'Complete') ] intern = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) task = models.ManyToManyField("app.Model", verbose_name="")(JobModel, verbose_name="jobs", on_delete=models.CASCADE) progress = models.CharField(choices=PROGRESS_STATUS, default="In Progress", max_length=20) start_time = models.TimeField(default=timezone.now) end_time = models.TimeField() total_time = models.IntegerField(default=0) checkout_time = models.DateTimeField(default=timezone.now) -
Delete an object automatically after specified time
Trying to delete an object after a specified time from the database. Here's my Code: from datetime import timedelta from django.db import models from django.utils.timezone import now class Email(models.Model): email = models.EmailField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return 'code: ' + str(self.code) @property def deletes_in_ten_seconds(self): time = self.created_at + timedelta(seconds=10) query = Email.objects.get(pk=self.pk) if time > now(): query.delete() Yet it's not working. Do I have to call the delete method after a while somehow? I really don't have a clue. (new to django) -
How to get the pk of the selected radio button in django
I'm having a hard time trying to learn Django :) I have the following line (which might not be in the best form but they work so far): models.py class Mani(models.Model): title = models.CharField(max_length=64) description = models.TextField() duration = models.ForeignKey(Duration, on_delete=models.CASCADE) price = models.PositiveSmallIntegerField() def __str__(self): return "%s %s kostet €%s und dauert %s min" % (self.title, self.description, self.price, self.duration.duration) forms.py class ManiForm(forms.Form): service_title = forms.ModelChoiceField(widget=forms.RadioSelect(attrs={'class': 'serviceForm'}), label='Bitte whälen Sie Ihre Packet', queryset=Mani.objects.all()) views.py def booking_service_detail(request, pk): service = Service.objects.get(pk=pk) if request.method == 'POST': service_form = ManiForm(request.POST) mani = Mani.objects.get(pk=pk) return render(request, template, { 'service': service, 'service_form': service_form, 'extra_form': extra_form, 'mani': mani }) mani = Mani.objects.all() service_form = ManiForm() context = { 'service': service, 'service_form': service_form, } return render(request, template, context) and finaly part of the html: <div class="content"> <form action="" method="POST"> {% csrf_token %} <h3>Bitte whälen Sie Ihre Packet</h3> <ul class="serviceForm"> {% for radio in service_form.service_title %} <li> {{ radio }} </li> {% endfor %} </ul> {% if extra_form %} <h4>Bitte whälen Sie Ihre Extra</h4> <p>{{ mani.pk }}</p> <ul class="serviceForm"> {% for radio in extra_form.extra_title %} <li> {{ radio }} </li> {% endfor %} </ul> {% endif %} <input type="submit" value="Auswählen"> </form> One of the li items from here: … -
Django and PostgreSQL dynamic schema creation and model manipulation
I've been searching all day and given up. Django does not have proper support for Postgres schemas, hence the question. Problem: I want each user in my app to have their own database schema with a unique name (created when signing up). The tables in each schema are identical to every those in every other schema but obviously the data is different (I want users to have their data isolated from each other). I need to create new DB schemas dynamically, migrate existing models to them dynamically AND retrieve data from the tables using models. This is for an API not a template. Sub-problems: Creating new Postgres DB schema dynamically Retrieving data from tables (with dynamic names) inside DB schema using models [assuming that the name is passed as an argument to a view] Thus far I've only been able migrate models to empty schemas I manually create (i.e. name is known) using the code below Inside the model: Meta: db_table='schema_name\.\.model_name'</pre> And during runtime: from django.core.management import call_command call_command('makemigrations') call_command('migrate') Questions Sub-problem (1): Is it best to create a Postgress procedure/function and then to call it from inside django? Can I just create a new empty schema in this procedure … -
How specify special class name li tag for pagination in django templates?
I want to add a class to my a tag named "active" But I can't specify a class because a tag is in a for loop with Django template language if I add a class like this, I will be added all the a tags {% for num in page_obj.paginator.page_range %} <a href="?page={{ num }}">{{ num }}</a> {% endfor %} Here is my pagination section {% if is_paginated %} {% if page_obj.has_previous %} <a href="?page=1">First</a> <a href="?page={{ page_obj.previous_page_number}}">Previous</a> {% endif %} {% for num in page_obj.paginator.page_range %} {% if page_obj.number == num %} <a href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'-3' %} <a href="?page={{ num }}">{{ num }}</a> {% elif num > page_obj.number|add:'3' %} <a href="?page={{ num }}">{{ num }}</a> {% endif %} {% endfor %} {% if page_obj.has_next %} <a href="?page={{ page_obj.next_page_number }}">Next</a> <a href="?page={{ page_obj.paginator.num_pages}}">Last</a> {% endif %} {% endif %} -
When trying to create a new Django CreateView form, my forms are being populated with the data that was entered in the last form
Using Class Based Views, ModelForms, and Inlline Formsets. I’m making a recipe application in Django. Each user has their own OneToOne RecipeBook object, which in turn can hold as many recipes as needed, as each Recipe has a ForeignKey relationship to the RecipeBook object. There are also Ingredient and Direction objects that each have a FK relationship to the Recipe object. The good news is that I can create a Recipe object using my CreateView, with as many associated Ingredient and Direction objects as I want. The Ingredient/Direction objects should be unique to each Recipe object (and by extension, each User). However, when I create a Recipe object, and then I try to create a new Recipe object, its Ingredient and Direction fields are already populated on the new object, form the old object. So if I had just created a Recipe with 3 Ingredient/Direction fields all set to '1', and then go to create another Recipe, the new Recipe object will have all blank fields, but will have 3 Ingredient/Direction objects all set to 1. This will happen to each user that is logged in. I want to make it so these objects are all staying together. I think … -
Cannot assign "{'business': ''}": "Job.business" must be a "Business" instance. DRF
Okay I have been at this for days and cannot figure it out. Whenever I make a new job post I get the following error Cannot assign "{'business': 'some existing business name'}": "Job.business" must be a "Business" instance. Business Model: from django.db import models from django_google_maps import fields as map_fields from django.conf import settings User = settings.AUTH_USER_MODEL Company = settings.COMPANY_USER_MODEL class Business(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) business = models.CharField(max_length=50, unique=True) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) about = models.TextField(max_length=1000, null=True) def __str__(self): return self.business Job Model: from django.db import models from django_google_maps import fields as map_fields import uuid as uuid_lib from django.conf import settings User = settings.AUTH_USER_MODEL Business = settings.BUSINESS_MODEL class Positions(models.Model): position = models.CharField(max_length=100) def __str__(self): return self.position class Job(models.Model): employer = models.ForeignKey(User, on_delete=models.CASCADE) business = models.ForeignKey('business.Business', related_name='jobs', on_delete=models.CASCADE) position = models.ForeignKey(Positions, on_delete=models.CASCADE) address = map_fields.AddressField(max_length=200, null=True) geolocation = map_fields.GeoLocationField(max_length=100, null=True) uuid = models.UUIDField(db_index=True, default=uuid_lib.uuid4, editable=False) job_detail = models.TextField() # TODO: set length full_time = models.BooleanField(default=False) part_time = models.BooleanField(default=False) date_posted = models.DateTimeField(auto_now_add=True) def __str__(self): return self.address Job Serializer: from rest_framework import serializers, fields from .models import Job, Type, Positions, Business # Position Serializer class PositionSerializer(serializers.ModelSerializer): class Meta: model = Positions fields = "__all__" class JobSerializer(serializers.ModelSerializer): date_posted = … -
DRF doesn't update instead create new instance in modelserializer
Searched throughout SO to find the matching questions doesn't answer mine as there are only few explanations. So hoping to get an answer here. I have a model named "testcase" with pk set as "testcase_name". On update operation in the serializer, instead of updating a new instance is created everytime. I suspect it is because of the pk. serializer.py class TestcaseSerializer(serializers.ModelSerializer): class Meta: model = testcase lookup_field = 'testcase_name' fields = ("testcase_name", 'description') def update(self, instance, validated_data): print(instance) # returns test1 as it is ithe current pk # ret = super(TestcaseSerializer, self).update(instance, validated_data) [setattr(instance, key, value) for key, value in validated_data.items()] instance.save() print(instance)# returns test2 as the testcase_name is changed to test2 #instead it is a new instance rather than the old instance getting updated return instance models.py class testcase(models.Model): testcase_name = models.CharField( max_length=20, primary_key=True) description = models.CharField(max_length=100, blank=True) def __str__(self): return self.testcase_name views.py class Testcaseviewset(viewsets.ModelViewSet): queryset = testcase.objects.all() serializer_class = TestcaseSerializer lookup_field = 'testcase_name' Is there any way to solve this in the serializer itself not from the views. -
Chmod fails when using fuse mount as media directory
I'm trying to use a remote FTP as a Django media source in docker. I have mounted a directory: /mnt/ftp_media with curlftpfs: curlftpfs -o allow_other user:pass@host /mnt/ftp_media I've noticed that when trying to upload a file, it actually does get created on the remote, but django fails on chmod with: Operation not permitted I've tried to directly execute chmod inside the mount: cd /mnt/ftp_mount chmod 666 some_file.txt But then I also get an error: chmod: changing permissions of 'some_file.txt': Operation not permitted Even as a root user. I've tried to remount with different users, but it always yields the same results. Is it just that you should not use chmod in fuse mounts? -
django: href doesn't redirect to the right page
This is my first django project, I'm not sure why the href = "{{ itema.get_absolute_url }}" doesn't work. Any help is appreciated, I'm not sure what I'm doing wrong here. html> <div id='Art' class='research'> {% if info %} {% for itema in research %} <a class = 'linka' href = "{{ itema.get_absolute_url }}"> <div class="research-box"> <img class='research-img' src='{{ itema.image.url }}'> <h3>{{itema.title}}</h3> </div></a> {% endfor %} {% else %} <div> <p>No data available</p> </div> {% endif %} </div> urls> # pages/urls.py from django.urls import path from .views import LinksContentDetailView urlpatterns = [ path('<int:pk>', LinksContentDetailView.as_view(), name='links_detail'), ] root>urls.py> path('', include('pages.urls')), models.py> class LinksContent(models.Model): author = models.ForeignKey(Author, on_delete=models.DO_NOTHING, default= True) title = models.CharField(max_length=100) content = HTMLField() image = models.ImageField(upload_to = 'images/%Y/%m/%d/') image2 = models.ImageField(upload_to = 'images/%Y/%m/%d/', blank = True) is_published = models.BooleanField(default = True) publish_date = models.DateTimeField(default = datetime.now, blank = True) def get_absolute_url(self): return reverse('links_detail', args=[str(self.id)]) views.py> # links research laboratory separate view class LinksContentDetailView(DetailView): model = LinksContent template_name = 'links_detail.html' -
Django - deployment on Heroku returns different HTML than local host
I have a Django app that works great on localhost. When deployed the Heroku, for some reason the app returns different HTMLs. A few examples: I have a form with button type submit. This is the template <button type="button" page="{{request.resolver_match.view_name}}" type="submit" id="bullets_submit" class="btn btn-primary px-5 py-2"> Next Step </button> In localhost everything works well but on Heroku the HTML I receives is without the type="submit". Same button just without this attribute. I have a for loop that iterates on a model and create a li <div class="h5 mx-4 px-3 bg-white" style="position: absolute; top: -20px;"> About the role <a href="{% url 'app:responsibilities' description.pk %}" type="button" class="btn btn-outline-light px-2 text-muted border border-0"><i class="far fa-edit"></a></button> </div> <div class="border border-primary rounded shadow p-2 pt-3 m-2"> <ul> {% for responsibility in description_responsibilities%} <li>{{responsibility}}</li> {% endfor %} </ul> </div> On Heroku, even though the <i class="far fa-edit"> is clearly outside of the for loop, it still get generated several times in the HTML I receive from the server, as if it was inside the for loop. Any idea what might cause this weird behavior? Or how I can debug it? -
Can't get Django REST to save POST object request in model
Trying to allow users to create an object and save it in my model. My front-end POST requests are getting a 201 confirmation response, so no traceback error from the backend. The data seems to be getting serialized but not saved in my model. Here is my code... model.py: class Bucket(models.Model): category_options = ( ('personal', 'Personal'), ('social', 'Social'), ) class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='buckets') admin_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='admin_user') guest_user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='guest_user', blank=True) category = models.CharField(max_length=30, choices=category_options) name = models.CharField(max_length=35) created = models.DateTimeField(default=timezone.now, blank=True) slug = AutoSlugField(populate_from = "random_string", blank=True) stock_count = models.IntegerField(blank=True, null=True) stock_list = ArrayField(models.CharField(max_length=6,null=True),size=30,null=True, blank=True) about = models.CharField(max_length=200) objects = models.Manager() bucketobjects = BucketObjects() class Meta: ordering = ('-created',) def save(self, *args, **kwargs): if self.stock_list: self.stock_count = len(self.stock_list) super().save(*args, **kwargs) serializer.py: class BucketCreateSerializer(serializers.ModelSerializer): class Meta: model = Bucket fields = ('owner','category','name','about') read_only_fields = ['owner'] def create(self, validated_data): user = self.context['request'].user bucket = Bucket.objects.create( owner=user, **validated_data ) bucket.save() return bucket view.py: class CreateBucket(generics.CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = BucketCreateSerializer queryset = Bucket.objects.all() How can I go about solving this? -
Django Email Not Working on Production Server
I have recently deployed a site that I developed in Django onto a production server running Ubuntu and Apache. The site functioning in every respect with the exception of sending emails wherever I configure an email to be sent, the page keeps loading and nothing happens although in the back end whatever information was made is saved like the contact us. On the local host emails are working perfectly fine and on the deployed site it is just not sending and the page keeps loading endlessly. Here is an example of the contact us config views.py def contact_us(request): if request.method == 'POST': # check post form = ContactForm(request.POST) if form.is_valid(): data = ContactMessage() # create relation with model data.name = form.cleaned_data['name'] # get form input data data.email = form.cleaned_data['email'] data.subject = form.cleaned_data['subject'] data.message = form.cleaned_data['message'] data.save() # save data to table messages.success(request, "Your message has ben sent. Thank you for your message.") template = render_to_string("marketing/contact_us_email.html", {'first_name': request.user.first_name, 'last_name': request.user.last_name, 'form': form}) msg = EmailMessage('Contact Us Message', template, settings.EMAIL_HOST_USER, ['email@email.com']) msg.content_subtype = "html" # Main content is now text/html msg.fail_silently = False msg.send() return HttpResponseRedirect('/') form = ContactForm context = {'form': form} template = 'marketing/contact_us.html' return render(request, template, context) Here is … -
CSS onclick animation
I have the following messages block at my Django application, see below. Its working beatifully if a new messages appear but what I dont understand is how can I also play a "fadeOut" animation as soon as the onclick function gets hit. {% if messages %} <div class="animated slideInRight messages glas-messages"> <span class="closebtn dot" onclick="this.parentElement.style.display='none';"><span class="cross">×</span></span> {% for message in messages %} <span><li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></span> {% endfor %} </div> {% endif %} It would be awesome if I could also exec a animation if I click on the cross, can smb help? kind regards -
Writing a cleaner function in python, a parameter to be either a set or a value
I have a struggling with a way of writing this function much cleaner and to make this function for the parameter objs to can be either a QuerySet or an single object, in case when the objs parameter is an set of objects I want to go with the for loop but in the case when is a single object I want to create the date parameter without looping, and also I am not sure if the try block is the good way for checking if the object with these information is already in db or not and if it's not I want to create it with these dates. Any help would be appreciated, thanx! the function: def check_recurrent_or_new(user, objs, obj): for item in objs: if item.created_date.month == 12: date = datetime( item.created_date.year + 1, 1, item.created_date.day, item.created_date.hour, item.created_date.minute, item.created_date.second, item.created_date.microsecond ) else: date = datetime( item.created_date.year, item.created_date.month + 1, item.created_date.day, item.created_date.hour, item.created_date.minute, item.created_date.second, item.created_date.microsecond ) try: obj.objects.get( user=user, name=item.name, amount=item.amount, created_date=date, category=item.category, recurrent=True ) except: obj.objects.create( user=user, name=item.name, amount=item.amount, created_date=date, category=item.category, recurrent=True -
In Django admin, how can I filter a MultipleChoiceField depending on a previous MultipleChoiceField?
In my django website, I have 3 classes: Thing, Category and SubCategory. Thing has 2 ForeignKeys: "Category" and "SubCategory" (such as Car and Ferrari). SubCategory has 1 ForeighKey: "Category" (Ferrari is in the category Car) When I create an instance of Thing in the Admin part and when I choose a Category, I would like that the "SubCategory" field only shows the SubCategories linked to the Category I chose. Is that possible? I saw the possibility to change the AdminForm like: class ThingFormAdmin(forms.ModelForm): def __init__(self,Category,*args,**kwargs): super (ThingFormAdmin,self ).__init__(*args,**kwargs) # populates the post self.fields['sub_category'].queryset = SubCategory.objects.filter(category= ... ) But I don't know what to write on the ... Thanks for the help! -
Docker Plesk Django React PostGre
I have a working Django React Postgres Nginx Project on local Docker and i need to upload it on a plesk server. I hade downloaded the plesk docker application, have downloaded the needed images, uploaded the files, but i cannot seem to make it work. I need help! Thanks. -
Django Rest Framework - Expected a time, but got a datetime on serializer.data
at the moment I have a project, where I need to edit the db through a backend. My problem is that I cant call "serializer.data", but everything else. I did this way of editing date time fields a few times and it always worked but not here. My Model: class Trackedtime(models.Model): personid = models.CharField(db_column='personId', max_length=255, blank=True, null=True) date = models.DateTimeField(db_column='date', blank=True, null=True) latstart = models.FloatField(db_column='latStart', blank=True, null=True) longstart = models.FloatField(db_column='longStart', blank=True, null=True) logout = models.DateTimeField(db_column='logout',blank=True, null=True) latstop = models.FloatField(db_column='latStop', blank=True, null=True) longstop = models.FloatField(db_column='longStop', blank=True, null=True) worktime = models.IntegerField(db_column='workTime', blank=True, null=True) class Meta: managed = False db_table = 'trackedtime' My Serializer: class TrackedTimeSerializer(serializers.ModelSerializer): class Meta: model = Trackedtime fields = ('personid', 'date', 'latstart', 'longstart', 'logout', 'latstop', 'longstop', 'worktime') My View with the error line: class TrackedTimeUpdateDateView(generics.UpdateAPIView): queryset = Trackedtime.objects.all() serializer_class = TrackedTimeSerializer def update(self, request, pk): instance = get_object_or_404(Trackedtime, pk=pk) data = {"date": request.data.get("date")} serializer = ZeiterfassungSerializer(instance, data=data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) The error message is Expected a time, but got a datetime. and I know its the serializer.data, because I also tried printing it out. I hope you can help me. Thank you! -
Django(not rest-framework) don`t remember the sessions if a make multiple request from react app
I trying to make request from react-app(http://localhost:8082/) to django-app(not rest-framework) and after each request , request.session.items() is empty. This is happend only when i make requests from browsers , if makes all this steps from postman the sessions middleware works good. I think the problem is from Headers , but i don`t find it React requests : var qs = require('qs'); const headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'withCredentials':false, 'X-CSRF-TOKEN':'cwE9Ddste5nblT6ADjyi1AVhyyh4bQVirjr7CKiC3e5Fazw0YpwLmAQLFuu1X315' } axios.get('http://127.0.0.1:8000/users/setSession',headers) .then(res => { console.log(res.data); },(error) => { }); axios.get('http://127.0.0.1:8000/users/getSession',headers) .then(res => { console.log(res.data); },(error) => { }); Python views.py methods : #@csrf_exempt def setSession(request): request.session['id'] = 12312312 request.session['token'] = 'test' return JsonResponse({'status':200},safe=False,status=202) #@is_auth #@csrf_exempt def getSession(request): print(request.session.items()); return JsonResponse({'status':200},safe=False) enter image description here -
Using different color than bootstrap default color scheme - Django Python
Pretty new to Django, Recently, while building a website using Django, I created the navbar and used bootstrap. Just to make it look better. However, it seems that I'm forced to use bootstrap default color scheme. I want to change the navigation bar background color to a color tag, inside the base.html file. Google left me empty-handed. With many advices on overwriting and adding your custom.css (which a lot of people aware you of doing so as it is not recommended). I tried adding custom script into the html file, failed. <script> .navbar-custom { background-color: #9f6967; } </script> I would appreciate help on (maybe) creating a custom.css file. So far the nav-bar is the default bootstrap navigation bar script from their website. <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> Other than dark/light/other colors from the scheme, there isn't any way to add a color tag. (specific : #9f6967) -
How to upload an image in django using S3Boto3Storage where the path is set dynamically from the view in django
I'm wanting to save images to an S3 bucket using the session_key as the directory inside the bucket, in django. I have created a test page that uploads an image to a set location in the bucket but don't know how to use the session_key to set the upload location dynamically. I've looked at the docs for django-storages and I can see a way to do this if it wasn't for the fact that I am using a ModelForm. Here is the code I have (I have omitted my settings.py with the bucket name and credentials): storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage class TestS3MediaStorage(S3Boto3Storage): location = 'dev/' default_acl = 'public-read' file_overwrite = False models.py from .storage_backends import TestS3MediaStorage class TestS3Upload(models.Model): uploaded_at = models.DateTimeField(auto_now_add=True) file = models.FileField(storage=TestS3MediaStorage()) forms.py from .models import TestS3Upload class TestS3UploadForm(forms.ModelForm): class Meta: model = TestS3Upload fields = ['file'] views.py from django.shortcuts import render from django.http import HttpResponse from .forms import TestS3UploadForm def test_s3_upload(request): # create session if it doesn't already exist if not request.session.session_key: request.session.create() # not quite sure how to use this to set upload destination session_key = request.session.session_key if request.method == 'POST': form = TestS3UploadForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse("upload successful!") else: form = TestS3UploadForm() …