Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
(1054, "Unknown column '' in 'field list'")
I know this question has been asked a couple of time but no previous answer was able to solve my problem. I had a perfectly working model in Django that looked like this: class Template(models.Model): mat = models.CharField(max_length=50, null=True) ... I had many instances of this model and up to now I was very happy with it. I recently decided that instead of a Charfield, this model was better suited to work with a ForeignKey in this position instead. To get into details, the attribute ''mat'' was previously only referring to the name of another object instance. I decided to change it to the full fledged instance with a ForeignKey instead, like it should have always been. Therefore, the model was modified as follows: class Template(models.Model): mat = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='mat_stock', verbose_name="mat", null=True) ... I followed this change with the regular */manage.py makemigrations, */manage.py migrate. While these two commands worked, I was unable to select any instance of Template in the shell without raising the following error: OperationalError: (1054, "Unknown column 'myapp_template.mat_id' in 'field list'") Similar situations I encountered were solved by manually adding a column in SQL with the following line: ALTER TABLE database.myapp_template ADD mat INT; Unfortunately this … -
Django| Multiple forms on one page, Only one displayed
Started coding during lock down so I'm very new, what I've made may be a ugly monster so beware. Any help would be appreciated as google has abandoned me in my time of need. I've added a form in a bootstrap modal which can be either Film/TV/Book. My issue is it always thinks its TV. This all worked when it had 3 different URL's and 3 separate POST requests but I wanted to feel fancy. I'm trying to tell it with the 3 buttons what its type is using the button name. <div class="btn-group mr-2" role="group" aria-label="second group"> <div class="dropright"> <a class="btn btn-primary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Add Items </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink"> <a class="dropdown-item" data-toggle="modal" data-target="#exampleModal" name="Film">Add Film</a> </form> <a class="dropdown-item" data-toggle="modal" data-target="#exampleModal" name="TV">Add TV</a> <a class="dropdown-item" data-toggle="modal" data-target="#exampleModal" name="Book">Add Book</a> </div> </div> </div> I set it to "TV" on the get request (only for the reason that it fell over when I left it blank) and I assume this is the first part of my issue. On a post request I check the for the button name. def franchise_details(request,franchise_slug): franchises_details = Franchise.objects.get(franchise_slug=franchise_slug) form_type = forms.CreateFranchiseItemEp if request.method == 'POST': if "Film" in request.POST: area = … -
NoReverseMatch when using versioning in django
I'm trying to implement versioning in django. My project urls.py looks like: url(r"^v1/sites/", include((site_urls, "sites"), namespace="v1")), url(r"^v2/sites/", include((site_urls, "sites"), namespace="v2")), In st_site/urls I got following url: url(r"^$", site_list, name="site-list"), in my settings/base.py I added: REST_FRAMEWORK = { "DEFAULT_VERSIONING_CLASS": "rest_framework.versioning.NamespaceVersioning", "DEFAULT_VERSION": "v1", } This works for the default version (v1). If I run a test class, it works. But when I try to test a v2 version test like: def test_get_all_sites_admin_version_2(self): self.client.force_login(self.admin_user) url = reverse("v2:admin-site-list") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) I got following error: django.urls.exceptions.NoReverseMatch: Reverse for 'admin-site-list' not found. 'admin-site-list' is not a valid view function or pattern name. Do I need to configure something else? This for example does work: self.client.force_login(self.admin_user) url = reverse("admin-site-list") response = self.client.get(url) self.assertEqual(response.status_code, status.HTTP_200_OK) -
Django custom Authentication get_user() error
The views.py def login_form_student(request): if request.method =='POST': roll_no = request.POST.get('username') password = request.POST.get('pass') user = authenticate(request, uniq_id=roll_no,password=password) if user is not None: login(request,user) return redirect('/userdetails/prof_page/') else: return redirect('/userdetails/thankyoupage/') return render(request,'user_interaction/login_form.html') The custom backend from .models import user_detail from django.contrib.auth.backends import ModelBackend class user_auth_custom(ModelBackend): def authenticate(self,request,uniq_id,password): flag = 0 try: user = user_detail.objects.get(roll_no=uniq_id) if password == user.password: flag = 1 return user except flag == 0: pass return None def get_user(self,user_id): try: return user_detail.objects.get(pk=user_id) except user_detail.DoesNotExist: return None The models.py class user_detail(models.Model): full_name = models.CharField(max_length=264,null=True) roll_no = models.CharField(max_length=264,unique=True,primary_key=True) management_name = models.CharField(max_length=264) contact_no = models.CharField(max_length=10) email = models.EmailField(max_length=254) department = models.CharField(max_length=264) residential_status = models.CharField(max_length=264) password = models.CharField(max_length=32,default='fmspsg2020') last_login = models.DateTimeField(auto_now=True) I get a Validation Error. ['“18pw13” value must be an integer.'] 18pw13 is actually a roll_no. What should i do? Should i create a new user_id attribute to the model of IntegerField? -
How to determine if a user has created a profile on django
I have been working on a view in which all of the users profiles are displayed but so that a user can see other peoples profiles in that page, the user has to first create a profile. So every user who has already created a profile can go to that page but if the user havent created one yet, then the user goes to a form until it has a profile. To make this happen, I am using if statments to determine if the user has a profile or not but this is not working because every user is being redirected to the form part of the page even if the user has already a profile. How can this error be fixed, is there something wrong with the database? Is there other way to make these happen besides using if statements on the html? models.py class Mates(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usermates') users_requests = models.ManyToManyField(User, related_name="users_requests") req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) views.py def matesmain(request): contents = Mates.objects.all() context = { 'contents': contents, 'form_mates': MatesForm(), } print("nice3") return render(request, 'mates.html', context) def mates(request): if request.method == 'POST': form_mates = MatesForm(request.POST, request.FILES) if form_mates.is_valid(): instance = form_mates.save(commit=False) instance.user … -
How do I link a button in html with my python code? (django)
I'm working with django and I want to calculate something depending on what the user put on the selectboxes of my page, but I don't know how to connect that with my python code that calculates everything, please help :( -
check if the user has logged in with social account - Django
in the web site that i'm working on , I have an authetication system and I'm using django allauth at the same time so the user can login with his gmail or facebook account if he wants . how can I check in the template if the user has logged in with his facebook/gmail account ? -
How can I make a django model upload its files to a folder named after the model instance?
How can I make a django model upload its files to a folder named after a property of the models instance? Here is my model. I am trying to make it upload all files to badgeTemplates/[model instance name here]. class BadgeTemplate(models.Model): name = models.CharField(max_length=50,unique=True) slug = models.SlugField(unique=True) template = models.FileField(upload_to='badgeTemplates/',unique=True) configFile = models.FileField(upload_to='badgeTemplates/',unique=True) def __str__(self): return self.name I've tried upload_to='badgeTemplates/' + self.name but it says that self isn't defined. -
Why am I getting this Import Error? ImportError: cannot import name 'setting' from 'social_django.utils'
I am not completely sure what all info is needed to diagnose this issue so I want to apologize in advance. I am trying to allow people to login via facebook and when I tried to migrate my changes I received this Import Error. ImportError: cannot import name 'setting' from 'social_django.utils' -
Updated: Django REST test error: *** django.db.utils.ProgrammingError: relation “” does not exist
Hi I am testing my rest endpoint. When I run my test, python manage.py test apps.pulse.tests.PulseTestCase.test_clinical_pubmed I get an error that the test model does not exist in the test db. *** django.db.utils.ProgrammingError: relation "pulse_targets" does not exist For my endpoint I need to create a test model instance, which should get populated in setUp(self), but that error gets throwed. Here is my test class, from django.test import TestCase from apps.pulse.models import Twitter from apps.pulse.models import Targets import json class PulseTestCase(TestCase): def setUp(self): Targets.objects.create(gene_id='wee1') target = Targets.objects.get(gene_id='wee1') Twitter.objects.create(target=target, tweet_id=21212121212112212, user_id=313133131313133, tweet='wee1 in cancer', user='DeplorableBob') def test_twitter(self): response = self.client.post('/api/pulse/twitter', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) def test_clinical_pubmed(self): response = self.client.post('/api/pulse/clinicalpubmed', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) Here is my models.py class Targets(models.Model): gene_id = models.CharField(max_length=50, blank=True, null=True) uniprot = models.CharField(max_length=50, blank=True, null=True) ensemble_id = models.CharField(max_length=50, blank=True, null=True) Here is views.py @api_view(['POST']) def get_clinical_pubmed(request): try: response = middleware.get_clinical_pubmed(request.data['geneID']) except: response = 'Something went wrong' return JsonResponse({'data': response}) -
addEventListener not working. error says main2.js:1 Uncaught TypeError: Cannot read property 'addEventListener' of null at main2.js:1
let carts = document.querySelectorAll('.add-cart'); let products = [ { name:'Heinz Beanz', tag: 'heinzbeans', price: 2.55, inCart: 0 }, {` name:'brown Beanz', tag: 'brownbeans', price: 2.55, inCart: 0 }, { name:'white Beanz', tag: 'whitebeans', price: 2.55, inCart: 0 }, { name:'black Beanz', tag: 'blackbeans', price: 2.55, inCart: 0 }, { name:'red Beanz', tag: 'redbeans', price: 2.55, inCart: 0 } ]; for (let i=0; i < carts.length; i++) { carts[i].addEventListener('click', () => { cartNumbers(products[i]); }) } //* i've also tried document.getElementById("carts").addEventListener("click", () => { alert("You clicked?"); }); and it hasn't worked either and I still get Uncaught TypeError: Cannot read property 'addEventListener' of null at main2.js:1*// -
403 error when using directory in django project with Apache
I am serving a django webserver using apache with mod_wsgi on windows 10. Actually I have a workaround for my issue but I need help understanding the reason. Below is my apache vhost httpd-vhosts.conf <VirtualHost *:80> ServerName localhost DocumentRoot "C:/wamp/www/djangoproj" WSGIPassAuthorization On ErrorLog "logs/my_application.error.log" CustomLog "logs/my_application.access.log" combined WSGIScriptAlias / "C:/pythonstuff/djangoproj/djangoproj/wsgi_windows.py" <Directory "C:/pythonstuff/djangoproj/djangoproj"> <Files wsgi_windows.py> Require all granted </Files> </Directory> Alias /static "C:/pythonstuff/djangoproj/djangoproj/static" <Directory "C:/pythonstuff/djangoproj/djangoproj/static"> Require all granted </Directory> Alias /posters/ "C:/pythonstuff/djangproj/posters/" <Directory "C:/pythonstuff/djangproj/posters/"> Require all granted </Directory> </VirtualHost> bascially what I am trying to do is go to my /posters/ route, which is the last Alias in the code above. For those who are familiar with django, the route for my django project is "C:/pythonstuff/djangoproj/(my apps start here)" If I try to access my /posters/ route, I get a response 403 error, don't have permission to access this resource. In the error logs, I get below: [authz_core:error] [pid 1444:tid 1404] [client 127.0.0.1:52082] AH01630: client denied by server configuration: C:/pythonstuff/djangproj As mentioned above, I found a workaround. I just need to change my posters directory to another folder that is not in the django project folders. However may I know why is it like that? I don't see any part of … -
Failure to render static files django with no visible error
when i run runserver and try to load my css files as well as the html all i get is a white page nothing comes up, html only appears when i remove static links to leave it as bare html . I'm running the project in development mode settings.py STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')] base.html {% load static %} <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <title></title> <meta name="description" content="" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="stylesheet" href="" /> <!--Templates CSS--> <link href="https://fonts.googleapis.com/css?family=Work+Sans:300,400,500,600,700&amp;amp;subset=latin-ext" rel="stylesheet" /> <link rel="stylesheet" href="{% static 'plugins/font-awesome/css/font-awesome.min.css' %}" /> <link rel="stylesheet" href="{% static 'fonts/Linearicons/Linearicons/Font/demo-files/demo.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/bootstrap/css/bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/owl-carousel/assets/owl.carousel.min.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/owl-carousel/assets/owl.theme.default.min.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/slick/slick/slick.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/nouislider/nouislider.min.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/lightGallery-master/dist/css/lightgallery.min.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/jquery-bar-rating/dist/themes/fontawesome-stars.css' %}" /> <link rel="stylesheet" href="{% static 'plugins/select2/dist/css/select2.min.css' %}" /> <link rel="stylesheet" href="{% static 'css/style.css' %}" /> </head> <body> <!--[if lt IE 7]> <p class="browsehappy"> You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience. </p> <![endif]--> {% block content %} {% endblock … -
How do I compare Django user inputted DateFields to date.today() or similar objects?
I'm trying to compare a date captured using the DateField input in Django to today's date or other metrics, but am running into these type of errors error: TypeError: unsupported operand type(s) for -: 'DateField' and 'datetime.date' TypeError: '>' not supported between instances of 'DateField' and 'datetime.date' It looks like I need to convert DateField to a different type, but I am running into roadblock in doing so. An example of my code is below. class MyDate(models.Model): my_date = models.DateField() today = date.today() if my_date > today: print("The date entered is in the future") elif my_date == today: print("The date entered is today") else: print("The date entered is in the past") -
Django Rest Framework: Get unique list of values from nested structure
I want to be able to return a list of strings from a deeply nested structure of data. In this scenario, I have a API that manages a chain of bookstores with many locations in different regions. Currently, I have an API endpoint that takes a region's ID and returns a nested JSON structure of details about the region, the individual bookstores, and the books that can be found in each store. { "region": [ { "store": [ { "book": { "name": "Foo" } }, { "book": { "name": "Bar" } }, { "book": { "name": "Baz" } } ], }, { "store": [ { "book": { "name": "Foo" } }, { "book": { "name": "Bar" } } ], }, { "store": [ { "book": { "name": "Foo" } }, { "book": { "name": "Baz" } }, { "book": { "name": "Qux" } } ] } ] } The serializers I created for the above response look like: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = "__all__" class BookstoreSerializer(serializers.ModelSerializer): books = BookSerializer() class Meta: model = Bookstore fields = "__all__" class RegionSerializer(serializers.ModelSerializer): stores = BookstoreSerializer(many=True) class Meta: model = Region fields = "__all__" class BookstoreChainSerializer(serializers.ModelSerializer): regions = RegionSerializer(many=True) class … -
How Can I properly Customise LoginView
I am trying to customize the LoginView to user my Form That I created but getting an error when trying to enter the login page. TypeError: init() got an unexpected keyword argument 'request'. This is the Form Created class LoginForm(forms.Form): username = forms.CharField(label='', widget=forms.TextInput( attrs = { 'placeholder': 'username or email', } )) password = forms.CharField(label='', widget=forms.PasswordInput( attrs = { 'placeholder': 'password' } )) And I want to use it in the Login View in django.contrib.auth.views IN views.py from .forms import LoginForm from django.contrib.auth.views import LoginView class CustomLoginView(LoginView): template_name = 'login.html' form_class = LoginForm The Url I use path('login/', views.CustomLoginView.as_view(), name='login'), -
Serving a static file in a Django project that is outside my project folder
In a Django template, I want to serve a file that is outside of my project directory. Something like this: my-project (contains project, app, manage.py, etc) my-folder | +----styles.css In a template, I want to serve styles.css. Is it possible to do without copying the file to somewhere inside my project? Please, no answers about how this is bad practice and all that. I know this is not ideal, its not for production, but can not move my file for reasons. -
How to show image on a browser with opencv using django
I don't understand how to use opencv with django. I would like to have a view (HTML/CSS). I'm able to show Image on linux window and resize an image. I don't understand how to change size using slider to make variation. picture.py def resizeImage(): src = cv2.imread(PATH_IMAGES + "50cent.jpeg", cv2.IMREAD_UNCHANGED) #percent by which the image is resized scale_percent = 50 #calculate the 50 percent of original dimensions width = int(src.shape[1] * scale_percent / 100) height = int(src.shape[0] * scale_percent / 100) # dsize dsize = (width, height) # resize image output = cv2.resize(src, dsize) cv2.imwrite(PATH_IMAGES + "50cent-resized.jpeg", output) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Pictures Manager - éditeur d'images</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous"> </head> <body> {{ image }} <h1>Pictures Manager</h1> </body> </html> views.py def index(request): return render(request, 'home/index.html', { 'image': resizeImage }) architecture How can I use slider to change size of image ? -
why is my href not working in django python?
i'm working on a method for a user to be able to make posts on my django site project, the user should only be able to click on the button/link if they are logged in. I have tested it out multiple times and can't understand why i wont direct me to the page i specified i dont know what the problem is as i don't get an error. Here is my URL's.py file: from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.contrib import admin from django.urls import path from users.views import login_view, logout_view, register_view from blog.views import post_create_view, home_view from django.contrib.auth import views as auth_views urlpatterns = [ path('logout/', logout_view, name='logout' ), path('', login_view, name='login'), path('post-create/', post_create_view, name='post_create_view'), path('home', home_view, name='home'), path('admin/', admin.site.urls), path('register/', register_view, name='register') ] Here is the html for the button/href text: <div class="container"> <div class="row"> <!-- Top 'create post' bar --> <div class="create-post-bar d-lg-none col-lg-7 offset-lg-1"> <p><a href="{% url 'post_create_view' %}">Create post</a></p> </div> Here is my forms.py file: from django import forms from .models import BlogPost class PostForm(forms.ModelForm): class Meta: model = BlogPost fields = [ 'title', 'description', 'image' ] Here is my views.py file: from django.shortcuts import render, redirect from django.http import HttpResponse from .models import BlogPost from … -
GraphQL + Django, Filter two classes
I have 2 django apps each of them have their own schema. They are connected with "GroupId ". So I have a groupId in my Team model and GroupId in Players. What I'm trying to do is make a query which call team id and get the all players based on groupId. (if groupId from Team model is equal to groupId from Player model -> get all results). tasks/team.py class TeamType(DjangoObjectType): class Meta: model = models.Team class Query(graphene.AbstractType): team= graphene.Field(TeamType, id=graphene.String()) def resolve_team(self, info, **kwargs): id = kwargs.get("id") if id is not None: return models.Team.objects.get(id=id) players/schema.py class PlayerType(DjangoObjectType): class Meta: model = models.Player def resolve_all_players(self, info, **kwargs): return models.Player.objects.all() What I'm getting so far: { team(id: "1") { name id groupId{ id // 2 } } } all_players { name groupId } So What Im trying to achieve: if all_players->groupId is equal team->groupId then: { team(id: "1") { name id player { id name } } } is it even possible? Thanks in advance! -
How to know if there is a user in a model
I have been trying to create a view that lets a user create a "profile" but if the user already has a profile then the user is redirected to page where the user can see other people's profiles(in order to vuew this other people's profiles, the user has to create a profile as a requirement), for doing this proces I have 2 templates, one that has a form to create the profile and other one that displays other user's profile. So far I think that the error is on the views.py file. models.py class Mates(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='usermates') users_requests = models.ManyToManyField(User, related_name="users_requests") req_bio = models.CharField(max_length=400) req_image = models.ImageField(upload_to='requestmates_pics', null=True, blank=True, default=False) views.py def matesmain(request): contents = Mates.objects.all() if contents == request.user: context = { 'contents': contents, 'form_mates': MatesForm(), } print("nice3") return render(request, 'mates.html', context) else: return render(request, 'mates-form.html') def mates(request): if request.method == 'POST': form_mates = MatesForm(request.POST, request.FILES) if form_mates.is_valid(): instance = form_mates.save(commit=False) instance.user = request.user instance.save() return redirect('mates-main') print('succesfully uploded') else: form_mates = MatesForm() print('didnt upload') context = { 'form_mates': form_mates, 'contents': Mates.objects.all() } return render(request, 'mates-form.html', context) forms.py class MatesForm(forms.ModelForm): class Meta: model = Mates fields = ('req_bio', 'req_image',) exclude = ['user'] mates.html {% if contents … -
Django dict data not showing in form
I tried to zip a lot of data and a some lists into on huge dict and pass it to the template and it didn't work out. So i decided to do a list of dicts(modelled so they contain only the info i need) and pass it to the template. so this is the method in my views.py def servicesoverview(request): form = ServicesOverviewForm() data = Leistung.objects.all() raummiete_list = [] geraeteaufwand_list = [] verbrauchsmaterial_list = [] artik_list = [] labor_list = [] marketing_list = [] arzt_list = [] for l in data: raummiete = 0 geraeteaufwand = 0 verbrauchsmaterial = 0 artik = 0 labor = 0 marketing = 0 arzt = 0 artikel_values = l.artikel.filter(artikel_typ=1).values('preis') for i in artikel_values: raummiete = raummiete + i['preis'] raummiete_list.append(raummiete) print('Raum:' + str(raummiete)) artikel_values = l.artikel.filter(artikel_typ=2).values('preis') for i in artikel_values: artik = artik + i['preis'] artik_list.append(artik) print('Artikel:' + str(artik)) artikel_values = l.artikel.filter(artikel_typ=3).values('preis') for i in artikel_values: geraeteaufwand = geraeteaufwand + i['preis'] geraeteaufwand_list.append(geraeteaufwand) print('Geraete:' + str(geraeteaufwand)) artikel_values = l.artikel.filter(artikel_typ=4).values('preis', 'menge') for i in artikel_values: marketing = l.preis * (i['preis'] / i['menge']) print('Marketing' + str(marketing)) artikel_values = l.artikel.filter(artikel_typ=5).values('preis') for i in artikel_values: labor = labor + i['preis'] labor_list.append(labor) print('Labor' + str(labor)) artikel_values = l.artikel.filter(artikel_typ=6).values('preis') for i in … -
How do I configure my Django serializer to return validation errors in its errors array as opposed to throwing an exception?
I'm using Django 3.0 with Python 3.7 and the Django rest framework. I want to test one of my serializers (code below) so I wrote this test. Notice I intentionally wanted some of the fields to be invalid to test the error messages ... @pytest.mark.django_db def test_coop_create_with_incomplete_data(self): """ Test coop serizlizer model """ phone = "7731112222" serializer_data = { "name": "", "types": [ ], "addresses": [{ "formatted": "", "locality": { "name": "", "postal_code": "", "state": "" } }], "enabled": "true", "phone": { "phone": phone }, "email": { "email": "" }, "web_site": "" } serializer = CoopSerializer(data=serializer_data) serializer.is_valid(raise_exception=False) print(serializer.errors) print("=================\n\n\n") but instead of returning the errors in the ".errors()" function, "is_valid" is throwing an exception, below, File "/Users/davea/Documents/workspace/chicommons/maps/web/tests/test_serializers.py", line 132, in test_coop_create_with_incomplete_data serializer.is_valid(raise_exception=False) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 234, in is_valid self._validated_data = self.run_validation(self.initial_data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 433, in run_validation value = self.to_internal_value(data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/serializers.py", line 490, in to_internal_value validated_value = field.run_validation(primitive_value) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/fields.py", line 565, in run_validation value = self.to_internal_value(data) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 519, in to_internal_value return [ File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/rest_framework/relations.py", line 520, in <listcomp> self.child_relation.to_internal_value(item) File "/Users/davea/Documents/workspace/chicommons/maps/web/directory/serializers.py", line 31, in to_internal_value locality, created = Locality.objects.get_or_create(**locality) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/db/models/query.py", line 562, in get_or_create return … -
Django REST test error: *** django.db.utils.ProgrammingError: relation "" does not exist
Hi I am testing my rest endpoint. When I run my test, python manage.py test apps.pulse.tests.PulseTestCase.test_clinical_pubmed I get an error that the test model does not exist in the test db. *** django.db.utils.ProgrammingError: relation "pulse_targets" does not exist Here is my test class, from django.test import TestCase from apps.pulse.models import Twitter from apps.pulse.models import Targets import json class PulseTestCase(TestCase): def setUp(self): Targets.objects.create(gene_id='wee1') target = Targets.objects.get(gene_id='wee1') Twitter.objects.create(target=target, tweet_id=21212121212112212, user_id=313133131313133, tweet='wee1 in cancer', user='DeplorableBob') def test_twitter(self): response = self.client.post('/api/pulse/twitter', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) def test_clinical_pubmed(self): response = self.client.post('/api/pulse/clinicalpubmed', {'geneID': 'adrb2'}, format='json') self.assertEqual(response.status_code, 200) -
How to filter django models data by Date and id using Django Restframwork?
I am Using Django Rest Frame Work and I Want to build filter time by date and id urls.py path('health-heartrate/',healthHeartRate,name='health-heart-rate') views.py @api_view(['GET']) def healthHeartRate(request): if request.method=='GET': strDate=request.query_params.get('strDate',None) strDate=datetime.datetime.strptime(strDate, "%Y-%m-%d").date() endDate=strDate + datetime.timedelta(days=1) filter_date=Health.objects.filter(pk=id).filter(time_gte=strtDate).filter(time_lte=endDate) serializer=HealthFilterSerializer(filter_date,many=True) return Response(serializer.data) Url > http://127.0.0.1:8000/api/v1/health-heartrate/?id=1&strDate=2016-03-28 I got the Following Error in Browser TypeError at /api/v1/health-heartrate/ int() argument must be a string, a bytes-like object or a number, not 'builtin_function_or_method'