Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django rest_framework response changes list order
Print command result: Rest framework response The api looks like: high_margin = StoreInvoiceBreakup.objects.filter(store_invoice__store_id=store_id) \ .order_by('-gross_margin') \ .values_list('product_name', 'gross_margin')[:int(sell_range)] low_margin = StoreInvoiceBreakup.objects.filter(store_invoice__store_id=store_id) \ .order_by('gross_margin') \ .values_list('product_name', 'gross_margin')[:int(sell_range)] print(high_margin) print(low_margin) return Response({"code": 200, "high-margin": high_margin, "low-margin": low_margin}) though the response is ordered still why does rest_framework.response.Response returns in list in a different order? How can i get the list ordered via Response or do i have to serialize this? -
Django throws UnreadablePostError on deploying DigitalOcean - issue
I have deployed django on digitalocean Everything works good for POST messages with less content to send. But when i use forms to send much of data in the textarea i am getting this error Internal Server Error: /edit/5 Traceback (most recent call last): File "/home/user/venv/lib/python3.6/site-packages/django/http/request.py", line 322, in read return self._stream.read(*args, **kwargs) File "/home/user/venv/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 36, in read result = self.buffer + self._read_limited() File "/home/user/venv/lib/python3.6/site-packages/django/core/handlers/wsgi.py", line 30, in _read_limited result = self.stream.read(size) File "/usr/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer ......................... ......................... raise UnreadablePostError(*e.args) from e django.http.request.UnreadablePostError: [Errno 104] Connection reset by peer This happens when i update the server to use SSL. Any suggestion ? -
Django loads save twice for any model
After upgrading to Django 2 from Django 1.7.4, I face the following issue. In django admin save() method is called twice for any model in the project. When it comes to add new, it add the same entry twice, if edit it also saves twice, as a result admin result notification gives the same notice twice.If you click delete button, it first deletes and then gives notification that the entry does not exist, because it also calls delete function twice. So far checked: - settings file is loaded only once - rewrote post_save But no avail. Settings #SSL settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True INSTALLED_APPS = ( 'dal', 'dal_select2', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'django.contrib.sitemaps', 'django.contrib.admin', 'compressor', 'mptt', 'django_mptt_admin', ----- 'myappA', 'myAppB', ) -
@channel_session_user_http message.user is always showing AnonymousUser
I'm using channels 1.0.2. My website is running at http://example.com and websocket is running at ws://example.com:8080/live_chat/ from channels import Group, Channel from channels.sessions import channel_session from channels.auth import channel_session_user, channel_session_user_from_http @channel_session_user_from_http def ws_connect(message): print message.user message.reply_channel.send({"accept": True}) message.channel_session['rooms'] = [] @channel_session_user def ws_receive(message): print message.user print message.channel_session.__dict__ payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("chat.receive").send(payload) Everything is working well. I can establish a connection and send data back and forth. But, unable to get the authenticated user. Even though I have logged in. This is what I get: Performing system checks... System check identified no issues (0 silenced). July 24, 2018 - 12:03:28 Django version 1.11.11, using settings 'django_project.settings' Starting Channels development server at http://0.0.0.0:8080/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CONTROL-C. 2018-07-24 12:03:28,147 - INFO - worker - Listening on channels chat.receive, http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-07-24 12:03:28,149 - INFO - worker - Listening on channels chat.receive, http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-07-24 12:03:28,151 - INFO - worker - Listening on channels chat.receive, http.request, websocket.connect, websocket.disconnect, websocket.receive 2018-07-24 12:03:28,153 - INFO - server - HTTP/2 support enabled 2018-07-24 12:03:28,154 - INFO - server - Using native Twisted mode on channel layer 2018-07-24 12:03:28,154 - INFO - server - Listening … -
Exception Type: ValueError at /music/1/favourite/ Exception Value: invalid literal for int() with base 10: 'on'
I am new to Django and I am using it's latest version 2. I am referring to this particular tutorial https://www.youtube.com/watch?v=irH98-4eKmQ&list=PL6gx4Cwl9DGBlmzzFcLgDhKTTfNLfX1IK&index=24 I am getting this error. I tried a lot but couldn't fix the issue. ValueError at /music/1/favourite/ Environment: Request Method: POST Request URL: http://127.0.0.1:8000/music/1/favourite/ Django Version: 2.0.7 Python Version: 3.6.6 Installed Applications: ['music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\exception.py" in inner 35. response = get_response(request) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\base.py" in _get_response 128. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\core\handlers\base.py" in _get_response 126. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Adesh\Desktop\website\music\views.py" in favourite 22. selected_song = album.song_set.get(pk=request.POST['song']) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\manager.py" in manager_method 82. return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\query.py" in get 394. clone = self.filter(*args, **kwargs) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\query.py" in filter 836. return self._filter_or_exclude(False, *args, **kwargs) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\query.py" in _filter_or_exclude 854. clone.query.add_q(Q(*args, **kwargs)) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\sql\query.py" in add_q 1253. clause, _ = self._add_q(q_object, self.used_aliases) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\sql\query.py" in _add_q 1277. split_subq=split_subq, File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\sql\query.py" in build_filter 1215. condition = self.build_lookup(lookups, col, value) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\sql\query.py" in build_lookup 1085. lookup = lookup_class(lhs, rhs) File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\lookups.py" in __init__ 18. self.rhs = self.get_prep_lookup() File "C:\Users\Adesh\AppData\Local\Programs\Python\Python36\lib\site- packages\django\db\models\lookups.py" in get_prep_lookup 68. … -
nested serialization dont now create a forignkey it requires a new Object instead of 'id'
here is my model, serializer and output but when i want to create a new page it ask me to add a whole new user as its just a foreign-key it need to be a number like 1 (user id) and same in the case of categories how can i solve it.... help me please -
Django : Use the same tamplateview for create and update
I have this TemplateView : class DamageEntry(TemplateView): template_name = "damage/damageadd.html" def get(self, request): general = General.objects.get(pk=1) form = DamageEntryForm() args = {'form': form, 'general': general, } return render(request, self.template_name, args) def post(self, request): general = General.objects.get(pk=1) form = DamageEntryForm(request.POST) form.non_field_errors() if form.is_valid(): post = form.save(commit=False) if self.request.user.is_authenticated(): post.user = request.user post.userip = get_client_ip(request) # το IP του χρήστη location = get_cocation(post.lat, post.lng) post.location = location post.formatted_address= location.formatted_address post.entry_date = datetime.datetime.now(tz=timezone.utc) post.save() form = DamageEntryForm() args = {'form': form, 'general': general } return http.HttpResponseRedirect('damage/add/') else: print('form is not valid') print(form.errors) # form = DamageEntryForm() args = {'form': form, 'general': general } return render(request, self.template_name, args) It works fine for create new record. I want to use thw same view for update , because of the extra code on Post section I use this url for update : # /damage/damage/list/1 url(r'damage/list/(?P<pk>[0-9]+)/$', views.DamageEntry.as_view(), name="damage-by-id"), Can I do this? How can I pass pk for create and update record Thanks in advanced -
Proble with unti test put method django rest
I'm trying to write tests for APIviewSet. GET and POST work fine, but I can not combine tests for the PUT method. I think that the problem in the path that I pass to the function, but I can not figure out how to fix it. I found nothing in the documentation. class ResponseTracebackTestCase(TestCase): """class for traceback""" class JustTest(ResponseTracebackTestCase): maxDiff = None def setUp(self): # Every test needs access to the request factory. self.factory = APIRequestFactory() self.time = datetime.datetime(2010, 1, 1) self.user = User.objects.create_user( username='admin', email='admin@admin.com', password='top_secret1', born_date=self.time, date_joined=self.time) self.view = ClientViewSet.as_view({'get': 'list', 'post': 'create', 'put': 'update'}) #...some_code def test_admin_update(self): request = self.factory.put('/api/service/client/', {...some_data}) force_authenticate(request, user=self.user) response = self.view(request, pk=1) self.assertResponseCodeEquals(response, 200) response.render() self.assertEqual(json.loads(response.content), {...some_data}) Traceback: File "/code/service/tests.py", line 138, in test_admin_update self.assertResponseCodeEquals(response, 200) File "/code/service/tests.py", line 32, in assertResponseCodeEquals ) + '\n' + ''.join(format_list(response._init_stack)) AssertionError: 404 != 200 : Response code was '404', expected '200' response.detal: {'detail': ErrorDetail(string='Not found.', code='not_found')} -
ecommerce customer custom login auth in django python
Created separate customer model app for front-end and when trying to login using custom code its working fine but when I was trying to pass and validate front-end user auth, every time I am getting "AnonymousUser" from django.db import models from django.utils import timezone Create your models here. class gender(models.Model): title = models.CharField( max_length=10 ) def __str__(self): return self.title class customer(models.Model): id_gender = models.ForeignKey(gender, on_delete=models.CASCADE,default=1) id_default_group = models.IntegerField(default=1) firstname = models.CharField( max_length=256 ) lastname = models.CharField( max_length=256 ) email = models.CharField( max_length=128 ) password = models.CharField( max_length=32 ) Create your views here. def customer_login(request): context = {} if request.method == "POST": username = request.POST['username'] password = settings.ENCRYPT_KEY+request.POST['password'] password_encrypt = make_password(password) customer_auth = customer.objects.filter(email=username,password=password_encrypt) if customer_auth: return HttpResponseRedirect(reverse('customer_account')) else: context["error"] = "Provide valid credentials !!" return render(request, "login.html", context) else: return render(request, "login.html", context) def customer_account(request): context = {} if 'logout' in request.POST: return customer_logout(request) #print(request) #if not request.user.id: # return HttpResponseRedirect(reverse('customer_login')) print(request) ## gettting AnonymousUser #context['customer'] = request.customer return render(request, "myaccount.html", context) def customer_logout(request): return HttpResponseRedirect(reverse('customer_login')) -
Django is applying background color , but not apllying background image from style.css
I run my django project with uwsgi. It reads style.css file in statics/css . There are two areas in style.css It applies 1st area, but it does not apply 2nd area to the page. and 1) #skin-blur-violate { background: #581528; } and 2) #skin-blur-violate { background-image: url(../img/body/violate.jpg); } Below is statics configuration in settings. STATIC_URL = '/home/proj1/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = ( '/home/proj1/staticorj/static/', ) -
django channels message.user is always AnonymousUser even after login
I'm using django channels 1.0.2 from channels.auth import channel_session_user, channel_session_user_from_http @channel_session_user_from_http def ws_connect(message): message.reply_channel.send({"accept": True}) message.channel_session['rooms'] = [] @channel_session_user def ws_receive(message): print message.user payload = json.loads(message['text']) payload['reply_channel'] = message.content['reply_channel'] Channel("chat.receive").send(payload) message.user is always AnonymousUser. My website runs at http://example.com and the websocket connection is done on ws://example.com:8080/live_chat/. Everything is working well. The socket gets connected and I can send data. But unable to know if a user is authenticated. -
django2 search form UnboundLocalError at /
I try to add a search box with this code's i got the error: local variable 'name' referenced before assignment def home(request): if 'search' in request.GET: term = request.GET['search'] name = Products.objects.filter(titulo__icontains=term) return render(request,'base.html', {'name':name}) in the model: from django.db import models class Products(models.Model): name = models.CharField(max_length=255, blank=True, null=True) def __str__(self): return self.name on the views from django.shortcuts import render from .models import Products def home(request): if 'search' in request.GET: term = request.GET['search'] item = Products.objects.filter(name__icontains=term) return render(request,'base.html', {'item':item}) if i use this i got the error local variable 'name' referenced before assignment And if i add the variable name from django.shortcuts import render from .models import Products def home(request): name="" if 'search' in request.GET: term = request.GET['search'] item = Products.objects.filter(name__icontains=term) return render(request,'base.html', {'item':item}) i don't see nothing -
Add chat group's slug into websocket entry | Django | ws4redis
I've made a chat application using Django==1.9.7 and ws4redis. I have Chat, ChatUser and Message models. Every chat instance has its slug field created from its name, for example "JoJo's Bizarre Adventures" will be 0.0.0.0:9000/jojos-bizarre-adventures/, but on front end, part that defines websocket entry is ws://0.0.0.0:9000/ws/chat?subscribe-group for every chat link. Well it doesn't crash or anything, it works like this: I write text into input and send message, the message isn't on the screen, but after I reload the page all my messages are here, because they are get saved into database. I suppose it happens because of slug isn't in websocket entry. If so, I need every chat's slug to be between port and ws parts. -
Django: collectstatic raises OSError: [Errno 39] Directory not empty: (ckeditor)
Suddenly, I can't do collectstatic. python manage.py collectstatic Type 'yes' to continue, or 'no' to cancel: yes Found another file with the destination path 'admin/js/jquery.init.js'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path. Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 344, in copy_file if not self.delete_file(path, prefixed_path, source_storage): File "/home/django/maklerienv36/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 294, in delete_file self.storage.delete(prefixed_path) File "/home/django/maklerienv36/lib/python3.6/site-packages/django/core/files/storage.py", line 299, in delete os.rmdir(name) OSError: [Errno 39] Directory not empty: '/home/django/makleri/static/ckeditor' I tried to delete whole static folder and rerun collectstatic but it didn't help. Do you know how to make it work? It works on my PC, this is a server. -
Getting and posting data to external web API, server-side or client-side?
I'm working on a web-app which has a section for getting some data from external APIs (e.g. usgs and google-maps) and showing them to the user and another section for getting input from user (e.g. couple of input fields) and posting it to some other API. I can do the server side using Django/Flask and the client side using Reactjs (or vanilla js, bootstrap, etc). In terms of speed, security and user friendliness, where should I make those API calls? Server side or client side? Does it make any difference wheter I want to save some of the data to my server or not? -
Django/Nginx 403 Error on new static files
Can't figure out why, but after collecting new static files (collectstatic), nginx throws 403 Error. New files have different permissions from old static files. -rw-rw-r-- 1 django django 115206 Jul 9 15:23 dom.jpg -rw-r----- 1 django django 884 Jul 23 20:42 error.svg -rw-rw-r-- 1 django django 308934 Mar 11 16:30 header.bmp -rw-rw-r-- 1 django django 20188 Mar 11 16:30 header.jpg -rw-r----- 1 django django 910 Jul 23 20:42 success.svg -rw-rw-r-- 1 django django 1826 Jul 9 15:23 user.svg As you can see - error.svg and success.svg have different permissions, that's why nginx throws 403. Do you know how to fix this? I don't want just change permission for existing files, I want universal solution so this never happens again. -
Making a CreateView in Django using kwargs from a different model template
I am not able to create the object review using the CreateView I am not sure what I am doing wrong. Below is a brief intro Intro: My Order history page is where a user can see all the items that he/she has bought. In the Order history page I have a button that lets the buyer leave a review for the seller. Below is the button <a href="{% url 'accounts:review' username=item.made_by pk=item.pk %}"> <button class="text-success">Leave Review</button> </a> from here I get the items item.id and the sellers username {% for item in order.items_in_this_order.all %} <!--models below --> url(r'^(?P<username>[-\w]+)/(?P<pk>\d+)/review/$', views.ReviewCreate.as_view(), name='review'), {% endfor %} The url expresses correctly in the address bar when I click on leave a review. It then displays a form. where I enter feedback, ratings, feedback_image, feedback_video the rest of the fields are supposed to be made in the views.py. After I fill the form and hit submit. The url is still correct. But I get the below error IntegrityError at /accounts/nikhil/10/review/ NOT NULL constraint failed: accounts_review.item_id Request Method: POST Request URL: http://127.0.0.1:8000/accounts/nikhil/10/review/ Django Version: 1.11 Exception Type: IntegrityError Exception Value: NOT NULL constraint failed: accounts_review.item_id Below are the views.py this is inside the accounts app … -
Celery Django discover task but doesn't receive it
I have set up celery (4.2) on Django and set up tasks in separate modules. I run celery and see my tasks in the task list, but when I call the task celery worker doesn't receive it. No error logs or any other logs about the task. my_app.tasks.custom_task from config.celery import app # or from celery import shared_task @app.task # or @shared_task def custom_task(): print("Custom task called") ... custom_task.delay() I tried to set up the task in the module where celery app created and when I start celery it sees the task and receives it on call. ... app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task def temp_task(): print("Temp task is called") temp_task.delay() So the source of the issue is that my tasks are in separate module and my tasks imports db models so the issue could also be in imports, but no errors logs so far. -
Django is searching wrong statics directory
When i run django on uwsgi with; uwsgi --http :8081 --module proj1.wsgi It gives below error when i open start page from browser: Not Found: /accounts/login/static/css/style.css But my settings.py is : STATIC_URL = 'static/' STATIC_ROOT = '/home/proj1/static/' STATICFILES_DIRS = ( '/home/proj1/staticorj/static/', ) When i make collectstatic, it copies files to static root without problem. I dont understand why does it look for /accounts/login. It should look in /home/proj1 directory for static dir. So the browser opens the page but without serving static files. -
Django dependent dropdown with Ajax problems with ids
I am trying to implement a dependent dropdown. Vitor Freitas did this in his blog and I am basically following his solution. (A really cool blog with clear code which helped me a lot of times). I have adopted it to my pages but it stuck exactly where the dropdown should be restricted. I am pretty sure that I messed up with the foreign key or with Ajax/javascript (as I have no clue about ajax+javascript.) Maybe you see my 'basic' error and can help me. Would be thankful. models.py class Country(models.Model): name = models.CharField(max_length=3) def __str__(self): return self.name class Provider(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class CustomerSubsidiary(models.Model): subCountry = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True) subName = models.CharField(max_length=50, blank=True) urls.py urlpatterns = [ path('test', views.CustomerSubsidiaryListView.as_view(), name='CustomerSubsidiary_changelist'), path('test/add/', views.CustomerSubsidiaryCreateView.as_view(), name='CustomerSubsidiary_add'), path('test/<int:pk>/', views.CustomerSubsidiaryUpdateView.as_view(), name='CustomerSubsidiary_change'), path('ajax/load-provider/', views.load_provider, name='ajax_load_provider'), ] views.py def load_provider(request): country_id = request.GET.get('country') provider = Provider.objects.filter(country_id=country_id).order_by('name') return render(request, 'Customer/city_dropdown_list_options.html', {'provider': provider}) providerForm class ProviderForm(forms.ModelForm): class Meta: model = CustomerSubsidiary fields = ('subName', 'subCountry', 'provider') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['provider'].queryset = Provider.objects.none() customersubsidiary_form.html {% extends 'base.html' %} {% block content %} <h2>Provider Form</h2> <form method="post" id="providerForm" data-provider-url="{% url 'ajax_load_provider' %}" novalidate> {% csrf_token %} <table> {{ form.as_table … -
OperationalError, connecting to another Django/DB project
I'm trying to connect to another database (project-B) that also uses Django. I would like to ask for help on how to resolve the following error? Here's the error from Django debug: could not connect to server: Connection refused Is the server running on host "111.222.333.444" and accepting TCP/IP connections on port 5432? Here's the firewall from project-B Status: active Logging: on (low) Default: deny (incoming), allow (outgoing), disabled (routed) New profiles: skip To Action From 5432 ALLOW IN 111.222.333.444 I also put it in the allowed host ALLOWED_HOSTS = [ '111.222.333.444'] Other than that, I have not modified anything from project-B. -
How to generate Email Automatically ,After Registration In Django Rest Framework?
I have A models.py as this 1. models.py class User(AbstractUser, BaseModel): full_name = models.CharField(max_length=64) addresss=models.CharField(max_length=40) phoneno=models.IntegerField(null=True, blank=True) email=models.EmailField() password=models.CharField(max_length=40) re_password=models.CharField(max_length=40) gender=models.IntegerField(choices=gender_choice,default='0') Serializers.py is like this: 1. serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields=('full_name','id','addresss','phoneno','email','gender') Views.py class StudentViewset(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer http_methods = ['get', 'post','put','delete'] def create(self, request): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) row = serializer.data user=User.objects.get_or_create( defaults={'full_name':row['user']['full_name'],'addresss':row['addresss'], 'phoneno':row['phoneno'],'password':row['password'] ,'re_password':row[['re_password'], 'gender':row['gender'] ,'username':username}) Then My Question is . After Registering Student . I want To generate Email like his/her(address@gmail.com). how can i do This??? -
Behaviour of django order_by
I have 3 models: class Parent(models.Model): name = models.CharField() class StudentDriver(models.Model): parent = models.ForeignKey(Parent, on_delete=models.CASCADE) class Car(models.Model): student_driver = models.ForeignKey(StudentDriver, on_delete=models.CASCADE) Why is it, that if I do the following, the order_by is not honoured (my qs will not be ordered by the student_driver.parent_id)? And is there a way I can get it ordered? I need it for a groupby. for car in Car.objects.order_by('student_driver__parent'): print(car.student_driver.parent) If I do: for car in Car.objects.order_by('student_driver'): print(car.student_driver.parent) it works no problem (the qs is ordered by student_driver_id). Seems to be the ForeignKey link, but I can't figure it out. -
quick fill forms in django
Sorry I have a really basic question while learning Django and could not find an easy answer. My model is : class Entry(models.Model): name = models.CharField(max_length=200) type = models.CharField(max_length= 200) date = models.DateTimeField(auto_now= False, auto_now_add=True) updated = models.DateTimeField(auto_now= True, auto_now_add= False) description = models.TextField() And so my general form implementation is : class EntryForm(forms.ModelForm): class Meta: model = Entry fields = ['name','type', 'description'] views: def add(request): if request.method == 'POST': form = EntryForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.save() return HttpResponseRedirect('/') else: form = EntryForm() return render(request, "form.html", {'form': form}) I want to add a quick fill button next to add button (that calls above view ) where the name and type is statically filled in the object and only textbox appears for description field. I could not find a way to statically assign the values to my field in Django. I had tried creating a different HTML file ( quickform.html) but {{form.as_p}} will put all the fields. my forms.html is <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-success" type='submit'>Submit</button> </form> what would be the best way to add a quick link to my index page where the name ( is auto-filled to the "general"+str(id)) and type is auto-filled … -
Can't send data back to django from JS ajax
here's the javascript: $.ajaxSetup({ data: {csrfmiddlewaretoken: '{{ csrf_token }}' }, }); var ajaxdata = { exam: $('#Exam').val() }; $('#Save').click(function () { $.ajax({ url: '/vsform', type: 'POST', dataType: 'json', data: JSON.stringify(ajaxdata), success: function () { ... }, error:function (xhr, ajaxOptions, thrownError){ ... } }); } the #Save is a button and the #Exam is a textbox. when I click the button, it always shows error 403 forbidden. can't find the problem, please help! thanks in advance.