Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My Html Table footer doesn't render correctly
I'm trying to create a simple table. I would like a footer with only one cell but I don't know why it's divided in two. Any idea? <table class="table-cart-view-producer"> <thead> <tr> <th>Produit</th> <th>Quantité</th> <th>Prix</th> </tr> </thead> <tfoot> <tr> <th> Prix Total du Panier : <strong>{{cart_price}}€</strong></th> </tr> </tfoot> <tbody> {% for item in cartitems %} <tr> <td>{{item.stock_item.product_stockitem.name}}</td> <td>{{item.quantity}} {{item.stock_item.product_stockitem.unit}}</td> <td>{{item.get_total_price}}€</td> </tr> {% endfor %} </tbody> </table> It renders this way: -
Celery Django: Resource temporarily unavailable: 'celerybeat-schedule'
Have some problems with setting celery a schedule Trying to create celerybeat-schedule with command: "celery -A my_app beat -l info" It has infinity starting msg: LocalTime -> 2023-01-30 14:36:49 Configuration -> . broker -> amqp://guest:**@192.168.101.36:5672// . loader -> celery.loaders.app.AppLoader . scheduler -> celery.beat.PersistentScheduler . db -> celerybeat-schedule . logfile -> [stderr]@%INFO . maxinterval -> 5.00 minutes (300s) [2023-01-30 14:36:49,493: INFO/MainProcess] beat: Starting... When im trying to call command: "celery -A my_app beat" I got an error: [2023-01-30 14:36:37,316: ERROR/MainProcess] Removing corrupted schedule file 'celerybeat-schedule': error(11, 'Resource temporarily unavailable') Traceback (most recent call last): File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 533, in setup_schedule self._store = self._open_schedule() File "/home/knefedov/PycharmProjects/unica_b2b_1/venv/lib/python3.10/site-packages/celery/beat.py", line 523, in _open_schedule return self.persistence.open(self.schedule_filename, writeback=True) File "/usr/lib/python3.10/shelve.py", line 243, in open return DbfilenameShelf(filename, flag, protocol, writeback) File "/usr/lib/python3.10/shelve.py", line 227, in __init__ Shelf.__init__(self, dbm.open(filename, flag), protocol, writeback) File "/usr/lib/python3.10/dbm/__init__.py", line 95, in open return mod.open(file, flag, mode) _gdbm.error: [Errno 11] Resource temporarily unavailable: 'celerybeat-schedule' celery.py import os from celery import Celery from django.conf import settings from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_app.settings') app = Celery('unica_b2b', broker_url='some_ip') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) app.conf.beat_schedule = { 'add-update-every-5-minutes': { 'task': 'authentication.tasks.create_counter_party', 'schedule': 300.0, 'args': (16, 16) }, } app.conf.timezone = 'UTC' -
Django - Problem with Model Manager - Query
I'm still a beginner and I'm stuck in a challenging spot for me. I can't get data from a foreign key table to be inserted "correctly" into a column of a ListView. I basically want to create a list view of a table (FeatureFilm). This also works. But in one column I get information from another table and here I get data, but not the one that belongs to the particular table row. Here are my models. The table I want to show is "FeatureFilm" model. This model is inherited from my base Project class "ProjectBaseModel". Then there is another table "CompanyInvolved Model". This is attached to the FeatureFilm table with a foreign key (feature_id). So movies are stored (FeatureFilm) and different companies are involved in the creation process of the movies. (CompanyInvolved) class ProjectBaseModel(models.Model): title = models.CharField("Titel", max_length=100, blank=False, unique=True) leading_postproduction_id = models.ForeignKey( Company, verbose_name="Federführende Postproduktion", on_delete=models.SET_NULL, blank=True, null=True, ) phase = models.CharField(choices=post_phase, max_length=30, blank=True, null=True) former_title = models.CharField("Titel, ehemalig", max_length=100, blank=True) title_international = models.CharField( "Titel, international", max_length=100, blank=True, null=True, unique=True ) class FeatureFilm(ProjectBaseModel): class Meta: verbose_name = "Kinofilm" verbose_name_plural = "Kinofilme" ordering = ["title"] class ProductionManager(models.Manager): def get_production(self): return ( super() .get_queryset() .filter(company_role="Produktion", is_production_list=True) .values_list("company_involved__name") ) class CompanyInvolved(models.Model): … -
make mutualTLS between microservices (Django, Fastapi)
I have microservices on Django and FastAPI. I want to make mutualTLS between these services. When I send request from Django project to FastApi project for payment (need to check certificate in FastApi project from Django project) and then FastApi project send request for notify about success or not payment to Django project (need to check certificate in Django project from FastApi project). Like this :) I've tried a lot to implement MutualTLS between Django and FastAPI. -
Bundle django postgres nginx gunicorn docker in real projects [closed]
подскажите пж-ста как в реальных проектах используют связку django postgres nginx gunicorn docker? Т.е, к примеру, БД устанавливают на один сервер и к ней подключаются (мб тоже в докер контейнер устанавливают), nginx в докер, gunicorn тоже в докер, все отдельно, в потом как то связывают или как то иначе... -
Django Model Formset from ManyToMany not accepting queryset
I have my model called Game that has a ManyToMany field consoles = models.ManyToManyField('Console', through='GameConsole') That ManyToMany has some additional attributes class GameConsole(models.Model): game = models.ForeignKey(Game, on_delete=models.CASCADE) console = models.ForeignKey(Console, on_delete=models.CASCADE) released = models.DateTimeField exclusive = models.BooleanField(default=False) I have a page where I want to create/edit those relations. #forms.py class GameConsoleForm(ModelForm): class Meta: model = GameConsole fields = ['console', 'released', 'exclusive'] #to prevent the submission of consoles with the same id (taken from django topics forms formsets) class BaseGameConsoleFormSet(BaseFormSet): def clean(self): """Checks that no two alias have the same name.""" if any(self.errors): # Don't bother validating the formset unless each form is valid on its own return console_ids = [] for form in self.forms: if self.can_delete and self._should_delete_form(form): continue console= form.cleaned_data.get('console') if console in console_ids: raise ValidationError("Consoles in a set must be different.") console_ids.append(console) NewGameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=1, can_delete=True) GameConsoleFormSet = modelformset_factory(GameConsole, form=GameConsoleForm, formset=BaseGameConsoleFormSet, extra=0, can_delete=True) The creation of multiple GameConsole's works fine. The problem is on the edition. On the views, when I do the following: formset = GameConsoleFormSet(queryset = game_consoles) I get the following error __init__() got an unexpected keyword argument 'queryset' which is strange, since I already used this logic with another model (normal table, … -
Django Rest Framework - Why is serializer.data giving me an empty result set but printing the serializer shows me the data
I have created a view to search posts based on their body text. I added a breakpoint to the view and I tested it with mutliple search terms and it works. The problem I have is when I do a print(serializer) in the console then I see the data of all the posts it found. But doing a print(serializer.data) gives me body:null in the data object in the front end console and an empty dictionary in the back end console. Why am I getting body: null? Here is the response in the console for print(serializer): SearchSerializer(<QuerySet [<Post: This is a post>, <Post: This is another post>, <Post: Post THREE>, <Post: Post ONE>, <Post: Post ONE by the user>, <Post: Post TWO by the user>]>): body = CharField(allow_blank=True, allow_null=True, label='Content', max_length=5000, required=False, style={'base_template': 'textarea.html'}) Here is the view: class SearchPosts(APIView): permission_classes = [IsAuthenticated] def post(self, request, *args, **kwargs): term = request.data.get("term") posts = Post.objects.filter(body__search=term) serializer = SearchSerializer(posts) breakpoint() return Response(serializer.data, status=HTTP_200_OK) Here is the serializer: class SearchSerializer(serializers.ModelSerializer): class Meta: model = Post fields = [ 'body' ] Here is the post model: class Post(models.Model): body = models.TextField("content", blank=True, null=True, max_length=5000) slug = AutoSlugField(populate_from=["category", "created_at"]) user = models.ForeignKey( User, on_delete=models.CASCADE, related_name="posts") published … -
Django URL dispatcher - Try next view
Alright, let me give you guys an example; We have the following url configuration in Django. Django will try to match the url with the rules down below. Once it finds a match, it will use the appropriate view and lookup the object in the model. The thing is, once it finds a match in the URL pattern, it will match the view. But once the object in the view can't be found, it will return a page not found (404) error. #urls.py from django.urls import path from . import views urlpatterns = [ path('articles/<slug:category>/<slug:editor>/', views.articles_by_editor), path('articles/<slug:category>/<slug:theme>/', views.articles_by_theme) ] We have the following url patterns, we can sort articles either by the editor or by theme. We do this to create a logical url structure for SEO purposes. Is their any way we can redirect to another view once the object isn't found? Can we modify the dispatch method to return to the url patterns and find the following matching rule? Your help will be much appriciated. Kevin -
Django, Choices to Serilize
I have choices like this in my choices.py MATH_CHOICES_TYPE = ( ('1', 'test1'), ('2', 'teste2'), ('3', 'test3'), ('4','test4') ) I want to get result like this as json from APIVIEW using get method Is there any solution? Thanks { "MATH_CHOICES_TYPE": [ { "value": "1", "display_name": "test1" }, { "value": "2", "display_name": "test2" }, { "value": "3", "display_name": "test3" }, { "value": "4", "display_name": "test4" } ] } -
how to convert a range of dates to fill in for a drop down list in django
Trade(models.Model): user_id = models.CharField(max_length=5, null=True, blank=True) nse_index = models.ForeignKey('NseIndex', on_delete=models.CASCADE) trade_expiry = models.DateField(default=THURSDAYS[0], choices=THURSDAYS) trade_type = models.CharField(max_length=25, choices=TRADE_TYPE, default="paper") id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) I need to display the trade_expiry(all thursdays in a year) as a tuple to be displayed as a dropdown list on a form using django pls help -
How can I get return value from A class to class B in python?
class InputForm(forms.Form):ㅤ attachment = forms.FileField() class View1(FormView): template_name = 'main.html' form_class = InputForm def post(self, request) : I_want_this_file = request.FILES.get('attachment') return I_want_this_file class View2: blar blar ..... When there's this structure, Is there any way to get the value of I_want_this_file from a class called View2? I understand that I have to hand over the parameters to get the return value. But I couldn't bring it because of the "request". When a user uploads a file from a template called main.html, I want to take the file itself, put it in the return value I_want_this_file, and bring the file itself to View2. I have to bring that, but it's not my personal project, so there's no other way to add a file field than this. I'd appreciate it if you could help me. -
missing "Meta.model" attribute i can't find the solution
i'am statring create my rest Api with django restapi but my problem is when i create my meta class he show me this error i don't know why Class SoundSerializer missing "Meta.model" attribute and this is my code ` from rest_framework import serializers from sounds.models import Sound class SoundSerializer(serializers.ModelSerializer): class Meta: Model = Sound fields = '__all__'` from django.urls import path from sounds.api.views import SoundList urlpatterns = [ path('list/',SoundList.as_view() , name ='list'), #path('<int:pk>',sounds_names, name='name1'), ] from rest_framework.response import Response from sounds.api.serializers import SoundSerializer from sounds.models import Sound from rest_framework.views import APIView from rest_framework.decorators import api_view # Create your views here. class SoundList(APIView): def get(self,request): sounds =Sound.objects.all() serializer= SoundSerializer(sounds,many=True) return Response(serializer.data) def post(self, request): serializer=SoundSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) please help me i don't know the problem where is it -
How to detect the Android foldable/flip phone in Djagno
My project displays templates separately from PC/tablet and mobile. views.py ... from django_user_agents.utils import get_user_agent ... class indexView(View): def get(self, request, *args, **kwargs): ... user = get_user_agent(request) if user.is_pc or user.is_tablet: template_name = 'web/index.html' # for PC and Tablet else : template_name = 'mobile/index.html' # for Mobile ... However, Galaxy z fold 4 is recognized as tablet when folded and opened in the Chrome browser. In Samsung's basic browser, when folded, it is displayed as a mobile template. When I checked the userAgent, it included "Safari" instead of "Mobile Safari" in the Chrome browser. Mozilla/5.0 (Linux; Android 13; SM-F936N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36 When the foldable phone is folded, I want to display it as a mobile template on the cover screen in the Chrome browser. Is there a way to detect a foldable phone in Django? Or if you have another good idea, please recommend it :) -
useing logging.getLogger(__name__) in django where can i define logger path
I'm using logger = logging.getLogger(name) where can I define logger path in django. logger.warning("Batch files not found.") logger.error('error1') I want to know the log file path and how will create that path? -
expected str, bytes or os.PathLike object, not BoundField in instaapi
I was trying to post a picture in instagram, I have picture url, caption, instagram username and password in 3 different model, I'm sending primary key of the models in response. class InstagramPost(APIView): @staticmethod def post(request, user_id, pk, attachment_id, *args, **kwargs): user_name = get_user_name(user_id) caption = get_post(pk) url = get_attachment(attachment_id) bot = Bot() bot.login(username=user_name['name'], password=user_name['password'], is_threaded=True) print(user_name['name']) print(user_name['password']) bot.upload_photo(url[r'url'], caption=caption['caption']) print(url['url']) print(caption['caption']) return HttpResponse("posted") -
ReactJs Url is changing on its own on api call
I am hitting an api using my ReactJs application. My code is as follows export const getCustomers = (filters) => { return createAction({ type: GET__CUSTOMERS, action: async () => await axios.get(`${BASE_URL}/customers${filters}`, { data: {}, headers: HEADERS.AUTHENTIC(), }), }); }; In the above code, we can see that in the url -> '${BASE_URL}/customers$' , 'customers' is hard coded, but whenever I am running it actually, it hits the as 'Customers'. The case of c changes on its own. It is nowhere in my application. The same problem is with other routes as well. What can be the possible issue and solutions? I hard coded the api to find the issue but it persists. -
How to access request object of django in react?
I have multiple apps in my Django project but for One app I would like to use react, so I have create two apps one for apis and other for frontend. I used webpack to merge django and react. Now I want to access request.user and user.is_authenticated in my components. How can I access those without calling apis as I am not using token-based authentication so I can not call APIs. views.py def index(request): return render(request,'index.html') urls.py urlpatterns = [ re_path(r'^(?:.*)/?$',index), ] I would like to use is_authenticated in my sidebar everywhere. -
DRF, get foreignkey objects using option
i'm trying to make backend using DRF, and i just faced a problem This is models class SchoolYear(models.Model): title = models.CharField(max_length=255, unique=True) class Student(models.Model): name = models.CharField(max_length=10) school_year = models.ForeignKey( "students.SchoolYear", related_name="school_year", on_delete=models.CASCADE, ) class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' Result from POSTMAN when using the option. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": { "type": "field", "required": true, "read_only": false, } } } } But I want to get a result like this. Because I have to deliver this to the front-end developer to make select form I'd like to use this method, so I'd appreciate it if you could let me know if there's any other good method. Thanks. { "name": "Student Signup", "description": "", "renders": [ "application/json", "text/html" ], "parses": [ "application/json", "application/x-www-form-urlencoded", "multipart/form-data" ], "actions": { "POST": { "name": { "type": "string", "required": true, "read_only": false, }, "school_year": [ { "id" : 1, "title": "title1", }, { "id" : 2, "title": "title2", }, { "id" : 3, "title": "title3", }, { "id" : 4, "title": "title4", } ] … -
change color of button after click
I have a question with four answers and I want the button to flash green when the correct answer is selected and red when the wrong answer is selected. How can I do that? i want to solve this problem with django and not with javascript. html {% for q in questions %} {% if q.kategorie == category and q.flaag == True %} {% if questions.has_next %} <br/> <div class="flex-container"> <div class="container1"> <div class="position_startButton"><button type="submit" name="next" value="{{q.question}}" class="nächstefrage_btn">Nächste Frage!</button></div> <div class="game_options_top"> <div class="option"> <p><button class="option_btn" name="next" value="{{erste_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">A: <span id="option_span">{{erste_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" [ngClass] = value="{{zweite_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">B: <span id="option_span">{{zweite_frage}}</span></button></p> </div> </div> <div class="game_question"> <h1 class="display_question">{{q.question}}</h1> </div> <div class="game_options_bottom"> <div class="option"> <p><button class="option_btn" name="next" value="{{dritte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">C: <span id="option_span">{{dritte_frage}}</span></button></p> </div> <div class="option"> <p><button class="option_btn" name="next" value="{{vierte_frage}}" formaction="{% url 'quiz' %}?page={{ questions.next_page_number }} " type="submit">D: <span id="option_span">{{vierte_frage}}</span></button></p> </div> </div> </div> <div class="menü"> <button class="menü_button" formaction="{% url 'Example_dashboard' %}" ><i class="fa fa-bars" aria-hidden="true"></i><b> Menü</b></button> <div class="items"> <a href="{% url 'Example_dashboard' %}"> <i class="fa-solid fa-house"></i> Startseite </a> <a href="{% url 'Example_fragenkatalog' %}"> <i class="fa-solid fa-pen"></i> Fragenkatalog </a> <a href="{% url 'statistics' … -
Django cannot display a PDF inline on a web page using <embed> or <object> or <iframe> tags
I am trying to embed a PDF into a web page in Django. This is the message I see in the console: Refused to display 'http://127.0.0.1:8000/' in a frame because it set 'X-Frame-Options' to 'deny'. Here is the function definition in my python file: from django.http import HttpResponse from django.views.decorators.clickjacking import xframe_options_exempt from django.template.loader import render_to_string ... @login_required @xframe_options_exempt def resource_entity_screen(request,pk): ... rendered = render_to_string('classroom/resourcecenter/resource_entity_display.html', \ {'src' : url_src, \ 'embed_pdf' : embed_pdf, \ 'embed_video' : embed_video, \ 'embed_audio' : embed_audio, \ 'embed_image' : embed_image, \ 'obj_type' : obj_type, \ 'image_info' : image_info}) return HttpResponse(rendered) I ncluded this code instead of a straight render because I read in another post that the decorator only works with HttpResponse. However even with this code I am still getting the message shown above (in the console). I did clear my cache and do a reload, and also tried Ctrl-Shift R as well. No change. Can anyone tell me what I am missing? Is there something additional needed in settings.py? I have not tried deploying this to a testing server on the web to see if it just my local testing environment. -
Django media image not showing up in template but can acces it via .../media/thumbnail/image.png
Altough context does render in html, i can use other variables but cant accsess the image. My code is: html: {% for a in Manga %} <div class="manga_container"> <div class="manga_image"> <p>{{a.manga_image}}</p> <img src="{{ x.manga_image.url }}" alt=""> </div> </div> {%endfor%} model: class Manga(models.Model): manga_name = models.CharField(max_length= 255, default="null") manga_image = models.ImageField(upload_to="thumbnail", default="thumbnail/noimage.png") def __str__(self): return f"{self.id}, {self.manga_name}" and lastly view: def Index(request): manga = Manga.objects.all().values() chapter = Chapter.objects.all().values() fansub = Fansub.objects.all().values() context= { "Manga": manga, "Chapter": chapter, "Fansub": fansub, } template = loader.get_template("Index.html") return HttpResponse(template.render(context, request)) ı have used function based views since ı have to deal with multiple models at once. my media and url is as following: import os MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urlpatterns = [ ... ... ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I have put that p tag for me to see its url and as you can see it was in the right place, when i go to 127.0.0.1:8000/media/thumbnail/noimage.png i can see it and it does come up to my screen. i have tried most of the ways i could have think of. I want to see the image on my html and i didnt touch anything so it is basicly default image as i have … -
Image not getting uploaded in Django
I tried to save a record using two different methods but both are not working. Django Form Models (create method) 1 I have created a ModelForm class ProductForm(ModelForm): class Meta: model= ProductDetails fields= ("name","category","subcategory","price","mrp","product_details","main_img","img1","img2","img3") labels={ "name":"Product Name", "product_details":"Description", "category":"Category", "subcategory":"Sub-Category", "price":"Price", "mrp":"MRP", "main_img":"Main Image", "img1":"Image 1", "img2":"Image 2", "img3":"Image 3", } widgets = { 'name':forms.TextInput(attrs={'class':'form-control validate',}), 'product_details':forms.TextInput(attrs={'class':'form-control validate',}), 'category':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'subcategory':forms.TextInput(attrs={'class':'custom-select tm-select-accounts',}), 'price':forms.TextInput(attrs={'class':'form-control validate',}), 'mrp':forms.TextInput(attrs={'class':'form-control validate',}), 'main_img':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img1':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img2':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), 'img3':forms.FileInput(attrs={'class':'btn btn-primary btn-block mx-auto',}), } Models File # For Product details class ProductDetails(models.Model): name= models.CharField(max_length=100) price= models.FloatField() mrp= models.FloatField() main_img = models.ImageField(upload_to='product_img') img1 = models.ImageField(upload_to='product_img') img2 = models.ImageField(upload_to='product_img') img3 = models.ImageField(upload_to='product_img') category = models.ForeignKey(Category, related_name='produits', on_delete=models.CASCADE) subcategory = models.ForeignKey(SubCategory, related_name='produits', on_delete=models.CASCADE) product_details = RichTextField(blank=True, null=True) trending = models.BooleanField(default=False) def __str__(self): return self.name Method 1 Save record using form.save() getting Form validation error I have tried by removing main_img,img1,img2,img3 from all place (Forms.py, template, views,py). Then there is not validation error and record is getting saved successfully. The validation error is just because of some issue with the image uploading print(form.errors)= <ul class="errorlist"><li>main_img<ul class="errorlist"><li>This field is required.</li></ul></li><li>img1<ul class="errorlist"><li>This field is required.</li></ul></li><li>img2<ul class="errorlist"><li>This field is required.</li></ul></li><li>img3<ul class="errorlist"><li>This field is required.</li></ul></li></ul> def add_product(request): if request.method … -
Django context pass only None value
I have a view where I want to pass a variable to my template, however the value is always passed as None, as shown in numerals 1 , 2 and 3. What am I doing wrong please your help, I know it's a newbie question, actually I'm very newbie. views.py def create_address(request, dni): person = None addresses = None if request.method == 'POST': form = CreateAddressForm(request.POST) if form.is_valid(): try: person = Persona.objects.get(numero_documento=dni) addresses = Direccion.objects.filter(numero_documento=dni) print(f'Persona: {person}') # (1) print person ID. f = form.save(commit=False) f.numero_documento = person f.save() messages.success(request, 'Dirección registrada con éxito.' ) if 'save' in request.POST: return HttpResponseRedirect(reverse('persons:list')) if 'add_data' in request.POST: return HttpResponseRedirect(reverse('persons:create_address', kwargs={'dni': dni})) except Persona.DoesNotExist: person = None messages.error( request, 'El número de DNI no existe en la base de datos.' ) except Direccion.DoesNotExist: addresses = None messages.error( request, 'No se ha registrado ninguna dirección.' ) else: person = None messages.error( request, 'No se pudo registrar la dirección.' ) else: form = CreateAddressForm() template = 'persons/addresses/create_address.html' context = { 'pre_title': 'Direcciones domiciliarias', 'person': person, # (2) The value of "person" is "None". 'form': form, 'addresses': addresses, } return render(request, template, context) template.html (3) Value of "person" is "None". <div class="tab-pane active show" id="tabs-address-data"> Number … -
DRF Response VS Django - JSONResponse
from rest_framework.response import Response from django.http import JsonResponse What is the difference between these two? how can I decide which one should I use? -
How to get IP address of all devices connected on WLAN
Am working on a Django website. Basically, I want to block and IP once it perform an operation, when that Particular IP comes to perform that same operation then the system will not allow it. Now my problem is if a set of devices are connected on the same network and an operation is performed on the site, another person on that same network cannot perform that operation again because the IP has already been used, so how do I get all IP address connected through WLAN. This the code am using import ipaddress import socket import re def is_valid_ip(ip_address): """ Check Validity of an IP address """ try: ip = ipaddress.ip_address(u'' + ip_address) return True except ValueError as e: return False def is_local_ip(ip_address): """ Check if IP is local """ try: ip = ipaddress.ip_address(u'' + ip_address) return ip.is_loopback except ValueError as e: return None def get_ip_address_from_request(request): """ Makes the best attempt to get the client's real IP or return the loopback """ PRIVATE_IPS_PREFIX = ('10.', '172.', '192.', '127.') ip_address = '' x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR', '') if x_forwarded_for and ',' not in x_forwarded_for: if not x_forwarded_for.startswith(PRIVATE_IPS_PREFIX) and is_valid_ip(x_forwarded_for): ip_address = x_forwarded_for.strip() else: ips = [ip.strip() for ip in x_forwarded_for.split(',')] for …