Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multiple Integer Arguments in Django Rest Framework Router URL
I'm setting up a url using Django Rest Framework viewsets and routers, and I'm trying to get the url to accept two values: first, to filter objects by a user id, and then by the object's id. (In my case, the objects are from a model called Request.) For example, mysite.com/api/requestsbyuser/1/ would return all Request objects for user 1, and mysite.com/api/requestsbyuser/1/23/ would return Request object with pk=23 for user 1. Right now I have: # urls.py from django.conf.urls import url, include from rest_framework import routers from . import views router = routers.DefaultRouter() router.register(prefix=r'requestsbyuser/(?P<user_id>.+)', viewset=views.RequestsByUser, base_name='request') urlpatterns = [ url(r'^', include(router.urls)), ] # views.py class RequestsByUser(viewsets.ModelViewSet): serializer_class = RequestsSerializer def get_queryset(self): u_id = self.kwargs['user_id'] return Request.objects.filter(user_id=u_id) This works well for listing all Request objects when the url is passed in only the user_id. But when I try to go to mysite.com/api/requestsbyuser/1/23/, I get the error: invalid literal for int() with base 10: '1/23'. Django debugging says that the following four url patterns are in my URLConf: ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)\.(?P<format>[a-z0-9]+)/?$ [name='request-list'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)/$ [name='request-detail'] ^api/ ^ ^requestsbyuser/(?P<user_id>.+)/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$ [name='request-detail'] Am I missing something? I thought the DRF router would handle url paths with individual object primary key values, … -
data did'nt validate error django
Can anyone please help me..... I keep on getting "data didn't validate" error when saving data from a ModelForm. Everything worked fine for me until I added some CSS and JS for the frontend, used form widgets and manually displayed the form field on the template. Here are the codes: forms.py from django import forms from .models import List_of_Res class fordtp(forms.Form): month_choices=( ('JAN','January'), ('FEB','February'), ('MAR','March'), ('APR','April'), ('MAY','May'), ('JUN','June'), ('JUL','July'), ('AUG','August'), ('SEP','September'), ('NOV','November'), ('DEC','December'), ) day_choices=[] for ddd in range(1,32): day_toS=(str(ddd),str(ddd)) day_choices.append(day_toS) year_choices=[] for yyy in range(1990,2100): year_toS=(str(yyy),str(yyy)) year_choices.append(year_toS) month = forms.ChoiceField(choices = month_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) year = forms.ChoiceField(choices = year_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) day = forms.ChoiceField(choices = day_choices,widget=forms.Select(attrs={'class':'form-control form-control-sm'})) class ResearchForm(forms.ModelForm): class Meta: model = List_of_Res fields={ 'prog_title', 'proj_title', 'stud_title', 'prog_lead', 'stud_lead', 'co_res', 'res_site', 'campus', 'category_res', 'classif_res', 'amt_granted', 'date_started', 'res_status', 'date_completed', 'res_SF', 'res_pubstat', 'res_JN', 'res_JV', 'date_pub', 'res_iprstat', 'apptype', 'date_appl', 'date_pprv', 'app_pending', 'res_abs' } widgets = { 'prog_title': forms.TextInput(attrs={'class':'form-control'}), 'proj_title': forms.TextInput(attrs={'class':'form-control'}), 'stud_title': forms.TextInput(attrs={'class':'form-control'}), 'prog_lead': forms.TextInput(attrs={'class':'form-control'}), 'stud_lead': forms.TextInput(attrs={'class':'form-control'}), 'co_res': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 name per line'}), 'res_site': forms.Textarea(attrs={'class':'form-control','placeholder':'Enter 1 site per line'}), 'campus': forms.Select(attrs={'class':'form-control'}), 'category_res': forms.RadioSelect(attrs={'class':'form-check-input'}), 'classif_res': forms.Select(attrs={'class':'form-control'}), 'amt_granted': forms.TextInput(attrs={'class':'form-control'}), 'date_started': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_status': forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_completed': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_SF': forms.CheckboxSelectMultiple(attrs={'class':'form-check-input'}), 'res_pubstat': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_JN': forms.TextInput(attrs={'class':'form-control'}), 'res_JV': forms.TextInput(attrs={'class':'form-control'}), 'date_pub': forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'res_iprstat':forms.RadioSelect(attrs={'class':'form-check-input'}), 'apptype':forms.RadioSelect(attrs={'class':'form-check-input'}), 'date_appl':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'date_pprv':forms.DateInput(attrs={'placeholder':'YYYY-MM-DD','class':'form-control'}), 'app_pending': forms.RadioSelect(attrs={'class':'form-check-input'}), 'res_abs': forms.Textarea(attrs={'class':'form-control'}) } (views.py): from … -
Combining multiple Regex
im looking to combine multiple regexes using a AND condition. For example, the following words should not be matched (starting of string): database audit index analysis extract good bad The strings that start with these strings will not be matched. Similarly, words such as others, error will be matched. I have done a regex that is able to filter for each word but has not been successful at filtering out the list of words to be not matched. #This will only match those that do not start with database r'(^((?!database).+)' While trying to combine, it has failed to check both conditions. r'(^((?!database).+)(^((?!audit).+)))' Note: This regex is to be used in the django framework, urls.py file -
Unable to connect to gunicorn via Ingress
I'm trying to deploy a Django application on Kubernetes. I'm using Gunicorn to serve the Django application. Gunicorn accepts connections when running at 0.0.0.0:8000, but not 127.0.0.1:8000. Can anyone help explain why? Kubernetes service.yaml ... spec: type: NodePort ports: - protocol: TCP port: 80 targetPort: 8000 ... Kubernetes deployment.yaml ... spec: containers: - name: app image: <img> livenessProbe: httpGet: path: /healthz port: 8000 initialDelaySeconds: 10 ports: - protocol: TCP containerPort: 8000 env: ... Dockerfile ... CMD python manage.py makemigrations && \ python manage.py migrate && \ gunicorn -w 3 app.wsgi:application Django app/settings.py ... DEBUG = True ALLOWED_HOSTS = [os.environ.get('ALLOWED_HOSTS')] ... Container startup logs No changes detected Operations to perform: Apply all migrations: <migrations 1..n> Running migrations: No migrations to apply. [2018-01-25 06:35:30 +0000] [9] [INFO] Starting gunicorn 19.7.1 [2018-01-25 06:35:30 +0000] [9] [INFO] Listening at: http://127.0.0.1:8000 (9) [2018-01-25 06:35:30 +0000] [9] [INFO] Using worker: sync [2018-01-25 06:35:30 +0000] [12] [INFO] Booting worker with pid: 12 [2018-01-25 06:35:30 +0000] [13] [INFO] Booting worker with pid: 13 [2018-01-25 06:35:30 +0000] [14] [INFO] Booting worker with pid: 14 Error message when going through an Ingress mapped to a domain name (eg. curl example.com) <html><head> <meta http-equiv="content-type" content="text/html;charset=utf-8"> <title>502 Server Error</title> </head> <body text=#000000 … -
Django Pagination "Page not found"
I'm currently having issues with my Django pagination. I have a query set of 9 objects and am paginating one object to a page. So I should have 9 pages total. Paginator is showing that I have 9 pages, but when I click the "next" page button my (Always on the last/last two pages) my url turns to: http://127.0.0.1:8000/forum/1?page=7 Then I get a 404 page not found error along with "Invalid page (7): That page contains no results" Here is my class code: class DirectoryClass(generic.ListView): template_name = "forum_directory.html" model = Directory paginate_by = 1 def get_context_data(self, **kwargs): context = super(DirectoryClass, self).get_context_data(**kwargs) directory = Directory.objects.filter(pk=self.kwargs['directory_id']) context['page'] = 'forum' context['name'] = directory.first().name context['user'] = self.request.user topic_set = directory.first().topic_set.all().order_by('-last_post') print(topic_set.all()) paginator = Paginator(topic_set, self.paginate_by) page = self.request.GET.get('page') try: topic_set = paginator.page(page) except PageNotAnInteger: topic_set = paginator.page(1) except EmptyPage: topic_set = paginator.page(paginator.num_pages) context['topics'] = topic_set context['page'] = page return context What am I doing wrong here? I'm completely lost. Thank you! -
Django model property with parameter
I've the following models in Django. class User(models.Model): name = models.CharField(max_length=50) ... ... @property def get_info(self, key=None): value = self.name if key else 'Hello World' return value But when I try to execute the code in Django shell, I'm getting the following error. n [4]: user = User.objects.get(id=1) n [5]: user.get_info(key='test_key') --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-5-f7b917070aee> in <module>() ----> 1 user.get_info(key='test_key') TypeError: _get_info() takes exactly 2 arguments (1 given) -
nginx+uwsgi+django emperor mode not working
I am doing multi-application nginx+uwsgi setup in django. I am following this documentation to set up emperor mode for my project. It works fine when I run "uwsgi --ini myproject_uwsgi.ini" but I am not able to deploy emperor mode following this documentation. I have researched many docs but not able to find relevant information related to emperor mode setup. My nginx.conf file:(angularJS frontend) server { listen 80; server_name 192.168.xx.xx; root /home/user/Myspace/workspace/Myproject_frontend/dist; } My "etc/uwsgi/vassals/uwsgi.ini" file looks like: [uwsgi] #Django-related settings #Django's wsgi file wsgi-file = /home/user/Myspace/workspace/myproject/myproject/wsgi.py http = 192.168.xx.xx:8080 virtualenv = /home/user/Myspace/VENV_MYPROD Also, i have created a uwsgi.service file in "/etc/systemd/system/uwsgi.service" to start emperor mode service and it looks like: [Unit] Description=uWSGI Emperor service After=syslog.target [Service] ExecStart=/usr/local/bin/uwsgi --emperor /etc/uwsgi/vassals/ RuntimeDirectory= uwsgi Restart=always KillSignal=SIGQUIT Type=notify StandardError=syslog NotifyAccess=all [Install] WantedBy=multi-user.target Please provide help on setting up uwsgi emperor mode. -
django-import-export specify id in order from ‘1’
Hi,When I import data from excel, I find the default id is random: ID NAME 5 A 9 B I want to like below when I import data "NAME: A, NAME: B" from excel : ID NAME 1 A 2 B How should I do? -
Run a cron job to check the due date of a task
I'm working in an integration between Django and Chatfuel. Right now the bot is almost complete, I have difficulties with the last task, I have certain tasks to do and each them have a due time, so three days before it expires I have to send a message to my client remindering him/her that he/she have to complete this task. I'm available to obtain the messenger_user_id after the first interaction with my bot, now, I know i have to run a cron job at a frequent interval to check the due date and if it's close, send a message through Broadcasting API. But I don't know how to achieve that goal. models.py class Tasks(models.Model): task = models.CharField(max_length=100) objective = models.TextField() created_date = models.DateTimeField( default=timezone.now) due_date = models.DateTimeField( default=timezone.now) def __str__(self): return self.task views.py #in here I obtain user's fb id def save_fb_id(request, username, fb_id): profile = Profile.objects.get(user__username=username) if profile.fb_id != fb_id: profile.fb_id = fb_id profile.save() return HttpResponse() -
errors while running python scripts triggered by django app
I am building a fully open source testrunner for my needs but I am running into some problems. the test runner parses a yaml file for a set of scripts in various paths and executed the scripts and uses a lib that i will be creating to return the outcome. right now i have a simple ping script that im working to get running and testing as i progress but i am getting a lot of errors. the errors are below and all the source code is also shown below the errors. The github repo for this is here. feel free to pull it in and test the issues i am seeing. https://github.com/castaway2000/testrunner The issue: I am trying to use the testrunner i built to parse a yaml file for paths to scripts i am writing for projects im using. For example if want to use a group of certain tests on a target, i can make a yaml file for each set of the types of tests. There is a certain problem I am seeing with this however, the relative path and exact path of the files are not able to use the django libraries, cause its unable to … -
Django rest framework & external api
i wanna get my data from an external API (https://example.com/consumers). Can I build my urls.py like this? url(r'^(?P<test.com/consumers)>[0-9]+)$/', views.get, name="get"), Or do you have any other(s) good idea(s) ? Thanks. -
Integrity Error: using primary_key=True
This is my Models: from django.db import models from django.contrib.auth.models import User class Bookmark(models.Model): id = models.PositiveIntegerField(primary_key=True) name = models.CharField(max_length=50) url = models.URLField() isPublic = models.BooleanField(default=True) dateTimePosted = models.DateTimeField(auto_now=True,verbose_name="posted at") user = models.ForeignKey(User, on_delete=models.CASCADE) This is my 0001_initials.py: from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Bookmark', fields=[ ('id', models.PositiveIntegerField(primary_key=True, serialize=False)), ('name', models.CharField(max_length=50)), ('url', models.URLField()), ('isPublic', models.BooleanField(default=True)), ('dateTimePosted', models.DateTimeField(auto_now=True, verbose_name='posted at')), ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ] When I am inserting values using: python manage.py shell: >>from django.contrib.auth.models import User >>user = User.objects.create_user('test', 'test@abc.com', 'test@123') >>from bookmark.models import Bookmark >>bookmark = Bookmark.objects.create(name='First Bookmark', url='example.com', user=user) this error occurs: Traceback (most recent call last): File "", line 1, in File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Python34\lib\site-packages\django\db\models\query.py", line 394, in create obj.save(force_insert=True, using=self.db) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "C:\Python34\lib\site-packages\django\db\models\base.py", line 961, in _do_insert using=using, raw=raw) File "C:\Python34\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) … -
How to fix ImproperlyConfigured in django 1.7?
ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. [2018-01-25 02:20:16 +0000] [13560] [INFO] Worker exiting (pid: 13560) Traceback (most recent call last): File "/home/web/git/myprojc/.env/bin/gunicorn", line 11, in <module> sys.exit(run()) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/wsgiapp.py", line 74, in run WSGIApplication("%(prog)s [OPTIONS] [APP_MODULE]").run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 203, in run super(Application, self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/app/base.py", line 72, in run Arbiter(self).run() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 231, in run self.halt(reason=inst.reason, exit_status=inst.exit_status) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 344, in halt self.stop() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 393, in stop time.sleep(0.1) File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 244, in handle_chld self.reap_workers() File "/home/web/git/myprojc/.env/lib/python2.7/site-packages/gunicorn/arbiter.py", line 524, in reap_workers raise HaltServer(reason, self.WORKER_BOOT_ERROR) gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> this is the stacktrace I get when I try to start the project, How to fix ImproperlyConfigured in django 1.7? -
django user_permissions.clear() not work
My user_permissions.clear() and remove() can't work at all! The two print is same. And when I create a new user, the user always contains all of models permissions. class ChangeTeacherPermission(APIView): def post(self, request): user = self.request.GET.get('user', None) user = User.objects.get(username=user) print(user.get_all_permissions()) user.user_permissions.clear() print(user.get_all_permissions()) permissions = json.loads(self.request.POST.get('obj'))['permissions'] flag = json.loads(self.request.POST.get('obj'))['flag'] class User(BaseUser): class BaseUser(AbstractBaseUser, PermissionsMixin): -
Django save and enter data after API call in views
I have 2 django project, D1 and D2. D1 has a table call T1 and D2 has a table call T2. So i have a view in D1 that do api call to the api in D2 and save the value that i get after a POST request into T1. But i also want to be able to enter data in other field of table T1. example: t2 only has book field, t1 has book and author field. When D1 do a post method to t2 in D2, it will return a book value which will be save into t1 but i also want the user to enter the author themself. How do i do it ? Here is my code models.py In D1: class T1(models.Model): book = models.CharField(max_length=10, blank=True, null=True) author = models.CharField(max_length=10, blank=True, null=True) In D2 class T2(models.Model): book = models.CharField(max_length=10, blank=True, null=True) views.py @csrf_exempt def my_django_view(request): if request.method == 'POST': r = requests.post('http://127.0.0.1:8000/api/test/', data=request.POST) else: r = requests.get('http://127.0.0.1:8000/api/test/', data=request.GET) if r.status_code == 201 and request.method == 'POST': data = r.json() testsave_attrs = { "book": data["book"], } testsave= T1.objects.create(**testsave_attrs) return HttpResponse(r.text) elif r.status_code == 200: # GET response return HttpResponse(r.json()) else: return HttpResponse('Could not save data') -
Invalid literal for int() with base 10 in template with multiple forms
I have a form that only links to one of the fields in one of my models. I'm trying to save the form, but I keep getting errors and don't know what to change. Models.py class FunctionManager(models.Manager): def editover(self, Function_id, postData): woo = Function.objects.get(id=Function_id) woo.new = postData["new"] woo.save() class Function(models.Model): tableA = models.CharField(max_length=50) new = models.TextField() def __str__(self): return str (self.tableA, self.id) objects = FunctionManager() views.py def function_page(request, Function_id): assignments = Function.objects.get(id=Function_id) context = { 'assignments': assignments, } return render (request, 'project/function.html', context) def new_save(request, Function_id): newest = WarFightingFunction.objects.editover('Function_id', request.POST['new']) return redirect ('project/function.html') urls.py url(r'^function_page/(?P<Function_id>\d+)$', views.function_page, name "function_page"), url(r'^new_save/(?P<Function_id>\d+)/$', views.new_save, name = "new_save") html <div id=new> <form action= "/SCS/new/{{assignments.id}}/" method="POST"> {% csrf_token %} <textarea name="new" id="Obox"></textarea> <input class="save" type="submit" value="Save"> </form> </div> What am I doing wrong? Thanks in advance. -
Add a field in Serializer, but the DRF is no the field
I have the Serializer to add a user_id field, see my bellow code: My PhysicalServerManualGenerateOrderSerialzier: class PhysicalServerManualGenerateOrderSerialzier(ModelSerializer): physicalserver_model = serializers.IntegerField(write_only=True) operate_system = serializers.CharField(write_only=True) extra_desc = serializers.CharField(allow_null=True, write_only=True) user_id = serializers.IntegerField(write_only=True) class Meta: model = Order fields = [ "billing_type", "buytime", "count", "physicalserver_model", "operate_system", "extra_desc", "user_id", # you see, I add the `user_id` there. ] def to_representation(self, instance): serialized_data = super(PhysicalServerGenerateOrderSerialzier, self).to_representation(instance) serialized_data['order_num'] = instance.order_num serialized_data['order_type'] = instance.order_type serialized_data['order_status'] = instance.order_status serialized_data['billing_type'] = instance.billing_type serialized_data['buytime'] = instance.buytime serialized_data['count'] = instance.count serialized_data['cost'] = instance.cost serialized_data['ctime'] = instance.ctime serialized_data['product_describe'] = instance.product_describe return serialized_data def create(self, validated_data): user_id = validated_data.get("user_id") user = User.objects.get(id=user_id) try: order = getOrder(user=user, validated_data=validated_data) except Exception as e: order = None return order My PhysicalServerManualGenerateOrderAPIView: class PhysicalServerManualGenerateOrderAPIView(CreateAPIView): """ generate order """ serializer_class = PhysicalServerManualGenerateOrderSerialzier permission_classes = [] queryset = Order.objects.all() But in the DRF, there is no user_id option: -
Specifying basic authentication credentials for a Django REST framework API client
I'm trying to run some tests to go with the Django REST tutorial (see source code). I got a solution working using the APIClient's .force_authenticate method, but I'd prefer to construct the credentials more explicitly. I've tried the following: import json import base64 from django.contrib.auth.models import User from django.test import TestCase from rest_framework.test import APITestCase, force_authenticate from snippets.models import Snippet class SnippetTestCase(APITestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) # self.client.force_authenticate(user=self.user) credentials = base64.b64encode(f'{self.username}:{self.password}'.encode('utf-8')) self.client.credentials(HTTP_AUTHORIZATION='Basic {}'.format(credentials)) def test_1(self): response = self.client.post('/snippets/', {'code': 'Foo Bar'}, format='json') self.assertEqual(response.status_code, 201) This test passed with the commented-out line with .force_authenticate, but fails in its current form, which I based on Using Basic HTTP access authentication in Django testing framework: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.022s FAILED (failures=1) Apparently, the authentication is not working because I'm getting a 403 Forbidden error. Any ideas on how to fix this? -
How can send data from nodemcu/arduino to raspberry pi via wifi?
I made a webapp using django framework and setup a web server in raspberry pi 3 following this tutorial(using gunircon and nginx), also a set up the raspberry as access point.In the other hand, I have sensor that is measuring, this sensor was made using Nodemcun and de Arduino IDE,I want send de data from nodemcu to rapsberry pi via WiFi and get de data in raspberry and save it in my database, my question is howt to do it using python? I have been reading and I found that that is possible using telnet but I don't know how to do it. some clue, information or tutorial pleas. Thanks a lot -
How to handle legacy php-generated passwords in Django
I'm moving a server from php(5.6.32) to Django(1.11.7) that contains thousands of users with passwords encrypted using the password_hash(<pwd>, PASSWORD_DEFAULT) function. Does Django have support for this encryption? It appears neither theBCryptPasswordHasher or the BCryptSHA256PasswordHasher handle this. I believe a custom hasher may be required, but its not clear how to handle this. -
Django: displaying a foreign key of a model in template
this is a rather basic question (I'm new to Django) i'm having trouble displaying a foreign key in the template. i have this model which has 'employer' as a ManyToManyField in the Job model: from django.db import models # Create your models here. class Employer(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50,default="") business = models.CharField(max_length=25, default="") team = models.IntegerField() about = models.TextField(max_length=1000) country = models.CharField(max_length=25, default="") city = models.CharField(max_length=25, default="") class Job(models.Model): date = models.DateTimeField(auto_now_add=True, blank=True) specialism = models.CharField(max_length=25) employer = models.ManyToManyField(Employer) I try to get all jobs that contains "Computers" as specialism: from django.shortcuts import render from .models import Job, Employer # Create your views here. def index(request): return render(request, 'pages/index.html') def post_list(request): jobs = Job.objects.all().filter(specialism="Computers") return render(request, 'wall.html',{'jobs':jobs}) And for every job i wanna display the employer name in the template: <!DOCTYPE html> <html> <head> <title></title> </head> <body> <center><h1>WALL</h1></center> {% block content %} {{jobs.count}} {% for job in jobs %} <h2>specialism :{{job.specialism}} employer: {{job.employer.name}}</h2> {% endfor %} {% endblock %} </body> </html> I get None as a value for job.employer.name. so how can i display the name of the employer for every job? -
Django: I cant create a model, I got this error:[pylint] E0001:invalid syntax (<string>, line 8)
file: models.py from __future__ import unicode_literals from django.db import models class Register(models.Model) name =models.Charfield(maxlength=100,blank=True,null=True) email =models.EmailField() timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) def__unicode__(self): return self.mail def__str__(self): return self.mail error: [pylint] E0001:invalid syntax (, line 8) I try to execute command-line: python manage.py makemigrations message is: No changes detected. I use python 3.7 -
Adding tests to the Django REST framework tutorial
I'm trying to replace an existing function-based view using the login_required decorator with a Django REST framework API using a ModelViewSet. However, it seems like the authentication works a bit differently. In order to try to adapt my unit tests to the Django REST framework case, I cloned https://github.com/encode/rest-framework-tutorial and added a tests.py at the top level directory: import json from django.contrib.auth.models import User from django.test import TestCase, Client from snippets.models import Snippet class SnippetTestCase(TestCase): def setUp(self): self.username = 'john_doe' self.password = 'foobar' self.user = User.objects.create(username=self.username, password=self.password) self.client = Client() self.snippet = Snippet.objects.create(owner=self.user, code="Foo Bar") def test_1(self): self.client.login(username=self.username, password=self.password) response = self.client.post( path='http://localhost:8000/snippets/1/', data=json.dumps({'code': 'New code'}), content_type="application/json") self.assertEqual(response.status_code, 201) However, this returns a 403 Forbidden response: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_1 (tutorial.tests.SnippetTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/kurtpeek/Documents/source/rest-framework-tutorial/tutorial/tests.py", line 23, in test_1 self.assertEqual(response.status_code, 201) AssertionError: 403 != 201 ---------------------------------------------------------------------- Ran 1 test in 0.049s FAILED (failures=1) Destroying test database for alias 'default'... On the other hand, using HTTPie with the -a flag works fine: Kurts-MacBook-Pro:rest-framework-tutorial kurtpeek$ http -a kurtpeek:foobar123 POST http://localhost:8000/snippets/ code="print 123" HTTP/1.1 201 Created Allow: GET, POST, HEAD, OPTIONS … -
Linking user to other tables in django
I have the below in my models.py file: class Film(models.Model): title = models.CharField(max_length=200) director = models.CharField(max_length=200) description = models.CharField(max_length=200) pub_date = models.DateField('date published') class Comment(models.Model): film = models.ForeignKey(Film, on_delete=models.CASCADE) body = models.CharField(max_length=200) When I logged into Django admin I added some films, and then added some comments, selecting which film object the comment related to. I then created a couple of users via the admin panel also. I would like my relationships to be: Film can have many comments / Comments belong to film User can have many comments / Comments belong to user I think, like with comments and films, I just need to define user as a foreign key to comment. I am struggling to do this. I am working through the Django tutorials but I can't see the tutorials covering how I can link other tables to the user. I thought I would be able to do something like this: user = models.ForeignKey(User, on_delete=models.CASCADE) While importing User like this: from django.contrib.auth.models import User The result at the moment is if I keep user = models.ForeignKey(User, on_delete=models.CASCADE) I get err_connection_refused -
disable logout after adding user django
I need to create admin panel in django , admin will be able to add students"which extended from users " , I finally be able to add them , but after that I get "'AnonymousUser' object has no attribute '_meta' User is added to the database correctly , But django logged me out ! How Can I keep my current user session ! class student(models.Model): Computers = 1 Communications = 2 Dep_CHOICES = ( (Computers, 'Computers'), (Communications, 'Communications'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) dep = models.PositiveSmallIntegerField(choices=Dep_CHOICES, null=True, blank=True) deg = models.FloatField(null=True, blank=True) def __str__(self): # __unicode__ for Python 2 return self.user.username def create_user_profile(sender, instance, created): if created: student.objects.create(user=instance) def save_user_profile(sender, instance , **kwargs): instance.student.save() class UserForm(ModelForm): class Meta: model = User fields = ('username', 'email', 'password') class studentForm(ModelForm): class Meta: model = student fields = ('dep', 'deg') The view def add_stu(request): if request.method == 'GET': return render(request, "add_student.html") else: user_form = UserForm(request.POST, instance=request.user) profile_form = studentForm(request.POST, instance=request.user.student) user_form.save() profile_form.save()