Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Lock web page in Django admin if another user in that page
I'm new to Django. I'm looking for a way to lock a custom template in the Django admin for accessing more than 1 user at a time. Is there a way to do it with Sessions? Or do it with javascript? Thanks in advance! -
How To Migrate IntegerField To ForeignKey
I have a legacy database I am migrating towards Django. I have model like this: class MyModel(models.Model): other_id = models.IntegerField() This is an existing table filled with valid data. I want to migrate to class MyModel(models.Model): newbie = models.ForeignKey( OtherModel, on_delete=models.CASCADE, db_constraint=False, db_column="other_id", ) However, the generated migration keeps insisting on adding the already existing field and than dropping it: python manage.py sqlmigrate app 0069 BEGIN; -- -- Add field -- ALTER TABLE `mymodel` ADD COLUMN `other_id` integer DEFAULT 1 NOT NULL; ALTER TABLE `mymodel` ALTER COLUMN `other_id` DROP DEFAULT; -- -- Remove field -- ALTER TABLE `mymodel` DROP COLUMN `other_id`; Is there a way to convince Django to treat the field as ForeignKey without this exercise? I'd like to avoid a need to --fake the migration. -
Strange issue when calling same piece of code in multiple places in one template
I am facing a strange issue. I have two method in a model. get_delivery_taxes and get_subtotal_taxes as shown below: def get_delivery_taxes(self): delivery_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): if tax.get('delivery_tax', None): delivery_tax_dict = tax.get('delivery_tax') delivery_tax_amount = delivery_tax_dict['amount'] delivery_tax_dict['amount'] = Money(delivery_tax_amount, settings.DEFAULT_CURRENCY) delivery_tax_list.append(delivery_tax_dict) return delivery_tax_list def get_subtotal_taxes(self): subtotal_tax_list = [] if self.modifiers: if self.modifiers.get('Taxation', None): for tax in self.modifiers.get('Taxation'): subtotal_tax_dict = None if tax.get('subtotal_tax', None): subtotal_tax_dict = tax.get('subtotal_tax') subtotal_tax_amount = subtotal_tax_dict['amount'] subtotal_tax_dict['amount'] = Money(subtotal_tax_amount, settings.DEFAULT_CURRENCY) subtotal_tax_list.append(subtotal_tax_dict) return subtotal_tax_list Those two methods are then used by these below methods to calculate their totals. def get_subtotal_tax_price(self): subtotal_tax_price = 0 for sub_tax_price in self.get_subtotal_taxes(): subtotal_tax_price = subtotal_tax_price + sub_tax_price['amount'] return subtotal_tax_price def get_delivery_tax_price(self): delvry_tax_amount = 0 for del_tax_price in self.get_delivery_taxes(): delvry_tax_amount = delvry_tax_amount + del_tax_price['amount'] return delvry_tax_amount A final total is calculated using above two methods as below. def get_order_final_total(self): subtotal = self.get_order_subtotal_price() subtotal_taxes = self.get_subtotal_tax_price() devilery_charges = self.get_order_delivery_charges_price() devilery_charges_taxes = self.get_delivery_tax_price() order_total = subtotal + subtotal_taxes + devilery_charges + devilery_charges_taxes return order_total In my template, I use them as below: {% for tax_dict in object.get_delivery_taxes %} ... {% endfor %} {% for tax_dict in object.get_subtotal_taxes %} ... {% endfor %} {{object.get_order_final_total}} Doing this was working fine until I … -
How to get file from django-import-export?
I want to use groupby() function from pandas, but dont know how to get file before export. I've tried dehydrate, but I dont think it's what i want. phone = Field() class Meta: model = Phones # exclude = ('id', ) def dehydrate_url(self,phone): -
Django: How do I get referenced objects in a symmetric ManyToMany relationship?
I've created a Many-to-Many relationship for the model UserProfile, to enable users to grant access to a particular feature to one another. The relationship works as expected with the use of symmetrical=False to ensure a user access is one-way. Model from django.contrib.auth.models import User class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) phone = models.IntegerField(blank=True, null=True) image = models.ImageField(upload_to='profile_image', default="default_thumbnail.jpg") department = models.ForeignKey(DepartmentModel, on_delete=models.SET_NULL, null=True) allow_booking_access = models.ManyToManyField("self", blank=True, symmetrical=False) def __str__(self): return self.user.username class UserInline(admin.StackedInline): model = UserProfile can_delete = False verbose_name_plural = 'UserAccounts' class UserAccount(BaseUserAdmin): inlines = (UserInline,) I am able to query the users that a particular user wants to grant access to via: (for example id=1) UserProfile.objects.get(id=1).allow_booking_access.all() However, I would like to retrieve the users that have granted access to the particular user. How would I do this? -
Why is selenium not finding an element on a website
I have the following test that I want to run. A payment request is being made from my application. For the user to complete the payment they have to visit a link on a website that processes payments. I want selenium to enter the email address which is required to complete the payment. I am getting the following error. E ====================================================================== ERROR: test_submit_payment (order.tests.test_views.TestViewsLiveServer) ---------------------------------------------------------------------- Traceback (most recent call last): File "/home/patrice/django-apps/dropby/dropby/order/tests/test_views.py", line 222, in test_submit_payment username = self.selenium.find_element_by_id('username') File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 360, in find_element_by_id return self.find_element(by=By.ID, value=id_) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 978, in find_element 'value': value})['value'] File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/webdriver.py", line 321, in execute self.error_handler.check_response(response) File "/home/patrice/django-apps/dropby/lib/python3.6/site-packages/selenium/webdriver/remote/errorhandler.py", line 242, in check_response raise exception_class(message, screen, stacktrace) selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [id="username"] Below is my code for the test. def test_submit_payment(self): # get the url to goto the payment view submission view url = self.live_server_url + reverse('order:payment', kwargs={'pk': self.order.pk}) self.selenium.get(url) # self.selenium.find_element_by_xpath("//select[@name='method_of_payment']/option[text()='ecocash']").click() phone_number_input = self.selenium.find_element_by_name('phone_number') phone_number_input.send_keys('0777777777') # Submit the form submit_button = self.selenium.find_element_by_id("submit-payment") submit_button.click() # Now find the url that goes to the paynow website to complete a payment complete_payment_url = self.selenium.find_element_by_id('complete-payment-url') complete_payment_url.click() # Now we are on the paynow website, enter in the email address of the user who is going … -
Why is Django API Get working but Post not working?
I'm using Django to develop an API, the GET method works but the post method gives "Failed to Add." error. Following is the model, class Video(models.Model): VideoId = models.AutoField(primary_key=True) VideoName = models.CharField(max_length=100) FPS = models.CharField(max_length=100) TotalFrame = models.CharField(max_length=100) Duration = models.CharField(max_length=100) The API, @csrf_exempt def videoApi(request, id=0): if request.method == 'GET': video = Video.objects.all() video_serializer = VideoSerializer(video, many=True) return JsonResponse(video_serializer.data, safe=False) elif request.method == 'POST': video_data = JSONParser().parse(request) video_serializer = VideoSerializer(data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Added Successfully!!", safe=False) return JsonResponse("Failed to Add.", safe=False) elif request.method == 'PUT': video_data = JSONParser().parse(request) video = Video.objects.get(VideoId=video_data['VideoId']) video_serializer = VideoSerializer(video, data=video_data) if video_serializer.is_valid(): video_serializer.save() return JsonResponse("Updated Successfully!!", safe=False) return JsonResponse("Failed to Update.", safe=False) elif request.method == 'DELETE': video = Video.objects.get(VideoId=id) video.delete() return JsonResponse("Deleted Succeffully!!", safe=False) URLs url(r'^video/$',views.videoApi), url(r'^video/([0-9]+)$',views.videoApi), serializers , class VideoSerializer(serializers.ModelSerializer): class Meta: model = Video fields = '__all__' JSON Input [{"VideoId": 2, "VideoName": "lol", "FPS": "1", "TotalFrame": "1", "Duration": "1"}] output , "Failed to Add." -
NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$']
I'm learning Django framework and I have in the extend templates part, Error during template rendering,i have received this error.When i add slug field we get template error NoReverseMatch at / Reverse for 'product_detail' with arguments '(1, 'sgm')' not found. 1 pattern(s) tried: ['(?P<category_slug>[-a-zA-Z0-9_]+)$'] from django.urls import path from shop import views app_name='shop' urlpatterns = [ path('', views.product_list, name='product_list'), path('search', views.product_search, name='product_search'), path('<slug:category_slug>', views.product_list, name='product_list_by_category'), path('<slug:slug>', views.product_detail, name='product_detail'), ] {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>{% block title %}online shop{% endblock %}</title> <link rel="shortcut icon" type="image/png" href="{% static 'img/save.ico' %}"/> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <!-- Bootstrap core CSS --> <link href="{% static 'vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet"> <script src="{% static 'vendor/jquery/jquery.min.js' %}"></script> <script src="{% static 'vendor/jquery/custom.js' %}"></script> <script src="{% static 'vendor/bootstrap/js/bootstrap.bundle.min.js' %}"></script> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script> <!-- Custom styles for this template --> <link href="{% static 'css/shop-homepage.css' %}" rel="stylesheet"> </head> <body> <!-- Navigation --> <nav class="navbar navbar-expand-lg navbar-default navbar-fixed-top"> <div class="container"> <a href="/"> <img src="{% static "img/logo.png" %}" height="30px"></a> <button class="navbar-toggler" type="button" … -
Retrieve and Manipulate media files in Django
I am making a system, where I will let users upload excel files, and then I am saving the file to the 'media' folder. I am able to do it till this stage. Next, I want to be able to read the excel file, update its values/ add new columns/ add new rows, etc and then save the file and let the user download it. I am new to Django, and not able to do it. Can anyone help Here is the code, I used for uploading the file in the 'views.py' file def index(request): context = {} if request.method == 'POST': uploaded_file = request.FILES['document'] # print(uploaded_file.size) # print(uploaded_file.name) path = settings.MEDIA_ROOT print(path) # print(uploaded_file.content_type) fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'index.html', context) -
Modelserializer related to users model
i have a model serializer which will create a post, and this post should be related to the user posting it, why this dont work ? class PostSerializer(serializers.ModelSerializer): class Meta: model = Posts fields = ('title', 'image') def create(self, validated_data): request = self.context.get('request', None) if request: user = request.user userobj=User.objects.get(username=user) post = Posts.objects.create(user=userobj, **validated_data) post.save() return user error message : AttributeError: 'User' object has no attribute 'title' -
Decoding (and equating) special characters with the Django REST framework SearchFilter?
I have implemented a Django Rest Framework SearchFilter in my backend, which for the most part works correctly. This is the code structure in views.py: class JobsViewSet(viewsets.ModelViewSet): queryset = Jobs.objects.all() serializer_class = JobSerializer filter_backends = [filters.SearchFilter] search_fields = ['^name', '^job_type'] The only remaining problem is that when sending get requests with a special character, for example the Swedish letter å, Django doesn't recognize that å is the same letter as Å only in lower case (as it does with for example a and A). In the GET calls from the front end, å gets converted to %C3%A5 for lowercase and %C3%85 for uppercase. This results in the search box not finding the jobs beginning with the letters åäö if the job title begins in uppercase (as in Återvinning). Does anyone know of a solution that makes the filter understand and equate uppercase and lowercase letters of special characters? Something along the lines of UTF-8 decoding? I have looked for answers both in the REST framework documentation and here on Stack Overflow, without any luck. New to Stack Overflow btw, I hope I'm doing the formatting correctly! -
not able to POST required data in django templates
I want to POST a form from my html to views.py in django, but I am not able do it. This is my html. This form should post the url of the downloaded image to the views.py function. {% for x in photo %} <a class="down" href="{{x.image.url}}" onclick="myfunc()" download="none">get</a> <form action="/image_info/" method="POST" id='dform'> {% csrf_token %} <input name='d_button' type="hidden" value="{{x.image.url}}"> </form> {% endfor %} This is my javascript function to submit form whenever the get link is pressed <script type="text/javascript"> function myfunc() { document.getElementById("dform").submit(); console.log('hello'); } </script> this is my views.py. This should take the image url from the form and display it in the new page. def show_image(): image_url = request.POST.get('d_button', None) return render(request, 'show_image.html', {'image': image_url) but my problem is that the form is not returning the url of the image that is clicked instead it is returning the url of first link. for example link1 link2 link3 link4 if I click on link3, it is downloading the image in link3 but POSTING the url of link1 This is a bit tricky to explain but this is the best I can. Thanks in adavnce. -
Django ORM taking long time to load
fund_df = pd.DataFrame(list(FundRolling.objects.filter(code__exact=str(code), rolling=rolling, start_date__gte=start_date, end_date__lte=end_date).values())) I have the above line of code in my views.py file. FundRolling is a model created in Django from MYSQL database. This model is having nearly 1 crore entries. This line is taking 20 seconds for execution. But I want it to reduce to milliseconds. What should I do? Thanks in advance. -
Django model field with a regex validator not working
The below model has a regex validator, however, when creating new objects (with standard model instantiation and model.objects.create() ), there is no error message given when creating an object that violates the validator. It allows the object to be saved. Below is the code for the model: class Area(models.Model): area = models.CharField(max_length=6, validators=[RegexValidator( regex='^[A-Z]{1,2}[0-9][A-Z0-9]?$', message='Area is not in correct format', code='invalid_area' )]) Any advise would be much appreciated. -
django-background-tasks not working with django-hosts
django-background-tasks package does not work when django-hosts package is configured. My background task function looks something like this: @staticmethod @background(queue="text") def sendMessage(phone_number, message): I am running this function on a specific queue. Also background task command is running too. python3 manage.py process_tasks --queue text My hosts configuration works properly. But not background tasks. When I remove hosts configuration background task function executes. -
data not pre populating in form when updating model data in DJANGO
I'm not sure what is going wrong but the data from the user is not pre populating into the form, even after following the django documentation, I'm only getting a empty form , in the url I have the correct id for the item , I have text and 2 'filefields' that i need to request into the update form and want the user to be able to update one or more of the fields , appreciate the help ? here are my views and updateform html views @login_required def music_upload(request, slug): if request.method == "POST": form = MusicForm(request.POST, request.FILES) if form.is_valid(): song = form.save(commit=False) song.artist = request.user song.track = request.FILES['track'] file_type = song.track.url.split('.')[-1] file_type = file_type.lower() if file_type not in MUSIC_FILE_TYPES: messages.error(request, f'ERROR - Track needs to be in MP3 format, Please try again!') return render(request, 'feed/music_upload.html', {'form':form}) else: song.save() messages.success(request, f'Track Uploaded') return redirect('my_profile', slug=slug) else: form = MusicForm() return render(request, 'feed/music_upload.html', {'form':form}) @login_required def edit_song(request, pk): artist = request.user.profile.user_id track = Music.objects.get(pk=pk).artist if request.method == 'POST': m_form = MusicUpdateForm(request.POST, request.FILES, instance=track) if m_form.is_valid(): m_form.save() messages.info(request, f'Your track has been updated!') return redirect('edit_track') else: m_form = MusicUpdateForm(instance=track) context ={ 'm_form': m_form, 'track': track, 'artist': artist, } return render(request, … -
Django many to many field, but display just the highest value
I want to know how I can display the highest ranking from the model education in the staff. The user would be able to select all of their educations, but for me it's irrelevant to know if the the user selected "high school" when he/she also has a master's degree. class Staff(models.Model): education = models.ManyToManyField('Education', verbose_name = 'Education') class Education(models.Model): name = models.CharField(max_length = 200, blank = False) rank = models.PositiveIntegerField(default = 0) def __str__(self): return self.name I gave every type of education a ranking. So in the Admin, the only thing I want returned would be the highest eduacation by a member of the staff - how do I write this function? class StaffAdmin(admin.ModelAdmin): list_display = ('rank') -
Error [{'error': 'NotRegistered'}] while using FCMNotification in python
I am getting the below error while running the snippet , even I tried uninstalling the app and login again, but no luck (using django REST as backend) Error msg {'multicast_ids': [5963190568359198474], 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}], 'topic_message_id': None} code def send_notification_multiple_devices(device_ids=None, data=None): push_service = FCMNotification(api_key=FIRE_BASE_KEY) result = [] for id in device_ids: try: resp = push_service.notify_single_device( registration_id=id, message_title=data["title"], message_body=data["desc"], data_message=data, extra_notification_kwargs=extra_notification_kwargs, content_available=True, ) result.append(resp) except: pass return result -
AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200)
i'm trying to test admin and getting AssertionError: 302 != 200 : Couldn't retrieve content: Response code was 302 (expected 200) even i check the solution over here but i already did the same and getting same error. My model file, admin file, and Testing file are below. admin.py from django.contrib import admin # Register your models here. from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from . import models class UserAdmin(BaseUserAdmin): ordering = ['id'] list_display = ['email', 'name'] admin.site.register(models.User, UserAdmin) tests/test_admin.py from django.test import TestCase, Client from django.contrib.auth import get_user_model from django.urls import reverse class AdminSiteTests(TestCase): def setUp(self): self.client = Client() self.admin_user = get_user_model().objects.create_user( email = 'admin@admin.com', password = 'admin' ) self.client.force_login(self.admin_user) self.user = get_user_model().objects.create_user( email = 'test@londondevapp.com', password = 'Test@123', name = 'Test 1' ) def test_user_listed(self): """Test that users are listed on user page""" url = reverse('admin:core_user_changelist') res = self.client.get(url) self.assertContains(res, self.user.name) self.assertContains(res, self.user.email) -
Not able to get image from django rest framework url
I've setup my django rest framework server in which I want to upload some news alongside their images. Actually I'm able to upload news and images because I retrieve them on my server filesystem, but when I request for a list of news I get an image url which, when pasted in my browser, shows me "The requested resource was not found on this server". Following is reported some code. models.py class News(models.Model): author = models.CharField(max_length=50) title = models.CharField(max_length=150) content = models.CharField(max_length=10000) image = models.ImageField(upload_to='news', blank=True, null=True) created = models.DateField(auto_now_add=True) def __str__(self): return "{}".format(self.title) serializers.py class NewsSerializer(serializers.ModelSerializer): class Meta: model = News fields = '__all__' settings.py MEDIA_URL = "/media/" MEDIA_ROOT = os.path.join(BASE_DIR, 'media') views.py class GetNews(generics.ListAPIView): queryset = News.objects.all() serializer_class = NewsSerializer def post(self, request): author = request.data['author'] title = request.data['title'] content = request.data['content'] try: image = request.data['image'] except KeyError: raise ParseError('Request has no resource file attached') news = News.objects.create(image=image, author=author, title=title, content=content) return Response("News successfully uploaded.", status=status.HTTP_200_OK) def delete(self, request): token = request.META.get('HTTP_AUTHORIZATION') if not check_token(token): return JsonResponse({'message': 'Unauthorized!'}, status=status.HTTP_401_UNAUTHORIZED) news = News.objects.get(id=request.data['id']) news.delete() return JsonResponse({'message': 'News was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) urls.py urlpatterns = [ ... path('news', views.GetNews.as_view()) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Django Bootstrap will not let me center this container
I have been trying to center this div container after my navbar so that there is an equal space on both sides of the page. But, it is not working for some reason. Can you guys help please? The post_job.html is the issue. The portion where i display the text is being rendered on the left side with a bit of text going down Here is my code snippet: post_job.html {% load static %} {% include 'recruiter_navigation.html' %} {% block content %} <div class="row"> <div class="col-lg-2 col-md-2 col-sm-12 col-xs-12 hidden-xs hidden-sm full_width"> <h2 style="color: darkblue;" class="text-center">Post an Internship</h2> </div> </div> {% endblock content %} recruiter_navigation.html <div class="container"> {% block content %} {% endblock content %} </div> -
Django Queryset on JSONField with nested data, whereby a dictionary key has a hyphen in the key name
I have a jsonfield called "data" that contains the following for one row, and I'm experimenting with querysets: { "id": "5cfbffb4-c03a-4905-aa3c-8ecd878f56d7", "owner": "string", "name": "some string", "short-name": "some string", "description": "some description", "sub-identifier": [{ "sub_id": "d2610379-abcc-4201-ad89-5f3ad3a4b1c2", "sub_name": "Test Dummy1", "sub-short-name": "some further name", "sub_description": "some description" }, { "sub_id": "7461b531-a181-483d-a554-ab8761c1d672", "sub_name": "Test Dummy2", "sub-short-name": "some further name", "sub_description": "some description" }] } So I can create a new query set queryset = TestModel.objects.filter(data__name='some string') this returns my queryset result correctly. However, I've noticed that if the dictionary key has a hyphen in it then it gives me an error. The following returns a syntax error: queryset = TestModel.objects.filter(data__sub-identifier__sub_id__0='d2610379-abcc-4201-ad89-5f3ad3a4b1c2') SyntaxError: expression cannot contain assignment, perhaps you meant "=="? Is there a way to tell Django to accept key names that may have a hyphen in? Or do I have to ensure that in my json data that all keys use underscores instead? Also, can I loop through each element in the list within sub-identifier to test the sub_id for a number I'm looking for. Naturally, I can do this as above using the 0, but hope there is a way to just loop through each element in the list of dictionaries … -
Is it possible to get extra value in a models.Model using django?
I would like to include some methode in the Model and was looking to get the "Supplier_Id" from an other table. class Thematic(models.Model): name = models.CharField(max_length=100, blank=True, null=True) ref = models.CharField(max_length=10, blank=True, null=True) def get_nber_of_questions(self): # count all questions in a thematic return Question.objects.filter(thema_id=self).count() def get_nber_of_answers_by_thematics(self): ### Extra value (**supplier_id**) I would like to get from the Model bellow ### return AuditSupplier.objects.filter(thematic_id=self, **supplier_id=18**).count() def __str__(self): return self.name class AuditSupplier(models.Model): supplier = models.ForeignKey(OrgaProfile, related_name='audit_supplier',on_delete=models.CASCADE) thematic = models.ForeignKey(Thematic, related_name='audit_thematic', on_delete=models.CASCADE) answer = models.IntegerField(choices=CHOICES, null=True, default=2) def __str__(self): return '{}'.format(self.supplier) Is it possible or Do I have to manage it in the view ? -
Django Channels: Web socket connection is failing in production
Locally its working fine. But when i deploy the same application in production. Its raising WebSocket connection to 'wss://example.com/ws/chat/room/list/' failed: (anonymous) @ (index):678 I checked the line 678 and code is below var ws_protocol = window.location.protocol == "https:" ? "wss:" : "ws:"; var url = ws_protocol+'//' + window.location.host +'/ws/chat/room/' +window.location.href.split("/")[4].replace("chat_","")+ '/'; var user = "User " + window.location.href.split("/")[4]$("#user").text(user) var chatSocketMsg = new WebSocket(url); Error @ line number 678 I'm suspecting the problem in deployment is Secure websocket connection. anyhow i fixed it using window.location.protocol == "https:" ? "wss:" : "ws:"; So, what else could be the problem? -
Newbie needs help understanding Docker Postgres django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres"
I am a newbie trying to follow this tutorial. https://testdriven.io/blog/dockerizing-django-with-postgres-gunicorn-and-nginx/#postgres I succeeded in building the docker containers but got this error django.db.utils.OperationalError: FATAL: password authentication failed for user "postgres". My question is why has authentication failed when the python and postgres containers env shows the correct user and password? And how can I solve the problem? I also tried poking around to find pg_hba.conf (because previous answers suggested editing it) but /etc/postgresql does not seem to exist for me. This is from my python container. # python Python 3.8.2 (default, Apr 23 2020, 14:32:57) [GCC 8.3.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> os.environ.get("SQL_ENGINE") 'django.db.backends.postgresql' >>> os.environ.get("SQL_DATABASE") 'postgres' >>> os.environ.get("SQL_USER") 'postgres' >>> os.environ.get("SQL_PASSWORD") 'password123' >>> os.environ.get("SQL_HOST") 'db' >>> os.environ.get("SQL_PORT") '5432' This is from my postgres container. / # env HOSTNAME=6715b7624eba SHLVL=1 HOME=/root PG_VERSION=13.2 TERM=xterm POSTGRES_PASSWORD=password123 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin POSTGRES_USER=postgres LANG=en_US.utf8 PG_MAJOR=13 PG_SHA256=5fd7fcd08db86f5b2aed28fcfaf9ae0aca8e9428561ac547764c2a2b0f41adfc PWD=/ POSTGRES_DB=postgres PGDATA=/var/lib/postgresql/data / # ls bin lib root tmp dev media run usr docker-entrypoint-initdb.d mnt sbin var etc opt srv home proc sys / # cd etc /etc # ls alpine-release fstab hosts issue modules-load.d opt periodic resolv.conf shadow- sysctl.d apk group init.d logrotate.d motd os-release profile securetty shells terminfo conf.d …