Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django search result with pagination
There is search field in template that can enter a keyword to search in a model and show the result with pagination. I need to pass this keyword in views.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) if 'color' in self.request.GET and self.request.GET['color']: context['query'] = self.request.GET.get('color') return context and combine it with pagination to prevent error.( If I don't do this, it will go to next page with raw data) {% if page_obj.has_next %} <a id="next" href="?page={{ page_obj.next_page_number }}{% if query %}&q={{ query }}{% endif %}">next</a> <a id="last" href="?page={{ page_obj.paginator.num_pages }}{% if query %}&q={{ query }}{% endif %}">last &raquo;</a> {% endif %} Is there any good idea to solve this problem? I know this is such a stupid solution... -
django-channels: No route found for path
I have a Django + Vue.js chat application that I'm trying to connect to django-channels. To access any chat room, you simply go to: http://localhost:8080/rooms/"id"/ My javascript connection looks like this: connectToWebSocket () { const chatSocket = new WebSocket( `ws://localhost:8000/ws/rooms/${this.$route.params.id}/` ) chatSocket.onopen = this.onOpen chatSocket.onclose = this.onClose chatSocket.onmessage = this.onMessage chatSocket.onerror = this.onError }, My consumers.py: class ChatConsumer(WebsocketConsumer): def connect(self): self.room_uri = self.scope['url_route']['kwargs']['uri'] self.room_group_name = 'chat_%s' % self.room_uri # Join room group async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, close_code): # Leave room group async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) # Receive message from WebSocket def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] user = text_data_json['user.username'] # Send message to room group async_to_sync(self.channel_layer.group_send)( self.room_group_name, { 'type': 'chat_message', 'user': user, 'message': message } ) # Receive message from room group def chat_message(self, event): user = event['user'] message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'user': user, 'message': message })) and my routing.py: from django.conf.urls import url from core import consumers websocket_urlpatterns = [ url(r'^ws/rooms/<uri>/', consumers.ChatConsumer), ] (it's connected the ProtocolTypeRouter in my main folder). The problem is, I can't connect to the websocket, my django server says: [Failure instance: Traceback: : No route found for path 'ws/rooms/759b9a8262ea4b7/'. What's wrong in my … -
Django template render html links does not works
In my django project i have to rendere a var ina template as html. I do this in my view: con_stat = "<div id='overlay_demo' style='display:block'><div id='text-demo'><div class='login-box-body'><p class='login-box-msg'><strong><font color='red'>MY TITLE HERE</font></strong></p><br>My text here<br><br><div><form><button onclick='location.href=https://mywebsite.com/contact;' class='btn btn-block btn-danger btn-lg'>REPORT THE PROBLEM</button><br><a href='/register/retry'><button class='btn btn-block btn-success btn-lg'>RETRY THE REGISTRATION PROCES</button></a></form></div></div></div></div>" context_dict = {'all_case': test_case, 'all_set': sg, 'the_stat': con_stat} response = render(request, b_temp, context_dict, context) well, at this point in my html template: {% autoescape off %}{{ the_stat }}{% endautoescape %} or also i try: {{ the_stat|safe }} template now display html correctly but the problem is the link, not my first button (with onclick= function) nor second one (with a href link) works. In every case when i click the behaviour is to reload the same page. Someone had experienced some problem related to link,javascript call in django template render like that above? So many thanks in advance -
Problems in Django
I don't know why this problem happened.enter image description here These errors occur when you read a book and follow it. I don't know what to do. Give me a hand. Source Code views.py in polls from django.shortcuts import get_object_or_404, render from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from polls.models import Question, Choice # Create your views here. def index(request): latest_question_list = Question.objects.all().order_by('-pub_date')[:5] context = {'latest_question_list':latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) def vote(request, question_id): question = get_object_or_404(Question, pk=question_id) try: selected_choice = question.choice.set.get(pk=request.POST['choice']) except (KeyError, Choice.DoesNotExist): return render(request, 'polls/detail.html',{ 'question': question, 'error_message': "You didn't select a choice.", }) else: selected_choice.votes += 1 selected_choice.save() return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) def results(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/result.html', {'question': question}) models.py in polls from django.db import models # Create your models here. class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text -
Upload unknown numbers (dynamically decided) of files under Django framework
I encountered an issue: if I want to apply this dynamically rows adding bootstrap code(ref here bootstrap) , I won't be knowing how many files user will upload in advance.(Although I define a maximum of numbers of files allowed to be uploaded:10) I am using Django 2.1.5. I have tried to write something like UploadFileForm in form.py, but in that way, I needed to write exactly 10 form.Charfield inside the class, which I am not willing to see. <form action="" method="post" enctype="multipart/form-data" id="bookform"> {% csrf_token %} <table id="createBookTable" class=" table order-list"> <thead> <tr> <td>book title(in original lang.)</td> <td>author(in original lang.)</td> <td>book title(in Eng.)</td> <td>author(in Eng.)</td> <td>book image</td> </tr> </thead> <tbody> <tr style="display:none"> <td colspan="5" style="text-align: left;" > <input type="text" id="counter" name="counter" value=""/> </td> </tr> <tr class="bookTr" id="bookTr-0"> <td class="col-sm-3"> <input type="text" name="orginBookname0" class="form-control" /> </td> <td class="col-sm-3"> <input type="mail" name="originAuthor0" class="form-control"/> </td> <td class="col-sm-3"> <input type="text" name="engBookname0" class="form-control"/> </td> <td class="col-sm-3"> <input type="text" name="engAuthor0" class="form-control"/> </td> <td> <input type="file" name="bookimg0"> </td> <td class="col-sm-1"><a class="deleteRow"></a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5" style="text-align: left;"> <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" /> </td> </tr> <tr> <td colspan="5" style="text-align: left;"> <input type="submit" name="button" id="bookSubmitBtn" class="btn btn-lg btn-block btn-beautiful" value="Submit"> </td> … -
Vue-Bootstrap doesn't work with Django. How can I start with it correctly?
I'm really new to VueJS. I'm trying to use vue-bootstrap instead of usual bootstrap (including jquery). But it doesn't work at all even though there's no error. All files are loaded. base.html {% load static %} <!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap/dist/css/bootstrap.min.css"/> <link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.css"/> </head> <body> {% block content %} {% endblock content %} <script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script> <script src="//unpkg.com/babel-polyfill@latest/dist/polyfill.min.js"></script> <script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.js"></script> </body> and I copied this from the example of vue-bootstrap doc https://bootstrap-vue.js.org/docs/components/navbar/ index.html {% extends 'base.html' %} {% block content %} <b-navbar toggleable="md" type="dark" variant="info"> <b-navbar-toggle target="nav_collapse"></b-navbar-toggle> <b-navbar-brand href="#">NavBar</b-navbar-brand> <b-collapse is-nav id="nav_collapse"> <b-navbar-nav> <b-nav-item href="#">Link</b-nav-item> <b-nav-item href="#" disabled>Disabled</b-nav-item> </b-navbar-nav> <!-- Right aligned nav items --> <b-navbar-nav class="ml-auto"> <b-nav-form> <b-form-input size="sm" class="mr-sm-2" type="text" placeholder="Search"/> <b-button size="sm" class="my-2 my-sm-0" type="submit">Search</b-button> </b-nav-form> <b-nav-item-dropdown text="Lang" right> <b-dropdown-item href="#">EN</b-dropdown-item> <b-dropdown-item href="#">ES</b-dropdown-item> <b-dropdown-item href="#">RU</b-dropdown-item> <b-dropdown-item href="#">FA</b-dropdown-item> </b-nav-item-dropdown> <b-nav-item-dropdown right> <!-- Using button-content slot --> <template slot="button-content"> <em>User</em> </template> <b-dropdown-item href="#">Profile</b-dropdown-item> <b-dropdown-item href="#">Signout</b-dropdown-item> </b-nav-item-dropdown> </b-navbar-nav> </b-collapse> </b-navbar> {% endblock content %} But it shows like this What am I wrong with it? -
django connec mysql --_mysql_exceptions.OperationalError: (2006, <NULL>)
In fact, I learn the django from the website:https://docs.djangoproject.com/zh-hans/2.1/intro/tutorial02/ The next is my settting.py DATABASES = { # 'default': { # 'ENGINE': 'django.db.backends.sqlite3', # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), # } 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_01', 'USER': 'root', 'PASSWORD': '9940', 'HOST': 'localhost', # Or an IP Address that your DB is hosted on 'PORT': '3306', } } mysql : enter image description here I want to know how to solve this problem,or I don't know what's the problem? Thank you very much! I think DATABASES is right, I want to connect mysql to django program named mysite, but I run 'python manage.py migrate': Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000000003B31D08> Traceback (most recent call last): File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\base\base.py", line 216, in ensure_connection self.connect() File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\base\base.py", line 194, in connect self.connection = self.get_new_connection(conn_params) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\db\backends\mysql\base.py", line 227, in get_new_connection return Database.connect(**conn_params) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\MySQLdb\__init__.py", line 85, in Connect return Connection(*args, **kwargs) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\MySQLdb\connections.py", line 208, in __init__ super(Connection, self).__init__(*args, **kwargs2) _mysql_exceptions.OperationalError: (2006, <NULL>) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "D:\Tools\Anaconda3\envs\test-django\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor … -
How to write the view of saving a model which having foreign key
I am new in Django developing and I have a model Customers that is in a relationship with a ZipCode model. So from the model Customers, I want to get the zipCode in the ZipCode model. This, the ZipCode model has 4 attributes such as pk which is an aut_increment, zipCode which is unique, city and state. Therefore, my issues are: How to get the zipCode attribute as a foreign key in the Customer model and how the view of saving the customer object can be written? Below is are the Customers and the ZipCode models: class Customers(models.Model): customerID = models.CharField(max_length=15, unique=True) firstName = models.CharField(max_length=20) lastName = models.CharField(max_length=25) phoneNumber = models.CharField(max_length=14) zipCode = models.ForeignKey(ZipCode, on_delete=models.CASCADE) address = models.TextField() class ZipCode(models.Model): zipCode = models.CharField(max_length=10, unique=True) city = models.CharField(max_length=30) state = models.CharField(max_length=25) def __str__(self): return self.zipCode + ' ' + self.city + ' ' + self.state Here also the view add_customers which is not working: def add_Custmers(request): # try: # zipCode=ZipCode.objects.get(slug=zipcode_slug) # except ZipCode.DoesNotExist: # zipCode=None form=CustomersForm(request.POST or None) if form.is_valid(): form.save() context = {'form': form} return render(request, 'customers.html', context I attached the add customer form for more details -
Connecting to Could SQL from local machine via proxy
I am following these instructions to deploy a Django app on Google App Engine: https://cloud.google.com/python/django/appengine I have got as far as downloading the proxy .exe file (I am on a Windows machine) and connecting to it: 2019/01/08 16:14:08 Listening on 127.0.0.1:3306 for [INSTANCE-NAME] 2019/01/08 16:14:08 Ready for new connections When I try and create the Django migrations by running python manage.py createmigrations I see the connection received by the proxy file: 2019/01/08 16:15:06 New connection for "[INSTANCE-NAME]" However, after a couple of seconds pause I get this error: 2019/01/08 16:15:28 couldn't connect to "[INSTANCE-NAME]": dial tcp 35.205.185.133:3307: connectex: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. I have tried disabling my local firewall in case this was causing any issues, but the result is the same. I've also checked the username, password and Cloud SQL instance name, they are all correct. What could be causing this error? -
Incorporating calendar into django application
I have a planning puzzle, where I have some resources like machines etc, and each machine has a calendar or multiple machines can share a calendar. For each task/process planned on a particular machine I have to attach a schedule on the associated calendar of the machine or book the time slot, the schedule consists of day and duration. Which module can serve my purpose effectively where I can also look for the next available slots and next working day? I am new to django and haven't worked on calendar before. Any suggestion? -
Django: got error when make Post request: CORS policy: Request header field body is not allowed by Access-Control-Allow-Headers
I installed django-cors-headers and have set everything correct in settings.py CORS_ORIGIN_ALLOW_ALL = True INSTALLED_APPS = [ 'corsheaders', ... MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', # new ... Here is how I make post request: fetch("http://localhost:8000/isaapi/isaitem/", { method: "POST", headers: { "Content-Type": "application/json", Authorization: `JWT ${localStorage.getItem("token")}`, body: "" //JSON.stringify(body) } }) .then(res => res.json()) .then(json => { console.log(json); }) .catch(error => console.error(error)); I checked the response's header: Access-Control-Allow-Headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with Access-Control-Allow-Methods: DELETE, GET, OPTIONS, PATCH, POST, PUT Access-Control-Allow-Origin: * Access-Control-Max-Age: 86400 Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Wed, 09 Jan 2019 08:22:27 GMT Server: WSGIServer/0.2 CPython/3.6.3 Vary: Origin which shows I already got Access-Control-Allow-Origin: *. Also I have tried clear broswer cache.. but no luck... still getting Error: Access to fetch at 'http://localhost:8000/isaapi/isaitem/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field body is not allowed by Access-Control-Allow-Headers in preflight response. Anyone knows what's wrong here ? -
Display images form the admin panel
I want to make a app in which admin upload a image on admin panel and it display on the template. I'm know there are some question related to this but I tried all of them but still can't display image. Django version: 2.1.4 python version: 3.6.7 In setting.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'image') In model.py from django.db import models class ImageModel(models.Model): caption = models.CharField(max_length=40) image = models.ImageField(upload_to='uploadImage', blank=True) def __str__(self): return self.caption In view.py from django.shortcuts import render from .models import ImageModel def image_page(request): images = ImageModel.objects.all() return render(request, 'input/hello.html', {'image':images}) In urls.py from django.contrib import admin from django.urls import path, include from image import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.image_page), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) In imageShow.html <img src="{{ ImageModel.image.url }}" alt="image" /> doing this show me a broken image and some time the full url of the image(where is the image is saved) What I'm doing wrong thanks in advance -
how to import classes from one module and initialise and run it in django
How to import classes from all .py in a module with same structure and run by iterating over it. For Example, module_one: script_a: class A: def __init__(self,**kwargs): code here def run(self,**kwargs): code here def finish(self,**kwargs): code here script_b: class B: def __init__(self,**kwargs): code here def run(self,**kwargs): code here def finish(self,**kwargs): code here and so on ... module_two: script: class Run: def run_all(self,**kwargs): for class in classes_from_module_one: c = class() c.run() c.finish() -
how to send email using smtp mail server in django
i want to allow users to send emails once they submit the form in order to inform that they submit the form and a new record is added to the database. i tried to add the basic arguments in settings.py and add the send_mail function with all the required arguments in order to send the email. settings.py # email setup EMAIL_HOST = 'smtp.hushmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'devleb@hushmail.com' EMAIL_HOST_PASSWORD = '**********' EMAIL_USE_TLS = True views.py send the email after to inform selected sections send_mail('New Te2shira', 'hello there this is a test email.', 'devleb@hushmail.com', ['camiw@mail-2-you.com'], fail_silently=False) i expect from this code to once the user submit the form the system automatically will send the email to the receiver list in order to inform them that a new record is added to the database. -
Define ForeignKey to a model before defining that model
So I am in a situation where I need to create a foreign key to a model before that model is defined. Consider the following models: class Question(models.Model): """Model for question.""" question_text = models.TextField(blank=True, null=True) answer = models.ForeignKey(Option, on_delete=models.PROTECT) # Can't do this class Option(models.Model): """Model for options of a question.""" question = models.ForeignKey(Question, on_delete=models.CASCADE) text = models.CharField(max_length=127) So as you can see, I have a model to save a Question(text and its answer). Also I have another model to save one option which is linked to a question. That way I can create variable number to options for a question, one of which will be correct. But I can't link the correct option to the model Question because the model Question needs to be declared first to link each Option to a Question. Is there some way I can achieve this. -
Updating User and its user profile in django
How to I bind User fields data and user profile data to a model form on my view, I only get user data rendered to a form when i use instance=user but it doesn't render any data of user profile on instance=profile, what i need is to render all user and its profile to a form. models.py class User(AbstractUser): is_supervisor = models.BooleanField(default=False) is_student = models.BooleanField(default=False) class Supervisor(models.Model): user = models.OneToOneField('User', on_delete=models.CASCADE, primary_key=True, related_name='supervisor') su_mobile_number = models.CharField(max_length=200) view.py def supervisor_update(request, user_id): # user = get_object_or_404(User, pk=user_id) user = get_object_or_404(User, pk=user_id) profile = get_object_or_404(Supervisor, pk=user_id) if request.method == 'POST': form = SupervisorSignUpForm(request.POST, instance=user) else: form = SupervisorSignUpForm(instance=user) return save_user_form(request, form, 'partials/partial_supervisor_update.html') form.py class SupervisorSignUpForm(UserCreationForm): su_mobile_number = forms.CharField(label="Mobile Number") class Meta(UserCreationForm.Meta): model = User fields = ('username', 'email', 'password1', 'password2', 'first_name', 'last_name') supervisor_update.html {% load crispy_forms_tags %} <form method="post" action="{% url 'supervisor_update' form.instance.pk %}" class="js-supervisor-update-form"> {% csrf_token %} <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <h4 class="modal-title">Update Supervisor</h4> </div> <div class="modal-body"> {% include 'partials/form_messages.html' %} {{ form.username|as_crispy_field }} {{ form.email|as_crispy_field }} {{ form.first_name|as_crispy_field }} {{ form.last_name|as_crispy_field }} {{ form.su_mobile_number|as_crispy_field }} </div> <div class="modal-footer"> <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Update Supervisor</button> </div> </form> -
Adding dynamic fields to a serializer in django-rest-framework
I have a model class Event(models.Model): random_fields... class Registrations(models.Model): user = models.ForeignKey(User...) event = models.ForeignKey(Event...) ts = models.DateTimeField(...) Now I want to fetch the list of all the events along with whether the user who made the request is registered in that event or not (is_registered field in the ModelSerializer of Event maybe). This should ideally happen in a single request and not too many database queries. What is the efficient way to do this? -
How to set Session on LoginView in-built Django
I want to set session in django after user logged in and destroy session on logout. i am using in-built Auth LoginView to Login path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/login.html'), name='logout'), -
Print CSV file in django like in jupyter
I want to print csv file in django project with the rows and column like in jupyter notebook I have print the csv with my code but i got like this main.py : def upload(): import pandas as pd dataset = pd.read_csv('./data.csv') return dataset views.py : def upload(request): upl = main.upload() upload = {'upl': upl} return render(request, 'apps/upload.html', upload) file.html : <p>{{upl}}</p> I got the result like this Src Eqid Version ... Depth NST Region 0 ak 10565543 1 ... 11.7 5 Central Alaska 1 nc 71848295 0 ... 4.3 8 Northern California 2 ci 15221369 0 ... 30.3 11 Greater Los Angeles area, California 3 us 2012fzay 4 ... 10.0 18 Tanzania 4 ak 10565529 1 ... 22.6 6 Central Alaska 5 nc 71848265 0 ... 2.2 10 Central California 6 nn 00389471 9 ... 10.3 10 Nevada 7 us c000cw89 4 ... 39.6 0 southern Iran 8 us c000cw7u 7 ... 52.3 28 Costa Rica 9 nc 71848255 0 ... 5.0 9 Northern California 10 nc 71848240 0 ... 9.3 21 Central California 11 nc 71848235 1 ... 0.1 30 Northern California 12 ci 15221361 0 ... 2.6 31 Central California 13 ci 15221353 0 ... 13.5 32 … -
Change errors in password change serializer in rest-auth
I am using Django rest-auth to have endpoints for my registration, password change, etc. I'm working with the password change endpoint which contains the old password, new password, and confirm password. I am trying to override somethings in the original serializer like adding my own error messages if the field is incorrect for example. However, one error message I'm having difficulty overriding is if the fields are blank. The default error message appears like so each time: { "old_password": [ "This field may not be blank." ], "new_password1": [ "This field may not be blank." ], "new_password2": [ "This field may not be blank." ] } I'd like to implement my own error message if the field is blank, however, I am not able to do that. Here's the serializer I created: class PasswordChange(PasswordChangeSerializer): set_password_form_class = SetPasswordForm def validate_old_password(self, value): invalid_password_conditions = ( self.old_password_field_enabled, self.user, not self.user.check_password(value) ) if all(invalid_password_conditions): raise serializers.ValidationError('The password you entered is invalid.') return value and here is the form class: class PasswordForm(ChangePasswordForm): oldpassword = PasswordField(label=_("Current Password")) password1 = SetPasswordField(label=_("New Password")) password2 = PasswordField(label=_("Confirm New Password")) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['oldpassword'].widget = forms.PasswordInput(attrs={"placeholder": ""}) self.fields['password1'].widget = forms.PasswordInput(attrs={"placeholder": ""}) self.fields['password2'].widget = forms.PasswordInput(attrs={"placeholder": ""}) def clean_oldpassword(self): … -
Are the global variables for a package in python can considered as evil?
For start, sorry for my bad English. Recently I read book called "elegant objects" by Yegor Bugayenko. One of the topics in this book is dedicated to using of objects instead of public constants. Author writes that public constants is a pure evil. There are a lot of reasons for this. For example, using of public constants breaks incapsulation - if we want to change this contant we need to know how classes of our package using this constant. If two classes in project are using this constant in its own way we need to change code of this two classes if we change constant. Author suggests that instead of using global constants we need to create objects and that's allows us to change code only in one place. I will give an example below. I already read similar topics on stackoverflow, but did not find the answer about best practices or use cases. Is the use of objects better than creating a global variable in some file, for example "settings.py"? Is this class WWStartDate: date_as_string = '01.09.1939' def asTimestamp(self): # returns date as timestamp def asDateTime(self): # returns date as datetime object better than this stored in some file … -
Display associated value of foreign key in createview of django
I have two models: store and claim where store is the foreign key of claim. I am using the CreateView generic views. In the form at frontend, I can see the list of store as like username + Store but I want to display the store's name as option's label and id in value in the dropdown list. The two models are like: class Store(models.Model): user = models.OneToOneField(Ext_User, on_delete=models.CASCADE) store_name = models.CharField(max_length=50, default='', null=True, blank=True) description = models.CharField(max_length=50, default='', null=True, blank=True) .... class Claim(models.Model): store = models.ForeignKey(Store, on_delete=models.CASCADE) expense = models.DecimalField(max_digits=999, decimal_places=0) customer = models.ForeignKey(Ext_User, on_delete=models.CASCADE) .... class of creating claim: class ClaimCreateView(CreateView): model = Claim template_name = 'claim/claim_form.html' fields = ['store', 'expense'] def form_valid(self, form): form.instance.customer = self.request.user return super().form_valid(form) def test_func(self): claim = self.get_object() if self.request.user == claim.customer: return True return False what I can see at frontend: I want to display the store name instead of these default values. -
Database model for scheduling
I need to create a database for a truck delivery scheduling app using Django. Each truck can have recurring orders (e.g mon, tues, wed). Sometimes the order can be unchecked/edited or added to a different truck for a specific date (e.g Monday 27th of Jan). How would this be represented in a database model? -
"This Field is Required" error even after sending the fields
class DroneList(generics.ListCreateAPIView): queryset = Drone.objects.all() serializer_class = DroneSerializer name = 'drone-list' filter_fields = ( 'name', 'drone_category', 'manufacturing_date', 'has_it_competed', ) search_fields = ( '^name', ) ordering_fields = ( 'name', 'manufacturing_date', ) permission_classes = ( permissions.IsAuthenticatedOrReadOnly, custompermission.IsCurrentUserOwnerOrReadOnly, ) def perform_create(self, serializer): serializer.save(owner = self.request.user) Views.py class DroneSerializer(serializers.HyperlinkedModelSerializer): # Display the category name drone_category = serializers.SlugRelatedField(queryset=DroneCategory.objects.all(), slug_field='name') owner = serializers.ReadOnlyField(source='owner.username') class Meta: model = Drone fields = ( 'url', 'name', 'drone_category', 'manufacturing_date', 'has_it_competed', 'inserted_timestamp', 'owner' ) class UserDroneSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Drone fields = ( 'url', 'name') Serializer.py class DroneCategory(models.Model): name = models.CharField(max_length=250, unique=True) class Meta: ordering = ('name',) def __str__(self): return self.name class Drone(models.Model): name = models.CharField(max_length=250, unique=True) drone_category = models.ForeignKey( DroneCategory, related_name='drones', on_delete=models.CASCADE) manufacturing_date = models.DateTimeField() has_it_competed = models.BooleanField(default=False) inserted_timestamp = models.DateTimeField(auto_now_add=True) owner = models.ForeignKey( 'auth.User', related_name='drones', on_delete=models.CASCADE ) class Meta: ordering = ('name',) def __str__(self): return self.name models.py {"name":"Python Drone", "drone_category":"Quadcopter", "manufacturing_date": "2017-07- 16T02:03:00.716312Z", "has_it_competed": "false"} Post request I had send. the fields are not read by django as shown in the response: "name": [ "This field is required." ], "drone_category": [ "This field is required." ], "manufacturing_date": [ "This field is required." ] -
Textbox for Other option of selectbox on django , openedx platform Best practice advice
I want to take an advice if my way is best practise or not . If not please give me your advice. I have a selectbox one option of the selectbox is "Other" while user select "Other" option then a textarea will shown for answering . I think making this process with those steps . Firstly i want to say i have build the selectbox via forms and model choices 1.Creating a new column for saving user's text on user_profile table (table is for conditional on this example). 2.Adding new hidden textarea field to register form . 3.Doing frontend tasks(hiding/showing textarea) with Jquery . 4.Making some validation for avoiding frontend changes by user on forms.py . Please give me advice this is good practice or not ? Any good recommand is acceptable. My model is for goal column : GOALS_CHOICES = ( ('1', unicode( 'Test1',encoding='utf-8')), ('2', unicode( 'Test2',encoding='utf-8')), ('3', unicode( 'Test3',encoding='utf-8')), ('4', unicode( 'Test4',encoding='utf-8')), ('5', unicode( 'Test5',encoding='utf-8')), ('6', unicode( 'Other',encoding='utf-8')) ) goals = models.CharField( blank=True, null=True, max_length=6, db_index=True, choices=GOALS_CHOICES )