Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Caculate order toatl in django ecommerce
So i am building an e-commerce website to advance my knowledge in python . So far my learning curve is going good . I am wondering on how to calculate cart total . I have my product model def Products(models.Model): price=models.Decimalfield(default=2.50,null=True,decimal_places=2) quantity=models.InterField(default=4,null=True) def Cart(models.Model): total=models.DecimalField(default=0.0,decimal_places=2) products=models.ManyToManyField(Products,null=True) lets assume a user added 2 products in the cart first product Product.quantity=3, Product.price=$40 Second Product Product.quantity=5, Product.price=$20 What will be the best way to calculate my cart total. i tried this, i created a save function under the cart model def save(self,*args,**kwargs): if self.id: total=0.00 products=self.products.all() total=math.fsum(pro.price * pro.quantity for pro in products) self.total=total super(Cart,self).save(*args,**kwargs) But this does not work out for me, please i need help. Thanks in Advance -
Passing a parameter through AJAX URL with Django
Below is my code. 'n' logs correctly in the console, and everything works perfectly if I manually enter the value for 'n' into url: '{% url "delete_photo" iddy=2%}'. Alas, when I try to use 'n' as a variable (seen below) it gives me a reverse match not found error. Can anyone help with this? javascript function test(n){ console.log(n); $.ajax({ type: 'get', url: '{% url "delete_photo" iddy=n%}', datatype:'json', success: function(data){ alert(n) console.log(data) console.log(n) }, error: console.log("SSS"), });} html {% for t in photos %} <div id="photobox" ><img id="img_pb3"src="{{t.photo.url}}"> <div><a><span onclick="test({{t.id}})" class="closeBtn">&times;</span></div></a> </div> {% endfor %} urls urlpatterns = [ path('', views.explore, name='explore'), path('home/', views.home, name='home'), path('home/comment', views.comment, name='comment'), path('home/photo_del/<iddy>', views.delete_photo, name='delete_photo') ] views def delete_photo(request, iddy): data = {'a':iddy, 'b': iddy} return JsonResponse(data, safe=False) -
Exception Type: ProgrammingError at /api/sidewalk/ Exception Value: (1146, "Table 'stepsdb.api_sidewalk' doesn't exist")
I don' t know what is going on. I follow the instructions about deploying the web app . migragte commands work well and no error appear, but when I have access to the website using ip or my domain name, there are bugs like these and the website cannot work well and the web app run well locally. These are the error logs. Environment: Request Method: GET Request URL: http://35.182.146.123:8080/api/sidewalk/ Django Version: 2.1.7 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'frontend', 'rest_framework', 'api.apps.ApiConfig', 'corsheaders', 'cloudinary'] Installed Middleware: ['corsheaders.middleware.CorsMiddleware', '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 "/usr/local/lib/python3.5/dist-packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) File "/usr/local/lib/python3.5/dist-packages/django/db/backends/mysql/base.py" in execute 71. return self.cursor.execute(query, args) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py" in execute 170. result = self._query(query) File "/usr/local/lib/python3.5/dist-packages/pymysql/cursors.py" in _query 328. conn.query(q) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py" in query 517. self._affected_rows = self._read_query_result(unbuffered=unbuffered) File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py" in _read_query_result 732. result.read() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py" in read 1075. first_packet = self.connection._read_packet() File "/usr/local/lib/python3.5/dist-packages/pymysql/connections.py" in _read_packet 684. packet.check_error() File "/usr/local/lib/python3.5/dist-packages/pymysql/protocol.py" in check_error 220. err.raise_mysql_exception(self._data) File "/usr/local/lib/python3.5/dist-packages/pymysql/err.py" in raise_mysql_exception 109. raise errorclass(errno, errval) The above exception ((1146, "Table 'stepsdb.api_sidewalk' doesn't exist")) was the direct cause of the following exception: File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/usr/local/lib/python3.5/dist-packages/django/core/handlers/base.py" in _get_response … -
How to create simple custom field in django?
I want to create a simple custom field so that I can access property1 and property2 in template like {% for field in form %} {{ field.property1 }} {{ field.property2 }} {% endfor %} my current model looks like class ResponseModel(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) ans1 = models.TextField() ans2 = models.TextField() submit_count = models.IntegerField(default=0) def __str__(self): return str(self.author) + str(self.submit_count) -
Hiding the products with quantity 0 from view django rest framework
How can I hide the products from view with quantity == 0? This is my models.py class Product(models.Model): title = models.CharField(max_length=255, db_index=True) description = models.TextField() price = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) quantity = models.PositiveIntegerField() color = models.CharField(choices=COLOR_CHOICES, default='BLACK', max_length=100) category = models.ManyToManyField(Category, related_name='products') class Meta: ordering = ('-id',) def __str__(self): return self.title @property def instock(self): return self.quantity > 0 and my views.py class ProductsList(generics.ListAPIView): queryset = Product.objects.all().order_by('-id') serializer_class = ProductSerializer filter_backends = (django_filters.rest_framework.DjangoFilterBackend,) filter_class = ProductFilter -
Problem with JWT authentication in django-rest-framework
I have a problem with JWT authentication using django-rest-knox. Error is: Detail: Authentication credentials were not provided. ENDPOINT: /api/auth/login/ Headers in the POST request to the endpoint: { Content-Type: application/json } body: { "username": "admin", "password": 1234 } Login API View: class UserLoginAPIView(generics.GenericAPIView): serializer_class = UserLoginSerializer def post(self, request, *args, **kwargs): data = request.data serializer = self.get_serializer(data=data) serializer.is_valid(raise_exception=True) user = serializer.validated_data token = AuthToken.objects.create(user) return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": token }) Serializer: class UserLoginSerializer(serializers.Serializer): username = serializers.CharField() password = serializers.CharField() def validate(self, data): user = authenticate(**data) if user and user.is_active: return user raise serializers.ValidationError("Invalid Credentials") Default Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'knox.auth.TokenAuthentication', ] } -
password authentication failed for user "saleor"
password authentication failed for user "saleor" FATAL: password authentication failed for user "saleor" when migrating the first time if it's something related to database please someone help me to figure this out I'm using Postgres as the saleor documentation says but I can't pass this migrations point I read somewhere I have to create a database called saleor with saleor as a user with password 'saleor' who is a superuser and if that is the solution tell me how to do that -
How can ı get value to html table?
i want to save value with html form. But i can't save admin panel and Db. And ı want to get values for requests API. But all user's values will be different. The process I want to do is not the same as the registration process. However, the user should be able to record the information to be entered. views.py @login_required def getorder(request): supplierIdInputValue = request.GET.get('apisupplier') usernameInputValue = request.GET.get('apikey') passwordInputValue = request.GET.get('apivalue') admin.py class ProfileInline(admin.StackedInline): model = UserProfileInfo can_delete = False verbose_name_plural = 'API Values' fk_name = 'user' class CustomUserAdmin(UserAdmin): inlines = (ProfileInline,) def get_inline_instances(self, request, obj=None): if not obj: return list() return super(CustomUserAdmin, self).get_inline_instances(request, obj) admin.site.unregister(User) admin.site.register(User, CustomUserAdmin) forms.py class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('apikey', 'apivalue', 'apisupplier') models.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) apisupplier = models.CharField(max_length=40, blank=True, default="SupplierId") apikey = models.CharField(max_length=40, blank=True, default="Kullanıcı Adı") apivalue = models.CharField(max_length=40, blank=True, default="Şifre") def __str__(self): template = '{0.user} {0.apikey} {0.apivalue} {0.apisupplier}' return template.format(self) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): user = instance if created: profil = UserProfileInfo(user=user) profil.save() form.html <form action="{% url 'userapp:profil' %}" method="POST" class="">{% csrf_token %} <div class="form-group"> <div class="input-group"> <div class="input-group-addon"> <i class="fa fa-user"></i> </div> <input type="text" id="apisupplier" name="apisupplier" placeholder="SupplierId" class="form-control"> </div> … -
Jquery AJAX request body is empty. (Django REST inside Docker)
Loading a template, index.html, with JS that's inside the /static directory. Javascript(app.js): var obj = new Object(); obj.startTime = "123"; obj.endTime = "456"; console.log("fetchNext "+JSON.stringify(obj)); var data1 = {"name":"John Doe"} $.ajax({ url:"http://localhost:8000/api/time/", contentType: "application/json; charset=utf-8", data: JSON.stringify(obj), success: function(data){ console.log(data); } }); } It's hitting the Django REST API, but body is empty. class QueryTime(APIView): def get(self, request, format=None): data = "false" jsonstr = request.body.decode('utf-8') # jsonstr is empty. What am I doing wrong here? I have installed CORS and tried whether it fixes or not, and had no luck. And I get these results. web_1 | [07/Mar/2019 17:36:52] "GET / HTTP/1.1" 200 314 web_1 | [07/Mar/2019 17:36:52] "GET /static/app.js HTTP/1.1" 304 0 web_1 | web_1 | [07/Mar/2019 17:36:52] "GET /api/time/?{%22startTime%22:%22123%22,%22endTime%22:%22456%22} HTTP/1.1" 200 7 Not sure what these status codes represent. Any suggestion would be appreciated! -
How to (manually?) drop and recreate foreignkey-restraint in django migration
I think I have a rather obscure case that is not covered by Django. I'm using Django 1.11.20 and this problem surfaces when using mySQL, with sqlite there is no problem (since that does not use foreignkey restraints) So here's the setup. I have a model named 'Function' and it has an automatic primary key field 'id' (made by Django) I have a model named 'Training' and on that there is a ManyToMany relation called 'subscribe_functions' which points to Function. class Training(RegistrationBlock): subscribe_functions = models.ManyToManyField('Function', blank=False, limit_choices_to={'avail_option': True}, related_name="trainings", verbose_name=_('Functiongroups that may register'), help_text=_('People in the selected functions may register their ' 'availability')) So Django made a nice intermediary table for this and on that table there is a foreign key constraint that the column 'function_id' points to Function.id. And here's the problem. Now I want to add a parent model to Function without loosing data and actually move some data to the parent. So I make the parent model ('CoreFunction') and migrate it (it's in a separate app) and then in my migration for Function I do the following things: rename the field 'id' on Function to 'corefunction_ptr' migrations.RenameField( model_name='function', old_name='id', new_name='corefunction_ptr' ), Transfer some data from child model … -
filter field width space django orm
I have a problem when doing a filter in a queryset since the field I want to filter with spaces and I can not modify the table that I consulted because it is an external table. I need do this: array = ['456FG','432TT','234CC','678TT'] query = MyModel.objects.filter(clave__in=array) however the values come like this '456FG ' '432TT ' '234CC ' '678TT ' with spaces because if I use the __in it does not bring me results and I need it to be exact because I can not use __icontains. help -
How would i implement a next page in django
So I'm creating a web application and I have a section where I get data from the database through a view, I was wondering if the data exceeds 100 e.g profiles is there a way to implement a next page button which carries on the profiles e.g limit it to 5 profiles per page. any help would be much appreciated -
iPad not updating page using javascript (with Django backend)
I'm writing a script on a page that checks to see if specific parts of a page should update (based on information in the page passed in from the Django view). The updating works on browsers on computers / notebooks, but fails on browsers on iPads (and, based on my reading, I expect iPhones). It even works on my Pixel phone. So, it looks like this is a problem limited to iPads (and phones?). At the moment, I am running on Django's dev server, if that has any bearing on the problem. From what I can see on the putty terminal, the iPad is making the request (there's a GET every 2 seconds), but I don't know what's happening on the iPad that nothing is updating. Both Safari and Chrome exhibit the same problem behavior. Last time I looked at this problem (with slightly different code) it was NOT a problem for Macbooks, just iPads. Here is the code in question: HTML {% block page_updates %} <div class="container-fluid" id="last_times"> <p style="display:none">Last action taken: <span id="actionTime">{{ update_times.action.isoformat }}</span></p> <p style="display:none">Last chat made: <span id="chatTime">{{ update_times.chat.isoformat }}</span></p> </div> <p style="display:none">Page last updated: <span id="updateTime"></span> {% endblock %} Javascript <script> $(function () { … -
Unknown column in where clause even if it is in MySQL database django
I added the models.IntegerField visit_id in my model. I migrated the changes to database. I can see visit_id in the table I am running a raw_query connected by MySQLdb.connect() method. I am able to run query on sql-workbech and getting the result but when I format query and try to run I get OperationalError: (1054, "Unknown column 'appts.visit_id' in 'where clause'") what could be the reason? -
Django for Mongodb can't find django-admin.py
I am starting to learn to use MongoDB with Django, so I followed this tutorial to start up. I created my virtual environment using python3.6 -m venv MongodbTestVenv, and activated it using source MongodbTestVenv/bin/activate. Everything worked fine, so far. I installed Django-nonrel using pip install git+https://github.com/django-nonrel/django@nonrel-1.5. I installed djangotoolbox using pip install git+https://github.com/django-nonrel/djangotoolbox. I installed Mongo DB engine using pip install git+https://github.com/django-nonrel/mongodb-engine. I checked with pip list to ensure everything is installed: (MongodbTestVenv) MacBook-Pro-de-Hugo:MongodbTestProject hugovillalobos$ pip list Package Version --------------------- ------- Django 1.5.11 django-mongodb-engine 0.6.0 djangorestframework 3.9.2 djangotoolbox 1.8.0 pip 19.0.3 pymongo 3.7.2 setuptools 28.8.0 But, when I type django-admin startproject MongodbTest, I get this error: -bash: django-admin: command not found. I checked this question, but all answer are related to the location of django-admin.py file, so I found it using which django-admin.py, and this is the result: (MongodbTestVenv) MacBook-Pro-de-Hugo:MongodbTestProject hugovillalobos$ which django-admin.py /Users/hugovillalobos/Documents/Code/MongodbTestProject/MongodbTestVenv/bin/django-admin.py I can see that the file is located on the active virtual environment directory, so I can't understand why it can't be located. I don't know what I am missing, I have never had problems with Django when using relational database and I install regular Django versions using just pip install Django. -
Anonymous feedback webpage template
I wanted to design a webpage for the Anonymous feedback basically similar to Sarahah, Yik Yak and all. So does anyone have already designed templates? If yes could you share with me, it would be a great help for me. Or your help and suggestions are most welcome. Please respond here. Not any particular languages. Any languages would be preferred. -
Reflection/Lookup on Django model doesn't find internationalized (shadow) fields
I use a CMS that does a mapping of my models through an API at runtime. It works fine, except for localized fields, because I use https://django-modeltranslation.readthedocs.io/en/latest/registration.html which add "shadow" fields that are obviously not mapped (they're not present in the model itself, but added through "register") Is there any way I can tell my model that it owns those fields? It can find the label field, but misses the label_fr and label_en which are dynamically added at runtime. Here is the translation.py: from modeltranslation.translator import translator, TranslationOptions from tfp_backoffice.apps.org.models import Org class OrgTranslationOptions(TranslationOptions): """ See https://django-modeltranslation.readthedocs.io/en/latest/registration.html """ fields = ('label',) required_languages = ('fr',) # ex: {'de': ('title', 'text'), 'default': ('title',)} translator.register(Org, OrgTranslationOptions) -
Django: populate modal with a form through Ajax
I´m trying to show a prepopulated form in a modal so users can click on an item, the modal opens showing a form with that item´s data that users can edit and save. I can send data from a view to a modal with json serializer but I can´t find how to send a form. When I test this, I get an error declaring that "Object of type FormularioTareas is not JSON serializable" The problem seems to be clear, I can´t send the form through a json response. How can I handle this? Thanks in advance! The modal call in the template <form name="form" action="#" id="form_tarea_{{tarea.id}}" method="POST"> {% csrf_token %} <input name="id" id="tarea_id_submit" type="text" value="{{tarea.id}}" hidden="true"/> <a href="" id="{{tarea.id}}" class="show_tarea" data-toggle="modal" >Este link</a> </form> The Ajax script Here I´m using now $('#caca').text(tarea_data.caca); only to test I can send some info to the modal correctly. It works. I guess I should update that "text" type to another one in order to work. <script> $(function(){ $('.show_tarea').on('click', function (e) { e.preventDefault(); let tarea_id = $(this).attr('id'); $.ajax({ url:'/catalog/tareas-detail/', type:'POST', data: $('#form_tarea_'+tarea_id).serialize(), success:function(response){ console.log(response); $('.show_tarea').trigger("reset"); openModal(response); }, error:function(){ console.log('something went wrong here'); }, }); }); }); function openModal(tarea_data){ $('#caca').text(tarea_data.caca); $('#modal_tareas').modal('show'); }; </script> The view def … -
ModuleNotFoundError: No module named 'celery'
I was trying to make e-commerce with a third party application in Django its called saleor whenever I try to migrate this error show up ModuleNotFoundError: No module named 'celery' I tried to manually install celery and still, I am sure that I activated my virtual environment -
Changing records in database using Django
In my project there are cards. Each of them has its price, and there is balance of user. I want to change account_balance in database (which is balance of current account) when clicked on cards. html part: {% for webmoney in webmoneys %} <div class="col-md-4 col-12"> <div class="card" style="width: 22rem; margin-bottom:30px;"> <div class="card-body"> <p class="card-text">{{ webmoney.price }} AZN</p> <button type="submit" class="btn btn-primary" onclick= "window.balance += {{ webmoney.price }}; alert('Cari balans: ' + window.balance)">Al</button> </div> </div> </div> {% endfor %} </div> <script> window.balance = {{ account_balance }}; </script> views.py def get_webmoney(request): account_balance = Account.objects.values_list('balance', flat=True) webmoney = WebMoney.objects.all() return render(request, 'webmoney.html', {'webmoneys': webmoney, 'account_balance': account_balance[0]}) models.py class Account(models.Model): account = models.OneToOneField(User, on_delete=models.CASCADE) balance = models.IntegerField(default=0) -
How do I save a form in many to many field in django
I have a profile which contains education and created a many to many relation i.e many profiles can have many educations. Problem is whenever I save education form in the db, it saves form but it does not create a m2m link between profile and education. Models class Profile(models.Model): phone = models.CharField(max_length=11, null=True, blank=True) education = models.ManyToManyField(Education, null=True, blank=True, related_name="education") full_name = models.CharField(max_length=30, null=True, blank=True) class Education(models.Model): degree = models.CharField(max_length=100, null=True, blank=True) school = models.CharField(max_length=100, null=True, blank=True) edu_start_date = models.DateField(null=True, blank=True) edu_end_date = models.DateField(null=True, blank=True) View class EducationView(CreateView): model = Education form_class = EducationForm pk_url_kwarg = 'pk' template_name = "profile_settings.html" class ProfileSettingsView(UpdateView): model = Profile form_class = ProfileSettingsForm pk_url_kwarg = 'pk' context_object_name = 'object' template_name = 'profile_settings.html' def get_success_url(self): return reverse_lazy('users:profile_settings', args = (self.object.id,)) def get_object(self): pk = self.kwargs.get('pk') return get_object_or_404(Profile, id=pk) def get_context_data(self, **kwargs): context = super(ProfileSettingsView, self).get_context_data(**kwargs) context['prof'] = self.get_object() return context Form class EducationForm(forms.ModelForm): class Meta: model = Education fields = ('degree','school','edu_start_date','edu_end_date') class ProfileSettingsForm(forms.ModelForm): class Meta: model = Profile fields = ['phone','full_name','education'] widgets = { 'full_name': forms.TextInput({'class': 'form-control'}), 'phone': forms.TextInput({'class': 'form-control'}), } urls urlpatterns = [ path('<int:pk>/education/update/', views.EducationUpdate.as_view(), name='education_update'), path('<int:pk>/profile/settings', views.ProfileSettingsView.as_view(), name='profile_settings'), ] -
Heroku Django Collectstatic error: "CIDFSubst/DroidSansFallback.ttf not found"
I am getting the following error when trying to collectstatic as a part of deploy on Heroku. The only package that seems to interact with ghostscript is PIL which may get installed via django-easy-thumbnails: -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 11, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 335, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 189, in handle collected = self.collect() File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 114, in collect handler(path, prefixed_path, storage) File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 353, in copy_file with source_storage.open(path) as source_file: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 33, in open return self._open(name, mode) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 218, in _open return File(open(self.path(name), mode)) FileNotFoundError: [Errno 2] No such file or directory: '/usr/share/ghostscript/9.26/Resource/CIDFSubst/DroidSansFallback.ttf' I can't find anything on this error, can someone render assistance with things to help troubleshooting? I have tired: - Explicitly installing pillow in my requirements. - Clearing heroku app cache - Ensuring the python runtime was the most recent I checked docs on heroku stack, and it shows that ghostscript is part of the environment packages: https://devcenter.heroku.com/articles/stack-packages -
Using django Channels in rest api
Im using restframework to handle api calls in my project. recently I added channels and channels_redis to Project. Here is My Consumer : class BikeConsumer(AsyncWebsocketConsumer): async def websocket_connect(self, event): await self.accept() async def websocket_receive(self, event): j_data = json.loads(event['text']) print(j_data) mode = j_data['mode'] if mode == 1: await self.channel_layer.group_add("events", self.channel_name) else: await self.channel_layer.group_send( 'events', { 'type': 'chat_message', 'message': {'sth':'sth'}, } ) async def chat_message(self, event): message = event['message'] await self.send(text_data=json.dumps(message)) async def websocket_disconnect(self, event): await self.send({'type': 'websocket.disconnect'}) And Here is my api method And I want to send messages to client by this method : @action(methods=['POST'], detail=False, permission_classes=[AllowAny]) def unlock_car(self, request): from channels.layers import get_channel_layer from asgiref.sync import async_to_sync channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send( 'events', { 'type': 'chat_message', 'message': 'sth' } )) return Response(ApiResponse().api_success('data sent')) But Nothing happened on API call. I thing the problem is type param of my message in api , so what should it be ? -
Django Rest Framework optional nested relationship
is it possible to use a nested relation serializer as an option? This is the serializer example from the docs: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = '__all__' class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True, read_only=True) class Meta: model = Album fields = '__all__' when i call the album list localhost:8000/album/1/, this is the response: { 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, ... ], } is there any option like this localhost:8000/album/1/?include=tracks, so the tracks data only appear when it stated on the include param. -
Cannot create superuser in Django
I wanted to use email instead of username to login. But while creating superuser I am getting the following error TypeError: create_superuser() missing 1 required positional argument: 'username' users/view.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from django.views.generic import TemplateView from .forms import CustomUserCreation class SignUp(generic.CreateView): form_class = CustomUserCreation success_url = reverse_lazy('home') template_name = 'signup.html' class HomePage(TemplateView): template_name = 'home.html' def dispatch(self, request, *args, **kwargs): print (self.request.user) return super(HomePage, self).dispatch(request, *args, **kwargs) users/models.py #users/models.py import sys sys.path.insert(0,'..') from django.db import models from django.contrib.auth.models import AbstractUser import questions_and_answers from django.utils.translation import gettext as _ fields_ = questions_and_answers.fields def apply_defaults(cls): for name, value in fields_.items(): setattr(cls, name, models.CharField(default=value[1])) return cls #@apply_defaults class CustomUser(AbstractUser): q1 = models.CharField(max_length=200, default='0') q2 = models.CharField(max_length=200, default='0') count = models.IntegerField(default=0) USERNAME_FIELD = 'email' email = models.EmailField(_('email address'), unique=True) # changes email to unique and blank to false REQUIRED_FIELDS = [] # removes email from REQUIRED_FIELDS users/forms.py class CustomUserCreation(UserCreationForm): class Meta(UserCreationForm.Meta): model = CustomUser fields = ('username', 'email') class CustomUserChange(UserChangeForm): class Meta: model = CustomUser fields = ('username', 'email',) I am pretty beginner in django, hence no idea what went wrong. Please help. Thanks in advance.