Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serialize a Hstore field in drf
I have an HStoreField in my model. Example: attributes = HStoreField(default=dict, blank=True) My view and serializer: class CarSerializer(serializers.ModelSerializer): class Meta: model = Car fields = "__all__" class CarViewSet(viewsets.ModelViewSet): queryset = Car.objects.all() serializer_class = CarSerializer model = Car Ok. When I try some tests, like this: @pytest.mark.django_db def test_car_view(client, create_car): response = create_car response_get = client.get(f'/myapi/v1/car/{response.data["id"]}/') assert response_get.status_code == 200 I receive this error: self = HStoreField(required=False), value = '"key"=>NULL' def to_representation(self, value): """ List of object instances -> List of dicts of primitive datatypes. """ return { six.text_type(key): self.child.to_representation(val) if val is not None else None > for key, val in value.items() } E AttributeError: 'str' object has no attribute 'items' Looking for information about this problem I found references to use DictField for working with HStoreField. But I did not find examples. Does someone have an idea or examples? -
Last two pages in the pagination do not work
I would like to create a link, which will allow you to go to the next page, then so built the link pass to context. My problem is that there are no last two pages. Error 404 appears, although parameter has_next is "True". url url(r'(?:/(?P<page>[-\w]+))?$', views.BlogListView.as_view(), name='list'), method in BlogListView: def get_next_page_url(self): article_list = models.Blog.objects.order_by('-pub_date') paginator = Paginator(article_list, self.paginate_by) kwargs = {'page': self.kwargs.get('page') or 1} p = paginator.page(kwargs['page']) if p.has_next(): return reverse('blog:list', kwargs={'page': p.next_page_number()}) else: return None Details on paging: paginate_by = 30 paginator count: 204 paginator num_pages: 7 paginator paginator.page_range: [1, 2, 3, 4, 5, 6, 7] <Page 1 of 7> -
how to implement xeditable table with legacy database in Django
I want to implement x-editable table with legacy database but i have no idea how to implement it, please help this is my model.py file model.py from django.db import models class Certificate(models.Model): application = models.CharField(db_column='Application', primary_key=True, max_length=255, blank=True, null=False) # Field name made lowercase. startdate = models.CharField(db_column='startDate', max_length=255, blank=True, null=True) # Field name made lowercase. expiredate = models.CharField(db_column='ExpireDate', max_length=255, blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'certificate' -
Django model form not being received in post request when fields are modified by AJAX
Im new to javascript and Django so sorry if my question might be simple. I am using a Django model form to render my fields. It renders fine in HTML. Then I decided to add a select2 component. What I wanted to achieve was to make the select2 component get its data from an API endpoint, and if an option is selected, I wanted to get the data of the selected option in the DB, then replace the value in the Django textboxes. I did this by getting the IDs of the Django rendered components, then using jquery to select them and alter their value to the result of the API call. so heres the model form: class ProfileModelForm(ModelForm): def __init__(self, *args, **kwargs): class Meta: model = Profile exclude = ['id'] and heres a sample template snippet: <div class="row mt-1"> <div class="col-4 offset-md-4"> <label for="existing">Search</label><br/> <select class="form-control" id="existing"> <option></option> </select> </div> </div> <hr/> <div class="row mt-1"> <div class="col-3"> <label for="input-first-name">First name</label> {% render_field ProfileModelForm.first_name class+="form-control form-control-sm" placeholder="First name" %} </div> <div class="col-3"> <label for="input-middle-name">Middle name</label> {% render_field ProfileModelForm.middle_name class+="form-control form-control-sm" placeholder="Middle name" %} </div> <div class="col-3"> <label for="input-last-name">Last name</label> {% render_field ProfileModelForm.last_name class+="form-control form-control-sm" placeholder="Last name" %} </div> <div class="col-3"> β¦ -
serializing data from multiple table in drf
I have two models user and organization. The user model is the default Django model. My organization model looks like below class Organization(models.Model): name = models.CharField(max_length=254, blank=False) url = models.URLField(blank=True, null=True) year = models.PositiveSmallIntegerField(blank=True, null=True) users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, through='Membership') class Meta: db_table = '"org_organization"' class Membership(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True, ) organization = models.ForeignKey(Organization, on_delete=models.CASCADE) position = models.CharField(max_length=254, blank=True, null=True) is_admin = models.BooleanField(default=False) class Meta: db_table = '"org_organization_user"' A user is tied to one (or more) organization through Membership. I can get the detail for a user through UserReadSerializer which looks like this class UserReadSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) organization = MembershipSerializer(source='membership_set', many=True) class Meta: model = UserModel fields = ('id', 'email', 'username', 'password', 'first_name', 'last_name', 'organization') Thus for a user id 1, I get the following response: { "email": "******@gmail.com", "first_name": "Hello", "last_name": "User", "username": "myuser", "organization": [ { "name": "Org1", "url": "https://org1.net/", "year": 1893, "position": "position1", "is_admin": true }, { "name": "Org2", "url": "https://org2.net/", "year": 1983, "position": "position2", "is_admin": false } ] } Now I want to modify the user organization detail, for example, the position through PUT method and for this I am passing the edit data in a similar format as: { "email": β¦ -
Django Projeto migrations
I started to have some problems regarding the migration of my project, since it did not migrate anything, and did not update the data I need to be updated. I start to following some suggestion's that i read and until now , nothing it is working. I already try to delete my sqllite3 database , and do all the migrations again and nothing happen. When i try to do manage.py showmigrations i realease that none of my app's have migrations , so that's why they dont do nothing. So right know what is my best solution to resolve this ? -
Django ajax not working on multiple href inside for loop of jinja2 template
I am working on ajax based message system using Django. I have Rooms and Messages in those rooms. The basic idea is on the left side there will be rooms by the user and on the right side there will be detail view of one particular room. Ajax is used to view each rooms message. <div class="inbox_chat"> {% for room in rooms %} <div class="chat_list"> <div class="chat_people"> <a href="#" id="view_message" data-catid="{{ room.id }}"> <div class="chat_img"> <img src="https://ptetutorials.com/images/user-profile.png"> </div> <div class="chat_ib"> <h5>{{room.course}} <span class="chat_date">{{room.timestamp}}</span></h5> <p>{{room.messages.last.message}}</p> <small>by <strong>{{room.messages.last.sender}}</strong></small> </div> </a> </div> </div> {% endfor %} </div> above is the jinja code for displaying the rooms. I am facing problem in href tag. I can click on first result of for loop, but nothing happens on the second result of for loop. My Javascript code: {% block script %} $(document).ready(function(){ $('#view_message').on('click', function(e){ var BASE_URL = window.location.origin + window.location.pathname; console.log(BASE_URL); var room_id = $(this).attr("data-catid"); console.log(room_id); $.ajax({ url: BASE_URL + "view_message/", method: 'GET', data: { room_id: room_id } }); }); }); {% endblock %} -
Django adding comment pagination in a detailview
Hi I'm just a student and still new in Django Framework. I want to add pagination in my comment section in my Book detailview. I tried to use the paginate_by but it doesn't work. I don't know if my syntax is wrong or something. here's my views.py def BookDetail(request, id): most_recent = Book.objects.order_by('-timestamp')[:3] book= get_object_or_404(Book, id=id) form = CommentForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.instance.post = book form.save() return redirect(reverse("book-detail", kwargs={ 'id': book.pk })) if request.user.is_anonymous: user_membership = None else: try: user_membership = Customer.objects.get(user=request.user) except Customer.DoesNotExist: user_membership = None context = { 'user_membership': user_membership, 'form': form, 'book': book, 'most_recent': most_recent, } return render(request, 'catalog/book_detail.html', context) my forms.py class CommentForm(forms.ModelForm): content = forms.CharField(widget=forms.Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Type your comment', 'id': 'usercomment', 'rows': '4' })) class Meta: model = Comment fields = ('content', ) and my models.py class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) timestamp = models.DateTimeField(auto_now_add=True) content = models.TextField(max_length=200, null=True) post = models.ForeignKey('Book', related_name='comments', on_delete=models.CASCADE, null=True) def __str__(self): return self.user.username -
Displaying Python Web Scraping Output (Pandas table) on web page made by Django in views
I am a beginner when it comes to Python and Django. I have created a web scraper using Jupyter Notebook using bs4, requests and pandas. I have my desired output and formatted the extracted data into a table using pandas successfully. What I hope to achieve is displaying said table with my extracted data onto a web page built by Django. After some hours of research and experimenting I have become somewhat comfortable using the django interface. My first attempt: I downloaded my jupyter notebook scraper as a .py file. Then I created an app called law and placed my_file.py within law. Snippet Moving forward, inside views.py I typed the following code: views.py please disregard the 'tls.html' reference as this was just part of my experimentation and only displayed the literal code from the notebook not the desired output in table form. My Url and template looks like this: Urls.py templates My question is: How would I connect the output of tls.py to the views.py within law so that when I run the server I can successfully load the table with all the extracted data? In addition, I would like to add a reload or submit button so that the β¦ -
How to get the publishing date of a article from Aldryn News & Blog?
Okay, so I have a website/blog made with djangocms and Aldryn News & Blog. I have to fetch the user email and the blog publishing date and sent an sent to the user. I can't figure out how to do that. Models.py user = models.ForeignKey(User, on_delete=models.CASCADE) Here the variable user use extends django's user model. https://docs.djangoproject.com/en/2.1/ref/contrib/auth/ Here my code i.e. automail.py from django.db import models from gsoc.models import UserProfile from django.contrib.auth.models import User from django.core.mail import send_mail #Need to add whether the article is 7 days old or not. def SentMail(): email_list_count=len(UserProfile.objects.all()) for i in range(1,email_list_count+1): user = User.objects.get(id=i) user_email = user.email send_mail( 'It\'s been 7 days', 'Post something already.', 'from@example.com', [user_email], fail_silently=False, ) Did I do it correctly? Now, the next step is to retrieve the article's publishing date. Since the code uses Aldryn News & Blog and there is no information in it's documentation, I can't figure out how to do that. Then the next step would be schedule it using cronjob. I will ask about it in a separate question, I guess. Anyway, please help me. Thank you and if any more information is required please comment. -
Django Bootstrap Datetimepicker show at wrong position
I've tried to using Django widget to add a Datetimepicker to a form in the template. In the forms.py Event_time = forms.DateTimeField(widget = forms.TextInput(attrs={ 'id':'datetimepicker1'})) In the models.py class Event(models.Model): Description = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) Event_name = models.CharField(max_length=48) Event_time = models.DateTimeField() Event_venue = models.CharField(max_length=100) Max_players = models.IntegerField() Players_registratered = models.IntegerField() owner = models.ForeignKey(User, on_delete=models.CASCADE) and in template I write html as <div class="container-fluid container-transparent container-small"> <form action="{% url 'team_sports_app:new_event' %}" method='post'> {% csrf_token %} {% bootstrap_form form %} <div class="text-center"> {% buttons%} <button name="submit" class="btn btn-primary">Add event</button> {%endbuttons%} </div> </form> </div> <script type="text/javascript"> $('#datetimepicker1').datetimepicker({ format: 'YYYY-MM-DD HH:mm', }); </script> And the position of the picker always goes the bottom of the page: enter image description here Insted of above the TextInput or Under. Hope someone could give a help! Thank you very much! -
HttpError 403: Request might not be properly authorized
I am using django framework for my project which can upload videos to youtube using youtube v3 API. I have created a branded channel to add these videos. By using the credentials of an installed app i can easily upload video to the channel and but when i tried to list the details of the videos using video_ids, with the same credentials i am not able authorise. So i created a service account and used those service account credentials to list the details of the videos and it was working fine. All these process are done using oauth2 credentials and without any manual consent from user. But i need to delete some selected videos through my API from backend without the manual consent from google user. So i tried with the credentials of the previous installed application and the credentials of the service account i created and unfortunately both are not allowing me to delete the video from my account. The error i am getting is HTTP 403: Request might not be properly authorised. I am using the correct scopes suggested by youtube to access the APIs. So can anyone suggest any error possibilities which is occurring while authenticating, or β¦ -
How to render html from databse (Django 2)
My code like below Output Like below but I want to see html tags working like html and all css are working. How can I do this? -
Django add custom validation to choice field in form
I have a model form say, models.py Y_N = (('Y', 'Yes'), ('N', 'No')) M_A = (('M', 'Man'), ('A', 'Auto')) class Test(models.Model): feild1 = models.CharField(max_length=1, choices=Y_N, default='Y', db_index=True) feild2 = models.CharField(max_length = 1, choice=M_A, default = 'M') forms.py class TestForm(ModelForm): class Meta: model = Test feilds = ['feild1', 'feild2'] Now in a template I am adding another select value 'Don't update' whose value is 0. So how can I handle this 'Select a valid choice. 0 is not one of the available choices.'. I need that form submit if the feild value is either 0 or 'Y' or 'N'. -
How to fix response error while using ajax with django
I am using django 2.1 and have created a view that requires lot of time to be finished. The main objective of this view is that I have made a Scrapper using BeautifulSoup so as to collect images by getting each of the page url from a list of page urls of a particular site. Each page contains about 20 to 30 pages. I am using urllib, and NamedTemporaryFile and to create a file for image and save it to model as an object. For every 1 image, 1 object is created and saved. Anyway all this takes a lot of time. Since there are like about 30 pages to collect images from. Now here is the problem, I have created a link on admin using mark_safe that when clicked goes to this view to scrap images, and I know there is no problem in this process since it keeps loading on the browser tab and in another tab in django admin when I refresh on the model page I can see that the objects that store the images are being created. But after some time (maybe like 2 or 3 mins, I didn't count it), without any refresh or β¦ -
How to load the static files of django+nginx+gunicorn application using docker?
I can't get my static files to come up. I've tried various settings and directory configurations and so on, but they just turn up as 404s. Directory structure of application . βββ config β βββ nginx β βββ conf.d β βββ local.conf βββ docker-compose.yml βββ Dockerfile βββ aggre β βββ aggre β βββ manage.py | βββ static βββ requirements.txt I have included static_url and root in settings.py and it looks like STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR),'static'] STATIC_ROOT = os.path.join(os.path.dirname(os.path.dirname(BASE_DIR)), 'static') Dockerfile FROM python:3.6 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /opt/services/django/src WORKDIR /opt/services/django/src COPY requirements.txt /tmp/ RUN pip install --requirement /tmp/requirements.txt COPY . /tmp/ COPY . /opt/services/django/src RUN python aggre/manage.py collectstatic --no-input # <-- here CMD exec /bin/bash -c "trap : TERM INT; sleep infinity & wait" EXPOSE 8000 ADD . /opt/services/django/src CMD ["gunicorn", "--chdir", "aggre", "--bind", ":8000", "aggre.wsgi:application"] docker-compose.yml version: '2' services: djangoapp: build: . volumes: - .:/opt/services/django/src - static_volume:/opt/services/django/static/ networks: - nginx_network nginx: image: nginx:1.13 ports: - "80:80" volumes: - ./config/nginx/conf.d:/etc/nginx/conf.d - static_volume:/opt/services/django/static/ depends_on: - djangoapp networks: - nginx_network networks: nginx_network: driver: bridge volumes: static_volume: local.conf server { listen 80; server_name ***.***.io; location / { proxy_pass http://djangoapp:8000; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } location /static β¦ -
Insert comand in shell with python subprocess
I am writing a django project where the user starts the python script from the web browser. I am using websocket and django to create real-time communication. I am able to run a comand and display the results from the console in the browser, but I have a problem when script that user run expect user's input to resume or stop the work. My goal is to create confirmation window in the browser, wher user will be asked If he wants to continue or stop script. If he press "ok" the websocket message is send to the server and insert command in script to continue work. Otherwise insert command which stops script. consumers.py: class ConsoleDataConsumer(SyncConsumer): def websocket_connect(self, event): # when websocket get request to connect print('connected', event) self.send({ 'type': 'websocket.accept' }) def websocket_receive(self, event): # when a message is recived from the websocket print('recive', event) python_command = "python test.py" self.get_output(python_command) self.send({ 'type': 'websocket.close' }) def websocket_disconnect(self, event): # when the socket is disconnects print('disconnected', event) def get_output(self, command): p = subprocess.Popen(command, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) for line in iter(p.communicate()): decoded_line = line.decode('utf-8') # TODO dodaj string, ki bo ustavil izvajanje skripte if decoded_line == '': if decoded_line == '': break if β¦ -
Django Email stored in database
I have a problem in getting the data for employees sending reports through their outlook email. I want to measure their reports volume and timeliness. Is it possible to have a specific email set up in my django project and this email is cc'd on every email report they send hence I can the data to be stored in my database? -
django Admin list object print
My user model is as follows. **model.py** class User(models.Model): #user_idx = models.AutoField('user-num', primary_key=True) user_idx = models.OneToOneField(Counsel, primary_key=True, db_column="user_idx", related_name="useridx" , on_delete="models.DO_NOTHING") district_id = models.IntegerField(blank=True, null=True) user_email = models.CharField(unique=True, max_length=200) user_password = models.CharField(max_length=200) user_name = models.CharField(max_length=100) class Meta: managed = False db_table = 'user' verbose_name_plural = "USER" The django Admin then created the source as follows: class UserAdmin(admin.ModelAdmin): list_display = ('user_idx', 'show_firm_url', 'user_name',) def show_firm_url(self, obj): return format_html("<a href='/admin/user/view/{0}'>{1}</a>", obj.user_idx, obj.user_email) show_firm_url.short_description = 'E-mail' The results are like images. Counsel object (1494) Please tell me how to get this number out. Counsel object (1494) -----> 1494 -
How to use joins in rest framework and i want to do in serializers (Django)?
class MatchesSerializer(serializers.ModelSerializer): class Meta: model = Matches fields = ('id', 'series', 'teamA', 'teamB', 'season', 'umpire', 'toss_win_team', 'win_team', 'man_of_the_match', 'win_type', 'win_margin', 'toss_description', 'match_status', 'dl_method', 'tie_match', 'draw_match', 'match_date', ) read_only_fields = ('teamA',) depth = 1 -
How to remove the instance of ManyToMany field?
I have two models: class Organisation(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,related_name='organisation_user',on_delete=models.CASCADE) name = models.CharField(max_length=100,blank=True) location = models.CharField(max_length=100,blank=True) qualification_status = ( ('Pending for verification','Pending for verification'), ('Verified','Verified'), ) qualification = models.CharField(max_length=100,choices=qualification_status,default='Pending for verification',blank=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL,related_name='organisation_members',blank=True) class Organisation_member(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,null=True,blank=True) organisation = models.ForeignKey(Organisation,on_delete=models.CASCADE,related_name='organisation_staff') member_name = models.ForeignKey(settings.AUTH_USER_MODEL,related_name='organisation_staff_member',on_delete=models.CASCADE,null=True,blank=True) is_admin = models.BooleanField(default=False) I have this signal for creation of Organisation_member model: @receiver(post_save, sender=Organisation) def organisation_admin(sender, instance, created, **kwargs): for member in instance.members.all(): if Organisation_member.objects.filter(user=instance.user,organisation=Organisation.objects.filter(user=instance.user,name=instance.name).first(),member_name=member).exists(): pass else: Organisation_member.objects.update_or_create(User=instance.User,organisation=Organisation.objects.filter(user=instance.user,name=instance.name).first(),member_name=member,is_admin=False) The signal indicates that when I add a member in my manytomany field it will automatically create a Organisation_member object of the selected member. The signal works perfectly fine. My problem is the reverse i.e. when I try to delete an object of Organisation_member it should also remove the member from the manytomany relationship of the parent model. I have tried this: @login_required() def delete_members(request, pk): user_organisation = get_object_or_404(Organisation, user=request.user) member_to_delete = Organisation_member.objects.filter(pk=pk) if member_to_delete.exists(): member_to_delete[0].delete() for member in user_organisation.members.all(): user_organisation.members.remove(member=member_to_delete[0]) return redirect(reverse('userprofile:organisation_member_list')) But it doesnot removes the member from the parent model.. Anyone who knows the solution please help. Thank you -
Cuda Runtime Error cudaErrorNoDevice: no CUDA-capable device is detected
I am using Chainer, Cupy for CUDA 8.0 . I am trying to train machine learning model using python3.5 script but gives following error: Exception in main training loop: cudaErrorNoDevice: no CUDA-capable device is detected Traceback (most recent call last): File "/root/.see-master/lib/python3.5/site-packages/chainer/training/trainer.py", line 302, in run entry.extension(self) File "/usr/lib/python3.5/contextlib.py", line 77, in exit self.gen.throw(type, value, traceback) File "/root/.see-master/lib/python3.5/site-packages/chainer/reporter.py", line 98, in scope yield File "/root/.see-master/lib/python3.5/site-packages/chainer/training/trainer.py", line 299, in run update() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updater.py", line 223, in update self.update_core() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updaters/multiprocess_parallel_updater.py", line 195, in update_core self.setup_workers() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updaters/multiprocess_parallel_updater.py", line 186, in setup_workers with cuda.Device(self._devices[0]): File "cupy/cuda/device.pyx", line 106, in cupy.cuda.device.Device.enter File "cupy/cuda/runtime.pyx", line 164, in cupy.cuda.runtime.getDevice File "cupy/cuda/runtime.pyx", line 136, in cupy.cuda.runtime.check_status Will finalize trainer extensions and updater before reraising the exception. Traceback (most recent call last): File "chainer/train_svhn.py", line 258, in trainer.run() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/trainer.py", line 313, in run six.reraise(*sys.exc_info()) File "/usr/lib/python3.5/site-packages/six.py", line 693, in reraise raise value File "/root/.see-master/lib/python3.5/site-packages/chainer/training/trainer.py", line 302, in run entry.extension(self) File "/usr/lib/python3.5/contextlib.py", line 77, in exit self.gen.throw(type, value, traceback) File "/root/.see-master/lib/python3.5/site-packages/chainer/reporter.py", line 98, in scope yield File "/root/.see-master/lib/python3.5/site-packages/chainer/training/trainer.py", line 299, in run update() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updater.py", line 223, in update self.update_core() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updaters/multiprocess_parallel_updater.py", line 195, in update_core self.setup_workers() File "/root/.see-master/lib/python3.5/site-packages/chainer/training/updaters/multiprocess_parallel_updater.py", line 186, in setup_workers with cuda.Device(self._devices[0]): File "cupy/cuda/device.pyx", β¦ -
Using Architect with Django Abstract Model class
As specified by PyPI Architect, for partitioning we can use the decorator on any model class in the following way: import architect @architect.install('partition', **options) class Model(object): pass My model is abstract and I want all the child models to have the same partitioning. import architect @architect.install('partition', **options) class Model(object): class Meta: abstract = True Is the above structure correct way to use? Will all the child models implement the same partitioning automatically? If yes, is it safe to specify decorator at the abstract level (good practice)? Django: 2.x || Python: 3.x || MySQL: 5.x -
How to setup logging for a django based application in one common file
I have a django application, that is running on the production via apache2, so all the console outputs go to the apche2 logfiles. I did configured a logger in settings.py like this LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': os.path.join(BASE_DIR, 'VERTEX_APP.log'), }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'INFO', 'propagate': True, }, }, } However, this does not logs the console outputs, exception traces? Any idea how I can do this? -
Django REST Framework: force lowercase username
I am just starting to play around with Django REST Framework for a side project, and I am trying to force all usernames to be lowercase (since by default they are case sensitive and I don't want people to have usernames like kevin and Kevin for example). This is the code I am using to create a user: # The serializer class UserSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True) token = serializers.SerializerMethodField() def create(self, validated_data): user = get_user_model().objects.create(**validated_data) user.set_password(validated_data['password']) user.save() return user def get_token(self, user): token = Token.objects.create(user=user) return token.key class Meta: model = get_user_model() fields = ('username', 'first_name', 'last_name', 'email', 'password', 'token') # The View class RegisterUserView(CreateAPIView): model = User serializer_class = UserSerializer permission_classes = (permissions.AllowAny, ) # And the URL pattern urlpatterns = [ path(r'user/register/', RegisterUserView.as_view()), ] So the user can create a new account by posting at least a username and password to user/register, and in the response he'll get the full user object (with first name, last name, email and the auth token). This works. However, I am struggling with forcing lowercase usernames. For example when I add something like validated_data['username'] = validated_data['username'].lower() to the create function in the serializer, the server simply generates an error 500 "UNIQUE constraint β¦