Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can i store data from a form in the safest way possible in Django?
I'm creating a site in django; at a certain point, i should be able to store an API key. Obviosuly, this API key should not be stolen, so i need to store it in the safest way possible, just like Django does with passwords. My question is: is there a way to encrypt data submitted from a form in django? I know how to send data from a form, but how can i store it in the safest way possible? -
Django-Jet: How do I set a foreign key null, if it is autocompleted via AJAX requests?
I am using Django-Jet and have a model with many ForeignKey fields. For those fields I want their values retrieved dynamically via AJAX and not preloaded. One of the field is like this: class Person(Base_Entity): first_name = models.ForeignKey( 'Name', null = True, blank = True, default = None, verbose_name = _('first name of person'), on_delete = models.SET_NULL, related_name = 'is_first_name_of_%(app_label)s_%(class)s', ) ) @staticmethod def autocomplete_search_fields(): return 'first_name__name', (The Name model has hundreds of entries, and there will be even more later) It seems I cannot set that field to NULL in Django Admin (no line with dashes appears): If I turn on autocomplete (i.e. remove the autocomplete_search_fields method), I do get that NULL entry, BUT I also get all the possible values preloaded in the HTML select, and that slows down the page loading to a point it is not usable. I am using Django 2.1.4, Django-Jet 1.0.8 (I suspect the issue is closely related to Django-Jet) Any help is appreciated. -
Python Combining a FOR Loop and an IF statement
I have some issues with this small piece of code: for key in UserInput.objects.all(): if UserInput.category_id == 2: data = {} data['label'] = key.input_date data['value'] = key.input_value dataSource['data'].append(data) I just don't seem to get it working. The only thing I want to do is to retrieve all rows from the UserInput table which have a category_id of 2 and then execute the four data lines for each row to use in my bar chart. I get a variety of errors. I get an Object of type date is not JSON serializable on data['label'] = key.input_date. If I replace input_date with another (string) value, my bar chart seems to work, but it shows an empty bar chart. I tried to serialize my input_date, but I get even more errors when I try to do that. json_data = serializers.serialize("xml", UserInput.objects.all()) and fields = ['input_date'] qs = UserInput.objects.all() json_input_data = serializers.serialize('json', qs, fields=fields) My Python knowledge doesn't reach far enough to solve this on my own. I would prefer to sort the data to month-year instead of day-month-year, but I would understand if this is beyond the scope of my question EDIT: As many pointed it out in the comments, I do indeed … -
Why doesn't a website hosted at home offer the same download speed as just transferring files?
I am hosting a Django website at home on which I can watch specific video's and photos wherever I want. The only problem is that some of the video's take a while to load and keep buffering. Even when I am on the same wired network. When directly watching the video's from a shared network folder it all works fine. Transferring these video files from the network shared folder to my PC works at around 120 MB/S and speed-test online show me my network speed of around 250 MB/S so the internet speed shouldn't be the issue. But why am I not able to stream these video's properly from the Django web-page? When checking my network activity while watching a video from the network web-page it shows me around 1 MB/S which apparently isn't enough. Does anyone know I could fix or improve this? -
hmtl url button in django doesn't find my url ' not found. 1 pattern(s) tried: ['edit/(?P<pk>\\d+)$/$']'
I'm trying to build a button in django1 for send me the PK to one of my view but isn't working at all. I'm in a scren displaying mi data, withouth the button everything is OK, my array of objects show the data but when I add the button it crashes html {% if alumnos %} <ul> {% for alumno in alumnos %} <td>{{ alumno.dni }}</td> <td>{{ alumno.nombre }}</td> <td>{{ alumno.apellido1 }}</td> <td>{{ alumno.apellido2 }}</td> <td>{{ alumno.email }}</td> <td>{{ alumno.repetidor }}</td> <td> <a class="btn btn-secondary" href="{% url 'edit' pk=alumno.DNI %}">Editar</a> </tr> {% endfor %} url.py url(r'^edit/(?P<pk>\d+)$/$', views.edit_alumno3,name='edit'), view.py def edit_alumno3(request, pk): user = Alumno.objects.get(dni=pk) if request.method == 'GET': form = AlumnoForm2(instance=user) else: form = AlumnoForm2(request.POST, instance=user) if form.is_valid(): form.save() return redirect('edit.html', {'form': form}) return render(request, '/edit.html', {'form': form}) the error: NoReverseMatch at /mostrar_alumnos2/ Reverse for 'edit' with keyword arguments '{u'pk': ''}' not found. 1 pattern(s) tried: ['edit/(?P\d+)$/$'] enter image description here -
Complex three part query for db one to one messaging
Fairly new to Django and I have run into a wall with a pretty complex query for messages in a legacy db. Bear in mind I'm using a sql db to send messages and nothing fancy (for now) and DRF for API's. Scenario: User can be both message Sender and Message Receiver between self and another user. Model: class Tblmessages(models.Model): msg_id = models.AutoField(db_column='MsgId', primary_key=True) msg_sender = models.ForeignKey(AppUsers, db_column='MsgSender', related_name='msg_sender', on_delete=models.CASCADE) msg_receiver = models.ForeignKey(AppUsers, db_column='MsgReceiver', related_name='msg_receiver', on_delete=models.CASCADE) msgcontent = models.TextField(db_column='MsgContent') msgisimage = models.IntegerField(db_column='MsgIsImage') msgimage = models.CharField(db_column='MsgImage', max_length=255) msgsenttime = models.DateTimeField(db_column='MsgSentTime') msgisdeletedsender = models.SmallIntegerField(db_column='MsgIsDeletedSender') msgisdeletedreciever = models.SmallIntegerField(db_column='MsgIsDeletedReciever') msgisreaded = models.SmallIntegerField(db_column='MsgIsReaded') The goal is to merge the messages into a stack and get only the last message between the two users instead of having two pages one for receiving and the other for sending. I want to merge them into one. APIView: class MessagesListAPIView(APIView): def get(self, request, *args, **kwargs): userId = request.user.userid request_user = AppUsers.objects.get(userid=userId) sent_messages = request_user.msg_sender.all() received_messages = request_user.msg_receiver.all() sent_messages_users = list( set([message.msg_receiver for message in sent_messages])) received_messages_users = list( set([message.msg_sender for message in received_messages])) messages = [] for sent_messages_user in sent_messages_users: messages.append(models.Tblmessages.objects.filter( (Q(msg_sender=request_user) & Q(msg_receiver=sent_messages_user)) | (Q(msg_receiver=request_user) & Q(msg_sender=sent_messages_user))).order_by('-msg_id').first()) for received_messages_user in received_messages_users: messages.append(models.Tblmessages.objects.filter( (Q(msg_sender=request_user) & Q(msg_receiver=received_messages_user)) | (Q(msg_receiver=request_user) & … -
Can I check if user email verification was successful using Django automated testing?
My AccountActivationView expecting a GET request to path('email/confirm/', if the key exists, AccountActivationView invokes activation function and toggles is_active in user profile. I'm trying to implement a test for this feature using Django TestCase, but it does not produce the results I'm expecting. The view class redirects Client to the right location, but is_active state of the user account does not change. Can anyone point me in the right direction, please? Thanks in advance. class TestUserAccounts(TestCase): def setUp(self): self.client = Client() # Initial user data self.username = 'TestTest' self.email = 'test@test.com' self.password = 'test123test' # Creating user User.objects.create_user( email=self.email, username=self.username, password=self.password) def test_activating_user(self): '''Activating user account using link in the email''' user_email_activation_status = EmailActivation.objects.get( email=self.email).activated user = User.objects.get(email=self.email).is_active activation_key = EmailActivation.objects.get( email=self.email).key # The initial state of account and email should be inactive self.assertEqual(user_email_activation_status, False) self.assertEqual(user, False) # Activating the account with get request to email/confirm/<key> activation = self.client.get( reverse('accounts:email-activate', kwargs={'key': activation_key})) print(activation) # Checking if activation was successful self.assertEqual(user_email_activation_status, True) self.assertEqual(user, True) -
How add Patient in a PUT
I'm trying to add a new Paciente field to my Cita table. But you are not allowing me to add the id of this patient. { "fecha_cita": "2019-05-27", "hora_inicio": "20:00:00", "hora_final": "20:30:00", "Paciente" : [ 7 ] } Serializers.py class CitaMovSerializer(serializers.ModelSerializer): Paciente = PacienteMovSerializer(required=False,read_only=True,many = True,source='PacienteSerializer') class Meta: model = Cita fields = ('id','fecha_cita','hora_inicio','hora_final','enlace_videochat', 'tipo_servicio','descripcion','antecedentes_principales','Doctor','Paciente') views.py def put(self, request, pk): facturacion_datos_doctor = self.get_queryset(pk) if (facturacion_datos_doctor.Doctor.id==request.user.profile.id_dem): # If editors is who makes request serializer = Facturacion_datos_doctorSerializer(facturacion_datos_doctor, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) else: content = { 'status': 'UNAUTHORIZED' } return Response(content, status=status.HTTP_401_UNAUTHORIZED) -
How to use Django Haystack woosh search field in multiply templates
I have implemented a working Django 1.6 haystack/whoosh search field following Mike Hibbert's tutorial:https://www.youtube.com/watch?v=B-n6_m66TmA. The implementation works in a twitter bootstrap search field in the navbar in the url 'search'. I'd like to use the implementation in several pages in my application but it doesn't work. I've tried with implementing the search.html code in other pages with search bars but it changes the search url prefix from 'search/...' to the page url, e.g. to 'front/...' on the frontpage. I've also tried to include the search.html in other pages, both as the block content and with an include tag in the template but it hasn't worked. # in app/templates/search/indexes/search.html {% extends 'base_searches.html' %} {% block content %} <form method="get" action="."> <table> <tr><th><label for="id_q"></label></th><td><input type="text" id="id_q" name="q" placeholder="Search..." class="form-control" /><button class="btn btn-success" type="submit" value="Search"><spaclass="glyphicon glyphicon-search"></span></button></td></tr> <tr> <td>&nbsp;</td> {% if query %} {% for result in page.object_list %} <div class="alert alert-success" role="alert"> Hi, {{ user }}, here's the found database match for your search <a href="{{ result.object.get_absolute_url }}"> {{result.object.title }}.</a></div> {% empty %} <div class="alert alert-info" role="alert"> <strong>Hi {{ user }}, there's no match found in the database for your search !.</strong> </div> {% endfor %} {% endif %} <div class="col-xs-6 col-sm-3 sidebar-offcanvas" … -
Manually start uwsgi with python3.6 and python2 and django 2
I just started to use uwsgi and django. I want to invoke uwsgi manually and after that using file. I'm using python36, django 2 and if I install uwsgi (pip install uwsgi) in venv everthing is ok. Q1: When using outside of venv I first installed uwsgi: pip install uwsgi -> 2.0.18 version Installed plugins: sudo apt-get install python3-setuptools Trying to run with python36: uwsgi --plugin-dir=/usr/lib/uwsgi/plugins --plugin python3 --master --http :5000 --home ~/my_playground/webapps/ --chdir ~/my_playground/webapps/p_tscze/ --module p_tscze.wsgi:application Plugins in /usr/lib/uwsgi/plugins: /usr/lib/uwsgi/plugins$ ls | grep python3 asyncio_python36_plugin.so asyncio_python3_plugin.so python36_plugin.so python3_plugin.so Result obtained -> note python 2.7: !!! UNABLE to load uWSGI plugin: ./python36_plugin.so: undefined symbol: uwsgi_legion_scrolls !!! *** Starting uWSGI 2.0.18 (64bit) on [Wed May 29 18:04:24 2019] *** compiled with version: 7.4.0 on 29 May 2019 15:30:14 os: Linux-4.15.0-45-generic #48-Ubuntu SMP Tue Jan 29 16:28:13 UTC 2019 nodename: start-tehnicka machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 1 current working directory: /usr/lib/uwsgi/plugins detected binary path: /usr/local/bin/uwsgi chdir() to /home/anel/my_playground/webapps/p_tscze/ your processes number limit is 3618 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with --thunder-lock) uWSGI http bound … -
Insert lists into tables in postgres database
How to Insert those lists into tables in postgre database ? I want to insert these two lists into tables in postgres database in my django project. I also need return a dictionary containing top 10 words on the blog and top 10 words on the blog per author So I'd better do counter first and then put those two lists or Should I do it a different way ? These lists are in the code but I will write them below: unique_authors = list(set(authors)) unique_contents = list(set(contents)) Scrap code: import requests from bs4 import BeautifulSoup as bs from selenium import webdriver from collections import Counter import psycopg2 as pg2 from sqlalchemy.dialects.postgresql import psycopg2 url = 'https://teonite.com/blog/page/{}/index.html' all_links = [] headers = { 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8', 'User-Agent': 'Mozilla/5.0' } with requests.Session() as s: r = s.get('https://teonite.com/blog/') soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) num_pages = int(soup.select_one('.page-number').text.split('/')[1]) for page in range(2, num_pages + 1): r = s.get(url.format(page)) soup = bs(r.content, 'lxml') article_links = ['https://teonite.com' + item['href'][2:] for item in soup.select('.post-content a')] all_links.append(article_links) all_links = [item for i in all_links for item in i] d = webdriver.Chrome() contents = [] authors = [] for article … -
Change display of field.value on a per field basis?
I'm using reusable form templates to manually render form fields and I want to display the values of the form fields in a specific way. I'm looping over the fields in the form and filtering field.value based on the field name which feels sloppy. I feel like I should be able to tie how a field's value displays to the field itself, not on conditional logic within the loop. I've already tried making my fields Select widgets with explicit choices, but that has no effect on field.value, and that's what I want to display differently. Here's what I'm currently doing: {% if field.name == 'sending_domain' %} {{ field.value | default:"[ANY DOMAIN]" }} {% elif field.name == 'from_email' %} {{ field.value | default:"Not set. Required!" }} {% elif field.name == 'custom_api_key' %} {{ field.value | default:"Required custom API key not set." }} {% elif field.name == 'custom_subaccount' %} {{ field.value | default:"Not set." }} {% else %} {{ field.value | default:"None" }} {% endif %} That code works - Sending Domain displays "[ANY DOMAIN]" by default, From Email displays "Not set. Required!" by default, etc - but it also hurts my soul. What's a better way of doing this? -
Iterate over another url with a for loop in django
I'm setting up a button that save API datas into my database and I'm trying to find a way to get the description out of every products but they are not included with the main url that get all products by city: (https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr), they are only included if we use this link which call a product by its id: (https://www.test-headout.com/api/public/v1/product/get/508). So I was adviced to first hit the Listing API to get all products. Iterate over the list and get id and hit the product/get API to get the description. This is what I've tried so far but I don't get how to do the iteration part: My Django views: def api_data(request): response = requests.get("https://www.test-headout.com/api/public/v1/product/listing/list-by/city?cityCode=BARCELONA&limit=5000&language=fr", headers={ "Headout-Auth": HEADOUT_TEST_API_KEY } ).json() if (request.GET.get('mybtn')): for item in response['items']: # for loop Product.objects.get_or_create( title=item['name'], destination=item['city']['name'], #description=response['contentListHtml'][0]['html'], link=item['canonicalUrl'], image=item['image']['url'], ) return render(request, "form.html") How can I do this? -
Django: Is it possible to download a csv file from another website and add it to FileField through Django shell?
While using Django, when I need to do something on data from DB, I've always been using Django shell. For this time, I want to do something like the below scenario in Django shell. I have a model Store with a bunch of stores. In Django shell, 1. import Store model 2. With each of store name, I search each name and download a csv file based on each store name. 3. Add the downloaded csv file to a FileField in Store model. I know how to #1 and #3, but I'm confused how I can do #2. How can I input the store name and download a csv file from the store name in Django shell? -
How to have model method run automatically if field is greater than 12
If my model field hours is more than 12.0 I want end_time to be set automatically without the user having to save or even be in the app. Is there a way to do this in a model method without the user having to save the time entry? Models.py class Entry(models.Model): TUID = models.IntegerField() start_time = models.DateTimeField() end_time = models.DateTimeField(blank=True, null=True, db_index=True) seconds_paused = models.PositiveIntegerField(default=0) pause_time = models.DateTimeField(blank=True, null=True) date_updated = models.DateTimeField(auto_now=True) hours = models.DecimalField(max_digits=11, decimal_places=2, default=0) pause_time_end = models.DateTimeField(blank=True, null=True) def _str_(self): return self.TUID def timeStop(self): if self.hours >= 12: self.end_time = timezone.now() return self.end_time -
How does a queryset knows what records are in the database if it doesn't hit the database
Django querysets are lazy person_set = Person.objects.all() In the documentation it says the above code doesn’t run any database queries. But with the above command it generates a queryset in this case person_set and this object contains all the person objects. person_set = Person.objects.all() print(person_set) This is the output. <QuerySet [<Person: Person object (7)>, <Person: Person object (8)>, <Person: Person object (9)>]> If it didn't hit the database then how does it know that what records are in the database? As it is supposed to run queries only when it is evaluated using a loop or others methods. -
Ordered List through Django Admin
Is there a way to make an ordered list (from a list of choices) with Django? For example in the Admin page having a table of options, you select the order and it saves the ordering? Running on Python 2.7 -
Django: Adding user to groups in a signal
I created a signal which is supped to do 3 things: Create a User Create the Profile of said user Add User to a Group Using a signal, steps 1 and 2 work fine but I can't seem to add the user to a group (step 3). # Signals @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) group = Group.objects.get(name='generics') instance.groups.add(group) Did some debugging and found out that even if I comment out Profile.objects.create(user=instance) I still can't add any groups to instance. Am I missing anything here? I'm not getting any errors. -
I had this error when creating a new user in the django admin page: NotImplementedError at /admin/auth/user/add
I'm trying to create a new user from the admin page, but I got this error. should I add a founction? or a model? Thank's in advance -
Is there any way to print date dynamically in footer of webpage
I am creating a blood bank website in django. I have a seperate layout.htm page, which is extended by various pages. Now i have to get the system date and print in the footer, footer lies in layout.htm. I have done similar kinds of project in laravel and there I used <?php echo date("Y")?>. Now i need to do similar kind in django. How is it possible? I have tried searching similar kinds of problem in various source. I didn't find proper solution. I am new to django :) <footer> &copy; 2017- <?php echo date("Y")?> Copyright Rashikraj Shrestha <br> 9860080002 <br> KTM, Nepal </footer> I need alternative to <?php echo date("Y")?> in django for jinja format expected outcome in webpage is : 2017-2019 -
Is there a way to filter data when passing it in ModelForm and how can we edit them?
I'm creating a site to register students. So basically it is divided into 3 parts 1. A student register model which take the name, fathername, etc of student. 2. A student fee model which use foreignkey to get register student. 3. ModelForm for showing student fee model to enter data. Now the problem if I want to fill a student fee of class 1 it shows all the student of other classes, but I want the student filter according to their classes and their name show and in front of them. By some reach I got to know about ModelForm instance I wrote code for automatically add register students to student fee. def student_fee(request): # add a selection field to a variable for filtering student_class below this. students = StudentRegister.objects.filter(student_class="1") .... for x in students: if not StudentFee.objects.filter(student=x): StudentFee.objects.create(student=x, fee=0, pending_fee=0) But for instance I have to know primary key of every student I can loop through them but it only get the last element. models.py class StudentRegister(models.Model): student_image = models.ImageField(upload_to="register_student", blank=True) student_class = models.CharField(max_length=2, choices=STUDENT_CLASS, default="1") mobile_number = models.CharField(max_length=50) student_name = models.CharField(max_length=50) father_name = models.CharField(max_length=50) mother_name = models.CharField(max_length=50) address = models.CharField(max_length=200) student_fee = models.CharField(max_length=10, default="0") Date_Of_Birth = models.DateField(auto_now=False) admission_fee … -
Customising and adding to Django registration page, with check box option
I have a Django registration form created using crispy forms and by importing the 'UserCreationForm'. (i.e 'form' in the code is an instance of UserRegisterform). Currently, the register form is set up to ask for the user's username, email and password (twice). I would like to add a requirement for the user to fill in, before clicking submit, in the form of selecting a check box. (code shown below) Additional snippet that I would like to appear before the submit button on my existing registration page <div class="container"> <p>Please select the option that is most relevant to you</p> <form> <div class="radio"> <label><input type="radio" name="optradio" checked>I am a W</label> </div> <div class="radio"> <label><input type="radio" name="optradio">I am a WP</label> </div> </form> </div> As a newbie to Django, I have looked at the other questions, but none is this specific, and others skirt around the topic but in much older versions of Django. Essentially, I need some guidance on the best way to implement this. First off, I simply added the code to the registration page itself (the html), like so: register.html {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Register for … -
Reset Password Device Issue
I'm having an issue with reset password. Whenever I request change password from my mobile app, password reset fails. Open web view for password reset in mobile app. Request password reset. Email is sent sent to users email address. (The Problem) When user taps on link and let's say user has the gmail app, gmail will open the link in chrome and the link immediately becomes invalid. How can I fix this issue and make the link valid regardless of browser or client? Weirdly it works the opposite way around. If I request password reset from app web view and then go to my computer browser to reset the password then it works just fine. -
how to handle Image with serializer
i have some problem in uploading picture in user profile its already extended onetoone from users , when i wanted to upload pic via postman it returned null value serializer : class UserProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = UserProfile fields = ('user', 'bio', 'avatar') def validate(self, data): print(data) self.context['avatar'] = self.context['request'].FILES.get('avatar') return data def create(self, validated_data): user_data = validated_data.pop('user') user = UserSerializer.create(UserSerializer(), validated_data=user_data) validated_data['avatar'] = self.context['avatar'] validated_data['user'] = user profile = UserProfile.objects.create(**validated_data) profile.bio = validated_data["bio"] profile.save() return profile The model: class UserProfile(models.Model): user = models.OneToOneField(User, primary_key=True, related_name='profile', on_delete=True) bio = models.CharField(max_length=50, blank=True) avatar = models.ImageField(upload_to="media", blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username -
Columns not working correctly. Bootstrap 4
Im trying to split two parts of my container inline with each other but instead everything in col-md-5 is just going underneath. {% extends 'base.html' %} {% block html %} <div class="container-fluid"> <div class="col-md-7"> <h1>Express Yourself</h1> <form method="post" <input type="text"> {% csrf_token %} {{ form.post}} <br> <button class="btn btn-primary" type="submit">Post</button> </form> <h2>{{text}}</h2> {% for post in posts %} <h1>{{ post.post }}</h1> <p>Posted by {{ post.user.get_full_name }} {{ post.created }} </p> {% endfor %} </div> <div class="col-md-5"> <h2>other people</h2> </div> </div> {% endblock %}