Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it safe to use primary keys(UUID) in forms on one webpage?
In one django view, I create a form. And I save a list of uuid to a char field of form. After the form is submitted, I will get the list of uuid. It works fine. But I am questioned about the security. Is it ok to release a lot of uuid to any user? -
Django ignores custom backend
I have custom auth backends: class VkBackend(object): def authenticate(self, vk_user_id=None): print('VK USER:', vk_user_id) if vk_user_id is None: return None # Try to find user social_profile = SocialProfile.get_profile_by_user_id(social_network=SocialProfile.SOCIAL_NETWORK_VK, social_user_id=vk_user_id) if social_profile is not None: return social_profile.user.user return None def user_can_authenticate(self, user): is_active = getattr(user, 'is_active', None) return is_active or is_active is None def get_user(self, user_id): user = get_or_none(User, pk=user_id) if user is not None: return user if self.user_can_authenticate(user) else None else: return None class GoogleBackend(object): def authenticate(self, google_user_id=None): print('GOOGLE USER:', google_user_id) if google_user_id is None: return None # Try to find user social_profile = SocialProfile.get_profile_by_user_id(social_network=SocialProfile.SOCIAL_NETWORK_GOOGLE, social_user_id=google_user_id) if social_profile is not None: return social_profile.user.user return None def user_can_authenticate(self, user): is_active = getattr(user, 'is_active', None) return is_active or is_active is None def get_user(self, user_id): user = get_or_none(User, pk=user_id) if user is not None: return user if self.user_can_authenticate(user) else None else: return None Declared in settings.py: AUTHENTICATION_BACKENDS = [ 'users.backends.VkBackend', 'users.backends.GoogleBackend', 'django.contrib.auth.backends.ModelBackend', ] I'm trying to auth with it in DRF view: class SocialAuthView(APIView): serializer_class = SocialAuthSerializer permission_classes = (AllowAny,) def __authenticate(self, social_network, user_id) -> Optional[User]: if social_network == SocialProfile.SOCIAL_NETWORK_VK: return authenticate(vk_user_id=user_id) else: return authenticate(google_user_id=user_id) def post(self, request, *args, **kwargs): # Skip some code user = self.__authenticate(social_network, user_id) logging.error('Auth result: {}'.format(user)) if user is … -
Django authenticate with python-requests
Having trouble sorting out how to correctly authenticate a python-request client against a django app to permit POST. Our code tries to login first, and then use our established python-request session to POST data, but our POST request is always unauthenticated. Here's what we are trying # client.py LOGIN_URL = 'http://localhost/accounts/login' ADD_URL = 'http://localhost/add' import requests rqst = requests.session() rsp = rqst.get(LOGIN_URL) token = rsp.coolies['csrftoken'] rsp = rqst.post(LOGIN_URL, auth=(uname, pwd), data={'csrfmiddlewaretoken':token, 'next':'/'}) # at this point, rsp.status_code == 200 and we are logged in payload = {'foo':'bar'} rsp = rqst.post(ADD_URL, json=payload) # Error -- this post always returns 403 -> HttpResponseForbidden # view.py def view_add(request): if request.user.is_authenticated: return HttpResponseForbidden('not authenticated') ... We have enabled django sessions in settings.py. We have no problem accessing GET views using this same pattern. Its only POST where we are having trouble. Any ideas, pointers? -
django get variables from html
So, i'm complety new to Django, my question is simple. I'm rendering a html page with objects called "tweets":calling tweets My goal is to save data from tweets in my model Tweet:Tweet model Is there any way my view function that will store some tweets can get variables like "tweet.screen_name" or "tweet.id" that are only knowed by html? html page Thank you for your time! -
User uploads with nginx and docker
I have a Django app where users can upload files containing data they want to be displayed in the app. The app is containerised using docker. In production I am trying to configure nginx to make this work and as far as I can tell it is working to some extent. As far as I can tell the file does actually get uploaded as I can see it in the container, and I can also download it from the app. The problem I am having is that once the form has been submitted it is supposed to redirect to another form, where the user can assign stuff to the data in the app (not really relevant to the question). However, I am getting a 500 error instead. I have taken a look at the nginx error logs and I am seeing: [info] 8#8: *11 client closed connection while waiting for request, client: 192.168.0.1, server: 0.0.0.0:443 and [info] 8#8: *14 client timed out (110: Operation timed out) while waiting for request, client: 192.168.0.1, server: 0.0.0.0:443 when the operation is performed. I also want the media files to be persisted so they are in a docker volume. I suspect the first log … -
I have a large csv dataset and i want to import into django database? Django 2.1
I read somewhere on here that it can be done with Django, so yesterday i wrote a program & spent most of the day scrapping a website and have over 20k in a few separate files, i will get more in future but want to see this done first. I am using sqlite3 for database that Django defaults too... I'm thinking i may need to change to a different database with the amount of data i could be using? Also how do i go about getting this data in to my columns in the database? Thanks! -
Django- custom field
I'm new to django and i've got the following problem. I am trying to add some feature for an existing object. To do this, I've added a new model for the feature in models.py file: class Book(models.Model): title = models.CharField( null=False, max_length=30, verbose_name=_('title')) description = models.TextField( blank=True, null=False, verbose_name=_('description')) Then I updated the class of the existing object in models.py and added a field of the feature I created: class Library(Content): books = models.ManyToManyField(Books, blank=True) The problem begins with the form of Library.I added a new field for the feature: class LibraryForm(forms.Form): title = forms.CharField( max_length=100, required=True) description = forms.CharField( widget=forms.Textarea, required=False, max_length=1000) **strong text**books = forms.CharField(required=False, max_length=1000)** after submit the new form the data updated in django but actually for the existing library there are no changes and the books field is empty. what have i missed? -
handle '&' in url parameter DJANGO
I am creating an api in django in which I have a parameter (state_name) and the value of state_name can include '&' in its value which is causing certain problems ? For example if my url is like http://localhost:8080/api?state_name=jammu&kashmir&value=2 so in the above example when i try to fetch the values from the url it takes the value of state_name only 'jammu' and treats kashmir as a parameter? What can i do to resolve this issue in django ? -
How to share cache between a task and a view with Django?
In my django project, I got a task running every 5 minutes (with Celery and Redis as a broker): from django.core.cache import cache @shared_task() @celery.task(base=QueueOnce) def cache_date(): cache.set('date', datetime.now) print('Cached date : ', cache.get('date')) And it's running fine, printing the new cached date everytime it runs But then, somewhere in one of my views I try to do this : from django.core.cache import cache def get_cached_date(): print('Cached date :', cache.get('date') And then it prints "Cached date : None" Here's my cache settings : CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.filebased.FileBasedCache', 'LOCATION': '/tmp/cache', } } I don't get it, why is the value available in one place and not in the other while I'm using a singe location file ? Am I trying to do something wrong? Thanks for the help -
Issue with Sorl Thumbnail not rendering certain url
I have searched for a solution to this issue to no avail. Im using sorl thumbnail in a django app. Take the 2 urls below: https://i.ebayimg.com/images/g/lVYAAOSw1XFbzwjM/s-l300.jpg https://i.ebayimg.com/00/s/MTIwMFgxNjAw/z/lVYAAOSw1XFbzwjM/$_57.JPG?set_id=8800005007 They both point to the same image but in different sizes. In my html files the first url seems to work just fine, here is a snippet: {% thumbnail "https://i.ebayimg.com/images/g/lVYAAOSw1XFbzwjM/s-l300.jpg" as thumb %} <img src="{{ thumb.url }}"> {% endthumbnail %} When I use the second link like so {% thumbnail "https://i.ebayimg.com/00/s/MTIwMFgxNjAw/z/lVYAAOSw1XFbzwjM/$_57.JPG?set_id=8800005007" as thumb %} <img src="{{ thumb.url }}"> {% endthumbnail %} The image is not rendered at all I have tried to debug this issue by using both links in a simple html page and implementing the <img src="link"/> and they both display fine so Im inclined to suspect the issue here lies with sorl thumbnail -
Trying to retrieve data from POST petition
I'm new to HTML and I've got this sort of quiz which displays one question and multiple answers to the user. Now I'm trying to retrieve which answers the user selected but I haven't been able to do so. This is the code of the answers of the quiz: <form action="/reto_resultado/{{ clave_primaria }}" method="post"> {% csrf_token %} {% for respuesta in respuestas %} <li class="list-group-item"> <div class="form-check"><input class="form-check-input" type="radio" name="respuesta" id="respuesta{{ forloop.counter }}"><label class="form-check-label" for="respuesta{{ forloop.counter }}">{{ respuesta.texto }}</label></div> </li> {% endfor %} <div class="buttons"><input class="btn btn-primary" type="submit" role="button" style="background-color: rgb(52,58,64);"></form> This is the code in which I try to retrive those answers: respuesta_marcada = request.POST.get('respuesta', '') The problem is that I only get 'None' or 'on', which means nothing for me. -
Where in the project code are groups instances created and permissions assigned?
I was going through the documentation of django 2.1, I see that group permissions can be created inside a user model, or directly and then they can be assigned to a group instance using the permissions attribute. What I don't get is where in my project should I add the code which creates a Group instance and assigns a permission to that instance. -
Write not fully displayed Django field
I need to write a Django custom field where the stored value is not fully displayed. For example if the stored value is "079684" I need it to be displayed as "---84". Is it possible to do so ? If yes how should I implement my custom field ? -
sphinx-apidoc vs autosummary
I'm running into a bit of brick wall trying to work out the best way to implement automatic documentation generation for a Django project my project structure is similar to the following: myproj/ # project root |- docs/ # docs root |- myproj/ # package root |- app1/ |- app2/ |- app3/ utils.py ... I would like to automatically generate documentation for everything under the package root directory- and initially started using sphinx-apidoc, but then read something that implied I should be using autosummary instead and have not been able to find any information outlining what the difference between these two options is. -
js and css tries to be loaded from internet in closed network
Good day! Making a django project in closed network, using a bootstrap-datepicker-plus as datepicker widget. Store all css and js localy. When i open a page, witch uses a datepicker widget, in chrome developer mode (F12) see this jss and css double load bootstrap-datetimepicker.css, bootstrap-datetimepicker.min.js, moment-with-locales.min.js loaded from local static folder and tries to be opened from https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.css https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment-with-locales.min.js https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js My project templates doesn't have any external links, looks like <link rel="stylesheet" href="{% static 'css/bootstrap.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-theme.min.css' %}"> <link rel="stylesheet" href="{% static 'css/bootstrap-datetimepicker.css' %}"> <script type="text/javascript" src="{% static 'js/jquery-3.3.1.min.js' %}"> </script> <script type="text/javascript" src="{% static 'js/bootstrap.js' %}"> </script> <script type="text/javascript" src="{% static 'js/moment-with-locales.min.js' %}"> </script> <script type="text/javascript" src="{% static 'js/bootstrap-datetimepicker.min.js' %}"> </script> Page is loading 2 min. How to disable this second load of bootstrap-datetimepicker.css; bootstrap-datetimepicker.min.js; moment-with-locales.min.js from global network ? Thanks a lot, sorry for my English. -
Display a form feild i.e., a choice field of form in the template django
I've have forms.py file in that i have a choice field which i've to display it in the template.html forms.py Choices = [('Yelp',)] class UtilitiesForm(forms.Form): api_select = forms.MultipleChoiceField(widget=forms.Select(), choices=Choices) text_url = forms.CharField() template.html {% block body_content %} <form action="/utilities/fetch-data/" method="post" id="utitliy__form"> <div class="form-row"> <label>Select an API</label> {{ form.api_select }} </div> </form> {% endblock body_content %} i'm getting Value error can you guys help me how to write the choice field in template.html -
Problems with parsing soap request using Spyne django python?
I am learning to build a soap server and soap client in django. Went through google and found out that Spyne is a great library for building Soap API and so i tried it. Everything worked fine. Now, i wanted to add header authentication in my client-server request and for some reason, I keep getting this annoying error. What could i be doing wrong ? raise Exception("message'%s', not-found" % mn) Exception: message's0:headers', not-found Soap server class Requestheader(ComplexModel): username = Unicode password = Unicode class SoapService(ServiceBase): __in_header__ = Requestheader @rpc(Unicode(nillable=False), _returns=Unicode) def hello(ctx, name): username = ctx.in_header.username password = ctx.in_header.password print('username',username,password) return name Soap client from suds.client import Client from suds.cache import NoCache my_client = Client('http://127.0.0.1:8000/demo/soap_service/?WSDL',cache=NoCache()) username ='rj' password ='m12345' my_client.set_options(headers=(username , password)) print ('Function hello: ', my_client.service.hello('BLUE')) -
Compare dictionary in template django
views.py : @login_required(login_url='/account/login/') def TaskCreateView(request,pk,todo_id): completed={} if not request.user.is_authenticated: return redirect('accounts:index') elif User.objects.filter(pk=request.user.pk, mentor__isnull=True).exists(): instance = get_object_or_404(Level, pk=pk) messages.warning(request, 'You have not added a trainer yet') print("TRAINER ILADA") return HttpResponseRedirect(instance.get_absolute_url()) else : instance = get_object_or_404(Level, pk=pk) qs = instance.todo_set.get(id=todo_id) #user = Task.objects.filter(student=request.user) todo = Task.objects.filter(todo=qs, student=request.user) if todo.exists(): form = StudentTaskForm(request.POST or None, request.FILES or None) if form.is_valid(): form.instance.user = User.objects.get(id=request.user.id) obj = form.save(commit=False) obj.student = request.user obj.todo = qs obj.level = instance obj.save() ImageFormSet = modelformset_factory(Images, form=ImageForm,min_num=0, max_num=3, validate_min=True,extra=3) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES, queryset=Images.objects.none()) if formset.is_valid(): for form in formset.cleaned_data: try: image = form['image'] Images.objects.create(post=todo[0],image=image) except KeyError: pass return redirect('student:dashboard') else: formset = ImageFormSet(queryset=Images.objects.none()) notifications = Notification.objects.filter(receiver=request.user) context={ 'form': form, "qs": qs, 'formset': formset, 'notifications': notifications, 'completed':completed, 'hubnotify': hubnotifications, 'acceptnotify': acceptnotify, 'follownotify': follownotify, } return render(request,'task_form.html',context) inside tempate: {% for key,value in completed.items } {% if {{value}} == True %} <script type="text/javascript"> $('[data-click="swal-taskcompleted"]').click(function (e) { e.preventDefault(), swal({ title: "Already Completed", text: "You have already completed this task!", icon: "error", buttons: { cancel: { text: "Cancel", value: null, visible: !0, className: "btn btn-default", closeModal: !0 }, } }) }); </script> {% endif %} {% endfor %} <form id="post_form" action="" method="post" enctype="multipart/form- data"> <!- - {{ form.media … -
How to ssh connection another server with Django
Hi everyone. as mentioned in the title My project is django web interface for xml edit and .conf file edit. How to ssh connection another server(for xml file and .conf file save) because I need to write another server path SSH_ADDRESS = "10.9.2.212" SSH_USERNAME = "django" SSH_PASSWORD = "asdfghj" SSH_COMMAND = "echo 'Hello World!'" ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh_stdin = ssh_stdout = ssh_stderr = None ssh.connect(SSH_ADDRESS, username=SSH_USERNAME, password=SSH_PASSWORD) ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(SSH_COMMAND) print("connected") -
Previous URL not being removed from actual one
I'm not familiar with HTML and I've got the following problem. I've got this button code in which I'm referencing another HTML with a parameter. <div class="buttons"><a class="btn btn-primary" role="button" href="reto_resultado/{{ clave_primaria }}" style="background-color: rgb(52,58,64);">Comprobar</a> The problem comes when I go to another page of my site clicking in a button in the navbar. I get this URL in the browser: http://localhost:8000/reto_resultado/reto.html Why doesn't 'reto_resultado' just disappear from the URL, as it has nothing to do with the page I just went to? -
Kafka Producer and Consumer Scripts to Run automaically
I have a Django project and I am using pykafka. I have created two files named producer.py and consumer.py inside the project. I have to change directory into the folder where these are present and then separately run python producer.py and consumer.py from the terminal. Everything works great. I deployed my project online and the web-app is running so I want to run the producer and consumer automatically in the background. How do i do that? -
How to create records when a model has one-to-many recursive relationship using TastyPie?
I am making POST requests using TastyPie. The Task model has a one-to-many recursive relationship via the parent_task_id field. Model: class Task(models.Model): title = models.CharField(max_length=100) description = models.TextField() due_date = models.DateTimeField(default=timezone.now) parent_task_id = models.ForeignKey( "self", on_delete=models.CASCADE, null=True, related_name='parenttaskid' ) status = models.CharField(max_length=3, default="PND") alert_time = models.DateTimeField(default=timezone.now) deleted = models.BooleanField(default=False) def __str__(self): return self.title In my api.py class TaskResource(ModelResource): class Meta: queryset = Task.objects.order_by('due_date').filter(deleted=False) authorization = Authorization() allowed_methods = ['get'] class CreateTaskResource(ModelResource): parent_task_id = fields.ForeignKey(TaskResource, 'id', full=True, null=True, blank=True) class Meta: queryset = Task.objects.all() authorization = Authorization() allowed_methods = ['post'] resource_name = "create_task" I am unable to create a Task when I specify the parent_task_id. This is the error message I am getting when I do that: "error_message": "An incorrect URL was provided '1' for the 'TaskResource' resource.", -
Editing view for multiple models with the same foreign key
Pretty new to Django, so apologies in advance. I have the following models, Reservation is for a particular reservation at a hotel. Each Reservation has related a Housekeeping model for each day of the stay: class Reservation(models.Model): arrival_date = models.DateTimeField() departure_date = models.DateTimeField() class Housekeeping(models.Model): reservation = models.ForeignKey(Reservation, on_delete=models.CASCADE) date = models.DateField() housekeeping_status = models.BooleanField(default = True) I am trying to create a single editing view that shows a form for all the Housekeeping.housekeeping_status booleans for a certain Reservation and allows one to update them. I have tried using the generic UpdateView class but got nowhere, does anyone know how one would do this? Or perhaps an alternative way of setting up the problem? Cheers -
How to perform multiplication in django model?
This is my model: class Purchase(models.Model): Quantity = models.PositiveIntegerField() rate = models.DecimalField(max_digits=5,decimal_places=2) Amount = models.DecimalField(max_digits=5,decimal_places=2) I want to perform multiplication between Quantity and rate and store the result in Amount... So I have done something like this: from django.db.models import F @receiver(pre_save, sender=Purchase) def update_amount(sender,instance,*args,**kwargs): totalamount = Purchase.objects.get(F('rate') * F('Quantity')) instance.Amount = totalamount But its giving me this error: 'CombinedExpression' object is not iterable Do anyone have any idea how to do this??? -
Using django channels with threading.Thead
I'm using django channels in order to send multiple responses to a single request. The code is something like this: class terminal(WebsocketConsumer): def connect(self): self.accept() def disconnect(self, close_code): self.close() def receive(self, text_data): data_json = json.loads(text_data) if data_json['event'] == 'initial': self.t = threading.Thread(target=self.send_data) self.t.daemon = True self.t.start() elif data_json['event'] == 'pause': pass print("done") def send_data(self): n = 100 end = 1000000 while (n + 1 < end) # some code self.send(json.dumps({'data':data}) n += 1 I've used thread to be able to listen to pause and other events while data is being sent to the client. The problem is that the thread keeps running after websocket gets disconnected. Is there a way to kill a python thread in disconnect function? Or maybe a better way to implement this?