Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving selected column data from dataframe into another CSV file
I am trying to select data columns from a csv dataframe using a list of columns and then save the extracted data into another csv_file. columns_to_extract = 'Name', 'Age', 'Address', 'Sex' df = pd.read_csv('some-data.csv', encoding='ISO-8859-1') df = df[[columns_to_extract]] # this doesn't work # also tried df = df[[columns_to_extract.split(',)]] and didn't work too import StringIO s_df = StringIO.StringIO() df.to_csv(s_df) -
How to join two serializers many to one in Django?
I am trying to join two serializers. I am trying to get table_db, otherwise, I am trying to insert in which register of the object (from table_db query), the list of other_table with table_db id. The relationship is many to one, so, one other_table has one table_db, but, table_db have many other_table. It is clearer in the example: t_db =table_db.objects.all() data_table_db = table_dbSerializer(t_db,many=True).data for t in t_db: o_t_db = other_table.objects.filter(table_db_id=t.pk) data_other_table= other_tableSerializer(o_t_db,many=True).data **data = data_table_db + data_other_table ????? //HOW CAN INSERT IT?** return Response(data, status=status.HTTP_200_OK) Models class other_table(models.Model): table_db = models.ForeignKey(Table_db, on_delete=models.CASCADE, blank=True,null=True) In table_db I do not have any reference to other_table, because it have many. The serializers are basic for now: from table_db.models import table_db from other_table.models import other_table class other_tableSerializer(serializers.ModelSerializer): class Meta: model = other_table fields = ( ) class table_dbSerializer(serializers.ModelSerializer): class Meta: model = table_db fields = ( ) -
My searchbox with ajax is not working in django
i am developing a project with django, is a eCommerce shop. And i want to implement a searchbox to search the products on it. I have developed with ajax, but at the moment that i search a product. It shows me all the products that i have and not just only tha product that i want. This is my view for the searchbar: def searchBar(request, option): busqueda = request.POST.get('busqueda', '') categoria = Clasificacion.objects.filter(existencia=True) items = Articulo.objects.filter(nombre_producto__icontains = busqueda) contexto = { 'items':items, 'categoria':categoria, } return render(request, 'adminview/article.html', contexto) this is the html with the form calling the view: <form action="{% url 'adminview:searchBar' option=1 %}" method="get" class="d-none d-sm-inline-block form-inline mr-auto ml-md-0 my-2 my-md-20 navbar-search"> <div class="input-group"> <input type="text" id="busqueda" class="form-control bg-light border-1 small" placeholder="Buscar producto..." aria-label="Search" aria-describedby="basic-addon2" name="busqueda"> <div class="input-group-append"> <button class="btn btn-primary" type="submit"> <img src="{% static 'img/search.png'%}"width="20px" height="20px" /> </button> </div> </div> </form> ... <script src="{% static 'js/search.js'%}"></script> My urls: url(r'^search/ajax(?P<option>\d+)/$', searchBar, name="searchBar"), url(r'^buscar/searchAjax/$', searchBar), And this is my script from javaScript to do that if you need it: $(function(){ $(‘#busqueda’).keyup(function() { $.ajax({ type: “POST”, url: “searchAjax/”, data: { ‘busqueda’: $(‘#busqueda’).val(), ‘csrfmiddlewaretoken’: $(“input[name=csrfmiddlewaretoken]”).val() }, success: searchSuccess, dataType: ‘html’ }); }); }); function searchSuccess(data, textStatus, jqXHR) { $(‘#resultado_busqueda’).html(data); } Hope you … -
Django-wordpress-api leads to "JSONDecode Error"
Trying to integrate Wordpress blog into a Django Project. Set it up like its described in the Django Wordpress API: First, I checked if WP Rest API isn't disabled. Then I added these lines after pip install django-wordpress-api-plugin: settings.py: INSTALLED_APPS += ('wordpress_api',) WP_URL = 'https://wordpress-site.com/blog' views.py: import wordpress_api re_path(r'^blog/', include('wordpress_api.urls')), Tried manage.py runserver and localhost:8000/blog. Then this Error disappeard: JSONDecodeError at /blog/ Expecting value: line 1 column 1 (char 0) Request Method: GET Request URL: http://localhost:8000/blog/ Hoping for some hints how to fix that problem -
Valid UUID django.core.exception
I am trying to create an object with a parent field but I got a n error and don't know how to solve it? oblast_obj = Place.objects.get_or_create(name=oblast) city_obj = Place.objects.get_or_create(name=city, parent=oblast_obj) and when I`m creating city_obj the exception is: django.core.exceptions.ValidationError: ["'Волинська Обл.' is not a valid UUID."] -
Django - Form error “Select a valid choice. That choice is not one of the available choices.”
I'm working with Python3 and Django 2.2. Basically I have a form that contains three dropdowns. The second dropdown depends on the value of the first one. The third dropdown depends on the value of the second. For exampe, dropdown #1 has the option "AreaA AreaB AreaC". If "AreaA" selected, dropdown #2 should display options "RailwayA, RailwayB and RailwayC", If Railway selected, dropdown #3 should display options "StationA, StationB and StationC". And, I want this widget of two like following. ●Your Near Station first: Area > Railway(Ajax) > Station(Ajax) second: Area > Railway(Ajax) > Station(Ajax) So here comes my question. How to define that form? This is what I have so far: ▪️model.py class NearStation(models.Model): area = models.ForeignKey(Area, on_delete=models.CASCADE, null=True) railway = models.ForeignKey(Railway, on_delete=models.CASCADE, null=True) station = models.ForeignKey(Station, on_delete=models.CASCADE, null=True) profile = models.ForeignKey(Profile, on_delete=models.CASCADE) class Area(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Railway(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Station(models.Model): name = models.CharField(max_length=255) railway = models.ForeignKey(Railway, on_delete=models.PROTECT) area = models.ForeignKey(Prefecture, on_delete=models.PROTECT) def __str__(self): return self.name ▪️form.py class NearStationForm(forms.ModelForm): area = forms.ModelChoiceField(queryset=Prefecture.objects.all(), label='Area', required=True) railway = forms.ModelChoiceField(queryset=Railway.objects.none(), label='railway', required=True) station = forms.ModelChoiceField(queryset=Station.objects.none(), label='station', required=True) def __init__(self, *args, **kwargs): super(NearStationForm, self).__init__(*args, **kwargs) for i in range(2): area = … -
I want to add a specific field in my table
I have a two user_type students and teachers. I want to add specific field to teachers and students when i update a profile class UserType(models.Model): user =models.OneToOneField(User, on_delete=models.CASCADE) USER_TYPE = ( (1, 'Student'), (2, 'Teacher'), ) user_type = models.IntegerField(choices=USER_TYPE) Here I created a Teacher model where i can add extra fields for teacher class Teacher(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = 2 specialty = models.CharField(max_length=20) picture = models.ImageField(upload_to = '', default = '') #return the teacher's name def __str__(self): return str(self.user) Similarly I created a Student model to add extra field for users class Student(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user.user_type = 1 picture = models.ImageField(upload_to = '', default = '') #return the student's name def __str__(self): return str(self.user) @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: if instance.user_type == 2: Teacher.objects.create(user=instance) elif instance.user_type == 1: Student.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): if instance.user_type == 2: instance.teacher.save() elif instance.user_type == "patient": instance.student.save() I don't know how to add usertype specific additional information. I couldn't save the instance of teacher and student as a separate table. and also the profile didn't work -
Django An invalid form control with name='' is not focusable
I created a Django form that have dropdown in one of the field. When I tried to submit the form without selecting the dropdown item, the form is not submitted because I set in my code that it won't submit unless the form valid using is_valid(). However, it was not showing the validation error message. In the browser console, the is an error message An invalid form control with name='start_position' is not focusable. I have read some questions about this and they said that it happened because there is a hidden field. After I inspect element, it is true that div class='start_position' is hidden. However, I don't know how to fix it in Django. This is the code that create dropdown field. class LocationForm(forms.Form): start_position = forms.ModelChoiceField( required=True, label="Start Position", queryset=Location.objects.all() ) I want the validation message show like in the other field (I tried DateField and the validation works normally). -
Remove whitespace from HTML django template response
My assert statement is self.assertContains(request, 'User Available\n Restaurant') The print(request) returns <TemplateResponse status_code=200, "text/html; charset=utf-8"> And the print(request.content) contains <button type="submit" class="btn btn-success">User Available\n Restaurant </button>\n \n\n </td>\n\n The problem is there is "double space" instead of "single space" in the print(request.content), therefore in an attempt to strip the spaces of the HTML response for a more robust testing. I did; html_page = str(request.content) html_page.replace(" ", "") self.assertContains(html_page, 'User Available\nRestaurant') AttributeError: 'str' object has no attribute 'status_code' -
'Action 'graceful' failed' when adding SSL in DigitalOcean
During SSL installation for my application in DigitalOcean on Uuntu Ubuntu 16.04.6 x64 which I perform according to this tutorial. I receives the error: Saving debug log to /var/log/letsencrypt/letsencrypt.log Plugins selected: Authenticator apache, Installer apache Starting new HTTPS connection (1): acme-v02.api.letsencrypt.org Obtaining a new certificate Performing the following challenges: http-01 challenge for ebluedesign.online Enabled Apache rewrite module Error while running apache2ctl graceful. httpd not running, trying to start Action 'graceful' failed. The Apache error log may have more information. AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message (98)Address already in use: AH00072: make_sock: could not bind to address [::]:80 (98)Address already in use: AH00072: make_sock: could not bind to address 0.0.0.0:80 no listening sockets available, shutting down AH00015: Unable to open logs Unable to restart apache using ['apache2ctl', 'graceful'] Cleaning up challenges Error while running apache2ctl graceful. httpd not running, trying to start Action 'graceful' failed. The Apache error log may have more information. AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message (98)Address already in use: AH00072: make_sock: could not … -
Django/Postgres Relation does not exists (it exists)
I have a weird problem with Django on production server (DigitalOcean). Suddenly, project started raising this error. I've not changed anything on server for 2 months so it is not caused by any code changes etc. relation "mainapp_price" does not exist LINE 1: ...rom_3", "mainapp_price"."stelinka_12kg_pack" FROM "mainapp_p... Trying to load QuerySet in shell raises the same error. I've checked /var/log/postgres/... which says something similar: 2019-04-27 13:40:26 UTC [13288-11] postgres@brennholzdb ERROR: relation "mainapp_availability" does not exist at character 179 2019-04-27 13:40:26 UTC [13288-12] postgres@brennholzdb STATEMENT: SELECT "mainapp_availability"."id", "mainapp_availability"."dry_wood", "mainapp_availability"."wet_wood", "mainapp_availability"."briquettes", "mainapp_availability"."area" FROM "mainapp_availability" WHERE "mainapp_availability"."area" = 'ar' LIMIT 21 I don't have a clue where is the problem. As I said everything is migrated and there are no new changes in the code. Do you know what to do? EDIT postgres process eats almost 100% CPU.. PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 13277 postgres 20 0 385212 4916 2740 S 98.0 1.0 352:44.85 postgres 14096 django 20 0 40388 3524 2996 R 0.3 0.7 0:00.02 top 1 root 20 0 119992 5124 2996 S 0.0 1.0 0:03.54 systemd 2 root 20 0 0 0 0 S 0.0 0.0 0:00.00 kthreadd 3 root 20 0 0 … -
Graphene-django with ManyToMany & through-table
my app has several many-to-many relationships with a through-model like so: class Person(models.Model): name = models.CharField() class Group(models.Model): name = models.CharField() members = models.ManyToManyField(Person, through='Membership') class Membership(models.Model): person = models.ForeignKey(Person) group = models.ForeignKey(Group) date_joined = models.DateField() # Extra info on the relationship It would seem intuitive to represent this data in graphql without an intermediate type for Membership (option A): { "data": { "persons": [ { "id": "1", "name": "Jack", "groups": [ { "id": 3, # From Group-model "name": "Students", # From Group-model "date_joined": "2019-01-01" # From Membership-model }, ... ] } ] } } vs. option B: { "data": { "persons": [ { "id": "1", "name": "Jack", "memberships": [ { "id": 9, "date_joined": "2019-01-01" "group": { "id": 3, "name": "Students" } }, ... ] } ] } } I could not find any examples on how to implement option A with (django-)graphene. How could it be done and is this supported out of the box? What are the pros and cons on both approaches? The data needs to be also mutated quite often, does it alter the verdict? -
context processor can not pass data
i made context_processors to pass data (objects of 'League' class) to 'base.html' but when i clicked on one of nav items (that contain league object) it produced " TypeError 'League' object is not iterable " i tried to pass data to 'base.html' .... to provide pass this data to all views 'context_processors.py' from .models import League def add_to_base(request): return { 'league' : League.objects.all() } 'base.html' <div id="league-container"> {% for l in league %} <a href="{% url 'core:openleague' l.pk %}"><h2>{{ l.leagues }}</h2></a> {% endfor %} </div> -
How to detect HTML text in test assertions
My assert statement is self.assertContains(request, 'User Available\n Restaurant') And my request contains <button type="submit" class="btn btn-success">User Available\n Restaurant </button>\n \n\n </td>\n\n However my test fails, how can I fix my assert statement ? -
NGINX disable buffers for one path
I am running a django webapp (gunicorn wsgi) with nginx as my server. One of the views in django is a StreamingHttpResponse and I need the nginx server to push data immediately to the client. Currently in my nginx.conf I completely turned off buffers like so. proxy_buffering off; proxy_buffer_size 4k; I was hoping there was a way to only turn off buffers so only one path in the proxy so that other requests could benefit from it. For example, buffers would only be off when receiving requests from /stream/ -
Pass arguments in django test
I am trying to pass both the user.id and object.id to a function in the views. Here is my urls.py path('<int:tag>', views.task, name='task'), Here is my views.py def task(request, tag): task_user = get_object_or_404(Team, id=tag) task_user.assigned_to = ProjectUser.objects.get(id=request.POST.get('user_id')) task_user.save() return HttpResponseRedirect(reverse('someOtherPage')) Here is my tests.py def someTest(self): self.client.login(username='jack', password='123') user1 = auth.get_user(self.client) assert user1.is_authenticated sample = Team.objects.create(sampleField='SampleName') request = self.client.post(reverse('analyst_view_app:task_analyst', kwargs={'tag': sample.id})) The error message is: SomeApp.SomeModel.ProjectUser.DoesNotExist: ProjectUser matching query does not exist. How can I pass the user1.id from my test to the function someTest -> user_id Here is my html template if it helps <form method='POST' action="{% url 'task' object.id %}"> {% csrf_token %} <label for="select1"></label> <select name="user_id" class="mdb-select md-form" id="select1" onChange="form.submit();"> {% for user in usernames %} <option value="{{ user.id }}"> {{ user }} </option> {% endfor %} </select> </form> -
Django Static files on production
My website is working quite all right, except for static files on admin: note: static files on frontend work just fine. Also, I'm using gunicorn + nginx on debian 9, for what it's worth. Here's relevant part of my settings.py: STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') and nginx config: server { listen 80; server_name my_domain; location = /static/images/favicon.png { access_log off; log_not_found off; } location /static/ { root /home/milos/django_project_dir; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } One more thing: on development server, I've been putting all my files in django_project_dir/static. -
A way to populate a database in Django from a JSON file?
I'm working on a Django project using a noSQL database MongoDB. I have the data I need to populate the database with stored in a JSON file, but I can't figure out how to do it. The model, which I'm trying to have a one to many relationship with other objects of the same class: name = models.TextField(max_length=120, null=True) counters = models.ForeignKey('self', null=True, on_delete=models.CASCADE) image = models.ImageField(blank=False, null=True, upload_to="") And the example of my JSON file data: { "Abaddon":{ "counters":[ "Ancient Apparition", "Brewmaster", "Doom", "Outworld Devourer", "Shadow Demon" ], "image":"media/Abaddon.png" },... Do I need to format the JSON data differently? I'm at a loss here. -
Django: CSRF cookie not set (subdomain + https + apache + wsgi)
The original error is: [Sat Apr 27 13:52:46.386072 2019] [wsgi:error] [pid 15601:tid 140129939744512] [remote <ip-address-removed>] Forbidden (CSRF cookie not set.): /login/ The application using default login view of Django. from .forms import UserLoginForm path('login/', authviews.LoginView.as_view(authentication_form=UserLoginForm)) And the form of the login view: <form action="" method="post"> {% csrf_token %} <div class="form-group has-feedback"> {{ form.username}} </div> <div class="form-group has-feedback"> {{ form.password}} </div> <div class="row"> <div class="col-8"> </div> <!-- /.col --> <div class="col-4"> <button type="submit" class="btn btn-primary btn-block btn-flat">Sign In</button> </div> <!-- /.col --> </div> </form> Apache virtual host conf file: <IfModule mod_ssl.c> <VirtualHost *:443> ServerName foo.example.edu.tr ServerAdmin foo@example.edu.tr DocumentRoot /home/<removed>/projects/abcpweb/production/ABCPWeb/webapp ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # WSGI configurations Alias /media/ /home/<removed>/projects/abcpweb/production/ABCPWeb/media/ Alias /static/ /home/<removed>/projects/abcpweb/production/ABCPWeb/webapp/static/ <Directory /home/<removed>/projects/abcpweb/production/ABCPWeb/webapp/static> Require all granted </Directory> <Directory /home/<removed>/projects/abcpweb/production/ABCPWeb/media> Require all granted </Directory> WSGIDaemonProcess abcpweb python-home=/home/<removed>/projects/abcpweb/production/EnvABCPWebProd python-path=/home/<removed>/projects/abcpweb/product ion/ABCPWeb:/home/<removed>/projects/abcpweb/production/EnvABCPWebProd/lib/python3.6/site-packages WSGIProcessGroup abcpweb WSGIScriptAlias / /home/<removed>/projects/abcpweb/production/ABCPWeb/ABCPWeb/wsgi.py process-group=abcpweb WSGIPassAuthorization On <Directory /home/<removed>/projects/abcpweb/production/ABCPWeb/ABCPWeb> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> </IfModule> wsgi.py file (I did not remove the comments to show what I tried before): import os, sys, django sys.path.append('/home/<removed>/projects/abcpweb/production/ABCPWeb') sys.path.append('/home/<removed>/projects/abcpweb/production/EnvABCPWebProd/lib/python3.6/site-packages') from django.core.wsgi import get_wsgi_application from django.core.handlers.wsgi import WSGIHandler os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ABCPWeb.settings") #django.setup(set_prefix=False) #from django.core.handlers.wsgi import WSGIHandler #application = WSGIHandler() application = get_wsgi_application() Finally, related parts of the settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', … -
No module named 'django.core.exception'
Current version of Python 3.7.3. Recently I reinstalled and all the components of Django were already. But such module does not work from django.core.exception import ValidationError cmd -
Generate static HTML page from Django pages
I have a small web site developed in Django. I want to generate static HTML pages from that web site. e.g. {% include "commondata.html" %} will be replaced by the HTML page content. How can I do that? -
How to connect an object automatically with user who is creating it and display those objects only which a specific user has created in django?
I am making a real estate app in django and the problem i am getting is that a user can login in his account and begin creating his properties and then he can view those properties but what i am getting is the properties of every user on page while it should be only the propety that specific user created. Here,s the models.py of property and i am using the django's user model from django.core.urlresolvers import reverse from django.contrib.auth.models import User class Property(models.Model): title = models.CharField(max_length = 210,default = 'None') STATUS_CHOICES = ( ('R','Rent'), ('S','Sale'), ) status = models.CharField(max_length = 210,choices = STATUS_CHOICES,default = 'None') price = models.IntegerField(default = 'None') area = models.CharField(max_length = 210,default = 'None') ROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ('MORE','More'), ) rooms = models.CharField(max_length = 210,choices = ROOM_CHOICES,default = 'None') BATHROOM_CHOICES = ( ('1','1'), ('2','2'), ('3','3'), ('4','4'), ) bathroom = models.CharField(max_length = 210,choices = BATHROOM_CHOICES,default = 'None') address = models.CharField(max_length = 210,default = 'None') state = models.CharField(max_length = 210,default = 'None') code = models.CharField(max_length = 210,default = 'None') images = models.ImageField(upload_to = 'media',default = 'None') info = models.TextField(max_length = 1000,default = 'None') parking = models.BooleanField(default = False) air = models.BooleanField(default = False) swimming = models.BooleanField(default … -
How to ensure django serves template in new tab after processing the post request params?
I have a button in my html that when clicked does some calculations and makes a post call to one of my API with some params and then from django I fetch the params and put them in the specific placeholders of the template and render the template. The problem is I can see the template being rendered (if I check the 'network' section of Google inspect element) but I don't see anything in the page. I expect the template to be rendered in a new tab with the values I fetched from the post params placed in respective placeholders in the template. Here is what I send through ajax post (I am using angular js in my project but I can also do it with plain js too) var toSend = { "user": username, "password": password, "text": text "context": $scope.newContext, } $http({ method: 'POST', url: '/correction', data: toSend }). then(function(response) { console.log(response.data); }) Here is my django function defined for the API which receives the post request @csrf_exempt def get_correction(request): if request.method == 'POST': context = {} try: print("recieved request") user_request = json.loads(request.body.decode('utf-8')) ''' some logic I use to check given the username and password, whether it is a … -
Is there a real Type Error in the following code snippet?
Can not able to render html pages with BASE_DIR in Django. 'DIRS': [os.path.join()], TypeError: join() missing 1 required positional argument: 'a' -
Creating many-to-many relationship via existing intermediary (pivot) table
I have some tables on a database and trying to create an API wrapper with Django. One of my resources to present is teachers and their related classes. The data stored in these tables: Professors: ProfessorUserId | ProfessorCode | ... TermLessons: (classes data) TermLessonId | ExamDate | ... ProfessorLessons: (pivot table) ProfessorUserId | TermLessonId | ... I designed models for Teacher and Class and then defined a many-to-many relation as below: class Teacher(models.Model): ProfessorUserId = models.CharField(max_length=255, primary_key=True) ProfessorCode = models.CharField(max_length=255) class Meta: db_table = "[Education].[Professors]" class Class(models.Model): TermLessonId = models.CharField(max_length=255, primary_key=True) teacher = models.ManyToManyField( Teacher, related_name='RelatedClasses', through='ProfessorLessons', through_fields=('TermLessonId', 'ProfessorUserId') ) class Meta: db_table = "[Education].[TermLessons]" class ProfessorLessons(models.Model): TermLessonId = models.ForeignKey(Class, on_delete=models.CASCADE, to_field='TermLessonId') ProfessorUserId = models.ForeignKey(Teacher, on_delete=models.CASCADE, to_field='ProfessorUserId') class Meta: db_table = "[Education].[ProfessorLessons]" Although I defined primary keys for all models when I try to get related results with something like: Teacher.objects.filter(ProfessorCode=' some code ').first().relatedClasses.all() I get this error message: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'TermLessonId_id'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'ProfessorUserId_id'. (207)")