Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inserting database search result into multiple rows not one in an excel file by django
I have written some django codes to read and save users xlsx data to database. each row in my database is one entry. Now, I want to write a function in views.py that can receive a word from the user and search it on that data base the rows containing that word, and write all of those rows to an excel file. I prefer to return it as an .xlsx file but it can be csv if xlsx is not possible. I have written this code but it has three problems: 1. The main problem: All of the found rows are saved in one row of the output. 2. the labels of them are saves at the same cell, but I prefer to have labels as the title. 3. The output is a csv file not xlsx my code: #views def download(request): try: assert request.method == 'POST' form = data_DownloadForm(request.POST) assert form.is_valid() data_types = form.cleaned_data.get('data') data = list(dataFields.objects.filter(data__contains=data_types).values()) except AssertionError: error = 'Your request has some problems.' data = error attachment = 'FoundData.csv' response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment;filename="{}"'.format(attachment) response.write(data) return response This is the output of my code in which two rows are written in one This is what … -
Render relationship model in template
I am trying to render a model with a relationship but I am not able to do so. class LogBook(models.Model): name = models.CharField(max_length=50, verbose_name="Nom du registre de maintenance") members = models.ManyToManyField(User) class LogMessages(models.Model): logbook = models.ForeignKey(LogBook) message = models.CharField(max_length=200, verbose_name="Détail du problème") class LogDone(models.Model): logmessage = models.ForeignKey(LogMessages) message = models.CharField(max_length=200) My view: log = get_object_or_404(LogBook, pk=log_id) logmessages = LogMessages.objects.filter(logbook=log_id) My template {% for logmessage in logmessages.all %} {{logmessage.logdone.message}} {{% endfor %}} But the logdone object is not showing, any idea ? -
How to seralize a MethodField with more than one object in Django?
I want to serialize a method that checks if the author of a story is the currently logged in user, if so returns true, if not false. However, the Docs of Django state that the Serliazer method requires only one argument besides self. So how can I access the user model in addition to the story (object)? I was thinking about something like that: class StorySerializer(serializers.ModelSerializer): story_owner_permission = serializers.SerializerMethodField('check_story_owner_permission') class Meta: model = Story fields = ['story_owner_permission'] def check_story_owner_permission(self, story, request): story_author = story.author.id current_user = request.user.id if (story_author == current_user): return True else: return False But it doesn't work. check_story_owner_permission() missing 1 required positional argument: 'request' -
'styles\bootstrap4\bootstrap.min.js.map' could not be found
I am new using Django and my web page is not rendering my bootstrap.css file because it simply cannot find it. This is my setting.py file: My Index.html My file structure MyProject/static/styles/bootstrap/bootstrap.min.cssstrong text Getting these errors: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/styles/bootstrap4/bootstrap.min.js.map 'styles\bootstrap4\bootstrap.min.js.map' could not be found -
How to add a specific level of access to a custom action in viewset in Django Rest Framework?
I have a ModelViewSet in Django Rest Framework with all crud functions and set the permissions to IsAuthenticated, but I made a custom action and want it to be public, but I have no clue on how to do that since the documentation only shows how to do that with an @api_view(), here's my ModelViewSet class UserViewSet(viewsets.ModelViewSet): """User viewset""" queryset = User.objects.all() serializer_class = UserModelSerializer authentication_classes = [TokenAuthentication] permission_classes = [IsAuthenticated] @action(detail=False, methods=['post']) def signup(self, request): """Sign Up users without profile. """ serializer = UserSignUpSerializer(data=request.data) if serializer.is_valid(raise_exception=True): user = serializer.save() data = { 'user' : user, } return Response(data, status=status.HTTP_201_CREATED) @action(detail=False, methods=['post']) def login(self, request, *args, **kwargs): """ Handle logins request. """ serializer = UserLoginSerializer(data=request.data) serializer.is_valid(raise_exception=True) user, token = serializer.save() data= { 'user': user, 'access_token' : token } return Response(data, status=status.HTTP_201_CREATED) I want to make the login @action public, I hope you guys can help me -
Can I associate a file uploaded to a model with a session id for anonymous users in Django?
With my web app visitors should click a button which generates a unique video file - stores it in a model - and display it to them. I'm having trouble understanding how to associate the video file with the visitor without making them sign in which I don't want to do. Can I do this with sessions a bit like how a shopping cart works for guests? -
Why is Javascript not working with Django HTML?
I am trying to put some javascript code in my Django website. The javascript code is supposed to check if the buttons are being pressed and alert the user if they are. This only works for the first button, however. Because I am looping over all the buttons to display them, I think javascript is not seeing it as HTML code. Here is the javascript code. const card = document.querySelector('.card'); card.addEventListener('click', e => { if (e.target.classList.contains('btn')) { alert('hi') } }) Here is the HTML/Django code : {% extends "/Users/marco/Documents/codes/Python/Django/vracenmasse/templates/base_generic.html" %} {% load static %} {% block content %} <center><h1>Nos Produits</h1></center> <hr> <div class="row" style = "border: 50px solid white;"> {% for product in products %} <div class="card" style="width: 18rem;"> <img class="card-img-top" src="../../../media/{{ product.product_picture.name }}" alt="{{ product.product_picture.name }}"> <div class="card-body"> <center> <h5 class="card-title">{{ product.name }}</h5> <p class="card-text">{{ product.product_price|floatformat:2 }}$ / unité</p> <p class="card-text">Catégorie : {{ product.type_of_product }}</p> {% if product.new_product == "yes" %} <b><p class="card-text"><font size="3.5" color="Orange">Nouveaux!</font></p></b> {% endif %} {% if product.availability == "Out Of Stock"%} <b><p class="card-text"><font size="1.5" color="red">En rupture de stock</font></p></b> <hr> <button type="button" class="btn btn-primary" disabled>Ajouter au Panier</button> {% else %} <p style="font-size:15;">Quantité : </p><input type="number" step="12" min="0" /> <span class="validity"></span> <hr> <button type="button" class="btn btn-outline-primary" id='realbutton'>Ajouter … -
Django rest framework throttling on basis of API response
I using DRF and using it's throttling feature. All is working fine. But I want to implement throttling in my Register API in such a way that only requests with a successful response should count. Below is my code. class createUser(generics.CreateAPIView): permission_classes = (AllowAny,) throttle_scope = 'register' @transaction.atomic def post(self, request, *args, **kwargs): user_data = request.data.get('user') email = user_data.get('email') email_ser = verifyEmailSerializer(data={'email_id': email}) if email_ser.is_valid(): return errorResponse('USER_EXISTS') else: # do something Please suggest the way to achieve it. -
Django-import-export get auto generated id during import
I am trying to import an excel without an ID field specified and the ID is being auto genetrated by django. I need to access this auto generated ID field but i cannot figure out how to do it. accessing the entire row doesnot give the auto generated ID. Any ideas on how to access the auto generated ID field? -
How to run python code at the background without impacting rendering of html template?
Concept that I want to achieve: A web application that listens to user's speech at the background and do what the user wants. What I have: A Python - Django application with Speech Recognition enabled with the following two files. speechrecognition.py (This is where speech recognition related logic is) index.html Note: speechrecognition.py goes on a loop repeatedly listening to user's input. What I tried: I tried calling speechrecognition.py class before rendering index.html in views.py from SpeechRegApp.speechrecognition import SpeechRecognition def index(request): SpeechRecognition() return render(request, "index.html", {}) Problem that I'm facing: Since I'm repeatedly listening to user's input in speechrecognition.py, index.html doesn't get rendered. How to fix this issue? -
sign up with email instead username
i want the user to sign up with his email instead of registering with a username forms.py class ExtendedUserCreationForm(UserCreationForm): email= forms.EmailField(required=True) class Meta: model=User fields=('username','email','password1','password2') def save(self ,commit=True): user = super().save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user views.py: candidat here is just a model with a OneToOneField with user for more information in the sign up form def register(request): if request.method == 'POST': form = ExtendedUserCreationForm(request.POST) candidat_form = CreateCandidat(request.POST) if form.is_valid() and candidat_form.is_valid(): user = form.save() candidat = candidat_form.save(commit=False) candidat.user = user candidat.save() username= form.cleaned_data.get('username') password= form.cleaned_data.get('password1') user = authenticate(username=username ,password=password) login (request, user) return redirect('profil') else: form = ExtendedUserCreationForm() candidat_form = CreateCandidat() context= {'form' : form , 'candidat_form' : candidat_form} return render(request, 'registration/register.html',context) -
How to get user's site field auto-assigned while creating an user Instance depending upon the domain name it came through? (Django)
My user class is an extension of AbstractBaseUser and which has site field as a ForeignKey field from the Django Site Framework which I have made null and blank True for time-being. ## MyUser Model import uuid from django.contrib.sites.managers import CurrentSiteManager from django.utils import timezone from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from phonenumber_field.modelfields import PhoneNumberField from django.contrib.sites.models import Site from django.contrib.sites.shortcuts import get_current_site from django.contrib.auth.models import User # Create your models here. class MyUser(AbstractBaseUser, PermissionsMixin): id = models.UUIDField(primary_key=True, editable=False,unique=True, default=uuid.uuid4) email = models.EmailField(max_length=350, unique=True) phone = PhoneNumberField(null=True, blank=True) date_of_birth = models.DateTimeField(blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_Te = models.BooleanField(default=True) date_joined = models.DateTimeField(default=timezone.now) site = models.ForeignKey(Site, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = "email" REQUIRED_FIELDS = [] # by default username field and password objects = MyUserManager() on_site = CurrentSiteManager() def __str__(self): return self.email class Meta: unique_together = ('site', 'email') @property def is_admin(self): return self.is_superuser My question is, how do I write code such that any user instance trying to get created will have site field auto-assigned depending on the domain-name it came through ?? For.eg if the user was created from http://127.0.0.1:8000/admin/user/myuser/ assign the user's site field to "1" (by my current setting) … -
How to accept a WebSocket extension in Django channels?
I am trying to add compression support to my django-channels consumer using WebSocket extensions. from channels.generic.websocket import WebsocketConsumer class MyConsumer(WebsocketConsumer): def connect(self): self.accept() def receive(self, text_data=None, bytes_data=None): self.send(text_data="Hello world!") The problem is that I cannot find a way to inform client that compression extension was accepted. If a client provides 'Sec-WebSocket-Extensions: permessage-deflate' header the server should respond with the same header, however it seems that django-channels doesn't have a way to provide it, because accept() implementation is as follows: def accept(self, subprotocol=None): """ Accepts an incoming socket """ super().send({"type": "websocket.accept", "subprotocol": subprotocol}) I guess one option is to use HTTP response start to add headers to the response, but I am not sure if this is the right path. -
NameError: name 'ForeignKey' is not defined in my Django code
I am getiing an error Foreign Key not defined task_name=ForeignKey(Task_List, on_delete=models.SET_NULL, null=True) NameError: name 'ForeignKey' is not defined models.py: class Task_List(models.Model): task_name=models.CharField(max_length=100, default="NOT SPECIFIED") c1=models.CharField(max_length=30, default="OTHER") c2=models.CharField(max_length=30, default="OTHER") c3=models.CharField(max_length=30, default="OTHER") time_esc=models.IntegerField(default=1) def __str__(self): return self.title class Task_manager(models.Manager): def create_Task(self, title): Task1 = self.create(title=title) # do something with the book return Task1 class Task(models.Model): task_name=ForeignKey(Task_List, on_delete=models.SET_NULL, null=True) title=models.CharField(max_length=30,default="Other", blank=Ture) created=models.DateTimeField(auto_now_add=True) objects=Task_manager() class Meta: ordering = [ '-created'] def __str__(self): return self.title -
How can I complete the to do app list task?
I have just started to learn django, and my first project is ToDo app list(from a tutorial). I want to add more features on the project by adding a checkbox in update_task tamplet, so the user after he had finish his task can be completed. This is update_task.html <div class="center-column"> <!---h3>Update Task</h3---> <div class="item-row"> <h3>Update Task</h3> <form method="POST" action=""> {% csrf_token %} {{form.title}} <input class="btn btn-primary" type="submit" name="Update Task"> <a type="button" class="btn btn-secondary" href="{% url 'todo:index' %}">Cancel</a> <div class="item-row1"> <h5 class="text-dark font-weight-bold">Is this task complete?</h5> <div class="regular-checkbox"> {% if task.complete == True %} <input type="hidden" class="taskCheckbox" name="done" id="{{ task.id }}" value="on"> <label for="{{ task.id }}" class="text-dark">Complete<strike>{{ task }}</strike></label> {% endif %} </div> </div> This is index.html <div class="center-column"> <form method="POST" action="/"> {% csrf_token %} {{form.title}} <input class="btn btn-info" type="submit" name="Create task"> </form> <div class="todo-index"> {% for task in tasks %} <div class="item-row"> <a class="btn btn-sm btn-info" href="{% url 'todo:update_task' task.id %}">Update</a> <a class="btn btn-sm btn-danger" href="{% url 'todo:delete' task.id %}">Delete</a> <span>{{task}}</span> </div> {% endfor %} This is view.py def index(request): tasks = todo.objects.all() form = todoForm() if request.method == "POST": form = todoForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = {'tasks':tasks, 'form':form} return render(request, 'todo/index.html', context) def updateTask(request, pk): task … -
Django import export has error "Tablib has no format 'None' or it is not registered"
I am trying to implement csv import in my application and I have this error, Tablib has no format 'None' or it is not registered. I am using python 3.5 and Django 2.2. I tried the same code with python 2.7 with Django 1.8 and it worked well. Is there any problem with my code? My model: class Stock(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE, blank=True) item_name = models.CharField(max_length=50, blank=True, null=True) quantity = models.IntegerField(default='0', blank=False, null=True) receive_quantity = models.IntegerField(default='0', blank=True, null=True) receive_by = models.CharField(max_length=50, blank=True, null=True) issue_quantity = models.IntegerField(default='0', blank=True, null=True) issue_by = models.CharField(max_length=50, blank=True, null=True) issue_to = models.CharField(max_length=50, blank=True, null=True) phone_number = models.CharField(max_length=50, blank=True, null=True) created_by = models.CharField(max_length=50, blank=True, null=True) reorder_level = models.IntegerField(default='0', blank=True, null=True) last_updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __str__(self): return self.item_name Resources.py from import_export import resources from .models import Stock, Person class StockResource(resources.ModelResource): class Meta: model = Stock Views.py: from .resources import StockResource def upload(request): if request.method == 'POST': stock_resource = StockResource() dataset = Dataset() new_stock = request.FILES['myfile'] imported_data = dataset.load(new_stock.read()) result = stock_resource.import_data(dataset, dry_run=True) # Test data import if not result.has_errors(): stock_resource.import_data(dataset, dry_run=False) # Run import return render(request, 'csv_import.html') csv_import.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <input type="file" name="myfile"><br><br> <button type="submit">Upload</button> </form> csv_import.csv 1,phone,1,0,9,0,9,9,9,,ssaine,0,2020-06-11, 2,computer,2,0,9,0,9,9,9,9,ssaine,0,2020-08-11, -
int() argument must be a string, a bytes-like object or a number, not 'NoneType' Django Form
I have a issue when i submit a form on my checkout view. first of i have a form on my main view where i ask for quantity of an item. I post the data to my checkout view to make a summary on my front-end. On my Checkout view i have another form where i ask for email and name, when i try to submit the checkout form i have a typeError. int() argument must be a string, a bytes-like object or a number, not 'NoneType' Here is my checkout view # My view @login_required(login_url='login') def checkout(request): data = request.POST.copy() region = data.get('region-select') plateform = data.get('plateform-select') quantity = data.get('quantity-field') quantity = int(quantity) price = quantity * 3.99 context = { 'region':region, 'plateform':plateform, 'quantity':quantity, 'price':price } return render(request, 'main/checkout.html', context) I don't understand why this occurs because the data get rendered in my template <h1 class="title is-5" style="margin-bottom:5px;"> {{price|floatformat:2}} EUR </h1> -
sending multiple input with same name drf django
i have a simple form and an api with drf and in form i have add field button from that i am cloning the fields with ajax and i want to submit the data from cloned field also with same api models.py: class Sample(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) serializers.py: class SampleSerializer(serializers.ModelSerializer): class Meta: model = Sample fields = '__all__' views.py: class SampleViewSet(ModelViewSet): queryset = Sample.objects.all() serializer_class = SampleSerializer html page: <form method="post" id="sampleform" action="#"> {% csrf_token %} <div class="input_fields" style="text-align:center"> <input type="text" name="first_name" id="first_name" placeholder="first name"/> <input type="text" name="last_name[]" id="last_name" placeholder="Last Name"/> <button class="add_button">Add More Fields</button> <button type="submit">Submit</button> </div> </div> </form> script: <script> $(document).ready(function() { var max_fields = 10; var wrapper = $(".input_fields"); var add_button = $(".add_button"); var x = 1; $(add_button).click(function(e){ e.preventDefault(); if(x < max_fields){ x++; $(wrapper).append( '<div class="form-group" style="margin-top:5px"><input type="text" name="first_name[]" placeholder="first name" required/><input type="text" name="last_name[]" placeholder="last name" required/><a href="#" class="remove_field">Remove</a></div>' ); } }); $(wrapper).on("click",".remove_field", function(e){ e.preventDefault(); $(this).parent('div').remove(); x--; }) }); </script> <script> $('#sampleform').submit(function(e){ e.preventDefault(); var form = $(this); $.ajax({ url:"http://localhost:8000/api/", type:"post", data: { //data:form.serialize(), first_name: $('#first_name').val(), last_name:$('#last_name').val(), csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), }, //dataType:'json', success: function(data){ console.log(data) }, }); }); </script> as you can see i am creating 10 row with two fields and i'm getting the value of … -
i cant add an email to any user i created using the the django admin
here is my problem i have a website with multiple users,but i divided the users into 2,Doctor and Patient,the Doctor has higher authority than the Patient,but whenever i add a user.doctor,i wont get their email address, but only the email address can be used to login,meanwhile i set every sign up any user do to create a patient automatically,so i can upgrade them using the admin panel,but if i create any user directly i wont get their email just the rest of the info those email address shown are the ones i created using the website or the createsuperuser here are my code models.py class CustomUser(AbstractUser): is_doctor = models.BooleanField(default=False) def __str__(self): return self.email class Status(models.Model): title= models.CharField(max_length=5) def __str__(self): return self.title class Doctor(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="doctor") image = models.ImageField(default='jazeera.jpg', upload_to='profile_pics') bio = models.TextField() speciality = models.CharField(max_length=300) describtion = models.CharField(max_length=100) status = models.ManyToManyField(Status) def __str__(self): return f'{self.user.username}' def save(self, *args, **kwargs): super().save(*args, **kwargs) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (300, 300) img.thumbnail(output_size) img.save(self.image.path) class Patient(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, null=True, related_name="patient") subscribe = models.BooleanField(default=False) def __str__(self): return f'{self.user.username}' @receiver(post_save, sender=CustomUser) def create_user_profile(sender, instance, created, **kwargs): print("****", created) if instance.is_doctor: Doctor.objects.get_or_create(user=instance) else: … -
Trouble installing django with pipenv
I'm following the steps in this tutorial here: https://djangoforbeginners.com/initial-setup/ I installed pipenv and then went to install Django but was unable to. Any help would be very much appreciated. I'm running Windows 10 and have Python 3.8. Also I'm using Powershell. Collecting pipenv Downloading pipenv-2020.6.2-py2.py3-none-any.whl (3.9 MB) |████████████████████████████████| 3.9 MB 930 kB/s Collecting certifi Downloading certifi-2020.4.5.2-py2.py3-none-any.whl (157 kB) |████████████████████████████████| 157 kB 2.2 MB/s Requirement already satisfied: pip>=18.0 in c:\python38\lib\site-packages (from pipenv) (20.1.1) Requirement already satisfied: virtualenv in c:\python38\lib\site-packages (from pipenv) (20.0.21) Collecting virtualenv-clone>=0.2.5 Downloading virtualenv_clone-0.5.4-py2.py3-none-any.whl (6.6 kB) Requirement already satisfied: setuptools>=36.2.1 in c:\python38\lib\site-packages (from pipenv) (41.2.0) Requirement already satisfied: distlib<1,>=0.3.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (0.3.0) Requirement already satisfied: appdirs<2,>=1.4.3 in c:\python38\lib\site-packages (from virtualenv->pipenv) (1.4.4) Requirement already satisfied: six<2,>=1.9.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (1.15.0) Requirement already satisfied: filelock<4,>=3.0.0 in c:\python38\lib\site-packages (from virtualenv->pipenv) (3.0.12) Installing collected packages: certifi, virtualenv-clone, pipenv Successfully installed certifi-2020.4.5.2 pipenv-2020.6.2 virtualenv-clone-0.5.4 PS C:\Users\travi\desktop> mkdir django Directory: C:\Users\travi\desktop Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2020-06-16 9:15 AM django PS C:\Users\travi\desktop> cd django PS C:\Users\travi\desktop\django> pipenv install django==3.0 Traceback (most recent call last): File "c:\python38\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\python38\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Python38\Scripts\pipenv.exe\__main__.py", line 7, in <module> … -
502 Bad Gateway Error Displayed, Timeout Occurs
I am currently having some issues with my nginx and gunicorn setup. Once I have both of them enabled and go to the IP address established by digitalocean, it takes 5 minutes to show me 502 Bad Gateway Nginx. Afterwards I get a sentry error that reads: "OperationalError could not connect to server: Connection timed out Is the server running on host "myproject-postgres-staging-db-do-user-6482921-0.db.ondigitalocean.com" (64.225.42.160) and accepting TCP/IP connections on port 25060?" I have been trying all sorts of different things with my nginx and gunicorn configs as well as the settings.py file, but to no avail. I'm not sure if I did something wrong in relation to those methods hence why I didn't get any results, but I am out of ideas. Here's my code for reference. Nginx config: # You should look at the following URL's in order to grasp a solid understanding # of Nginx configuration files in order to fully unleash the power of Nginx. # https://www.nginx.com/resources/wiki/start/ # https://www.nginx.com/resources/wiki/start/topics/tutorials/config_pitfalls/ # https://wiki.debian.org/Nginx/DirectoryStructure # server { listen 80 default_server; listen [::]:80 default_server; server_name myproject.app www.myproject.app IP ADDRESS; error_log /home/myuser/nginxError.log warn; access_log /home/myuser/nginx.log ; server_tokens off; add_header X-Frame-Options SAMEORIGIN; add_header X-Content-Type-Options nosniff; add_header X-XSS-Protection "1; mode=block"; add_header Strict-Transport-Security "max-age=31536000; includeSubdomains; … -
can not create PointField() in GeoDjango
I can not create my database from this sample models.py. from django.contrib.gis.db import models class Subscriber(models.Model): id = models.IntegerField(primary_key=True) login = models.CharField(max_length=200, unique=True) email = models.CharField(max_length=200, unique=True) country = models.CharField(max_length=200) def __str__(self): return self.email class Localisation(models.Model): name = models.CharField(max_length=100) point = models.PointField() address = models.CharField(max_length=100) city = models.CharField(max_length=50) class Video(models.Model): id = models.IntegerField(primary_key=True) video_title = models.CharField(max_length=200) video_url = models.CharField(max_length=255, unique=True) video_file = models.CharField(max_length=50) video_date = models.DateTimeField('date published') video_user = models.ForeignKey(Subscriber, on_delete=models.CASCADE) loc = models.ForeignKey(Localisation, on_delete=models.CASCADE) def __str__(self): return self.video_title + " / " + self.video_file I get this error whatever I try (tried Stackoverflow and Google in vain) : File "/usr/lib/python3.8/site-packages/django/contrib/gis/db/models/fields.py", line 188, in get_prep_value raise ValueError("Couldn't create spatial object from lookup value '%s'." % obj) ValueError: Couldn't create spatial object from lookup value 'POINT(12.4604, 43.9420)'. I do not know where the value POINT((12.4604, 43.9420). I've never typed it. I guess I need to add a default value, which I tried also, by modifying the point = models.PointField() in: point = models.PointField(default='POINT(0 0) but the errors still occurs... -
Problem with user hierarchy mapping for Sales Team management app - Django
I need your help/guidance as 'm new to django-python web development and i'm stuck at one of my project. Below are the explained scenario for your reference. Project : Sales team management webapp platform : Django- python This app has multiple users Ie. customer, dealer, sales manager, regional manager and admins. So i need to create account for all of them with respective privileges. All of the user should be mapped to each other Ie. customer Upper user can see data of their mapped lower user. **What i have done: I have created models for all of the users and able to get them registered using views. Where i'm stucK: Unable to map the users to each other Also wants to show the upper hierarchy as selection dropdown while registration. which im unable to do.** Please help me. Thanks in advance. -
Getting Response 475 on making XHR Requests
I am making XHR Request to the Hotstar API, https://api.hotstar.com/s/v1/scout?q={movie_name}&perPage=50. The headers I am using are, headers = { 'x-country-code': 'IN', 'x-platform-code': 'PCTV', 'hotstarauth': 'st=1591731250~exp=1591737250~acl=/*~hmac=30e290968fac98e02d39b937ec556c42d1692d6493d0ae29e49bcb1723829e23', } Copied everything from the developer tools of the browser The request works fine on my local machine, but gives response 475 on heroku server. I think the problem lies with x-platform-code. Can someone please tell me, if I am correct, than what should I use in place of x-platform-code, or anything else to remove the error. Everything is working as expected on my local machine. -
(Django Templates) HTML page to select CSV fields from dropdowns to choose which Model field each relates to
What I'm trying to do is to build a simple HTML interface to Upload CSV, then select CSV fields related to each Model field. This is an example of csv file. id first_name last_name email gender ip_address app_name 1 Law Lismore llismore0@noaa.gov Male 87.223.253.208 Veribet 2 Phylis Rolfi prolfi1@ycombinator.com Female 205.75.2.218 Rank 3 Millisent Faulkner mfaulkner2@ted.com Female 35.97.69.238 Cardguard 4 Simone Minci sminci3@privacy.gov.au Male 178.6.109.253 Asoka 5 Virge Hadland vhadland4@artisteer.com Male 26.218.62.107 Latlux views.py def upload_csv_file(request): if request.method == 'POST': form = UploadCSVForm(request.POST, request.FILES) if form.is_valid(): file = request.FILES['file'] reader = csv.DictReader(io.StringIO(file.read().decode('utf-8'))) context = { 'fields': reader.fieldnames, ??? } return render(request, 'csv_mapper/field_choices.html', context) else: form = UploadCSVForm() return render(request, 'csv_mapper/index.html', {'form': form}) models.py class CSVMap(models.Model): id_in_doc = models.IntegerField() first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField() How to write field_choices.html with interface like this and receive a dict after Confirm? And how pass reader to the next view which is going to store the data to DB? { id_in_doc: id, first_name: first_name, ... }