Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, looping inside a father-child tree
I am trying to loop over a father-child tree relationship were the child also can be a father and print it's children for the far being i'v only been able to print the primitive father and the children (but i cant figure out how to print the children's children) Here is the Model : class Component(models.Model): component_name = models.CharField(max_length=100) component_manufacturer = models.CharField(max_length=100) component_model = models.CharField(max_length=100) component_number = models.CharField(max_length=255) component_price = models.IntegerField() component_note = models.TextField() parent_component = models.ForeignKey("self", verbose_name=( "Parent Component"), blank=True, null=True, related_name='children', on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def __str__(self): return f"{self.id}, {self.component_name}" the view : def index(request): f = Component.objects.all() context = { 'f': f } return render(request, 'maintenance/index.html', context) the template : <div class='component'> Components<ol> {%for f in f%} {%if f.is_child is False %} <li> {{f.component_name}}</li> <ol> {% for f in f.children.all %} <li> {{f.component_name}}</li> {%endfor%} </ol> {%endif%} {%endfor%} </ol> </div> Thanks plenty! -
Value errror don't mix args and kwargs
ValueError at /postsignin Don't mix *args and **kwargs in call to reverse()! Request Method: POST Request URL: http://127.0.0.1:8000/postsignin Django Version: 3.2.3 Exception Type: ValueError Exception Value: Don't mix *args and **kwargs in call to reverse()! Exception Location: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\django\urls\resolvers.py, line 624, in _reverse_with_prefix Python Executable: C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.6 Python Path: ['S:\Work\Fortech', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39', 'C:\Users\ASUS\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\win32\lib', 'C:\Users\ASUS\AppData\Local\Programs\Python\Python39\lib\site-packages\Pythonwin'] Server time: Sat, 25 Dec 2021 14:45:40 +0000 Views def postSignIn(request): try: email = request.POST.get('email') password = request.POST.get('password') auth.sign_in_with_email_and_password(email, password) return redirect('/', request) except error: return redirect(reverse('signin', args=request, kwargs={'msg': 'id'})) urls urlpatterns = [ path('', views.index, name='index'), path('signin', views.signIn, kwargs={'msg': 'None'}, name='signin'), path('postsignin', views.postSignIn, name='postsignin'), ] -
Why does model not connect with user?
I have a model that appers in admin. But it doesn't connect with user automatically. I always have to specify user in admin. I have a form for creation. But when I create with this form it doesn't appear on the screen. Models class Notion(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notions', null=True, blank=True) title = models.CharField(max_length=100) body = models.TextField() -
How to print many-to-many field
models.py: from django.db import models class Course(models.Model): course = models.TextField(blank=True) class Student(models.Model): first_name = models.TextField() last_name = models.TextField() course = models.ManyToManyField(Course) forms.py: from django import forms from .models import Student, Course class StudentForm(forms.ModelForm): class Meta: model = Student fields = ['first_name', 'last_name', 'course'] class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['course'] views.py: def students_view(request): if request.method == 'POST': students_form = StudentForm(request.POST) if students_form.is_valid(): students_form.save() print(Student.objects.all().values()) students_form = StudentForm() context = { 'form':students_form } return render(request, 'courses/courses.html', context) If I print print(Student.objects.all().values()) than I see student's ID, first_name and last_name. But I don't see in which groups they belong to. How to print that? -
(fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract Django
I'm new in django, I faced with following error when I wanted to define two models which have foreignkey to each other . I searched about it and I find out this might happen when the models have been in two different apps, but my models are in one app . would you please help me about this . Thanks ERRORS: ?[31;1mstore.Collection.featured_product: (fields.E300) Field defines a relation with model 'Product', which is either not installed, or is abstract.?[0m class Collection(models.Model): title = models.CharField(max_length=255) featured_product = models.ForeignKey( 'Product', on_delete=models.SET_NULL, null = True, related_name= '+') class Product(models.Model): title = models.CharField(max_length=255) description = models.TextField() price = models.DecimalField(max_digits=6, decimal_places=2) inventory = models.IntegerField() last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT) promotion = models.ManyToManyField(Promotion) -
How to upload and deploy zip folder?
I want to upload and deploy the zip folder downloaded from repl.it to AWS eb, but it is difficult to find even if I google it.. -
Error10060 Time our when trying to send_mail with django
Here is my setting:(I'm pretty sure the password and user is correct, becauese if I intentionally input wrong password it will returen authenticationException but not time out) DEFAULT_FROM_EMAIL = 'xxxx' EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xxxx' EMAIL_HOST_PASSWORD = 'xxxxxxxx' I try this in python shell: send_mail('Test', 'This is a test', 'xxxx@gmail.com', ['xxxx@gmail.com'], fail_silently=False) It return timeout exception. plus:I'm using vpn, I think may be this is the culprit, but I don't know how to solve it, thanks for your help. -
How to get the name of the month instead of the month number from db
I am picking some data from the db to make some analytics in my website. I am rendering out the data graphically with the help of chart js. This is how I am doing it in views, views.py monthly_visitor = VisitorCount.objects.all().filter(date_of_record__year = currentYear.year).values( 'date_of_record__month' ).annotate( total_in_month=Count('ip') ).order_by('date_of_record__month') Here, I am picking up the data of all the visitors of every month of the current year. Now if I print the monthly_visitor I get the below result <QuerySet [{'date_of_record__month': 9, 'total_in_month': 1}, {'date_of_record__month': 10, 'total_in_month': 2}, {'date_of_record__month': 11, 'total_in_month': 3}, {'date_of_record__month': 12, 'total_in_month': 5}]> Which is correct but what I want is <QuerySet [{'date_of_record__month': sept, 'total_in_month': 1}, {'date_of_record__month': oct, 'total_in_month': 2}, {'date_of_record__month': nov, 'total_in_month': 3}, {'date_of_record__month': dec, 'total_in_month': 5}]> So that I can display names of the month in the graph rather the numbers. I came across some methods to use tags in the html. But I am importing this data into a different javascript file with the help of ajax. Please suggest me what should I do. -
Python Django html templating
I'm building a web portfolio for albums photography and others features, but the html templating is a bit messy for me, I have few diferents questions related to this subject. Here are my models: class Album(models.Model): title = models.CharField(max_length=150) date_init = models.DateField("From", default=date.today) date_end = models.DateField("To", default=date.today) album_cover = models.ForeignKey('Photo', null=True, blank=True, on_delete=models.RESTRICT, related_name='Album') class Photo(models.Model): image = models.ImageField(upload_to="photos/") alt_text = models.CharField(max_length=100) album = models.ForeignKey(Album, on_delete=models.CASCADE, related_name='photos') tags = TaggableManager(blank=True) 1- I have a Navbar in a base.html : {% block sidebar %} ... <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> <li><a class="dropdown-item" href="#">2021</a></li> <li><hr class="dropdown-divider"></li> <li><a class="dropdown-item" href="#">2018</a></li> <li><a class="dropdown-item" href="#">2014</a></li> ... {% endblock %} </ul> My idea is to show only years for where at least one album is saved in database (ghost 2020 and 2019 cause there is no data for example). But my problem is that this code is in the base.html that I extend everywhere. I know I can modify this with {% block sidebar %}, but this informations need to be in all templates too. If I'm right I can't send data to the base.html to populate the list ? Is there a way to achieve this without copy/paste code into all html templates? If needed, my request … -
Why is my frontend (VueJS) being blocked by CORS policy in API (Django)
I am using Django-Rest-Framework for a project, and VueJS as the frontend. I send the API requests using Axios. For all endpoints, I have not faced any issues. But I created an endpoint for changing an account's user, it takes the old password, new password, and the token of the user. When I try to hit that endpoint I get an error such as this: I tried most of the solutions here, like adding the localhost to CORS_ALLOWED_ORIGINS and setting CORS_ORIGIN_ALLOW_ALL = DEBUG. I also download cors-headers Here is my settings.py: DEBUG = True CORS_ORIGIN_ALLOW_ALL = DEBUG ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'accounts', 'clubs', 'events', 'announcements', 'comments', 'corsheaders', 'requests', 'clubenrollment' ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware', ] CORS_ALLOWED_ORIGINS = [ 'http://localhost:8080' ] this is the urls.py path('api/change-password/', ChangePasswordView.as_view(), name='change-password'), This is my views.py class ChangePasswordView(generics.UpdateAPIView): """ An endpoint for changing password. """ serializer_class = ChangePasswordSerializer model = Account permission_classes = (permissions.IsAuthenticated,) def get_object(self, id): obj = Account.objects.get(id=id) return obj def update(self, request, *args, **kwargs): self.object = self.get_object() serializer = self.get_serializer(data=request.data) if serializer.is_valid(): # Check old password if not self.object.check_password(serializer.data.get("old_password")): return Response({"old_password": ["Wrong … -
Save coordinates from Folium map to Django
I want to make a web application that let user create notes about different places. Is there a way to save coordinates from the folium map to the Django database, SQLite 3 for example? -
Django: Slow query set to retrieve the order in which the specified tags are mostly included
I would like to get the so-called similar posts, but for some reason the following query set is For some reason, the following query set takes a long time. (500-1000ms) What we are doing below is trying to filter by tags associated with a particular object and retrieve articles in order of the number of tags included. Removing annotate and order_by improves the speed but still takes about 200ms. tag_pks = Video.objects.get(pk=video_pk).tags.values_list("pk") Video.objects.annotate(n=Count("pk")) .exclude(pk=video_pk) .filter(tags__in=tag_pks) .order_by("-n") QUERY PLAN ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- Limit (cost=1059.82..1059.87 rows=20 width=24) (actual time=461.401..461.407 rows=20 loops=1) -> Sort (cost=1059.82..1063.43 rows=1444 width=24) (actual time=461.400..461.404 rows=20 loops=1) Sort Key: (count(videos_video.id)) DESC Sort Method: top-N heapsort Memory: 26kB -> HashAggregate (cost=1006.95..1021.39 rows=1444 width=24) (actual time=385.859..445.844 rows=144784 loops=1) Group Key: videos_video.id Batches: 5 Memory Usage: 4145kB Disk Usage: 7000kB -> Nested Loop (cost=39.20..999.73 rows=1444 width=16) (actual time=0.076..330.037 rows=150442 loops=1) -> Nested Loop (cost=38.78..354.85 rows=1444 width=16) (actual time=0.059..48.867 rows=150445 loops=1) -> HashAggregate (cost=38.35..38.41 rows=6 width=32) (actual time=0.041..0.046 rows=3 loops=1) Group Key: u0.id Batches: 1 Memory Usage: 24kB -> Nested Loop (cost=0.71..38.33 rows=6 width=32) (actual time=0.032..0.039 rows=3 loops=1) -> Index Only Scan using videos_video_tags_video_id_tag_id_f8d6ba70_uniq on videos_video_tags u1 (cost=0.43..4.53 rows=6 width=16) (actual time=0.015..0.016 rows=3 loops=1) Index Cond: (video_id = '9af2f701-6272-4714-b99f-afe5e4deb741'::uuid) Heap Fetches: 0 -> Index Only … -
django 4.0 - can't login with registered user
Here is the django shell output: >>> for user in User.objects.all(): ... print(user.username, user.password, len(user.password)) ... ll_admin pbkdf2_sha256$320000$zm6RcAswZJR6B7uXaCVNVd$hRs9nZKWBPpfemhC2yL16XE0wLCRa4Z0dlbUATywleA= 88 ams 1243 4 who 1243 4 whos 1243 4 whosa 1243 4 maksd 1243 4 1243 1243 4 abcde 12345 5 ids 1243 4 amsfd 1234567 7 cancal 1111 4 >>> Here is the login view code: def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse('homepage:index')) else: message = "User doesn't exist or password is incorrect." + "( " + username + ", " + password + " )" else: message = '' form = UserForm() context = {"form": form, "message": message} return render(request, 'users/login.html', context) I sign in with ams, 1243 for example, it shows: https://imgur.com/a/XmJr1Aj I checked the password and username and they match. So kind of feel confused right now. Thanks for your help! -
How do I create , test (and if possible deploy) a django project using only an android 10 device?
How do I create,test(and if possible deploy) a django project using only an android 10 device? -
expected str, bytes or os.PathLike object, not tuple django media file upload
I created a model and add a filefield in it and trying to add this model from admin panel but when I save it it shows me this error. This is emergency pls help me. Thanks -
Django Unit Test not executed
I'm still struggling with tests in Django. Now i've rewrite a test, but it's not executed, so i see no results when i run the test command. Is it because of the wrong test or i'm missing something? Thank you once again :) Models: class Lab(models.Model): lab_name = models.CharField(max_length=200) category = models.ForeignKey(Category, unique=True, null=True, on_delete=models.PROTECT) pub_date = models.DateTimeField('date published') lab_theory = models.TextField() def __str__(self): return self.lab_name class QuestionMultipleChoice(models.Model): lab = models.ForeignKey(Lab, on_delete=models.CASCADE) type = QuestionType.multiplechoice question = models.CharField(max_length=200,null=True) option1 = models.CharField(max_length=200,null=True) option2 = models.CharField(max_length=200,null=True) option3 = models.CharField(max_length=200,null=True) option4 = models.CharField(max_length=200,null=True) answer = models.IntegerField(max_length=200,null=True) def __str__(self): return self.question @property def html_name(self): return "q_mc_{}".format(self.pk) @property def correct_answer(self): correct_answer_number = int(self.answer) correct_answer = getattr(self, "option{}".format(correct_answer_number)) return correct_answer def check_answer(self, given): return self.correct_answer == given Test: def test_past_question(self): """ Questions with a pub_date in the past are displayed on the index page. """ past_date = date(1997, 3, 2) lab2 = Lab.objects.create(lab_name="test lab past question", pub_date=past_date, lab_theory="test lab past question") past_question = QuestionMultipleChoice.objects.create(lab=lab2, question='This is a test question', option1='1', option2='2', option3='3', option4='4', answer='1') response = self.client.get(reverse('labs:index')) print (response) self.assertEqual(str(past_question),'This is a test question') -
How to make reverse nested serialization when we have ManytoMany field in relation? using DRF
my data model is like ''' class Rack(models.Model): rack_id = models.CharField(primary_key=True,max_length=30, verbose_name="Rack Id") rack_set = models.ForeignKey(RackSet, on_delete=models.CASCADE, related_name='wh_rack_set', verbose_name="Rack Set") class Meta: db_table = "rw_rack" def __str__(self): return self.rack_name class RackBay(models.Model): bay_id = models.CharField(primary_key=True,max_length=30, verbose_name="Bay Id") rack = models.ForeignKey(Rack, on_delete=models.CASCADE, related_name='wh_rack', verbose_name="Rack") class Meta: db_table = "rw_bay" def __str__(self): return self.bay_name class RackShelf(models.Model): shelf_id = models.CharField(primary_key=True,max_length=50, verbose_name="Shelf Id") bay = models.ForeignKey(RackBay, on_delete=models.CASCADE, related_name='wh_rack_bay', verbose_name="Bay") class Meta: db_table ="rw_shelf" def __str__(self): return self.shelf_name class RackBin(models.Model): bin_id = models.CharField(primary_key=True,max_length=50, verbose_name="Bin Id") class Meta: db_table = "rw_bin" def __str__(self): return self.bin_name class CargoWarehouseSurvey(models.Model): job_id = models.ForeignKey(WarehouseJob, on_delete=models.CASCADE, null=True, related_name='inputted_job_order', verbose_name="Job Id") warehouse_locations = models.ManyToManyField(WarehouseCell, help_text='Assigned warehouse locations for current survey job.', related_name='warehouse_locations_set') rack_bin_locations = models.ManyToManyField(RackBin, help_text='Assigned rack_bin locations for current survey job.', related_name='rack_bin_locations_set') def __str__(self): return self.id class Meta: db_table = 'warehouses_survey' ordering = ['id'] ''' This is my data model, in CargoWarehouseSurvey has bins relation what ever the selected, i need to get bin belogs to which rack, bay, shelf, bin. like expected Response is "allotted_bins": [ { "rack_id": "A-1", "bays": [ { "bay_id": "B-1", "shelves": [ { "shelf_id": "S1", "bin_ids": [ "12343", "21232" ] }, { "shelf_id": "S2", "bin_ids": [ "43234", "42354" ] }, ] } ] } ] } -
how to fix You are trying to change the nullable field to non-nullable without a default?
i've tried to add a comment section to my blog app add I just added this section to my models: class Comments(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) date = models.DateTimeField(default = timezone.now) body = models.TextField(max_length = 600, default='') def __str__(self): return self.body then when i tried to makemigtations it gave me this : You are trying to change the nullable field 'user' on profile to non-nullable without a default; we can't do that (the database needs something to populate existing rows). which is related to this model; i didnt change anything on that and it has migrated long time ago without any problem class Profile(models.Model): user = OneToOneField(User, on_delete = models.CASCADE) bio = models.TextField(blank=True) profile_pic = models.ImageField(blank=True, upload_to ='uplodes/profiles', default='uplodes/profiles/default-profile-pic.jpg' ) instagram_url = models.CharField(max_length=350, blank=True, null=True) twitter_url = models.CharField(max_length=350, blank=True, null=True) linkedin_url = models.CharField(max_length=350, blank=True, null=True) website_url = models.CharField(max_length=350, blank=True, null=True) then to solve this problem i've added a defalt=none to user field on Profile, after that makemigrations worked but when i run migrate command this error comes up NOT NULL constraint failed: new__Blog_profile.user_id i have no idea why this happening because this model was created long time ago and worked just fine and now when i … -
ssl.SSLCertVerificationError When connecting to heroku redis with django-channels
I'm making chat. I have a need to use WebSocket and deploy my app to Heroku. I use free heroku-redis and django-channels In my settings py: CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [os.environ.get('REDIS_TLS_URL')], }, }, } I tried to use REDIS_URL but I was getting another error "ConnectionResetError: [Errno 104] Connection reset by peer when" Then I switched to REDIS_TLS_URL. Both errors were raised from consumers.py at "await self.channel_layer.group_add()" class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name print('==================================') print('==================================') print(self.room_name) print(self.room_group_name) print('==================================') print('==================================') await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() ......... Here is logs 2021-12-25T08:59:56.469939+00:00 app[web.1]: 2021-12-25 08:59:56,469 DEBUG Upgraded connection ['10.1.3.218', 11273] to WebSocket 2021-12-25T08:59:56.859805+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO ================================== 2021-12-25T08:59:56.859921+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO ================================== 2021-12-25T08:59:56.860015+00:00 app[web.1]: 2021-12-25 08:59:56,859 INFO FIRST 2021-12-25T08:59:56.860107+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO chat_FIRST 2021-12-25T08:59:56.860196+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO ================================== 2021-12-25T08:59:56.860287+00:00 app[web.1]: 2021-12-25 08:59:56,860 INFO ================================== 2021-12-25T08:59:56.860674+00:00 app[web.1]: 2021-12-25 08:59:56,860 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-25T08:59:56.861684+00:00 app[web.1]: 2021-12-25 08:59:56,861 DEBUG Creating tcp connection to ('ec2-34-241-115-34.eu-west-1.compute.amazonaws.com', 29080) 2021-12-25T08:59:56.872570+00:00 app[web.1]: 2021-12-25 08:59:56,872 DEBUG Closed 0 connection(s) 2021-12-25T08:59:57.708867+00:00 app[web.1]: 2021-12-25 08:59:57,706 ERROR Exception inside application: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1129) … -
Understand `basic_fields` attribute of django.form model
while walking through the source code of django.forms.forms.py, I am stuck in below line: self.fields = copy.deepcopy(self.base_fields) Q: In regards to self.basic_fields, can anyone please explain where does it come from ? Why it was introduced in the first place? It seems to me that it is originated from class DeclarativeFieldsMetaclass(MediaDefiningClass):, but class BaseForm does not inherit from it. -
Stylized HTML fields in Django admin
I Have TextField to store HTML text. I want to colorize HTML tags. I use TinyMCE but didn't need an HTML editor like WordPress just simple to colorize like IDE, Search a lot but didn't find anything useful, So if you can help I appreciate it. My field: I want output like this but changeable: -
django API view for javascript Ajax request
Let's say I have a Chart demo class Chart(models.Model): data = models.TextField() I store and load data in format of JSON, manipulate data and tries to render a chart on frontend. User case can be: user use app interface to generate data, upload it data is uploaded to backend and stored within an Chart instance use detail view and a redirect url to illustrate the result def chartDetailView(request, pk): chart = Chart.objects.get(pk=pk) return render(request, 'chart/chart.html', {'data': chart.data}) there are many website that allows costume JS request, for example, Web: how to redirect to a CodePen or JsFiddle with information filled?. since the static page only requires a data context to perform functionality, is there a way I can build an Ajax for javascript to open a new tab for the view? I mean, to code a view which can be requested by anchor link, form, Ajax or fetch with data passed in by JS, and return a static page. (no Chart instance stored) sorry the question may seems ignorant to you, I have learned little about rest framework. I will be very grateful for any suggestion you make. any source to look at. -
How to default language - error in changing it - Django
I have been struggling for quite a while with translation in django. I want to set a default language that is being set everytime user access the website (in a new session). I have studied django documentation, and I found the following algorithm: First, it looks for the language prefix in the requested URL. This is only performed when you are using the i18n_patterns function in your root URLconf. See Internationalization: in URL patterns for more information about the language prefix and how to internationalize URL patterns. Failing that, it looks for a cookie. The name of the cookie used is set by the LANGUAGE_COOKIE_NAME setting. (The default name is django_language.) Failing that, it looks at the Accept-Language HTTP header. This header is sent by your browser and tells the server which language(s) you prefer, in order by priority. Django tries each language in the header until it finds one with available translations. Failing that, it uses the global LANGUAGE_CODE setting. So I am trying to set the language prefix in the requested URL. I have configured my app as follows: settings.py MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'crm.middleware.RequestMiddleware', ] .... EXTRA_LANG_INFO = { 'md': … -
How to store static file on Google cloud storages using heroku deployment?
I used whitenoise to save static files, but now I want to save them to Google cloude storage. So I reset dyno and set it as follows, but the static folder is not created in storage. I'm not sure what I'm missing. google_credential is working well. The upload file is well stored. The level is also done without problems. However, static files are not generated in GCS. settings.py configuration if DEBUG is False : ALLOWED_HOSTS = ["cineacca.herokuapp.com", 'cineacca.com',] GOOGLE_APPLICATION_CREDENTIALS = os.environ.get("GOOGLE_APPLICATION_CREDENTIALS") DEFAULT_FILE_STORAGE = "config.custom_storages.UploadStorage" STATICFILES_STORAGE = "config.custom_storages.StaticStorage" STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') GS_DEFAULT_ACL = "publicReadWrite" GS_BUCKET_NAME = "cineacca_bucket" GS_PROJECT_ID = os.environ.get("GS_PROJECT_ID") MEDIA_URL = "/media/" STATIC_URL = "/static/" django_heroku.settings(locals()) custom_storages.py from storages.backends.gcloud import GoogleCloudStorage from storages.utils import setting class StaticStorage(GoogleCloudStorage): bucket_name = setting('GS_BUCKET_NAME') location = "static/" class UploadStorage(GoogleCloudStorage): bucket_name = setting('GS_BUCKET_NAME') location = "uploads/" -
Button type "submit" doesn't let bootstrap modal to open but type="button" doesn't fulfill my need
I have a web page in which there is an input field. And below is an edit button. When I enter some text in the input field and press the edit button, a modal pops up and there is an input field in it also. I want to pass the text from the first input field to the input field in the modal window. But then a problem arises. The modal window only opens when the edit button has type="button". But this type="button" doesn't submit the text input to the backend when I click the edit button. It submits the text to the backend when I use button type="submit", but then the modal doesn't open because the page reloads. Here's my HTML code: <div class="container"> <div class="row manage-groups"> <div class="row g-0 login_form justify-content-center" id="contactForm" novalidate="novalidate"> <form method="POST"> {% csrf_token %} <div class="col-md-12 form-group"> <input type="text" class="login-inpt" id="name" name="type-groups" placeholder="type in the group name"> </div> <div class="row g-0 justify-content-center group-action"> <div class="col-sm-4 submit-group"> <div> <button type="submit" data-bs-toggle="modal" data-bs-target="#ModalAddGroups" class="button-box">Add</button> </div> </div> <div class="col-sm-4 submit-group"> <button type="button" onclick="form_submit()" data-bs-toggle="modal" data-bs-target="#ModalEditGroups" class="button-box">Edit</button> </div> <div class="col-sm-4 submit-group"> <button type="submit" data-bs-toggle="modal" data-bs-target="#ModalDeleteGroups" class="button-box">Delete</button> </div> </div> </form> </div> </div> </div> <!-- Modal window for Edit button …