Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When I register a user, there is no password field on the page
When I register a user, there is no password field on the page: You see, there only Username and Email here, no password. My Serializers.py code: class UserCreateSerializer(ModelSerializer): """ 用户注册 """ class Meta: model = User fields = [ 'username', 'email', 'password', ] extra_kwargs = { "password":{"read_only":True} } def create(self, validated_data): username = validated_data["username"] email = validated_data["email"] password = validated_data["password"] user_obj = User( username = username, email = email, ) user_obj.set_password(password) user_obj.save() return validated_data My views.py code: # 普通用户注册 class UserCreateAPIView(CreateAPIView): serializer_class = UserCreateSerializer queryset = User.objects.all() -
`::=` and `|` in Documentation
There are ::= everywhere in Python Documentation: For instance: atom ::= identifier | literal | enclosure I searched and learned it's BNF syntax. It's really not easy to get a brief idea from dozens of files. In python : can be considered as a variant of 'assignment' symbol =, In Django's template syntax ,| is function symbol. What are ::=and | in BFN? -
I have set the Project Interpreter to `python 3.5.2`, but seems the my project still use `python 2.7`
I have set the Project Interpreter to python 3.5.2, pay attention there are two packages only python 3.5.2 have: but seems the my project still use python 2.7, when I runserver: the traceback: File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/apps/config.py", line 94, in create module = import_module(entry) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named rest_auth -
Django REST Framework updated nested object not in Model
I only want to update all order in my_stage by using PUT, something like: "Payload": { "stages": [ { "stage_id": 1, "position": 2 }, { "stage_id": 2, "position": 3 }, { "stage_id": 3, "position": 4 } ] } and "Response": { "stages": [ { "stage_id": 1, "position": 2 }, { "stage_id": 2, "position": 3 }, { "stage_id": 3, "position": 4 } ] } But I don't have "stages" in my model so I cannot use ModelSerializer. But I have to implement create() first. So what should I do to implement update? Thank you. My stage model is: class Stage(models.Model): class Meta: db_table = 'stage' position = models.IntegerField() Here are my serialzier.py class StagePositionSerializer(ModelSerializer): """Serialize order""" # company_id = IntegerField(read_only=True) stage_id = IntegerField(source='id', read_only=True) position = IntegerField(min_value=0) class Meta: model = Stage fields = [ 'stage_id', 'position' ] class PositionSerializer(Serializer): stages = StagePositionSerializer(many=True) and my view.py class StagePositionListView(APIView): serializer_class = PositionSerializer -
Cant migrate changed models.py initial - django
I created a new django project. I have a models.py file. I added a handful tables to the file. Now I am trying to migrate it so that I can start updating the project. I am trying to run the following lines but it is saying that there are no changes detected even though the file has changed. Comars-mbp:Yap omarjandali$ python3 manage.py makemigrations No changes detected omars-mbp:Yap omarjandali$ python3 manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: No migrations to apply. omars-mbp:Yap omarjandali$ omars-mbp:Yap omarjandali$ python3 manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 08, 2017 - 02:52:28 Django version 1.11.5, using settings 'Yap.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. this is the table added to the models.py from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from django_localflavor_us.models import USStateField #-------------------------------- # the following are tables realted to the app and general information #-------------------------------- # Profile saves every users profile information class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) # server first_name = models.CharField(max_length=25, default='first') last_name = models.CharField(max_length=25, default='last') bio = models.CharField(max_length=220, default='bio') dob = models.DateField(default='1950-01-01') street = models.CharField(max_length=200, default='street address') city = … -
How to update profile pic in DRF
I have created an api where one can upload pic for profile along with rest of the details. My problem is that if one wants to change the pic, how can it be done. At present, I am able to save pic for the first time. models.py class Profile(models.Model): User = get_user_model() branch = models.CharField(max_length=20, null=True) year = models.IntegerField(null=True) image = models.ImageField(upload_to="accounts/images/", null=True, blank=True) user = models.OneToOneField( User, on_delete=models.CASCADE, primary_key=False, null=True ) views.py class ProfileView(APIView): permission_classes = (IsAuthenticated,) serializer_class = ProfileSerializer queryset = Profile.objects.all() def post(self, request, format=None): current_user = request.user param = request.data profile = Profile.objects.filter(user=current_user.pk) if profile: serializer = ProfileSerializer(profile, many=True) return Response(serializer.data) else: serializer = ProfileSerializer(data=param) if serializer.is_valid(raise_exception=True): serializer.save(user=current_user) new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) -
Ajax issue of Django user login using bootstrap 3.x modal
My purpose is once modal form submitted, ajax pass the username and password to a view and get back the json info to update the modal form, I trace the djanog code ,and 100% sure the JsonResponse(rsdic) has been executed in server side, as well as client fully receive the son info with ajax success function. The problem is how to update the #error_message1 field which embeded in model. I tried .html() or .append(), all failed. I leave the core coding for your reference, many thanks again for your help again. ajax component: $.ajax( { type: "POST", url: url, data: { 'username': username, 'password': password }, dataType: 'json', success: function(data){ $('#login-form')[0].reset(); if (data.ret != '1107'){ var htmlcode ="<p> data.info </p>"; $('#modal').find('.error_message1').append(htmlcode); } }, error: function (data) { console.log('An error occurred.'); console.log(data); }, }); html component: <div class="modal fade" id="modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div id="form-modal-body" class="modal-body"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times</button> <h4>EXP LOGIN</h4> <form role="form" action="{% url 'auth_login' %}" method="post" id="login-form"> {% csrf_token %} <ul> <li> <div class="g-icon"><i class="iconfont icon-yonghu"></i></div> <input type="text" name="username" id="username" value="" placeholder="User name" /> </li> <li> <div class="g-icon"><i class="iconfont icon-mima"></i></div> <input type="password" name="password" id="password" value="" placeholder="Password" onblur="check1()" /> <div class="g-cue" id="error_message1">Your email or password was … -
Django - If one model field exists, another field must be empty/inaccessible
I have a model called Team. Team has one User as team_leader and can have multiple team_member's. Under User, I added the following fields: class User(AbstractUser): team_leader = models.OneToOneField(Team, null=True, blank=True) team_member = models.ForeignKey(Team, null=True, blank=True) Obviously a User shouldn't be a team_leader and team_member at the same time. I have set both fields as null/blank so I can always just leave one of them blank. However for extra precaution I'd like to completely disable one of these fields when the other field is activated. I'm aware of the disabled function, but it is only for disabling the field on a form. I want to eliminate any chance of tampering by completely disabling one model field. Is there a way to do this? -
Receiving data from the server without updating the page
Good day! I'll Forgive Forgiveness, I'm zero in programming. But I want to learn. I need to transfer data using the POST method, without updating the page. Through django, how should the javascript and views.py look like! <form class="form-horizontal" role="form" method="post" id="lol"> <div class="form-group"> <label for="" class="col-sm-2 control-label">ФИО</label> <div class="col-sm-4"> <input name="firstname" class="form-control" placeholder="ФИО"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Шифр Группы</label> <div class="col-sm-4"> <input name="Code" class="form-control" placeholder="Шифр Группы"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Пол</label> <div class="col-sm-4"> <input name="Pol" class="form-control" placeholder="М или Ж"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Семейное положение</label> <div class="col-sm-4"> <input name="Floor" class="form-control" placeholder="0 или 1"> </div> </div> <div class="form-group"> <label for="" class="col-sm-2 control-label">Номер комнаты</label> <div class="col-sm-4"> <input name="Room" class="form-control" placeholder="Номер комнаты"> </div> </div> <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type="submit" class="btn btn-default">Войти</button> </div> </div> </form> <div class="examples"> <script language="javascript" type="text/javascript"> </script> <div class="results">Ждем ответа</div> @csrf_exempt def polls(request, form=None): if request.method == 'POST' and form.is_valid(): pass else: return render(request, 'base.html') -
Most practical and efficient way to filter objects in Django?
What is the best approach to filter objects in Django? In my case, I need to filter objects by different params sent by GET request. So, in my get_queryset of CBV I send the values to the custom function of my custom models.QuerySet and retrieve the result: return MyModel.objects.all().custom_filter(param1, param2, param3) But in my custom function, the most doubtful things happening. At first, I check passed values for existence and clean them. Then, separately for every param I filter queryset using Q Objects. In custom models.QuerySet it looks like: def custom_filter(self, param1, param2, param3): # cleaning and checking staff # ... then result = self.filter(Q() | Q()) # related to param1 if (param2 != None): result = result.filter(Q()) # related to param2 if (param3 != None): result = result.filter(Q() & Q()) # related to param3 # and etc. return result.distinct() This works fine for that time. But I think it is definitely inefficient. If anyone has a better solution, please provide it. -
Run django shell in ipython
I attempt to run django shell in ipython. ipython manage.py shell # It report error: Type 'manage.py help <subcommand>' for help on a specific subcommand. I searched and found a popular solution which guides you to install django.extensions and to enable it in settings. I am creating a minimal project while the solution is heavy. Meanwhile,I have to install and enable it on every project. Is there a lightweight way? -
What is the appropriate way to add HTML to the top of a Django ModelForm/formwizard?
I'm putting together a long, multi-page application using ModelForm and formwizard. For some of the pages, I would like to add a short introductory paragraph to the form. What is the appropriate way to do this? The best method I can figure out is to add custom templates to each page and enter the HTML that way. It seems like there should be another method, though! If I just need to add a tag, it seems like bad practice to create an entire template. -
Add CSS Class to Django-Autocomplete-Light ModelSelect2
I have a model form that is made up largely of django-autocomplete-light ModelSelect2 boxes: class AlertForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'entity': ModelSelect2(url='eda', attrs={'data-minimum-input-length': 2}), 'logic': ModelSelect2(url='logic', attrs{'class':'hello'} The CSS class hello which I am attempting to add to the logic select box does not appear when the page is rendered. How do I add a CSS class to a dal select box? -
Pip having trying to uninstall appdirs while trying to install requirements.txt when deploying to pythonanywhere
I am trying to deploy my project on pythonanywhere. I have created my virtualenv and activated it but when I try to "pip install -r requirements.txt" it says "Found existing installation: appdirs1.4.2 Uninstalling appdirs-1.4.2:" and then gets a permission denied error. What's going on and how do I fix it? Full error in bpaste: https://bpaste.net/show/a7394c84c672 -
Django/WeasyPrint: Bangla Font Rendering Issue
My Python Version 3.6+, Django version 1.11.6 and OS: Windows-10 64bit. I am creating the PDF file with weasyprint within Django project. But the problem is Bengali font is not rendering. Please check this screenshot. Now this is my views.py file def get_pdf_file(request, customer_id, sys_type): sys_type = customer_id area = "pdf" site_credit = site_credit1 time_now = timezone.now() customers = get_object_or_404(CustomerInfo, pk=customer_id) due_taka_track = customers.duetaka_set.all() if due_taka_track == None: due_taka_track = 0 unpaid_taka = int(customers.customer_price - customers.customer_due_taka_info) due_taka_track = customers.duetaka_set.all() sum_cost_taka = due_taka_track.aggregate( sp=Sum('customer_due')).get('sp', 0) if sum_cost_taka == None: sum_cost_taka = 0 total_paid_taka = sum_cost_taka + customers.customer_due_taka_info payment_status = 'complete' payment_message = ' ' remain_taka='Full Paid ' remain_msg='' if customers.customer_due_taka_info < customers.customer_price: payment_status = 'incomplete' payment_message = 'সম্পূর্ন টাকা পরিষোধ করা হয়নি' remain_msg='টাকা বাকী আছে' baki_ase="পাওনা আছে " remain_taka = customers.customer_price - customers.customer_due_taka_info context = {'customers': customers, 'sys_type': sys_type, 'area': area, 'site_credit': site_credit, 'site_name': 'Moon Telecom', 'sys_type': sys_type, 'due_taka_track': due_taka_track, 'total_paid_taka': total_paid_taka, 'payment_message': payment_message, 'time_now': time_now, 'unpaid_taka': unpaid_taka, 'payment_message': payment_message, 'remain_taka': remain_taka, 'sum_cost_taka': sum_cost_taka, 'remain_msg': remain_msg} html_string = render_to_string('shop/pdf_invoice.html', context).encode(encoding="UTF-8") response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'inline; filename=invoice' + \ str(customers.id)+customers.customer_uid + customers.customer_name + '.pdf' HTML(string=html_string).write_pdf(response) return response and this is my html file <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-16"> <meta … -
Django - best way to replace custom image tag in textfield by imagefield
What is best way to replace custom "tag" (for example [IMG]image_name[/IMG]) with image url what exist in model as imagefield? For example: class ImageResource(models.Model): name = models.CharField(verbose_name='Name') img = models.ImageField(verbose_name='Image') class Post(models.Model): title = models.CharField(verbose_name='Title') text = models.TextField(verbose_name='Text') images = models.ManyToManyField(ImageResource,verbose_name="Images") DetailView to display template like this: {{ object.text }} I will replace all [IMG]name[/IMG] in object.text to html img code who has src = images.url when images.name == name only. I don't want use wysiwyg editor. I don't know what is best place to do this - on model, view (what function?) or in specific filter? -
Django Populate Hidden Input with request.user.get_username()
I have a model: class Alert(models.Model): entity = models.ForeignKey(Entity, on_delete=models.CASCADE, db_column='entity') group = user = models.CharField(max_length=12) #...More Fields def __str__(self): return '%s' % self.entity I have a corresponding model form and model formset rendered by crispy-forms: class AlertForm(ModelForm): class Meta: model = Alert fields = '__all__' widgets = { 'dispositionedBy': HiddenInput(), 'entity': ModelSelect2(url='eda', attrs={'data-minimum-input-length': 2}), AlertFormSet = modelformset_factory(Alert, extra=1, exclude=(), form=AlertForm) I have a view built on top of the formset: def alerts(request): helper = AlertFormsetHelper() if request.method == 'POST': formset = AlertFormSet(request.POST) for form in formset: if form.is_valid(): if form.has_changed(): if form.is_valid(): form.save() entity = form.cleaned_data['entity'] messages.success(request, 'SUCCESS: Alert for %s was dispositioned' % entity) return redirect('alerts') else: query = Alert.objects.filter(disposition='') paginator = Paginator(query, 12) page = request.GET.get('page') try: objects = paginator.page(page) except PageNotAnInteger: objects = paginator.page(1) except EmptyPage: objects = paginator.page(paginator.num_pages) page_query = query.filter(id__in=[object.id for object in objects]) formset = AlertFormSet(queryset=page_query.order_by('entity')) context = {'objects':objects, 'formset':formset, 'helper':helper} return render(request, 'alerts/alerts.html', context) I would like user to be populated by the current REMOTE_USER username that can be accessed with request.user.get_username(). user.get_username is performing correctly in my template and showing the current user. However, when I attempt to automatically populate the field and POST the data to the DB, the record … -
django inheritence admin site -- why do fields follow down the tree automatically whereas fields that are defined classes do not?
django inheritence admin site -- why do fields follow down the tree automatically whereas fields that are defined classes do not? I've been searching for the answer for several hours and this is my first question so please be gentle. here is my models.py from django.db import models import datetime from django.db.models import EmailField class XObj(models.Model): auto_increment_id = models.AutoField(primary_key=True) creation_date = models.DateTimeField(default=datetime.datetime.now) def __str__(self): return str(self.creation_date.datetime) def date_created(self): return self.creation_date def date_last_change(self): return str(self.auto_increment_id) class Address(XObj): # todo: differentiate between US and non US addresses and validate house = models.CharField(max_length=20, default="") street = models.CharField(max_length=200, default="") street2 = models.CharField(max_length=200, default="") city = models.CharField(max_length=200, default="") state = models.CharField(max_length=200, default="") zipcode = models.CharField(max_length=200, default="") country = models.CharField(max_length=200, default="") def __str__(self): return str(self.house, self.street, self.street2, self.city, self.state, self.zipcode, self.country) class Entity(XObj): full_name = models.CharField(max_length=200, default="") # todo: validate email email = EmailField() # def _init_(self): # self.full_name = models.CharField(max_length=200, default="") # def __str__(self): return "Entity" class Person(Entity): first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=200, default="") address = Address # def _init_(self): # self.first_name = models.CharField(max_length=200, default="") def __str__(self): return self.full_name class Vendor(XObj): name = models.CharField(max_length=200, default="") address = Address website = models.URLField point_of_contact = Person def __str__(self): return self.name class Hotel(Vendor): def __str__(self): return … -
Don't know how to convert the Django field skills (<class 'taggit.managers.TaggableManager'>)? graphql
I am trying to change my rest end points to graphql and I had a library called TaggableManager as one of the model fields. Anyone know how this can work with graphql? Thanks in advance -
Django - inclusion tag
In my html, there is a div containing all the comments. I need to restrict the amount of comments to be shown. So, I created an inclusion tag: <div class="past_comments"> {% limit_amount_in_a_page page_nr=page_nr topic_id=topic.id amount=4 %} </div> @register.inclusion_tag('post/comment_block.html') def limit_amount_in_a_page(page_nr, topic_id=1, amount=5): topic = get_object_or_404(Topic, id=topic_id) comments = Comment.objects.filter(topic=topic) selected_comments = [] starting_index = page_nr*amount for index in range(starting_index, starting_index + amount): if index >= len(comments): break; selected_comments.append(comments[index]) return { 'topic': topic, 'page_nr': int(page_nr), 'selected_comments': selected_comments, 'amount_comments': comments.all().count(), 'limit_amount_comment': amount, } so, this tag shows the code from comment_block.html {% load static %} {% load post_tags %} {% load post_filters %} {% for comment in selected_comments %} <div class="comment_body"> <div class="user_info_block"> <div class="content"> <div class="photo_profile"></div> <div class="user_info"></div> </div> </div> <div class="content_block"> <p>{{comment.content}}</p> </div> </div> {% endfor %} topic id is {{topic.id}} page nr is {{page_nr}}<br> comment amount is {{amount_comments}}<br> limit amount is {{limit_amount_comment}}<br> {% if page_nr != 0 %} <a href="{% url 'post:detail' topic.id page_nr|increase:-1 %}">Previous Page</a> {% endif %} {%page_not_over_amount page_nr amount_comments limit_amount_comment%} {% if comment_not_over_amount %} <a href="{% url 'post:detail' topic.id page_nr|increase:1 %}">Next Page</a> {% endif %} As you can see, I created another tag page_not_over_amount after all comments are shown to hide the link directing to the … -
Wrong table used when running tests Django Pycharm
I used inspectdb to import the Models schema from MySQL database connected with MySQL Connector/Python. When I run the tests, the system shows: django.db.utils.ProgrammingError: Table 'test_mydb.cards' doesn't exist But the table name is just mydb.cards, not test_mydb.cards Why is this prefix being added? My app's name is just container. -
Django Javascript
I'm trying to add some javascript to my Django template from this example, that dynamically changes the backround of rows in a table if a checkbox is selected. http://jsfiddle.net/hkL43/7/ $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked);}) .find(':checkbox').trigger('change'); I have other javascript scripts running in my block add_to_header - and all these scripts work like I expect them to, for the most they are encapulated in script tags with a function name eg. <script type="text/javascript"> function checkAll(bx) { var cbs = document.getElementsByTagName('input'); for(var i=0; i < cbs.length; i++) { if(cbs[i].type == 'checkbox') { cbs[i].checked = bx.checked; } } } </script> And activated by 'onClick' events and other events. I have jquery in my base template - and as far as I can tell there should be no problem running this code. I tried embedding the code in script tags to get it to execute when the page loads - but nothing seems to work eg. <script type="text/javascript"> $( function() { $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked); }) .find(':checkbox').trigger('change'); </script> or <script type="text/javascript">$(document).ready(function() { $('table').on('change', ':checkbox', function() { $(this).closest('tr').toggleClass('selected', this.checked); }) .find(':checkbox').trigger('change'); } </script> What am I doing wrong? -
Output a paragraph with line breaks in Django inside a list item
I have a bulletin board on a Django website. A single bulletin body is defined as bulletin_body = models.TextField('Body', max_length=5000) in class Bulletin inside models.py. When a bulletin body is placed in a template as a separate paragraph, it displays all the line breaks that the body contains as expected. That is, <h2>{{bulletin.bulletin_body|linebreaksbr}}</h2> works fine. But when a bulletin body is a list element, (e.g. in a page that contains bulletin feed) no line breaks are displayed. Example: <ul> {% for bulletin in latest_bulletin_list %} <li>{{bulletin.bulletin_body|linebreaksbr}}</li> {% endfor %} </ul> I've only found answers suggesting to check if the model is TextField and to use linebreaks or linebreaksbr tag. I follow both advice and still can't display line breaks. -
Trying to implement user owned tags in django-taggit for specific objects
I am trying to implement a Video model in Django 1.11 which are tagged by both global tags (which are added by the admin when the video is first uploaded) which are able to be viewed by everyone accessing, and user specific tags (added by users per video) which are specific to the user logged in. Currently, the model looks something like this: class Video(models.Model): video_name = models.CharField(max_length=50) video_pub_date = models.DateTimeField('date published') video_file = models.FileField() video_thumbnail = models.ImageField(null=True, blank=True) global_tags = TaggableManager() video_views = models.IntegerField(default=0) User model is just using from django.contrib.auth.models import User but not explicitly defined in my models.py file However, in addition to global_tags, I need a way to have private tags (user specific). This answer In django-taggit, how to get tags for objects that are associated with a specific user? shows how to filter tagged objects based on object ownership, but this is not what I want since the object themselves (in my case Video), is not owned by anyone in particular, but the tags themselves are to be owned by specific user. -
Django : Context processors
What is the mechanics behind context processors in Django? I have used them before, but if someone asks me to teach them what context processors are about, I probably could not answer. This is from Django documentation: context_processors is a list of dotted Python paths to callables that are used to populate the context when a template is rendered with a request. These callables take a request object as their argument and return a dict of items to be merged into the context. Can someone elaborate on this. What are context processors exactly ?