Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Expected Indented Block with DJANGO Rest framework
I have just started with django and I am getting the error on line 1 in models.py, I have not created a virtual environment and I have created app called wallet. from django.db import models # Create your models here. class Wallet(models.Model): raddress = models.CharField(max_length=100, blank=False) //Expected Indented Block here Error balance = models.TextField(max_length=50) sent = models.TextField(max_length=50) received = models.TextField(max_length=50) def __str__(self): self.raddress self.balance self.sent self.received Also when I put my app in name in the installed apps under settings INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', /// 'wallets', I am trying to put it here ] It gives me an error saying ModuleNotFoundError: No module named 'rest_frameworkwallet' It just concatinates the two? -
<django.db.models.query_utils.DeferredAttribute object at 0x0000021299297100> SHOWING INSIDE INPUT FIELDS for updating an Todo task
Hy, I am trying to solve an issue, I am new to Django and while doing a project I am getting <django.db.models.query_utils.DeferredAttribute object at 0x0000021299297100> inside the input fields. The function is for updating existing data and inside that its shows models. query instead of the actual values. HTML input fields HTML CODE THIS IS MY views: Views.py THIS IS MY forms.py forms.py THIS IS MY models.py models.py Please let me know where is the issue coming from. Thanks. -
How to fix url 404 issue in Django? Help needed
I hope anyone can help me with this. I am trying to build an Ecommerce website for myself. I used this [tutorial] and followed all it's steps. The issue is that in browser whenever I don't add '/' after the admin in 'http://127.0.0.1:8000/admin' it give's me this error: 404 Error Image Settings.py: # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_URl = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') urls.py: (project urls) from xml.dom.minidom import Document from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('store.urls')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urls.py: (app urls) from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('store/', views.store, name="store"), path('cart/', views.cart, name="cart"), path('checkout/', views.checkout, name="checkout"), path('update_item/', views.updateItem, name="update_item"), path('process_order/', views.processOrder, name="process_order"), ] This is same for all of the urls defined in the apps urls.py. If I put manually '/' it works just fine. I will be thankful for guidance and help. I have tried searching, reading docs and just figuring out just nothing has came up. Hope anyone here will shed some knowledge on it. And Yes! … -
IntegrityError at /merchant_create
UNIQUE constraint failed: f_shop_customuser.username Request Method: POST Request URL: http://127.0.0.1:8000/merchant_create Django Version: 3.2.8 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: f_shop_customuser.username Exception Location: C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\django\db\backends\sqlite3\base.py, line 423, in execute Python Executable: C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\python.exe Python Version: 3.9.10 Python Path: ['F:\Git\Client Git\f_worldSHop', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\python39.zip', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\DLLs', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib', 'C:\Users\ibsof\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\win32', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\win32\lib', 'C:\Users\ibsof\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\Pythonwin', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0', 'C:\Program ' 'Files\WindowsApps\PythonSoftwareFoundation.Python.3.9_3.9.2800.0_x64__qbz5n2kfra8p0\lib\site-packages'] Server time: Fri, 18 Feb 2022 17:29:24 +0000 -
Django Form - Override standard validation message from within custom validator function
In my forms.py file, I have a custom validation function that I pass to the EmailField's validators attribute. However, when I test this in browser, I get BOTH the standard error message AND my custom message. How do I hide the standard message and just display my custom message? browser form behavior: Email: bademail123 # Enter a valid email address. <-- default validation error # Email does not match expected format: example@email.com <-- my custom validation error msg forms.py # VALIDATORS FOR FORM FIELDS def clean_email(email): if not re.match("\S+@\S+\.\S+", email): raise forms.ValidationError( "Email does not match expected format: example@email.com" ) class IntakeFormSimple(Form): email = forms.EmailField( label="Email", widget=forms.TextInput(attrs={"placeholder": "example@email.com"}), validators=[clean_email], ) -
DRF APIClient Delete data arrives in request.data, not request.query_params
I use DRF's APIClient to write automated tests. And while is was writing the first delete test, I found it very strange that the data passed through arrived in request.data, while if I use Axios or Postman, it always arrives in request.query_params. Any explanation as to why this is, and preferably a method to use APIClient.Delete while the data arrives in query_params would be great! My test: import pytest from rest_framework.test import APIClient @pytest.fixture() def client(): client = APIClient() client.force_authenticate() yield client class TestDelete: def test_delete(client): response = client.delete('/comment', data={'team': 0, 'id': 54}) And my views from rest_framework.views import APIView class Comments(APIView): def delete(self, request): print(request.query_params, request.data) >>> <QueryDict: {}> <QueryDict: {'team': ['0'], 'id': ['54']}> Looked into DRF's APIClient. Feeding towards params doesn't seem to help. The delete method doesn't seem to have direct arguments that could help as well. So I'm a bit stuck. -
I am not getting expected result when I am multiplying price with quantity
I am working on a billing application. When I need to generate a bill, I open the CREATE form and I enter the quantity and price of two items. The quantity, price and total of both the items are stored in the django. suppose i want to change the quantity in Bill then i have made a similar form i call edit form. So when I edit the quantity and price of both the items in the edit form, then the first item's multiplication is getting correct but the second item's multiplication is getting wrong. You can see the problem in the rectangular box error Image <script> var item = {{itemid}}; var itemname = "{{itemname|escapejs}}"; services = itemname.replaceAll("'",'"') a =JSON.parse(services) itemid_list = '<option value="">Select Item</option>'; console.log((a)) console.log((a.length)) for(var x=0; x<item.length; x++){ itemid_list = itemid_list+ "<option value='"+item[x]+"'>"+a[x]+"</option>" } console.log(itemid_list) const maxPoints = 5; let count = 1; // Adds new point const deleteThisPoint = (target) => { target.parentNode.remove(); var sum = 0; $('input.extended_total').each(function() { var num = parseInt(this.value, 10); if (!isNaN(num)) { sum += num; } }); $("#totalcount").text(String(sum)); }; const addNewPoint = (target) => { const parentContainer = target.parentNode.parentNode; const addIn = parentContainer.querySelector('.multiple-points'); const childCounts = addIn.childElementCount; if(childCounts > maxPoints - … -
How to update post in Django with out using Django forms
I want to update a post in Django, but I don't want to use Django forms for this is there any way to do that. -
Python -Django - send rest request get http client get error - TypeError: expected string or bytes-like object
I create a Django App and send rest http request to Plaid. if I start up django alone(python manage.py run server), it works fine. But if I use Nginx + Gunicorn + Django, I will get error. The error message is: File "/var/www/sp_plaid/api/views.py", line 91, in create_link_token response = client.link_token_create(p_request) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 769, in __call__ return self.callable(self, *args, **kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api/plaid_api.py", line 6863, in __link_token_create return self.call_with_http_info(**kwargs) File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 831, in call_with_http_info return self.api_client.call_api( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 406, in call_api return self.__call_api(resource_path, method, File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 193, in __call_api response_data = self.request( File "/usr/local/lib/python3.9/dist-packages/plaid/api_client.py", line 452, in request return self.rest_client.POST(url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 264, in POST return self.request("POST", url, File "/usr/local/lib/python3.9/dist-packages/plaid/rest.py", line 150, in request r = self.pool_manager.request( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 78, in request return self.request_encode_body( File "/usr/lib/python3/dist-packages/urllib3/request.py", line 170, in request_encode_body return self.urlopen(method, url, **extra_kw) File "/usr/lib/python3/dist-packages/urllib3/poolmanager.py", line 375, in urlopen response = conn.urlopen(method, u.request_uri, **kw) File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 699, in urlopen httplib_response = self._make_request( File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 394, in _make_request conn.request(method, url, **httplib_request_kw) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 234, in request super(HTTPConnection, self).request(method, url, body=body, headers=headers) File "/usr/lib/python3.9/http/client.py", line 1279, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.9/http/client.py", line 1320, in _send_request self.putheader(hdr, value) File "/usr/lib/python3/dist-packages/urllib3/connection.py", line … -
IntegrityError FOREIGN KEY constraint failed - Django custom user model
I am new to creating custom user models in Django, so bear with me. My problem is that I get a IntegrityError at /admin/accounts/customuser/add/ FOREIGN KEY constraint failed when I delete a user in Django admin. This also happens when I try to add a user in Django admin. Code models.py from django.contrib.auth.models import AbstractUser, BaseUserManager from django.db import models from django.utils.translation import gettext_lazy as _ class UserManager(BaseUserManager): def _create_user(self, email, password, **kwargs): if not email: raise ValueError("Email is required") email = self.normalize_email(email) user = self.model(email=email, **kwargs) user.set_password(password) user.save() return user def create_user(self, email, password=None, **extra_fields): """Create and save a regular User with the given email and password.""" extra_fields.setdefault('is_staff', False) extra_fields.setdefault('is_superuser', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **kwargs): kwargs.setdefault('is_staff', True) kwargs.setdefault('is_superuser', True) kwargs.setdefault('is_active', True) if kwargs.get('is_staff') is not True: raise ValueError("Superuser must have is_staff True") if kwargs.get('is_superuser') is not True: raise ValueError("Superuser must have is_superuser True") return self._create_user(email, password, **kwargs) class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, null=True, blank=True) verification_code_time = models.IntegerField(_('time left for session id'), null=True, blank=True) … -
Group name not taking spaces django-channels
I am working on a chat app with django channels, everthing is working but messages don't get send when room name has spaces or other special carachter, ideally I'd like to be possible to the user to have spaces in their room name. /* consumers.py: 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 # Join room await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from web socket async def receive(self, text_data): data = json.loads(text_data) message = data['message'] username = data['username'] room = data['room'] await self.save_message(username, room, message) # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'chat_message', 'message': message, 'username': username } ) async def chat_message(self, event): message = event['message'] username = event['username'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message, 'username': username, 'timestamp': timezone.now().isoformat() })) @sync_to_async def save_message(self, username, room, message): if len(message) > 0: Message.objects.create(username=username, room=room, content=message) routing.py: websocket_urlpatterns = [ path('ws/<str:room_name>/', consumers.ChatConsumer.as_asgi()), ] urls.py: urlpatterns = [ path('', views.index, name='index'), path('<str:room_name>/', views.room, name='room'), ] index.html: <script> document.querySelector('#room-name-input').focus(); document.querySelector("#room-name-input, #username-input").onkeyup = function(e) { if (e.keyCode === 13) { document.querySelector('#room-name-submit').click(); } }; document.querySelector('#room-name-submit').onclick = function(e) { var … -
AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint'
Sys: Windows 11 Prof; Python v3.9.7 I've tried to install Wagtail Colour Picker but I got this error message back. Do I need to install or remove something? Please Help ! models.UniqueConstraint(fields=['page'], condition=Q(status__in=('in_progress', 'needs_changes')), name='unique_in_progress_workflow') AttributeError: module 'django.db.models' has no attribute 'UniqueConstraint' -
Is there a method to create a Django token for user objects with no last_login timestamp?
I have a Django app that contains advertisement recipients with no login timestamps (since they do not need to have an account anyways), is there a method to customize the Django default token generator to exclude the timestamp requirement? -
Strange behaviour when rendering X-Axis ticks
I'm rendering a chart with matplotlib through panda's df.plot() method, but somehow the tick labels on the X-Axis seem to be messed up. There seems to be a layer of numeric text above my "real" tick labels. I have no idea where this comes from. Strangely enough, this only happens in our production and staging environment, not in dev. Maybe it also has to do with gunicorn or django's dev server. Has somebody made this experience before? Here's the plot result: and this is the output when I clear the ticks with .set_xticks([], []): Here's a portion of my code, there's some abstraction but I think it should be understandable. self.data is a pandas dataframe. It outputs base64-encoded png data: class Line(ChartElement): def draw(self): self._plot = self.data.plot(kind='line', color=self.colors) self._rotation = 'vertical' self._horizontalalignment='center' # self._plot.set_xticks([], []) # ... class ChartElement(): # ... def base64(self): self.draw() figfile = BytesIO() if not self._plot: raise ValueError("Plot not generated.") if self._legend: self._plot.legend(self._legend, **self._legend_args) #plt.legend(self._legend, loc='upper center', bbox_to_anchor=(0.4, .05), ncol=5, fancybox=False, prop={'size': 6}) plt.setp(self._plot.get_xticklabels(), rotation=self._rotation, horizontalalignment=self._horizontalalignment, fontsize=8) self._plot.set_ylabel(self.y_title) self._plot.set_xlabel(self.x_title) #plt.figure() fig = self._plot.get_figure() fig.autofmt_xdate() if self.size and isinstance(self.size, list): fig.set_size_inches(inch(self.size[0]), inch(self.size[1])) fig.savefig(figfile, format='png', bbox_inches='tight') figfile.seek(0) figdata_png = base64.b64encode(figfile.getvalue()) plt.clf() plt.cla() plt.close('all') plt.close() return figdata_png.decode('utf8') -
dictsort or dictsortreverse doesn't work second time in same template of Django, How can I do that?
Here is my template code in template.html file {% for obj in dictionary|dictsort:"name" %} do something {%endfor%} {% for obj in dictionary|dictsort:"age" %} do other thing {%endfor%} but in second iteration there is nothing hapening, on the first iteration everything is ok. -
How to achieve this type of API in Django rest framework
I am new to the Django rest framework and I am wanting to acheive this kind of API: { question_no: "1", question: "How many sides are equal in a scalene triangle?", options: [ { que_options: "3", selected: false, isCorrect: true }, { que_options: "2", selected: false, isCorrect: true }, { que_options: "0", selected: false, isCorrect: true }, ], }, How can I achieve the above type of API? I have tried to make make it work with the following code but it doesn't work: from django.db import models # Create your models here. class AnswerOptions(models.Model): option= models.CharField(max_length=500) isCorrect = models.BooleanField(default=False) class Quiz(models.Model): question = models.TextField() options = models.ManyToManyField(AnswerOptions) -
Django PDF parser on POST request
I hope for your help. Because I have been struggling with this problem for a long time. A POST request comes from the frontend with one PDF file, after which I need to take a screenshot of the first page and extract its metadata and save it all in the database. at the moment I have overridden the POST method and am intercepting the JSON which contains the PDF. I pass this file to my parsing function. But other than the file name, the function cannot find the file. What could be the problem? view import fitz as fitz from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response from rest_framework import status from .serializers import FileSerializer def parce_pdf(test): doc = fitz.open(test) # open document pixel = doc[0] # page pdf pix = pixel.get_pixmap() # render page to an image pix.save("media/page.png") # store image as a PNG print(doc.metadata) class FileView(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = FileSerializer(data=request.data) # test = request.data['file'].content_type test = request.data['file'] # print(request.data.get) print(test) print(request.accepted_media_type) parce_pdf(test) print(file_serializer) # print(test) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) serializer from rest_framework import serializers from .models import File class … -
Django admin wont let me log in with a custom user model
I've done a custom user model and when I try to log in to django admin it says "Please enter the correct email address and password for a staff account. Note that both fields may be case-sensitive.". I've tried creating a superuser using python manage.py createsuperuser but it returns: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 61, in execute return super().execute(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\dyfri\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 156, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) TypeError: create_superuser() missing 1 required positional argument: 'username' I've tried creating a user through CustomUser.objects.create(email=email, ...) I've tried checking if it is a staff, superuser and active. All of these returned True. Code Models.py from django.contrib.auth.models import AbstractUser from django.db import models from django.utils.translation import gettext_lazy as _ class CustomUser(AbstractUser): username = None first_name = None last_name = None email = models.EmailField(_('email address'), blank=False, null=False, unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] full_name = models.CharField(_('full name'), max_length=1000, null=True, blank=True) user_id = models.CharField(_('session id'), max_length=10000, … -
Why Inline elements are disappearing when I use a filter through the get_queryset() in model.Admin?
I have a problem with Inline elements disappearing. It is linked to my overriding of get_queryset. I don't understand the mechanism which is behind. Any help would be great. I have two models like this : class Aventure(models.Model): title = models.CharField(max_length=30) sub_title = models.CharField(max_length=100) author = models.ForeignKey(User, on_delete=models.CASCADE) archive = models.BooleanField(default=False) def __str__(self): return self.title class Scene(models.Model): title = models.CharField(max_length=30) description = models.TextField() aventure = models.ForeignKey(Aventure, on_delete=models.CASCADE) author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title And two model.Admins like this : class AventureAdmin(admin.ModelAdmin): readonly_fields = ('author',) list_display = ('title', 'author',) inlines = [ SceneInline, ] # allow to save the logged in user to be set has the author def save_model(self, request, obj, form, change): # dans le cas où l’utilisateur n’est pas renseigné if getattr(obj, 'author', None) is None: obj.author = request.user obj.save() # Allow to show only the 'Aventure' instances where the author is the logged in user. def get_queryset(self, request): qs = super().get_queryset(request) print(qs) if request.user.is_superuser: return qs return qs.filter(author=request.user) class SceneInline(admin.TabularInline): list_display = ('title', 'author',) model = Scene show_change_link = True extra = 0 fields = ('title', 'author') And when the queryset is filtered on the author (means I am not superuser), the inline scene elements … -
How can we check on every login using stripe, Is payment of that specific user is successful?
How can we check on every login using stripe in DJANGO, Is payment of that specific user is successful? Because you know sometimes the payment is disrupted by the client or it may get unsuccessful after some time of successful payment of some reasons? -
Django - Wagtail: How to add classes to generated HTML elements from RichTextField
Using Wagtail 2.16.1, I have a BlogPage model that contains a body field which is a RichTextField. When I put {{ page.body|richtext }} into the template, the HTML that is rendered contains various html elements, as expected. I'd like to specify (tailwind) classes for these elements. E.g. every <p> element in a richtextfield should have <p class="mx-2 my-3">, h2 elements should have <h2 class="mt-5">, etc. -
Cannot add Django range filter to template
I am trying to get working the range-slider code from https://hackernoon.com/django-tutorial-creating-a-range-slider-filter-tt28359e I have got as far as creating views, models, templates adding some data to the Peoples model and displaying it. The code that works correctly displays the data from People model in a simple table. However, I cannot get the filter working. I have had to change some names in the sample code because of name conflicts with pre-existing items in my existing Django application. The first set of code works to display all the records from the model Peoples: #views.py from .models import People from .filters import PeopleFilter def Peopleindex(request): # display all the records from the People model/table all_people = People.objects.all() return render(request, 'pollapp2/Peopleindex.html', {'all_people':all_people}) template: <table border='1' style="width:50%; text-align:center"> <thead> <tr> <th> Name </th> <th> Surname </th> <th> Age </th> </tr> </thead> <tbody> {% for person in all_people %} <!-- for person in all_people --> <!-- for person in people_filter.qs --> <tr> <td> {{ person.name }} </td> <td> {{ person.surname }} </td> <td> {{ person.age }} </td> </tr> {% endfor %} </tbody> </table> The above correctly displays in an HTML table, all records from the Peoples model. Then when I try to modify the code to … -
Django multi-domain view set up / Django Sites. help needed
I'm trying to understand how to set up a Multisite codebase with Django (no external addons like Wagtail). I created several dummy domains and registered them on etc/hosts "example.com", "example2.com". They now both respond as if it's "localhost". I'm trying to find a way to make them go to different pages/views according to their different domains. I went through https://docs.djangoproject.com/en/4.0/ref/contrib/sites/ Sites documentation and am still stuck. The view that I'm trying to make work is this: def my_view(request): # current_site = request.get_host current_site = Site.objects.get_current() if current_site.domain == 'example2.com': html = "<html><body>Hello World at Example2 two</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass elif current_site.domain == 'example.com': html = "<html><body>Hello World at Example1 one</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass else: html = "<html><body>Hello World</body></html> " + "current_site.domain=" + current_site.domain Site.objects.clear_cache() return HttpResponse(html) pass I also tried changing the domain like below(It was done within a python shell within a pipenv shell), however it doesn't change it automatically by the domain address and will set it permanently to whichever one I saved: ((django-todo-react) ) ➜ backend git:(master) ✗ ./manage.py shell Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24) [Clang 6.0 (clang-600.0.57)] on darwin Type "help", "copyright", … -
What are the risk for Secret KEy in Django?
I have a question regarding Django and Secret Key. Unfortunately, I've did a commit to a public repositary with secret key visible. Then I got a message: GitGuardian has detected the following Django Secret Key exposed within your GitHub account. I then immediatelly deleted this repo from my github but still worried if something can happen to me. The app was just hello world on my localserver. I red some articles that it is very dangerous but I am not sure if someone can hack me by this. Can you advise? Thanks. -
Django-Reactjs : No Access-Control-Allow-Origin header is present on the requested resource
I'm trying to load an image from an image url and try to crop that image. Access to image at 'https://example.com/image.png' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I'm using React and Django. app.js import { useState,useCallback,useRef, useEffect} from 'react'; import React, { Component } from "react"; import ReactCrop from "react-image-crop"; import 'react-image-crop/dist/ReactCrop.css' function App() { const [crop, setCrop] = useState({ aspect: 1.7777777777777777, height: 84.92083740234375, unit: "px", width: 325.97037760416663, x: 0, y: 140.07916259765625} ); function onImageLoad() { const image = new Image(); image.src = "https://example.com/image.png"; image.crossOrigin = "Anonymous"; const canvas = document.createElement('canvas'); const scaleX = image.naturalWidth / image.width; const scaleY = image.naturalHeight / image.height; const ctx = canvas.getContext('2d'); const pixelRatio = window.devicePixelRatio; canvas.width = crop.width * pixelRatio * scaleX; canvas.height = crop.height * pixelRatio * scaleY; ctx.setTransform(pixelRatio, 0, 0, pixelRatio, 0, 0); ctx.imageSmoothingQuality = 'high'; image.onload = function() { ctx.drawImage( image, crop.x * scaleX, crop.y * scaleY, crop.width * scaleX, crop.height * scaleY, 0, 0, crop.width * scaleX, crop.height * scaleY ); } const base64Image = canvas.toDataURL("image/jpeg", 1); setResult(base64Image); console.log(result); } useEffect(() => { onImageLoad(); }, []); return ( { result && <div> <h2>Cropped Image</h2> <img alt="Cropped Image" src={result} …