Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Count the number of rows in a Django database : AttributeError
I have database created by Django model, where idRecruteur is the fields of the table Offre. I need to count the number of rows where idRecruteur = 1. This is my "Offre" table code: @python_2_unicode_compatible class Offre(models.Model): titre = models.CharField(max_length=100) dateAjout = models.DateField(auto_now=False, auto_now_add=False) nature = models.CharField(max_length=50) duree = models.CharField(max_length=50) niveau = models.CharField(max_length=50) description = models.CharField(max_length=50) salaire = models.FloatField(null=True, blank=True) idRecruteur = models.ForeignKey(Recruteur, related_name="Offre", on_delete=models.CASCADE) def __str__(self): return "Offre: {}".format(self.title) and this is my queryset: class OffresparEntrepriseViewSet(ModelViewSet): queryset = Offre.objects.filter(idRecruteur=1).count() serializer_class = OffreSerializer I get the error " AttributeError: 'int' object has no attribute 'model' " Any ideas what I am doing wrong? -
Django Forms multiple foreignkey
I have four models, three of which have ‘independent’ fields but the fourth models has ForeignKey links to the other three. class PreCheck(models.Model): name = models.CharField(max_length=120) time_in = models.DateTimeField(auto_now_add=True) is_insured = models.BooleanField() class MainCheck(models.Model): height = models.FloatField() weight = models.IntegerField() class PostCheck(models.Model): sickness = models.CharField(max_length=30) medication = models.CharField(max_length=30) class MedicalRecord(models.Model): patient = models.ForeignKey(User) next_check_date = models.DateTimeField() payment_amount = models.IntegerField() initial_check = models.ForeignKey(PreCheck) main_check = models.ForeignKey(MainCheck) post_check = models.ForeignKey(PostCheck) Assume a patient goes in a room, a precheck is done and saved, then other checks are done and finally a final record is set. Ideally, I would like to fill in forms for the different models at different times possibly in different pages/tabs. The admin has popups for the MedicalRecord model but in the frontend its hard to write javascript for that. Another option would be to fill in the modelforms separately and do a str return function then select that from dropdowns in the MedicalRecord form( which I’m trying to avoid) -
Remove accent in search term Django Rest Framework
I just want to know how to remove any accents (and where) on my search term before doing my query. I use Django 9. search_fields = ('name', ) filter_backends = (OrderingFilter, SearchFilter) ordering = ('name', ) My serializer : class MySerializer(serializers.ModelSerializer): another = AnotherSerializer() class Meta: model = My_model fields = ('id', 'name', 'position') My model : class My_model(models.Model): class Meta: ordering = ['index'] name = models.CharField(max_length=250, verbose_name=_("My_model name")) another = models.ForeignKey(Another, verbose_name=_("Another")) @staticmethod def autocomplete_search_fields(): return ("id__icontains", "name__icontains", "another__address__icontains") def __unicode__(self): return "%s %s : %s - %s" % (_("My_model"), self.pk, self.name, self.address) -
Filter Multiple Objects Average Ratings and Order in Ascending Order
I'm using Wildfish Django rating package. I want to filter ratings of multiple objects in a tuple, check the overall average rating for each object id, and return object ids with the highest average rating. I did this but not returning any result. from star_ratings.models import Rating video_post = Foam.objects.all() if video_post: dem_ds = [] for hu in video_post: dem_ds.append(hu.id) tup_videos = tuple(dem_ds) high_rated_vids = Rating.objects.filter(object_id__in=tup_videos) top_rated=(high_rated_vids.order_by('-average').values_list('average', flat=True).distinct()) top_by_rated=(top_rated.order_by('-average').filter(average__in=top_rated)) What am I missing? -
Is t possible to use get_fieldname_display() as annotate value?
Is it possible to use get_fieldname_display() as annotate value? Kindly see the code below. queryset.filter(is_draft=True).annotate(status=get_status_display() ) If yes, how do I do this and is there a pythonic or better way to do this? Thanks in advance! -
Django Dynamic Formsets with django-formset-js is not working
i need to dynamically add (after that delete) forms to my formset when i click on a button. i tryed so many approches . here is the last code i stoped on : forms.py: class ContactForm(forms.Form): nom=forms.CharField() VentsFormSet = formset_factory(ContactForm) views.py : class HomeViews(TemplateView): def get(self, request,*args,**kwargs): current_user = request.user data={ 'form-TOTAL_FORMS': '1', 'form-INITIAL_FORMS': '0', 'form-MAX_NUM_FORMS': '', } formset = VentsFormSet(data) context={"formset":formset,"current_user":current_user} return render(request,"appOne/testformset.html", context) testformset.html : <!DOCTYPE html> <html> <head> {% load staticfiles %} {% load formset_tags %} <script src="{% static 'js/jquery-3.3.1.js' %}"></script> <script src="{% static 'js/jquery.formset.js' %} "></script> </head> <body> <div id="formset" data-formset-prefix="{{ formset.prefix }}"> {{ formset.management_form }} <div data-formset-body> <!-- New forms will be inserted in here --> {% for form in formset %} <div data-formset-form> {{ form }} <button type="button" data-formset-delete-button>Delete form</button> </div> {% endfor %} </div> <!-- The empty form template. By wrapping this in a <script> tag, the __prefix__ placeholder can easily be replaced in both attributes and any scripts --> <script type="form-template" data-formset-empty-form> {% escapescript %} <div data-formset-form> {{ formset.empty_form }} <button type="button" data-formset-delete-button>Delete form</button> </div> {% endescapescript %} </script> <!-- This button will add a new form when clicked --> <input type="button" value="Add another" data-formset-add> <script>jQuery(function($) { $('#formset').on('formAdded', function(event) { newForm = … -
Can not restart gunicorn by supervisor
when i run "supervisorctl status hitbot" then i face this error FATAL Exited too quickly (process log may have details) #/bin/gunicorn_start /etc/supervisor/conf.d/hitbot.conf But when i type these command In log file But when it test gunicorn_start by "bash /bin/gunicorn_start"* then it working fine -
Django ORM Query optimization, gettting large pool error on `__in` or union `|`
Example code: choices = [['a', 'b', 'c', 'd'], ['a', 'c', 'd', 'e'], ['a', 'd', 'e', 'f'], ['a', 'f', 'j', 'k'], ........more then 30 choices list...... ] Now I have a one query set which has previeous data previous_queryset = Example.objects.filter(field__name__in=some_choices) When I excute below code query_set = Example.objects.filter(field__name__in=some_choices) for ch in choices: filter_set = some_function(ch) example_query_set = query_set.filter(filter_set).exclude(field__name__in= previous_queryset.values_list('field__name', flat=True))) | previous_queryset previous_queryset = example_query_set its throwing below error: DatabaseError: ORA-04031: unable to allocate 4152 bytes of shared memory ("large pool","unknown object","session heap","kxsFrame4kPage") if I modified previous_queryset.values_list('field__name', flat=True) to list(previous_queryset.values_list('field__name', flat=True)) its working fine but it is taking too much time to get data from the database. I need to improve the performance of above code but till now I did not find any solution. -
Django Beginner. How do I update all objects and set a certain field to a value that is a function of another field?
This is my model: class Course(models.Model): student_count = models.PositiveIntegerField(default=0) students = models.ManyToManyField() What I try to do is the following but it doesn't work. Course.objects.update(student_count=F('students__count')) The following works but it's not ideal courses = Course.objects.all() for course in courses: course.student_count = course.students.count() course.save() return Course.objects.all() -
Can django rest framework serializer fields set all and specify additional fields at the same time?
This is my model # models.py class Camera(models.Model): number = models.IntegerField(unique=True, primary_key=True) name = models.CharField(max_length=100) description = models.TextField(default='', blank=True, null=True) image = models.ForeignKey( Image, on_delete=models.CASCADE, related_name='camera' ) class Process(models.Model): camera = models.OneToOneField(Camera, on_delete=models.CASCADE, related_name='process', to_field='number') And the serializer # serializer.py class CameraListSerializer(serializers.ModelSerializer): process = ProcessSerializer(required=False, allow_null=True) class Meta: model = Camera fields = ('number', 'name', 'description', 'image', 'process') depth = 1 This is working, but the problem is I specified a foreign key(process), which requires additional fields to be specified and displayed in the field settings(fields), but if I have a lot of fields of the original model(a, ..., z), does not mean that I need to show them all one by one? just like: fields = ( 'a', ... 'z', 'process' # Finally add that specially specified foreign key field ) But if you specify fields = '__all__' directly, you won't see the foreign key I need to add. class CameraListSerializer(serializers.ModelSerializer): process = ProcessSerializer(required=False, allow_null=True) class Meta: model = Camera fields = '__all__' depth = 1 What you get is { "number": 1, "process": null, "name": "test", "description": "" "image": { "id": 1, "path": "", "building": 1 } } How can be work together? -
Collectstatic returns KeyError due to dj_database_url()
I'm implementing dj_database_url but receiving an error upon running collectstatic. Following the the dj_database_url readme, as well as the steps outlined by Heroku here, I added this to the bottom of my settings.py: import dj_database_url DATABASES['default'] = dj_database_url.config(default='postgis://USER:PASSWORD@HOST:PORT/NAME') DATABASES['default']['ENGINE'] = 'django.contrib.gis.db.backends.postgis' GDAL_LIBRARY_PATH = os.getenv('GDAL_LIBRARY_PATH') GEOS_LIBRARY_PATH = os.getenv('GEOS_LIBRARY_PATH') Upon adding, collectstatic will give me the this traceback: Traceback (most recent call last): File "./manage.py", line 29, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 308, in execute settings.INSTALLED_APPS File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 56, in __getattr__ self._setup(name) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 41, in _setup self._wrapped = Settings(settings_module) File "/usr/local/lib/python3.6/site-packages/django/conf/__init__.py", line 110, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/usr/local/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/usr/src/app/config/settings/production.py", line 211, in <module> DATABASES['default'] = dj_database_url.config(default='postgis://USER:PASSWORD@HOST:PORT/NAME') File "/usr/local/lib/python3.6/site-packages/dj_database_url.py", line 55, in config config = parse(s, engine, conn_max_age, ssl_require) File "/usr/local/lib/python3.6/site-packages/dj_database_url.py", line 103, in parse engine = SCHEMES[url.scheme] if engine is None else engine KeyError: '' There's sparse docs … -
How to solve the did not return httpresonse error with django?
I have a problem in registration with django, here is my views code: def register(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): form.save() return redirect('/') else: form = RegistrationForm() args = {'form': form} return render(request, 'users/reg_form.html', args) ,but i always get: ValueError at /user/register/ The view Users.views.register didn't return an HttpResponse object. It returned None instead. Request Method: POST Request URL: http://127.0.0.1:3001/user/register/ Django Version: 2.0.2 Exception Type: ValueError Exception Value: The view Users.views.register didn't return an HttpResponse object. It returned None instead. Exception Location: /home/iah/.local/lib/python3.5/site-packages/django/core/handlers/base.py in _get_response, line 139 -
I want delete serializer's content to show
I want delete serializer's content to show.I am using Django Rest Framework.I am making a system return Json of serializers.Furthermore,I did not want to show user_id data. I wrote in views.py class InfoViews(viewsets.ModelViewSet): queryset = Info.objects.all() serializer_class = InfoSerializer lookup_field = 'id' def update(self,request, *args, **kwargs): obj = UserInfo.objects.get(pk=kwargs['id']) data = request.data info_serializers = InfoSerializer(obj, data = data) if info_serializers.is_valid(raise_exception=True): info_serializers.save() del info_serializers.data['user_id'] return JsonResponse(info_serializers.data) Now all son data is shown.What is wrong in my code?How should I fix this? -
Python weird [n chars] encoding error?
I have a seemingly dumb and simple bug, but for the life of me I cannot figure out why this doesn't work. In my test, when I compare two dictionaries, i get this error: Traceback (most recent call last): File "/path/to_my_app/tests/test_unit.py", line 120, in test_destroy_data self.assertEqual(obsolete_data, expected_obsolete_data) AssertionError: {'cou[45 chars]es': {<Category: Test Category>}, 'beers': {<Beer: Test Beer>}} != {'cou[45 chars]es': {<Category: Test Category>}, 'beers': {<Beer: Test Beer>}} {'beers': {<Beer: Test Beer>}, 'categories': {<Category: Test Category>}, 'countries': {<Country: Test Country>}} Django 2.0, Python 3.5 My method: def destroy_data(self): """ Remove entries not in the csv file. """ obsolete_data = { 'beers': set(Beer.objects.all()) ^ set(self.beer_list), 'categories': set(Category.objects.all()) ^ set(self.category_list), 'countries': set(Country.objects.all()) ^ set(self.country_list), } for data in obsolete_data: [obj.delete() for obj in obsolete_data[data]] return obsolete_data My test: def test_destroy_data(self): """ Remove old entries. """ self.importer.import_data(destroy=False) obsolete_data = self.importer.destroy_data() expected_obsolete_data = { 'countries': {self.country}, 'categories': {self.category}, 'beers': {self.beer}, } self.assertEqual(obsolete_data, expected_obsolete_data) When I inspect these two values in my debugger, they're both same, or at least they print out that way. I've tried writing keys in unicode, but I get the same error. Why does this [45 chars] pop up? -
Django application not logging tornado daemon uwsgi
I am trying to log my django application. This works fine (I see all other logs in the logfile) unless I try to log my uWSGI daemonized processes. I am new to using a daemon, is there a reason why it would log differently? I am using in uwsgi.yaml: attach-daemon: /opt/application/bin/tornading This is my Logging in the settings module: LOGGING = { 'handlers': { 'logfile': { 'level':'DEBUG', 'class':'logging.handlers.RotatingFileHandler', 'filename': '/var/log/application.log', 'maxBytes': 1 * 1024 * 1024, 'backupCount': 2, 'formatter': 'standard', }, }, 'loggers': { 'application': { 'handlers': ['logfile'], 'level': 'DEBUG', 'propagate': True, }, } } Tornading.py starts an IOloop instance and a tornado consumer: import logging import settings LOGGER = logging.getLogger(__name__) def main(): app = tornado.web.Application(BroadcastRouter.urls) http_server = tornado.httpserver.HTTPServer(app) http_server.listen(port=settings.TORNADO_PORT, address=settings.TORNADO_HOST) ioloop = tornado.ioloop.IOLoop.instance() consumer = communication.TornadoConsumer(ioloop, BroadcastConnection.on_rabbit_message) consumer.connect() LOGGER.debug('Hello world') ioloop.start() if __name__ == "__main__": main() I have also tried LOGGER = logging.getLogger('application') and still no logging from tornading.py Any ideas on why this is not working? -
Getting date from Django datetime field with F() expression
Lets say I have a Django model object that requires to update a particular field if the last_updated datetime field is equal to today's date. If I were to use F expression to avoid race condition, what would be the best way to compare the date from last_updated with current date using timezone.now().date()? -
Django Redux Forgot Password
I am using django 1.11 and redux 2.2. I can register user by sending email but when someone clicks on forgot password and giving email to get password reset link, no email is being sent. Can anyone help me out? -
DateTimeField - separation in admin panel
I have two fields from and to. In my application (django 1.11.2), sometimes I do not need an hour, I just need the date itself. But validation does not allow me to save the object and asks for hour. Is it possible to somehow separate it or does the date and time always have to be given in the DateTimeField field? from = models.DateTimeField(blank=True, null=True) to = models.DateTimeField(blank=True, null=True) -
Python paypal api BillingPlan and BillingAgreement clarifications
In my python project i have to implement paypal recurrent payement. I have install tje paypal sdk and create a file for create a paypall payement page like this: import paypalrestsdk from paypalrestsdk import BillingPlan from paypalrestsdk import BillingAgreement from paypalrestsdk import Payment import webbrowser from urllib import parse paypalrestsdk.configure({ 'mode': 'sandbox', # sandbox or live 'client_id': <my app client id>, 'client_secret': <my app secret>}) def create_bill(): billing_plan = BillingPlan({ "name": "Plan with Regular and Trial Payment Definitions", "description": "Plan with regular and trial payment definitions.", "type": "INFINITE", "payment_definitions": [ { "name": "Regular payment definition", "type": "REGULAR", "frequency": "MONTH", "frequency_interval": "1", "amount": { "value": "100", "currency": "USD" }, "cycles": "0", "charge_models": [ { "type": "SHIPPING", "amount": { "value": "10", "currency": "USD" } }, { "type": "TAX", "amount": { "value": "12", "currency": "USD" } } ] }, { "name": "Trial payment definition", "type": "TRIAL", "frequency": "WEEK", "frequency_interval": "5", "amount": { "value": "9.19", "currency": "USD" }, "cycles": "2", "charge_models": [ { "type": "SHIPPING", "amount": { "value": "1", "currency": "USD" } }, { "type": "TAX", "amount": { "value": "2", "currency": "USD" } } ] } ], "merchant_preferences": { "setup_fee": { "value": "1", "currency": "USD" }, "return_url": "https://example.com", "cancel_url": "https://example.com/cancel", "auto_bill_amount": "YES", "initial_fail_amount_action": "CONTINUE", … -
sitemap for django-angular website
I have a website with django angular 5. I want to create sitemap for this website. I know how to create sitemap in django alone. but I do not know how to create sitemap when my front-end is angular 5. -
@login_required is not working giving 302 error
views.py @login_required # @never_cache # @cache_control(no_cache=True, must_revalidate=True, no_store=True) def dashboard(request): """ to show the dashboard page """ # print(request.user.email) return render(request, 'base.html') settings.py LOGIN_URL = '/auth/login/' LOGOUT_REDIRECT_URL = '/auth/login/' error on system console User: n User is valid, active and authenticated [27/Mar/2018 07:22:37] "POST /auth/login/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/dashboard/ HTTP/1.1" 302 0 [27/Mar/2018 07:22:37] "GET /auth/login/?next=/auth/dashboard/ HTTP/1.1" 302 0 i m trying to go in the dashboard after login .whenever we … -
I am try to login with django using Angular4
i create Rest API for login in Django and i want to call it in angular4 heare is my angular4 code login.components.ts import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Http, Response, Headers} from '@angular/http'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { constructor(private router:Router, private http:Http) { } getData = []; with this function i get data from my APIand i am trying to compare this data with form data fatchData = function(){ this.http.get("http://127.0.0.1:8000/loginAdmin/").subscribe((res:Response) => { this.getData = res.json(); }) } loginUser(e){ e.preventDefault(); var username = e.target.elements[0].value; var password = e.target.elements[1].value; if(username == 'this.getData.username' && password == 'this.getData.password') { this.router.navigate(['/deshbord']) } else{ console.log('Error Find'); } } ngOnInit() { this.fatchData(); } } this is my login.comonents.login i want that when user give user name and password its compare with my API data and it's true then navigate to other page.. <form (submit)="loginUser($event)"> <div class="input"> <label>UserName</label> <input type="text"> </div> <div class="input"> <label>password</label> <input type="password"> </div> <div class="input"> <input type="submit" value="Login"> </div> </form> -
Why am I getting a type error in django?
So I am trying to pass a query in views.py which is working just fine in python shell. I am facing problem in my django project. views.py: def result(request): # Shows the matched result query = request.GET.get('inc_search') check = Incubators.objects.filter(incubator_name__icontains= query).exclude(verify = False) return render(request, 'main/results.html', {'incubators': incubators,'check': check}) def details(request, incubator_id): inc = get_object_or_404(Incubators, pk = incubator_id) details = Details.objects.get(pk = incubator_id) return render(request, 'main/details.html', {'inc': inc, 'details': details}) def locate(request, incubator_id): pos = Incubators.objects.values_list('latt', 'lonn').filter(pk = incubator_id) return render(request, 'main/locate.html', {'pos': pos}) My urls.py is below: url(r'location/', views.location, name = 'location'), url(r'prediction/', views.prediction, name = 'prediction'), url(r'locate/', views.locate, name = 'locate'), I am getting the following traceback: TypeError at /locate/ locate() missing 1 required positional argument: 'incubator_id' Request Method: GET Request URL: http://127.0.0.1:8000/locate/ Django Version: 1.11.3 Exception Type: TypeError Exception Value: locate() missing 1 required positional argument: 'incubator_id' Can anyone help me find the error? -
django - postman login failed
use django 2.0.2 mac 10.13 postman 5.5.2 Web Use def login(request): form = UserCreateForm if request.method == "POST": form = UserCreateForm(request.POST) if form.is_valid(): username = form['username'].value() password = form['password'].value() user = authenticate(username=username,password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') else: return render(request , 'blog/user_create.html',{'form':form}) Post Man Use def login(request): if request.POST: username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username,password=password) if user is not None: if user.is_active: login(request, user) return redirect('/') return redirect('/') error Log File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 923, in to_python return int(value) ValueError: invalid literal for int() with base 10: 'None' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/junholee/django1/authtest/blog/views.py", line 43, in signin login(request, user) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 132, in login if _get_user_session_key(request) != user.pk or ( File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/contrib/auth/__init__.py", line 61, in _get_user_session_key return get_user_model()._meta.pk.to_python(request.session[SESSION_KEY]) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 928, in to_python params={'value': value}, django.core.exceptions.ValidationError: ["'None' value must be an integer."] connect 127.0.0.1:8000/login from web(Form) i succses login but i try http://127.0.0.1:8000/login?username=user1&password=test123 from postman raise excetion this(error Log) … -
How can I make django url alias?
I am using django rest framework filters in my app. For a viewset that looks like following: class ProductViewSet(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer lookup_field = 'slug' filter_backends = (SearchFilter, DjangoFilterBackend,) filter_fields = ('category__slug','brand__slug') It adds following url: http://*.compute.amazonaws.com:8000/product/?category__slug=smart-phone&brand__slug=asus& I want to keep using DjangoFilterBackend as I am using, but I want the api to look like following: http://*.compute.amazonaws.com:8000/categories/smart-phone/brands/asus I know that I can use RedirectViews but I don't want to redirect user. Can I somehow make alias urls without using nginx or other reverse proxy tools?