Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - how to make a CloudinaryField not mandatory and how to allow user to delete their uploaded image?
Hej, I am just beginning to learn Django and I want my users to be able to upload a profile picture, so I extended the User model with a Profile model, however, so far I have not figured out how to make the image upload non-mandatory. And when the user has added a picture, I would like them to be able to remove it as well. Screenshot - Not able to Submit without adding file Screenshot - Not able to remove the added file models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField() profile_image = CloudinaryField('profile_image') def __str__(self): return self.user.username forms.py class ProfileForm(ModelForm): class Meta: model = Profile fields = ('bio', 'profile_image',) views.py @login_required(login_url='login') def createPost(request): form = PostForm() if request.method == "POST": form = PostForm(request.POST, request.FILES) # request.FILES necessary so that file is submitted # also required to add enctype to the form if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('home') context = {'form': form} return render(request, 'my8gag/post_form.html', context) Couldn't find anything about this in the documentation or here on SO, so would appreciate any kind of help/hints! Thanks in advance. -
How To Make Data That Come From Django Database Appear Horizontally
enter image description here In This Image The Data Is Appear In Veticall Format But I Want Data In Horizontal Foramt {% block title %}Blog{% endblock title %} {% block body %} <div class="container"> <div class="row"> {% for post in posts%} <div class="col-lg-3"> <div class="card" style="width: 31.25rem;"> <!-- <div class="card"> --> <img class="img-fluid card-img-top" src="https://images.unsplash.com/photo-1591154669695-5f2a8d20c089?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=1887&q=80" alt="Card image cap" style="height: 250px;width: 500px;"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> </div> </div> <div class="post block"> <h2 class="subtitle">{{post.title}}</h2> <small>Posted At {{post.date_added}}</small> <p>{{post.intro}}</p> <a href="{% url 'post_detail' post.slug %}">Read More</a> </div> {% endfor %} {% endblock body %} Hi There I'm Newbie In Django How Can I Able To Appear Horizontally The Data Is Come From Database -
ERROR: error de sintaxis en o cerca de «<» LINE 2: SQL state: 42601 Character: 30 [closed]
estoy realizando un procedimiento almacenado que me permita listar un registro de filas condicionadas a un rango de fechas CALL public.listar_eventos( < IN ''''2022-04-14'''' date>, < IN ''''2022-04-16'''' date> ) Porque al ejecutar este procedimiento almacenado me produce este error?? ERROR: error de sintaxis en o cerca de «<» LINE 2: < IN ''''2022-04-14'''' date>, ^ SQL state: 42601 Character: 30 Teniendo en cuenta que esta fue la creacion del procedimiento almacenado. CREATE OR REPLACE PROCEDURE listar_evento(FechaMinima date, FechaMaxima date) LANGUAGE plpgsql AS $$ BEGIN SELECT clientes_cliente.nombre, clientes_evento.cliente_id, clientes_cliente.telefono, clientes_evento.ciudad,clientes_evento.fecha_evento,clientes_evento.cantidad_personas FROM clientes_evento INNER JOIN clientes_cliente ON clientes_eventos.cliente_id = clientes_cliente.id WHERE fecha_evento BETWEEN @FechaMinima and @FechaMaxima; END; $$ -
How to make your custom django migrations reversible?
My original problem was, given a db table with 60M rows I need to convert a field type from boolean to integer field. I thought of creating a custom django migration for this (please do let me know if you have a better approach than this) which looks like this- def make_changes(apps, schema_editor): vcs_model = apps.get_model('iot_app', 'AbstractVCSCompartmentData') vcs_model.objects.select_related('vcsdata').all().update(charging_status_v2=F('charging_status')) vcs_model.objects.select_related('vcsdata').all().update(charging_status_backup=F('charging_status')) # backup class Migration(migrations.Migration): dependencies = [ ('iot_app', '0030_auto_20220225_1027.py'), ] operations = [ migrations.AddField( # backup field model_name='AbstractVCSCompartmentData', name='charging_status_backup', field=models.PositiveIntegerField(blank=True, null=True), ), migrations.AddField( model_name='AbstractVCSCompartmentData', name='charging_status_v2', field=models.PositiveIntegerField(blank=True, null=True), ), migrations.RunPython(make_changes), migrations.RemoveField( model_name='AbstractVCSCompartmentData', name='charging_status', ), migrations.RenameField( model_name='AbstractVCSCompartmentData', old_name='charging_status_v2', new_name='charging_status', ), ] I want to unroll all the changes i.e., making my custom migration reversible. I have gone through RunPython doc. But I am confused as in how can i perform addition of a new field in my reverse_code() function. The idea of creating a backup field is to reinstate the db to its previous state. -
Django: AttributeError at /course/u/update-item/ 'WSGIRequest' object has no attribute 'data' using django
I get this error when i try accessing localhost:8000/course/u/update-item/: "AttributeError at /update_item/ 'WSGIRequest' object has no attribute 'data'" NOTE: When i change request.data to request.body i get another error message that says JSONDecodeError at /course/u/update-item/ Expecting value: line 1 column 1 (char 0) views.py def update_item(request): data = json.loads(request.data) productId = data['productId'] action = data['action'] print("Action:", action) print("ProductId:", productId) return JsonResponse("Item was added", safe=False) cart.js function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/u/update-item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } urls.py path('u/update-item/', views.update_item, name="update-item"), -
How to update a model with ManytoMany / ForeignKey in Django
I have a model Study containing many Targets (ManyToManyField) Each Target contains a Location (ForeignKey): class Study(models.Model): uid = models.AutoField(primary_key=True) targets = models.ManyToManyField(Target) class Target(models.Model): uid = models.AutoField(primary_key=True) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True ) class Localization(models.Model): x = models.FloatField(blank=True) in my view I want to update the Location that is in a specified Study -> Target def update_locations(request): data = json.loads(request.body.decode('utf-8')) if request.method == 'POST': study_to_update = Study.objects.get(uid = data["study"]) targets = study_to_update.targets.all() target_to_update = [target for target in targets if target.uid == data["target"]][0] new_location = Location(x = data["location"]) #target_to_update.remove(?) #target_to_update.add(new_location) study_to_update.save() else: return HttpResponseForbidden('Erreur dans la requéte') I don't know if this is right or not -
How to form a socket url in django channels?
How to form a socket url in django channels? I am able to use sockets in my templates, but I want to test it with postman. The URL router in routing.py consists of path('chat/<room_id>/', ChatConsumer.as_asgi()), I am accessing this URLws://127.0.0.1:8000/public_chat/1 in postman, but it says Access denied. Also, which address(127.0.0.1:8000) should I use? The one for Django Application or the redis one used for messages ? -
show JsignatureField as images in pdf for Django3
here i am using Python3 and Django3 i am unable to display the signatures in my pdf view here is my views.py where it shows how i am saving my signatures class GasSafetyRecordView(View): def get(self, request, job_id, form_id): client = request.user.client job = get_object_or_404(AddJob, id=job_id, client=client) safety_form = GasSafetyForm() ...... .... return render(request, 'crm/jobforms/gas_safety_record.html', { 'safety_form': safety_form,'client': client, .... .... }) def post(self, request, job_id, form_id): client = request.user.client safety_form = GasSafetyForm(request.POST) if safety_form.is_valid(): form_obj = safety_form.save(commit=False) form_obj.client = client form_obj.save() return render(request, 'crm/jobforms/gas_safety_record.html', { 'safety_form': safety_form, 'client': client, ..... .... }) here is my forms.py for saving the signatures class GasSafetyForm(forms.ModelForm): engineer_signature = SignatureField(required=False) class Meta: model = GasSafetyRecord fields = ('client','engineer_signature') here is my template gas_safety_record.html <div class="col-sm-6 col-xs-12 margT10"> {{safety_form.engineer_signature}} </div> Now i want to display this engineer_signature in my pdf here is my views.py for pdf view def render_to_pdf_gasrecordform_view(template_src, context_dict): template = get_template(template_src) # context = Context(context_dict) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result, encoding='UTF-8') if not pdf.err: response = HttpResponse(result.getvalue(), content_type='application/pdf') return response return HttpResponse('We had some errors<pre>%s</pre>' % cgi.escape(html)) def generate_gasrecordform_pdf_view(request,id,pk,serialnumber): client = request.user.client gasrecord = GasSafetyRecord.objects.filter(client_id=client,formjob_id=id,serial_number=serialnumber).values() return render_to_pdf_gasrecordform_view('crm/gas_record_pdf.html',{'gasrecord':gasrecord,'client':client}) Here is my gas_record_pdf.html for pdf <td> <img src="{{ gasrecord.0.engineer_signature }}"/> </td> … -
Why is my Python path configuration not changing in Apache
I am trying to setup Apache 2.4 on Windows to work with a Django project. As a first try, I made just a base application showing the "welcome-rocket" of Django. After configuring the httpd.conf file of Apache, the well knwon error ModuleNotFoundError: No module named 'encodings' appears. I tried out all suggestions from here. Sadly, none of the ideas had an effect. I ended up using the following line in the config file: LoadFile "C:/Python/Python37/python37.dll" LoadModule wsgi_module "D:/Projects/TestProject/venv/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "D:/Projects/TestProject/venv/Scripts" WSGIPythonPath "D:/Projects/TestProject/venv/Lib;D:/Projects/TestProject/venv/Lib/site-packages;C:/Python/Python37/DLLs" WSGIScriptAlias / "D:/Projects/TestProject/venv/backend/backend/wsgi.py" During this process, I noticed that the python path configuration printed to the error.log file never changed, no matter which paths I used in the lines above. Here is a snippet from the log: Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.base_exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.platlibdir = 'lib' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.exec_prefix = 'C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310' sys.path = ['C:\\Users\\myuser\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' … -
Django 'None-Type' AttributeError
I have the following model: class Customer(models.Model): GENDER = [ ('M', 'Male'), ('F', 'Female'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) dob = models.DateField(auto_now=False, auto_now_add=False, null=True) avatar = models.ImageField(upload_to='customer/avatars/', blank=True, null=True) height = models.DecimalField(max_digits=5, decimal_places=2, null=True, default=0) weight = models.DecimalField(max_digits=5, decimal_places=2, null=True, default=0, help_text="Please input your weight in kg") medical_gender = models.CharField(max_length=1, choices=GENDER, default='F', blank=True, null=True) membership = models.BooleanField(default=True) def age(self): today = datetime.datetime.now() age = (today.year - int(self.dob.year)) - ((today.month, today.day) < (self.dob.month, self.dob.day)) return age On local, it works. Once I deployed I got: Exception Value: 'NoneType' object has no attribute 'year' Exception Location: /workspace/core/models.py, line 51, in age The error appears to be coming from the age method in the model. <span>Age: {{ request.user.customer.age }}</span> Any ideas on how to fix this, please? -
Why in django-import-export doesn't work use_bulk?
I use django-import-export, line-by-line import via import_data works without problems, but when I turn on the use_bulk=True option, it stops importing and does not throw any errors. Why does not it work? resources.py class ClientsResources(resources.ModelResource): class Meta: model = Clients fields = ('id', 'name', 'surname', 'age', 'is_active') batch_size = 1000 use_bulk = True raise_errors = True views.py def import_data(request): if request.method == 'POST': file_format = request.POST['file-format'] new_employees = request.FILES['importData'] clients_resource = ClientsResources() dataset = Dataset() imported_data = dataset.load(new_employees.read().decode('utf-8'), format=file_format) result = clients_resource.import_data(imported_data, dry_run=True, raise_errors=True) if not result.has_errors(): clients_resource.import_data(objs, dry_run=False) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) data.csv id,name,surname,age,is_active 7,OFBCXMW,RTQPEWU,35,Y 8,DMEYSYQ,TVKHQXP,80,Y 9,ZQBQLKI,ACRDHPQ,73,Y 10,CETXHMS,BQNYNSA,52,Y 11,GWHVHAO,FUJUQLO,41,Y -
Django CBV queryset issue
this is my model class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=256) text = models.TextField() create_date = models.DateTimeField(auto_now_add=True, auto_now=False) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return f'{self.author} --> {self.title}' def get_absolute_url(self): return reverse('blog:post_detail', kwargs={'pk': self.pk}) def publish(self): self.published_date = timezone.now() self.save() def unpublish(self): self.published_date = None self.save() and i registered it on Django admin. i have created two post on Django admin, the new post when i publish it and hit now and refresh the page, it won't show this post: this is the view: As you can see result of query1, query2 is different with query3. I think this is a bug, if it's not please light me up. -
how to call a view function in django without refreshing page
this is my home page I am working on a web application where user searches for a product and i am fetching that product from amazon flipkart and rendering on my home page. All i want is to store the data in the database when the user clicks on "Get Alert" button for a specific product without refreshing the page Here is my model class where data is supposed to be stored: class product(models.Model): product_id=models.CharField(max_length=50,primary_key=True) product_name=models.CharField(max_length=50) link=models.URLField() curr_price=models.IntegerField() old_price=models.IntegerField() website=models.CharField(max_length=10) Here is the view function that is been called when user searches for a product def search(request): if request.method == "POST": webList=request.POST.getlist('websites') q=request.POST.get('search') view=request.POST.get('view') if(q=="" or len(webList)==0): if request.user.is_authenticated: return render(request,'userLogin/userDashboard.html',{'error':True,'search':q,'weblist':webList,'userName':request.user}) else: return render(request,'home/searchProduct.html',{'error':True,'search':q,'weblist':webList}) AllWebProductList=[] FlipkartList=[] AmazonList=[] shopcluesList=[] snapdealList=[] MyntraList=[] if 'flipkart' in webList: FlipkartList=getInfoFromFlipkart(q) AllWebProductList.append(FlipkartList) #return render(request,'home/searchProduct.html',{'lists':productObj}) if 'amazon' in webList: AmazonList=getInfoFormAmazon(q) # Scrapping # AmazonList=getInfoAmazon(q) #PAPI AllWebProductList.append(AmazonList) if 'shopclues' in webList: shopcluesList=getInfoFromShopClues(q) AllWebProductList.append(shopcluesList) if 'snapdeal' in webList: snapdealList=getInfoFromSnapDeal(q) print ("welcome in snapdeal") if 'ajio' in webList: ajioList=getInfoFromAjio(q) if 'myntra' in webList: MyntraList=getInfoFromMyntra(q) AllWebProductList.append(MyntraList) print(" welcome in myntra") #sorting(AllWebProductList) mergeList=FlipkartList+AmazonList+shopcluesList # sorting(mergeList,asc) print(request.user.is_authenticated) if request.user.is_authenticated : return render(request,'userLogin/userDashboard.html',{'lists':mergeList,'val':view,'search':q,'weblist':webList,'userName':request.user}) else: return render(request,'home/searchProduct.html',{'lists':mergeList,'val':view,'search':q,'weblist':webList}) #messages.warning(request,name) return render(request,'home/searchProduct.html') Once this view is called we get the above page showing all the products fetched … -
I am getting thsi module not found error for my app in django . Why though?
(belov_wed_venv) prateek@prateek:~/belov_wed/project_belov_wed$ python manage.py runserver ModuleNotFoundError: No module named ' belov_wed_app' -
In DRF how do I serialize a related model(OneToOne) and display the data not in a list data type but single value instance?
The code is given below with the present output and expected output. Please help if, Thank you. In the ProductPriceMapping table the ProductDetail table and PriceList is related with a OneToOne relation, but When the data for Price is fetched with related_name= argument there must be one value for one product, but the data is being displayed is List data type. ##models.py class PriceList(models.Model): priceCode = models.BigAutoField(primary_key= True) maxRetailPrice= models.FloatField(max_length=20) baseDiscount = models.FloatField(max_length=20, default=0) seasonalDiscount = models.FloatField(max_length=20, default=0) def __str__(self): return '%s'% (self.maxRetailPrice) class ProductDetail(models.Model): productCode = models.BigAutoField(primary_key=True) productName = models.CharField(max_length=100) manufacturer = models.CharField(max_length=100) def __str__(self): return self.productName class ProductPriceMapping(models.Model): productPriceCode= models.BigAutoField(primary_key=True) productCode= models.ForeignKey(ProductDetail,on_delete=models.CASCADE,related_name='price') priceCode= models.OneToOneField(PriceList,on_delete=models.CASCADE) def __str__(self): return '%s' % (self.priceCode) ##serializers.py from .models import CategoryDetail, EmployeeDetail, ProductCategoryMapping, ProductPriceMapping, SalaryDetail, ProductDetail, PriceList class ProductPriceListSerializer(serializers.ModelSerializer): class Meta: model = PriceList fields = ('priceCode','maxRetailPrice', 'baseDiscount', 'seasonalDiscount') class ProductPriceMappingSerializer(serializers.ModelSerializer): class Meta: model= ProductPriceMapping fields= ('productPriceCode','productCode', 'priceCode') class ProductDetailsSerializer(serializers.ModelSerializer): category= serializers.StringRelatedField(many= True, read_only= True) price = serializers.StringRelatedField( many= True, read_only= True) class Meta: model = ProductDetail fields = ('productCode', 'productName', 'manufacturer','category', 'price') The API as it looks: [ { "productCode": 1, "productName": "NeoChef", "manufacturer": "LG", "category": [ "1: Microwave Oven" ], "price": [ "26000.0" ##expected the price value not be in a list … -
Can there be a DevStack for django? [closed]
Can someone create a devstack like https://localwp.com/ and https://kinsta.com/devkinsta/ it will attract a lot of developers, esp small and medium size startups to try django. -
How can i use django rest framework to create an API that is secured using api key
Am trying to create a RESTful API in django using django rest-framework and am unable to secure it with access key and.How do i go about it.please help -
502 bad gateway: Nginx, gunicorn, Django
Here is my nginx.conf user nginx; worker_processes auto; error_log /var/log/nginx/error.log notice; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; sendfile on; #tcp_nopush on; keepalive_timeout 65; #gzip on; include /etc/nginx/conf.d/*.conf; server { listen 80; server_name 0.0.0.0; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /myproject; } location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_pass http://unix:/root/myproject/myproject.sock; } } } This is my directory This is my gunicorn.service file [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=root Group=nginx WorkingDirectory=/root/myproject/myproject ExecStart=/root/myproject/myprojectenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock myproject.wsgi:application [Install] WantedBy=multi-user.target error.log 2022/04/13 12:45:30 [crit] 20474#20474: *8 connect() to unix:/root/myproject/myproject.sock failed (2: No such file or directory) while connecting to upstream, client: 10.81.234.10, server: 0.0.0.0, request: "GET / HTTP/1.1", upstream: "http://unix:/root/myproject/myproject.sock:/", host: "10.10.89.8" My gunicorn service is working properly Nginx.conf is also working properly with no errors All permissions have been granted to myproject directory Still I am getting a 502 Bad Gateway error. Please let me know if any additional information needed -
Django Models ManyToMany
I have two models Target and Location, each Target contains a Location: class Target(models.Model): uid = models.AutoField(primary_key=True) name = models.CharField(max_length=100) location = models.ForeignKey(Location, on_delete=models.CASCADE, null=True, blank=True ) So, I created a default location and I added it to many targets, The problem is, when I update a location from one target, all target locations are updated. As if all the targets are referring to the same Location. I need to write a logic where each Target has its own Location -
I want to add custom countdown timer in my project where admin/teacher set time for exam,that time becomes input for timer
i tried creating timer in python but its not being as i wanted so i guess javascript is only going to help and im not very good in javascript do please help me to create a timer and page should close when timer runs out of time 'THIS IS : models.py' from django.db import models from student.models import Student class Course(models.Model): course_name = models.CharField(max_length=50) question_number = models.PositiveIntegerField() total_marks = models.PositiveIntegerField() time_to_solve = models.IntegerField() required_marks_to_pass = models.IntegerField() def __str__(self): return self.course_name class Question(models.Model): course=models.ForeignKey(Course,on_delete=models.CASCADE) marks=models.PositiveIntegerField() question=models.CharField(max_length=600) option1=models.CharField(max_length=200) option2=models.CharField(max_length=200) option3=models.CharField(max_length=200) option4=models.CharField(max_length=200) cat=(('Option1','Option1'),('Option2','Option2'),('Option3','Option3'),('Option4','Option4')) answer=models.CharField(max_length=200,choices=cat) class Result(models.Model): student = models.ForeignKey(Student,on_delete=models.CASCADE) exam = models.ForeignKey(Course,on_delete=models.CASCADE) marks = models.PositiveIntegerField() date = models.DateTimeField(auto_now=True) 'THIS IS HTML TEMPLATE WHERE COUNTDOWN TIMER SHOULD APPEAR ' {% extends 'student/studentbase.html' %} {% block content %} {%load static%} {% block scripts %} <script src="{% static 'quiz.js' %}" defer></script> {% endblock scripts %} <head> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script> {% comment %} <script src="//code.jquery.com/jquery-1.11.1.min.js"></script> {% endcomment %} <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> </head> <div class="jumbotron my-4"> <form class="form" autocomplete="off" onsubmit="return saveAns()" action="/student/calculate-marks" method="POST"> {% csrf_token %} <h2 style="text-align: left;">Course: {{course.course_name}}</h2> <h2 style="text-align: right;">Countdown: </h2> {% comment %} <h2 id="timer-box" style="text-align: right;">Time: {{5:00}} min</h2> {% endcomment %} <h1 style="text-align: right;"><span id = "time">00:00</span></h1> {% for q in … -
NETWORK_ERROR apisauce
when i try to fetch data from my django server i got a NETWORK_ERROR corsheader in backend is work i just try localhost and my machine ip and notwork this is the result of console.log(response.originalError) Network Error at node_modules/apisauce/node_modules/axios/lib/core/createError.js:15:17 in createError at node_modules/apisauce/node_modules/axios/lib/adapters/xhr.js:96:22 in handleError at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit -
how to create login authentication based on some condition in django restframework
Hi Everyone current i am using default token base authentication, but now i need to some restriction on login time, i have One model called as Team where i assign one team name to multiple managers(users) i need to login only those users have team. also login based on username, password and get output token and team name., please help me out. models.py class Team(BaseModel): name = models.CharField(max_length=30) Logo=models.ImageField(upload_to=team_directory_path,null=True, blank=True) managers=models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) def __str__(self): return self.name -
How to use token base authentication in Django channels and testing on postman
By using Django channels I want to use token authentication and test on postman but I can't connect after using authentication.It's a notification app where user receive notification on websocket without refresh and without authentication It is working fine.. I have uploaded all the files .Please check it out I will be thankful to you. consumers.py from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer from channels.generic.websocket import WebsocketConsumer from channels.auth import login from asgiref.sync import async_to_sync, sync_to_async import json from .models import * class OrderProgress(WebsocketConsumer): def connect(self): self.user = self.scope["user"] self.room_name = self.scope['url_route']['kwargs']['order_id'] print('the result is ....', self.scope['path']) print('the user is', self.scope["user"]) self.room_group_name = 'order_%s' % self.room_name print('order is this......', ) print(self.room_group_name) async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) if self.scope['user'].is_authenticated: order = Order.give_order_details(self.room_name) self.accept() self.send(text_data=json.dumps({ 'payload': order })) def disconnect(self, close_code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) def receive(self, text_data): async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'order_status', 'payload': text_data } ) def order_status(self, event): print('data in event............', event) data = json.loads(event['value']) self.send(text_data=json.dumps({ 'payload': data })) **middeleware.py** from django.contrib.auth.models import AnonymousUser from rest_framework.authtoken.models import Token from channels.db import database_sync_to_async from channels.middleware import BaseMiddleware @database_sync_to_async def get_user(token_key): try: token = Token.objects.get(key=token_key) return token.user except Token.DoesNotExist: return AnonymousUser() class TokenAuthMiddleware(BaseMiddleware): def __init__(self, inner): super().__init__(inner) async def __call__(self, scope, receive, … -
How to make a global filter in Django admin?
Is it possible to make a global filter in the admin panel? For example, there are models: class Company(models.Model): name = models.CharField( 'Name company', max_length=200, help_text='Name company' ) city = models.CharField( 'City', max_length=200, help_text='City' ) class Object(models.Model): name = models.CharField( 'Name object', max_length=200, help_text='Name object' ) number = models.CharField( 'Number object', max_length=200, help_text='Number object' ) company = models.ForeignKey( Company, on_delete=models.SET_NULL, verbose_name='Company', null=True ) class Person(models.Model): name = models.CharField( 'Name, max_length=200, help_text='Name' ) number = models.CharField( 'ID person', max_length=200, help_text='ID person' ) object = models.ForeignKey( Object, on_delete=models.SET_NULL, verbose_name='Object', null=True ) It turns out that there are several companies. Each company has several facilities, which in turn have staff. I want to make a global filter by Companies in the admin panel. That is, not to filter every time, but let's say I chose the company "Horns and Hooves" and calmly worked in the admin area with objects belonging to this company. This is just an example, in reality there are many more models -
implementing admin.stackedinline in frontend
I have an inlineformset_factory: PollFormset = inlineformset_factory(Post, Poll, form=PollForm, max_num=10, extra=1, can_delete=False) and I want below the form the option to add and create another Poll like in the django admin panel, template: {% for form in poll_form %} {{ form.non_field_errors }} <div class="container" id="poll_form"> <div class="row" name="service_form"> {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% for field in form %} <div class="col-sm"> {{ field.errors }} {{ field|as_crispy_field }} {% if field.help_text %} <p class="help">{{ field.help_text|safe }}</p> {% endif %} </div> {% endfor %} </div> </div> {% endfor %} I also tried {{poll_form.management_form}} but it doesnt work.