Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ignore csv column python/django
I am importing a csv into my django web app and get_or_creating new objects per row. However, I would like to skip a row if one of its columns does not contain one of a few approved phone numbers. Code below, what can I add to achieve the desired result? csv_file = request.FILES['file'] if not csv_file.name.endswith('.csv'): message.error(request, 'this is not a csv file') data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for column in csv.reader(io_string, delimiter=",", quotechar='"', quoting=csv.QUOTE_ALL, skipinitialspace=True): _, created = Call.objects.get_or_create( name=column[0], phone_number=column[1], etc... ) context = {} -
What should return custom authenticate_header that extend BaseAuthentication of DRF
I'm working in a Django-Python project, and have a class ApiAuthentication that extend of rest_framework.authentication.BaseAuthentication. This Class have the method authenticate_header(self, request). In this method I get the auth token from the header and make multiple checks; now at the end, after making sure that the token it's valid and get the user related to the request, what should return this method?. In the code of BaseAuthentication say: """ Return a string to be used as the value of the `WWW-Authenticate` header in a `401 Unauthenticated` response, or `None` if the authentication scheme should return `403 Permission Denied` responses. """ which string?, I need an example, I try multiple values and always receive {"status":401,"type":"api-error","description":"Authentication credentials were not provided.","error":"NotAuthenticated"} By other side, the method Authenticate works fine and return a two-tuple (user, token), I would like to return something like this un authenticate_header. -
Django admin templates looks different between server and local
When I deployed my app on heroku, it looked different from what I have on local server. It just displayed basic html, no css at all. I was trying to add local admin templates to my new template folder. But still didn't work. TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'main/templates/')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] How can I make it work. What other information should I provide? Thanks. -
i cant seem to get object from my detail view to appear in template
i wanted to have two pks in the url of my detail view but the template doesn't seem to get the object from the view: class DetailBook(generic.DetailView): model=Book template_name='./subject/bookdetail.html' def get_object(self, pk, pk_2): subject_obj = Subject.objects.filter(subject_name=pk).first() obj = Book.objects.filter(subject=subject_obj,book_name=pk_2).first() return obj def get(self, request, pk, pk_2): self.object = self.get_object(pk, pk_2) context = self.get_context_data(object=self.object) return self.render_to_response(context) enter code here path('subject/<int:pk>/book/<int:pk_2>/detail', views.detailBook.as_view(),name='detailbook'), -
Migration during heroku deployment fails
I have done this tutorial from Realpython on building a location-based app. I am now deploying to Heroku. The app was created and pushed to Heroku successfully. The problem now arises when I run heroku run python manage.py migrate. I get the error below in my terminal: File "manage.py", line 16 ) from exc ^ SyntaxError: invalid syntax I have installed gdal to Heroku by following this: heroku-buildpack-apt Another problem I have noted is that when I run heroku run python --version it shows that Heroku is using python 2 for my app while I have set python 3 in the runtime.txt file (I suspect its because of the Aptfile I added to install gdal) Please help. Consider me a beginner. -
Request.user as initial data don't work in django forms
I have a model named Porumbei, a form named AdaugaPorumbel and I want as initial data to be request.user. #My model class Porumbei(models.Model): COMPARTIMENTE = [ ('Matcă', 'Matcă'), ('Tineret', 'Tineret'), ('Zburători', 'Zburători'), ('Decedați', 'Decedați') ] SEXE = [ ('Mascul', 'Mascul'), ('Femelă', 'Femelă'), ('Pui', 'Pui') ] id_porumbel = models.AutoField(primary_key=True) data_adaugare = models.DateTimeField(default=timezone.now, null=True, blank=True) crescator = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, blank=True) serie_inel = models.CharField(max_length=25, null=False, blank=False, unique=True, help_text="Seria de pe inel. Ex: RO 123456") #My form class AdaugaPorumbel(forms.ModelForm): class Meta: model = Porumbei fields = ['data_adaugare', 'serie_inel', 'anul', 'culoare', 'culoare_ochi', 'sex', 'ecloziune', 'rasa', 'linie', 'nume', 'tata', 'mama', 'compartiment', 'status', 'data', 'vaccinat', 'info', 'imagine', 'imagine_ochi'] widgets = { 'ecloziune': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'data': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'vaccinat': forms.DateInput(format='%d/%m/%Y', attrs={'class': 'form-control', 'type': 'date'}), 'info': forms.Textarea(attrs={'class': 'form-control mt-15', 'rows': '3', 'placeholder': 'Vor apărea în pedigree'}), } error_messages = { 'serie_inel': { 'required': 'Introduceţi seria inelului!', 'unique': 'Porumbelul este deja adăugat în baza de date!', }, } #My view @login_required(login_url='/auth/login/') def porumbelnou(request): if request.method == "POST": form = AdaugaPorumbel(request.POST, request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return HttpResponseRedirect('/porumbei/vizualizare') else: form = AdaugaPorumbel() context = { 'form': form, } template = loader.get_template("adaugare-porumbel.html") return HttpResponse(template.render(context, request)) With these configuration, the crescator … -
Django - serializer returns update data but don't modify db
I have following serializer: class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = ( 'pk', 'user', 'isAdmin', 'isAccountant', 'isAuditor', 'isManager' ) def update(self, instance, validated_data): instance.isAdmin = validated_data['isAdmin'] instance.isAccountant = validated_data['isAccountant'] instance.isAuditor = validated_data['isAuditor'] instance.isManager = validated_data['isManager'] user = validated_data.pop('user') u = User.objects.get(email=user['email']) u.first_name = user['first_name'] u.last_name = user['last_name'] u.username = user['email'] u.email = user['email'] u.save() return instance when I send PUT request, in response I get updated data. But in database it remains the same. What am I doing wrong ? -
Django Object Filter
I have a simple filter where a user enters a string, term, which is compared against the column companyId in my local database. If there is a match, the appropriate record/s are then rendered in a table within my template. However, no data is being rendered in the template, only rows of empty fields matching the number of records for a particular query. I have similar logic used for displaying these records unfiltered which works fine. views.py def opportunity_dashboard(request): try: term = request.GET.get('search_query') if term: filtered_objects = Opportunity.objects.filter(companyId__icontains=term) filtered_local_zip = zip(filtered_objects) context = { 'term': term, 'filtered_local_zip': filtered_local_zip, 'filtered_connectwise_zip': filtered_connectwise_zip } return render(request, 'website/opportunity_dashboard.html', context) template.html {% if term %} {% for object in filtered_local_zip %} <tr> <th style="text-align: center;"> <a href="https://solutions.byteworks.com/new_opportunity/new_opportunity_review?id={{ object.id }}">&#9998;</a> </th> <td> <div class="select"> <select disabled id="bw_status" name="status"> <option value="{{ object.status }}">{{ object.status }}</option> </select> </div> </td> <td> <a{{ object.opportunityName }}</a> </td> <td>{{ object.companyId }}</td> <td> <div class="select"> <select id="bw_account_manager" name="account_manager"> <option value="{{ object.accountManager }}">{{ object.accountManager }}</option> </select> </div> </td> -
I'm trying to retrieve data from Template using the foreign key related tables. But not working
I'm trying to retrieve data from template level which is connected with foreign key to the derived class. But not working. Models: class School(models.Model): name = models.CharField(max_length = 256) principal = models.CharField(max_length = 256) location = models.CharField(max_length = 256) class Student(models.Model): name = models.CharField(max_length = 256) age = models.PositiveIntegerField() school = models.ForeignKey(School, related_name='students', on_delete = models.CASCADE) Views: class SchoolListView(ListView): context_object_name = 'schools' model = models.School template_name = 'basic_app/School_list.html' class SchoolListView(ListView): context_object_name = 'schools' model = models.School template_name = 'basic_app/School_list.html' Template <div class="jumbotron"> <h1>Welcome to School Detail page</h1> <h2>School Details:</h2> <p>Name: {{ school_detail.name}} </p> <p>Principal: {{ school_detail.principal}} </p> <p>Location: {{ school_detail.location}} </p> <h3> Students:</h3> {% for student in school_detail.students.all %} <p>{{ student.name }} who is {{ student.age }} years old.</p> {% endfor %} Cannot retrieve student data from the student table from the template. -
How to deploy angular 8 ssr and django rest framework separately on the same server (heroku or digitalocean) )
Most of the tutorials say that you have to integrate angular into django but I do not want to do that. I want to deploy both on the same server with angular using node-express and django using gunicorn. But I do not know how to do it. I know how to deploy angular ssr only and django alone but not both on the same server. Thanks in advance -
Unable to run Selenium tests for a Django app using Selenium docker services in GitLab-CI
Whenever I run my Selenium tests in GitLab-CI, I get a WebDriverException from Selenium. I've tried two different set ups, both of which run fine locally using Docker, but neither of which work in CI. Using Selenium Grid in CI, when I try to set up the remote driver I get the message Error forwarding the new session Empty pool of VM for setup Capabilities {acceptInsecureCerts: true, browserName: firefox, marionette: true, moz:firefoxOptions: {args: [-headless]}} Using standalone Firefox, I seem to be able to set up the remote driver, but when I run the tests I get Reached error page: about:neterror?e=dnsNotFound&u=http%3A//runner-dzqg9xmx-project-57-concurrent-0%3A38153/news/&c=UTF-8&f=regular&d=We%20can%E2%80%99t%20connect%20to%20the%20server%20at%20runner-dzqg9xmx-project-57-concurrent-0. If anyone can point me at a working GitLab-CI configuration that uses Selenium docker images as services, or tell me what's wrong with my configurations below, I'd be grateful. Using Selenium Grid Selenium Grid would be my preferred method because it would make it easier for us to run tests in multiple browsers. base/tests/utils.py I set up my tests using this base class. class SeleniumTestCase(LiveServerTestCase): host = os.environ('HOSTNAME') @classmethod def setUpClass(cls): super().setUpClass() options = webdriver.FirefoxOptions() options.headless = True cls.browser = webdriver.Remote( 'http://selenium-hub:4444/wd/hub', webdriver.DesiredCapabilities.FIREFOX, options=options, ) .gitlab-ci.yml test: stage: test image: $CMS_IMAGE_NAME variables: HUB_HOST: selenium-hub HUB_PORT: 4444 START_XVFB: 'false' services: - … -
My worker Celery works in localhost but not in heroku
I set up the workers on my localhost (windows) and it works perfectly but on heroku it doesn't work. I'm using Django, Reddis and Celery. celery.py from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'eco_gestao.settings') app = Celery('eco_gestao') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Procfile: web: gunicorn eco_gestao.wsgi --log-file - My problem i think is here-> worker: celery worker --app=eco_gestao.celery settings: CELERY_RESULT_BACKEND = 'django-db' # CELERY_BROKER_URL = 'redis://localhost:6379' REDIS_URL='redis://' BROKER_URL = os.environ.get("REDISCLOUD_URL", "django://") CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' -
an unlimited number of pictures for each list
I want to solve the problem for an unlimited number of pictures for each list. Whenever I want to put the pictures on the list, I get only one picture or type several fields for the picture.How is it class Listing(models.Model): title = models.CharField(max_length=200) address = models.CharField(max_length=200) class Photo(models.Model): image = models.ImageField(default="default.png", blank=True, null=True, upload_to="photos/%Y/%M/%D") listing = models.ForeignKey(Listing, related_name='Photos', on_delete=models.CASCADE) -
Filtering for entities that have equal related entities
I'd like to build a queryset that finds balls with equal attributes. 2 models exist: Ball | id | name | +----+----------+ | 1 | Neptun | | 2 | Speedy | | 3 | Highway | BallAttribute | id | ball_id | key | value | +----+--------------------+-------+ | 1 | 1 | color | blue | ← | 2 | 1 | size | xxl | ← | 3 | 2 | color | blue | | 4 | 2 | size | xl | | 5 | 3 | color | blue | ← | 6 | 3 | size | xxl | ← The equal attributes are marked with a ←. So in the end, I'd like to get the balls Neptun and Highway in return (Speedy is not selected because size is different, and all attributes are required to be equal). Please keep in mind that the required attribute keys and values are not known, so solutions like these are not possible: Ball.objects.filter( balls__key="color", balls__value="blue" ).filter( balls__key="size", balls__value="xxl" ) How can I build such a queryset with Django? -
Why HTTP response returns 2 codes
This is a django project, a very simple one indeed, i got a question about the response code of the HTTP header. I am running it on localhost. # URL Patterns in the Project folder. urlpatterns = [ path('blog/', include(blog.urls)), ] # URL Patterns in the blog folder. urlpatterns = [ path('index/', blog.views.index, name='blog_index'), path('about/', blog.views.about, name='blog_about') ] Everything runs fine but the shell response is: [21/Aug/2019 21:15:54] "GET /blog/index/ HTTP/1.1" 200 144 The question is about the HTTP Header response 200 144 After playing with urllib a bit i used to think that headers send only 1 response code 200 OK For some reason django sends 2 codes 200 OK 144 Corresponds with HTTP 404. # Reference https://developer.twitter.com/en/docs/basics/response-codes.html -
Django Getting Static Files
I am exhausted to link bundle.js in my template. This is my Django DIR client │ ├── components │ │ ├── about.js │ │ ├── App.js │ │ ├── contact.js │ │ ├── form.js │ │ ├── home.js │ │ └── table.js │ ├── index.html │ ├── index.js │ ├── postReducer.js │ ├── redux │ │ ├── component │ │ │ └── postAction.js │ │ └── reducers │ │ ├── postReducer.js │ │ └── rootReducer.js │ └── style.scss ├── dist │ ├── bundle.js │ ├── index.html │ └── main.js ├── package.json ├── package-lock.json ├── README.md ├── requirements.txt My bundle.js file is inside dist folder, I loaded static in template like this : {% load static %} {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Django & React Starter</title> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> </head> <body> <script src="{% static "bundle.js" %}"></script> </body> </html> and this is my settings.py fiel STATIC_URL = os.path.join(os.path.dirname(BASE_DIR), "dist") + '/' I dont know why it is not getting my bundle.js file. can anyone help me to fix this? -
How to troubleshoot Django web app connection to Teradata?
Can anyone please help me to troubleshoot this? A new Unix server is setup as test environment for an existing production django web app/server. On the test server I can pull data using bteq, but the web app doesn't (i.e. the json data doesn't populate. Everything else looks fine). All the configuration/settings are the same as the production server. I tried below steps in the production server and it returned with data, but in the test server I got the error. python manage.py shell >>> from project_web.shared_functions import teradata_con >>> import json >>> import pandas as pd >>> sql = """select distinct rgn_num, rgn_nm from RLDMPROD.SITE_HIER;""" >>> pd.read_sql(sql, teradata_con()) Error: python: libltdl/ltdl.c:1197: try_dlopen: Assertion `filename && *filename' failed. Aborted (core dumped) -
Custom 404 and 500 pages in django with -> DEBUG = True
I want to present the sample of my website to a client and it isn't quite finished yet but it is very important for me to hide the errors and to not show my codebase which django does if a server error occurs in development mode. Like so - Django depicting what went wrong Also I cannot turn DEBUG = False as in that case the media files aren't displayed as they are currently being served locally. Which won't be served if DEBUG = False. So is there a way to serve media files locally with DEBUG = False or to display custom 404 and 500 pages with DEBUG = True. -
Django Model is not JSON serializable
Im trying to return a dictionary of Django models in JSON format. I have tried serializers, model_to_dict, json.dump and can't seem to get it working. a small snippet of the code: queryset = (my_object.objects.all()) test_dict = {} for x in queryset.iterator(): m = some_value_i_calculate test = model_to_dict( x ) test_dict[m] = x sorted_dict = dict(sorted(test_dict.items())) return json.dumps(sorted_dict, ensure_ascii=False) the dictionary I create is a {int:object, int:object, int:object, ....} I want this to be returned as the response. I keep getting issues such as "TypeError: Object of type object is not JSON serializable" -
Why does Django run server hang when using docker-compose up?
When I run docker-compose up, Django starts to load. It goes thru the about four steps. After it does a system check and identifies (0 issues), it stops at displaying the current date and time. This is the point where it just hangs. Nothing else happens. C:\Users********\Desktop\code\hello>docker-compose up Creating hello_web_1 ... done Attaching to hello_web_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:33:11 When I do docker-compose down, the system exits Gracefully(lol). Then I run docker-compose logs and it shows the correct info: C:\Users********\Desktop\code\hello>docker-compose logs Attaching to hello_web_1 web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:36:44 web_1 | Django version 2.2.3, using settings 'hello_project.settings' web_1 | Starting development server at http://0.0.0.0:8000/ web_1 | Quit the server with CONTROL-C. web_1 | Watching for file changes with StatReloader web_1 | Performing system checks... web_1 | System check identified no issues (0 silenced). web_1 | August 21, 2019 - 17:55:22 web_1 | Django version 2.2.3, using settings 'hello_project.settings' web_1 | Starting … -
creating navigation based on models with foreign keys
I'm having trouble finding a solution, or even where to look for a solution to this, and am a beginner with Django. I'd like to create a dynamic navigation for a project I'm working on. from django.db import models from tinymce import models as tinymce_models class League(models.Model): name = models.CharField(max_length=50) description = tinymce_models.HTMLField() crest = models.ImageField(upload_to='league-crests/', default=0) def __str__(self): return self.name class Club(models.Model): name = models.CharField(max_length=50) description = tinymce_models.HTMLField() crest = models.ImageField(upload_to='club-crests/', default=0) league = models.ForeignKey(League, on_delete=models.CASCADE, default=0) def __str__(self): return self.name Basically I'd like a top level nav called "Leagues" with a dropdown list of all leagues saved in the database. For each league i'd like a second level dropdown with the clubs in each league. I've been googling around but haven't found anything pointing me in the right direction. -
Looking for an API for user authentication for Django
Is there any ready to use applications/API available for user authentication in Django? I am looking for one that has not only username, email and password but takes other fields(say, date of birth, website, image) too during user registration process. -
Django routing - The empty path didn't match any of these
Very basic question and I was surprised I wasn't able to find an answer. I'm just starting looking at django and did an out-of-box intallation. Created a project and created an app. The default content of urls.py is very simple: urlpatterns = [ path('admin/', admin.site.urls), ] And if I open the django site home page, I get the content with a rocket picture. However, like I said, I have created another app in the project, let's say called 'bboard'. And I have created a simple 'hello world' function in bboard/views.py def index(request): return HttpResponse('Hello world') to enable it for access through browser, I have modified the original urls.py file in the following way: from bboard.views import index urlpatterns = [ path('admin/', admin.site.urls), path('bboard/', index), ] This way I can access localhost:port/admin and localhost:port/bboard URLs, but if I try to open the home page with localhost:port now, I get Page not found error. Using the URLconf defined in samplesite.urls, Django tried these URL patterns, in this order: admin/ bboard/ The empty path didn't match any of these. if I comment out the second item in urlpatterns list, everything works. So why does the additional pattern impact this and what needs to … -
Django: How to fix NoReverseMatch for PasswordChangeDoneView?
i trying do use and understand the Django authentication system. So far everything works. I can register as a new user, login, logout, dashboard except the PasswordChangeDoneView or my success View did not work. Thats the error message after i changed my password. ...//127.0.0.1:8000/account/change_password/ NoReverseMatch at /account/change_password/ Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Request Method: POST Request URL: http://127.0.0.1:8000/account/change_password/ Django Version: 2.2.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'password_change_done' not found. 'password_change_done' is not a valid view function or pattern name. Exception Location: E:\coding\proj\farm_env\lib\site-packages\django\urls\resolvers.py in _reverse_with_prefix, line 668 Python Executable: E:\coding\proj\farm_env\Scripts\python.exe Python Version: 3.7.3 Python Path: ['E:\\coding\\proj\\farm', 'E:\\coding\\proj\\farm_env\\Scripts\\python37.zip', 'E:\\coding\\proj\\farm_env\\DLLs', 'E:\\coding\\proj\\farm_env\\lib', 'E:\\coding\\proj\\farm_env\\Scripts', 'c:\\python app\\python37-32\\Lib', 'c:\\python app\\python37-32\\DLLs', 'E:\\coding\\proj\\farm_env', 'E:\\coding\\proj\\farm_env\\lib\\site-packages'] Server time: Wed, 21 Aug 2019 16:57:21 +0000 account / urls.py (its my main app) from django.urls import path from . import views from django.contrib.auth import views as auth_views app_name='account' urlpatterns = [ path('login/', auth_views.LoginView.as_view(), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='account/logout.html'), name='logout'), path('change_password/', auth_views.PasswordChangeView.as_view(template_name='account/password_change.html'), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(template_name='account/password_change_done.html'), name='password_change_done'), path('register/', views.register, name='register'), path('dashboard/', views.dashboard, name='dashboard') ] This is my password change site with a link to password_change_done account / templates / account / password_change.html {% extends 'base.html' %} {% load static %} {% block custom_css %} <link … -
How to show objects from models by ForeignKey
I'm trying to show objects from Section models to home page.What do I need to do? I have tags(mechanism) on site which working absolutely identical. But Section objects don't showing models.py tags = models.ManyToManyField('Tag', blank=True,related_name='audio') section = models.ForeignKey('Section', blank=True,related_name='audio', on_delete=models.CASCADE, null=True) views.py def tag(request,slug): tags = Tag.objects.get(slug=slug) template = 'home/tags.html' return render(request, template, {'tags': tags}) def main(request): tags = Section.objects.all() template = 'home/home-page.html' return render(request, template, {'tags': tags}) html-file {% for content in tags.audio.all %} <img id="book__img" src="/media/{{content.img}}" alt=""> <p class="text__for__book">{{content.title}}</p> {% endfor %} Html tag file(tag.html) show all good. But when i'm trying to do it on main page it don't work