Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: creating a model from a raw sql query that performs a Join on 2 tables
So I have a mysql database that we use for reporting. We are trying to create an API that queries this database in order to find clients that deposit over a certain ammount: query looks like this: SELECT t.`LOGIN`,SUM(t.PROFIT) AS total_deposits,u.`phone` FROM mt4_trades t join mt4_users u on t.LOGIN = u.LOGIN where t.CMD=6 and t.COMMENT like 'DP%' and u.`group` like 'FX%' group by t.`LOGIN` having sum(t.PROFIT)>10000; I performed python manage.py inspectdb in order to create a model with those fields. The problem is those fields are coming from different tables. This is what my model looks like: from django.db import models # Create your models here. class BigDeposit(models.Model): login = models.IntegerField(db_column='LOGIN', primary_key=True) # Field name made lowercase. group = models.CharField(db_column='GROUP', max_length=16) # Field name made lowercase. profit = models.FloatField(db_column='PROFIT') # Field name made lowercase. phone = models.CharField(db_column='PHONE', max_length=32) # Field name made lowercase. class Meta: managed = False db_table = '?????' 1st question: what am I supposed to put in the db_table field in such a case. 2nd question: how can I perform a raw query to create a 'BigDeposit' queryset from this? Thank you -
How to using post_save to multiple model / table in django
I've a trouble to save many fields to multiple model/table. I wanna save fields name and email to UserDashboard and CustomUser. Basically my code comes through looking like this: class UserDashboard(models.model): name = models.CharField(unique=True, max_length=80) email = models.CharField(max_length=254) role = models.CharField(max_length=1, blank=True, null=True) class Meta: db_table = 'user_dashboard' class CustomUser(models.model): name = models.CharField(unique=True, max_length=80) email = models.CharField(max_length=254) birthday = models.DateField(blank=True, null=True) sex = models.CharField(max_length=1, blank=True, null=True) password = models.TextField(blank=True, null=True) class Meta: db_table = 'user' def add_user_dashboard(request): if request.method == 'POST': formRegis = UserDashboardForm(request.POST) if formRegis.is_valid(): //save to UserDashboard model userDashboard = formRegis.save(commit=False) userDashboard.name = formRegis.cleaned_data['name'] userDashboard.email = formRegis.cleaned_data['email'] userDashboard.password = random_pass(8) userDashboard.save() //save to CustomUser model customUser.name = userDashboard.name customUser.email= userDashboard.email customUser.role = formRegis.cleaned_data['role'] customUser.save() else: return HttpResponse(formRegis.errors) else: formRegis = UserDashboardForm() data = { 'formRegis' : formRegis } return render_view(request, 'user_dashboard/registerUserDashboard.html', data) I was trying with post_save and sender like this but failed : @receiver(post_save) def update_user(sender, instance=None, created=False): list_of_models = ('CustomUser', 'UserDashboard') if sender.__name__ in list_of_models: if created: pass I have trouble understanding with post_save, guys can u help me?? thanks a lot -
django-debug-toolbar: Is there a way i can see sql formatted
django-debug-toolbar: The sql shown in not formatted with indents and new lines. Is there a way the sql can be formatted so its easy to understand. -
Redirect all api calls on Http to Https in Nginx
I am running a Django app and deployed it on server using Gunicorn and Nginx. It was running on Http for a year. Now I changed it to Https using "letsencrypt". Here is my nginx configuration. server { server_name my_project.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/ubuntu/my_project/my_project/; } location / { proxy_pass_header Server; proxy_set_header Host $http_host; proxy_redirect off; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Scheme $scheme; proxy_connect_timeout 10; proxy_read_timeout 10; proxy_pass http://localhost:8000; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/my_project.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/my_project.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = my_project.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name my_project.com; return 404; # managed by Certbot } This configuration works fine when I open project page in browser i.e. it redirects me to https page. But none of my Api calls work. I got error that method not found. Kindly guide me how can I resolve this issue? -
AttributeError at /post/106/
I want to create a "update post" function for my django post app. But I get an error. AttributeError at /post/106/ 'Post' object has no attribute 'slug' views.py def post_update(request, slug): if not request.user.is_authenticated(): return Http404() post = get_object_or_404(Post, slug=slug) form = PostForm(request.POST or None, request.FILES or None, instance=post) if form.is_valid(): form.save() messages.success(request, "updated") return HttpResponseRedirect(post.get_absolute_url()) context = { 'form': form } return render(request, "blog/post_edit.html", context) models.py class Post(models.Model): author = models.ForeignKey('auth.User', on_delete=models.CASCADE) title = models.CharField(max_length=200) text = RichTextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title def get_update_url(self): return reverse('post:update', kwargs={'slug': self.slug}) post_detail.html <a href="{{ post.get_update_url }}" class="btn btn-default" role="button">update</a> urls.py ... url(r'^(?P<slug>[\w-]+)/update/$', post_update, name="update"), How can I my mistake? Thanks. -
How to pass non-form data in django form object?
I have a data dictionary and want to validate and clean that data to store in database table as defined in models.py My approach was creating a form class then create an instance of that form class and pass data dictionary instead of request.POST in the view.py. But this is not working. No error, but cleaned_data returning an empty dictionary. data = { 'story_title': i.title.text, 'story_source': Sources.objects.get(source_url= source_url), 'pub_date': i.pubDate.text[5:16], 'body_text': des, 'url': i.link.text } story_form = StoryForm(data) if story_form.is_valid(): story_data = story_form.cleaned_data new_story = Stories( story_title = story_data['story_title'], story_source = story_data['story_source'], pub_date = story_data['pub_date'], body_text = story_data['body_text'], url = story_data['url'] ) new_story.save() I am not confirm that my approach is right or wrong. While searching for solution I came across HttpRequest.body in Django docs which only says that HttpRequest.body is used to populate form instance with the non-form data / raw data (nothing about how to use). -
Q.DjangoRestFramework (Cannot resolve keyword 'ContentType' into field)
I have models.py looks like this: class StudentAdmission(BaseModel): student = models.ForeignKey(Student,on_delete=models.CASCADE) admission_date = models.DateTimeField(auto_now_add=True) batch = models.IntegerField() course = models.ForeignKey(Course,on_delete=models.CASCADE) description = models.CharField(max_length=120) class Student(BaseModel): user = models.ForeignKey(User,on_delete=models.CASCADE) registration_no = models.IntegerField() class User(BaseModel, AbstractUser): type = models.IntegerField(choices=USER_TYPE,null=True) gender = models.IntegerField(choices=GENDER,null=True) TYPE =( ('PHONE',1), ('LANDLINE',2), ('CDMA',3), ) class Phone(BaseModel): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = fields.GenericForeignKey('content_type', 'object_id') type = models.IntegerField(choices=TYPE) number = models.IntegerField() class Address(BaseModel): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, null=True) object_id = models.PositiveIntegerField(null=True) content_object = fields.GenericForeignKey('content_type', 'object_id') province = models.CharField(max_length=120) district = models.CharField(max_length=120) city = models.CharField(max_length=120) And I have added Student as Shown Below: Views.py: def create(self,request): ---------- ...lots of code ... user,b = User.objects.get_or_create( email=ud['email'], defaults={ 'username':ud['email'], 'first_name':ud['first_name'], 'last_name':ud['last_name'], 'gender':ud['gender'], 'type':ud['type'] } ) if not b: raise serializers.ValidationError({ 'detail':["Email Already Exist"] }) c = ContentType.objects.get_for_model(user) Phone.objects.get_or_create(content_type=c, object_id=user.id, number=data['phone_detail']['number'], type=data['phone_detail']['type'] ) Address.objects.get_or_create( content_type=c,object_id=user.id, defaults={ 'province':data['address_detail']['province'], 'district':data['address_detail']['district'], 'city':data['address_detail']['city'], 'address':data['address_detail']['address'] } ) And When I try to get the list of student it show error like this Cannot resolve keyword 'ContentType' into field. Choices are: address, city, content_object, content_type, content_type_id, date_created, date_deleted, date_updated, district, id, object_id, province Cannot resolve keyword 'ContentType' into field. Choices are: address, city, content_object, content_type, content_type_id, date_created, date_deleted, date_updated, district, id, object_id, province Cannot resolve … -
What is the best way to check response STATUS Code?
I have doubt that, Am I using the correct method to check the status codes and set appropriate flag. Here Am setting the status and success flags, depend on RESPONSE status codes. here is the code if str(r.status_code) == '200': response = json.loads(r.text) # if response['code'] == '0': # success = False elif str(r.status_code) == '400': response = json.loads(r.text) status = False success = False elif str(r.status_code) == '404': response = {'code':'0','status':'failed','msg':'User not found'} success = False elif str(r.status_code) == '401': response = {'code':'0','status':'failure','msg':'Session Expired..Login again..'} status = False success = False -
Django : Updating model by overriding save method
This is my first model from django.db import models from django.contrib.auth.models import User CHOICES = (('Earned Leave','Earned Leave'),('Casual Leave','Casual Leave'),('Sick Leave','Sick Leave'),('Paid Leave','Paid Leave')) STATUS_CHOICES = (('0', 'Rejected'),('1', 'Accepted'),) class Leave(models.Model): employee_ID = models.CharField(max_length = 20) name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) type_of_leave = models.CharField(max_length = 15, choices = CHOICES) from_date = models.DateField() to_date = models.DateField() status = models.CharField(max_length = 15, choices = STATUS_CHOICES) @property def date_diff(self): return (self.to_date - self.from_date).days This is my second model class History(models.Model): first_name = models.CharField(max_length = 50) last_name = models.CharField(max_length = 50) employee_ID = models.CharField(max_length = 20) earned_leave = models.IntegerField() casual_leave = models.IntegerField() sick_leave = models.IntegerField() paid_leave =models.IntegerField() Here upon saving the first model Leave, I have written to override save method like, def save(self, *args, **kwargs): super(Leave, self).save() if self.employee_ID == History.employee_ID: if self.status == '1': if self.type_of_leave == 'Earned Leave': history = History.objects.update( earned_leave = self.date_diff, ) But upon saving the first model, all the entries in the History model are getting updated. Where in the history table every user have a separate entry with user's details(first_name, last_name, employee_ID) and default values as 10 for the rest. Upon saving the Leave model only the entry … -
Parse ISO 8601 date format in django tables2
I am using django tables2 which: Note that format uses Django’s date template tag syntax. According to django date ISO 8601 is selected by the format string 'c': c ISO 8601 format: 2008-01-02T10:30:00.000123+02:00 So that's what I do: import django_tables2 as tables ... created = tables.DateTimeColumn(format='c') But that does not work (the created column in the table is shown empty, a sign of parsing problems) This is the data coming from the API: "created": "2018-09-05T14:00:35.672433Z", which is actually coming from DRF, which by default uses: format - A string representing the output format. If not specified, this defaults to the same value as the DATETIME_FORMAT settings key, which will be 'iso-8601' unless set To summarize, my question is: How to parse iso8601 with django tables2? -
What is ":" in "reverse()"?
So, I was watching TheNewBoston's video on YT and noticed he wrote this - def get_absolute_url(self): return reverse("music:detail", kwargs = {"pk" : self.pk}); And that took him to the detail view of his model, but how did ":" work? Did this automatically created the detail view for him or did he somehow referenced it? -
Advice on how to design a good architecture for a chat app?
Hello I'm going to implement a social chat app that I what it to meet some requeriments but I'm not sure how to achieve this. Required: The app "frontend" should be written in React Native Support end to end encryption Support user to user chats OAuth2.0 Push notifications History Django or Node backend The problems comes in the backend design. I'm thinking on Node.js with websockets or Django with channels but I don't know which is a good DB design to store chats (like telegram) nor how to build a message queue. Can anyone give me some tips on the design of a chat app? Thanks -
Django - automatically create a model instance when another model instance is created
I have an overrided User model and a Cart model. I expect that a Cart model instance is created automatically once a User model instance is created. I am trying to pass the registered user into the get_queryset method, but no idea how to do it. Are there any other better ways to do this? It's because I may need to do the same thing for other models unlike the User model which has a form which can pass values to the get_queryset method. account/models.py: class Cart(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) def __str__(self): return self.user.email + '_cart' account/views.py: class RegisterView(generic.CreateView): template_name = 'account/register.html' form_class = RegisterForm success_url = reverse_lazy('book:home') def get_queryset(self): sign_up = self.request.POST.get('register') if sign_up: c = Cart.objects.create(user=???) c.save() account/templates/account/register.html: <form name="register" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Sign Up"> </form> -
html5 data-* attribute not working the same way on 2 computer
I'm currently creating a little application using django-utocomplete-light, One of the problem I'm facing is that I need to render the app on a Windows 10 Panasonic FZ-G1 Tablet and the data attributes of Select2 won't seems to work properly. Example : On my computer I can add Select2 configuration option and they work, but on my tablet none of the data-* attributes seems to do anything. I'm using the exact same version of Chrome on both PCs and I have tried with Firefox and Edge but nothing render neither. If someone got any idea, of an option that I might have to check on the tablet to make this work. Thanks a lot. -
pip install django-import-export read timed out
I am trying to using django-import-export to populate my models with excel files. However, when I do pip install django-import-export, I get this following error C:\Users\Billy Somers\webapps>pip install django-import-export Collecting django-import-export Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'ReadTimeoutError("HTTPSConnectionPool(host='pypi.org', port=443): Read timed out. (read timeout=15)")': /simple/django-import-export/ Could not find a version that satisfies the requirement django-import-export (from versions: ) No matching distribution found for django-import-export How do I resolve this? -
request.user is giving me only email address but I want all information of user using email primary key as
whenever is authenticated user post in My device I've to check id the device is associated with this user or not? for that, I've get all the information using request.user, but instead I am just getting an email address, is there any solution for this? My custom User model class User(AbstractUser): """User model.""" username = None email = models.EmailField(_('email address'), unique=True) mobile_token = models.CharField(max_length=20,blank=True,null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = UserManager_1() My device model class Device(models.Model): # user_id = models.CharField(max_length=20,primary) device_id = models.CharField(max_length=20 ,primary_key=True ) email = models.ForeignKey(User,on_delete=models.CASCADE,blank = True,null=True) date_added = models.DateField(default=timezone.now) def __str__(self): return self.device_id My serailzers class UserSerializer(serializers.ModelSerializer): # my_field = serializers.SerializerMethodField() # def get_field_name(self, obj): # return "name" class Meta: model = models.User # key= {'status':'success'} fields = ('first_name', 'email','last_name','mobile_token',) class DeviceSerializer(serializers.ModelSerializer): # locations = serializers.PrimaryKeyRelatedField(many=True, queryset=models.User.objects.all()) class Meta: model = models.Device fields = ('date_added','email','device_id',) And The View for device class DeviceView(viewsets.ViewSet): queryset = models.Device.objects.all() serializer_class = serializers.DeviceSerializer def list(self,request): queryset = models.Device.objects.all() serializer = serializers.DeviceSerializer(queryset, many=True) final_data = serializer.data import json api={} api['data'] = final_data api['message'] = "Device ids" # Device_name_api = final_data[] # validators = serializer.get_validators() api['status'] = 1 # print(request.data) return Response(api) def create(self, request, *args, **kwargs): # response = super().post(request, … -
Inner join like search using many to many relationship
I am unable to figure out how to retriever objects using an advanced Q search any perhaps am approaching it in the wrong way entirely. I think it'll be easier for me to fully define the models before I attempt to describe the problem. The problem I am trying to solve is slightly more complex than the example I am going to give here, but that is because I want to give a clearer picture of what I'm trying to do. I have two models here: class Tag(models.Model): name = models.CharField() class Container(models.Model): tags = models.ManyToManyField(Tag) I'm able to retrieve a list of tags that I want: valid_tags = [Tag(x) for x in ['a', 'b', 'c', 'd']] And here would be an example of some containers: containers = [ Container(tags=[Tag(x) for x in ['a', 'b']), Container(tags=[Tag(x) for x in ['b']), Container(tags=[Tag(x) for x in ['a', 'b', 'c']), Container(tags=[Tag(x) for x in ['e']), Container(tags=[Tag(x) for x in ['a', 'e']), ] What I want the output of the query that I am trying to write is this: valid_containers = [ Container(tags=[Tag(x) for x in ['a', 'b']), Container(tags=[Tag(x) for x in ['b']), Container(tags=[Tag(x) for x in ['a', 'b', 'c']), ] So, essentially what … -
How do I Create a Sort By ModelMultipleChoiceFeild in Django
I'm new to python and coding and was wondering if anyone had some pointers for me. I'm making an e-commerce website using Django and I would like to allow the user to easily sort the all products from High to low, low to high, new in, etc. I would like the field to look similar to this: I've created filters on my website that filter by color, product type, and size. my models.py looks like this: class e_info(models.Model): product = models.CharField(max_length=120) description = models.TextField(default="desctription default text") price = models.IntegerField(default=0) product_group = models.ForeignKey(ProductGroup, on_delete=models.SET_NULL, null=True) #sub_product_group = models.ForeignKey(SubProductGroup, on_delete=models.CASCADE) size = models.ForeignKey(Size, on_delete=models.SET_NULL, null=True) color = models.ForeignKey(Color, on_delete=models.SET_NULL, null=True) image = models.FileField(upload_to= 'post_image', blank=True) image_1 = models.FileField(upload_to='post_image', blank=True) image_2 = models.FileField(upload_to='post_image', blank=True) image_3 = models.FileField(upload_to='post_image', blank=True) image_4 = models.FileField(upload_to='post_image', blank=True) date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural= 'e_info' def __str__(self): return self.product[:50] My views looks like this: def about(request): about = e_info.objects.all() product = ProductGroup.objects.all() color = Color.objects.all() info_search = e_info.objects.all().order_by('-price') info_filter = ColorFilter(request.GET, queryset=info_search) context = { 'about': about, 'color': color, 'product': product, 'info_filter': info_filter, } template = 'about.html' return render(request, template, context) I want to sort the info in the e_info model. Any help would be greatly appreciated. Thank you! -
"You passed an empty string for 'account_token' - Django production
I am having an issue when creating Stripe connect accounts on the production website. When I run my website locally with my Stripe test keys everything works fine and I am able to create new costumers. However, on the live website, the code is not working and I am having the following error: "You passed an empty string for 'account_token'. The code is similar on the server and in the development version. Here is the view: if request.method == 'POST': stripe.api_key = settings.STRIPE_SECRET_KEY form = CreateCustomer(request.POST) token = request.POST.get('token') print(form.errors) if form.is_valid(): try: stripeId = stripe.Account.create( country=form.cleaned_data['country'], type="custom", email=form.cleaned_data['email'], account_token=token, I have the following javascript code: const myForm = document.querySelector('.my-form'); myForm.addEventListener('submit', handleForm); async function handleForm(event) { event.preventDefault(); const result = await stripe.createToken('account', { legal_entity: { type:'individual', first_name: document.querySelector('.inp-first-name').value, last_name: document.querySelector('.inp-last-name').value, dob:{ year: parseInt(document.querySelector('.inp-dob-year').value), month: parseInt(document.querySelector('.inp-dob-month').value), day: parseInt(document.querySelector('.inp-dob-day').value), }, address: { line1: document.querySelector('.inp-street-address1').value, line2: document.querySelector('.inp-street-address2').value, city: document.querySelector('.inp-city').value, state: document.querySelector('.inp-state').value, postal_code: document.querySelector('.inp-zip').value, }, }, tos_shown_and_accepted: true, }); if (result.token) { document.querySelector('#token').value = result.token.id; myForm.submit(); }else if (result.error) { console.log(result.error); const errorTypeFieldMap = { // a .inp-dob-year-error would be a new div/span/.. positioned near the input element 'account[individual][dob][year]': '.inp-dob-year-error', 'account[individual][dob][month]': '.inp-dob-month-error', } let errorElementSelector = errorTypeFieldMap[result.error.param]; [...] The account token is the culprit … -
Django refactoring how ListView iterates over data
What I would like to do is iterate over the list of colors and place the card within the proper column within the template if the card contains said color. I'm having a hard time refactoring the code to allow this in a DRY manner. I'd like to be able to update the code once and have it apply to all colors rather than having separate logic for each color (like it is currently). Here is the View I am working with currently: class SetList(ListView): template_name = 'set_list.html' context_object_name = 'cards' def get_queryset(self): set_name_from_url = self.kwargs['set_name'] set_name_title = set_name_from_url.title() return sorted(CardModel.objects.all().filter( set_name=set_name_title), key=lambda x: x.name) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) set_name_from_url = self.kwargs['set_name'] set_name_title = set_name_from_url.title() colors = ['white', 'blue', 'black', 'red', 'green', 'gold-artifacts-and-lands'] context['colors'] = colors for color in colors: context[color] = sorted(CardModel.objects.all().filter( set_name=set_name_title, color_identity=color), key=lambda x: x.name) return context and the template content: {% block content %} <div class="row"> <div class="col-2"> {% for card in white %} <p> {{ card }}</p> {% endfor %} </div> <div class="col-2"> {% for card in blue %} <p>{{ card }}</p> <img src="{{ card.image_url }}"> {% endfor %} </div> </div> {% endblock %} I want the template (or view if that's more … -
Change Chart.js Query with Dropdown
I have my chart.js chart loading fine using django rest framework. I want to preset different queries and have the chart change with a drop down, but not too sure where to start on this one, i have been able to piece together the current code from reading different articles online, but I am no expert currently my restframework pages produces this data. All good when i want to show all queries. { "lables": [ "2017-09-06", "2017-09-24", "2018-07-06", "2018-07-10", "2018-08-13", "2018-08-16", "2018-09-06" ], "default": [ 526, 200, 666, 543, 345, 422, 111 ], "lables_2017": [ "2017-09-06", "2017-09-24" ], "data_2017": [ 526, 200 ] } Here is a cutdown version of my code: View.py class ListComputers(APIView): authentication_classes = [] permission_classes = [] def get(self, request, format=None): lables = [computer.date for computer in Computer.objects.all().order_by('date')] default_items = [computer.computer_count for computer in Computer.objects.all().order_by('date')] lables_2017 = [computer.date for computer in Computer.objects.filter(date__year=2017)] data_2017 = [computer.computer_count for computer in Computer.objects.filter(date__year=2017)] data = { "lables": lables, "default": default_items, "lables_2017": lables_2017, "data_2017": data_2017, } return Response(data) Myhtml.html <div class="card-body" id="card_body"> <select class="text_select" id="chart-select" onchange="myFunction()" name="chart-select"> <option value="All">All Time</option> <option value="2017">2017</option> </select> <canvas id="ComputerChart" width="100%" height="30"></canvas> </div> <script> var endpoint = 'api/chart/data' var defaultData = [] var lables = [] … -
Django - Translate name of Permission model
I'm trying to translate the name of the permissions, but it does not work with this code. I do not get any error. Permissions are still in English, I want them to be in the language set in settings. Any idea what that might be? # forms.py from django.utils.translation import gettext as _ class PermissionModelMultipleChoiceField(forms.ModelMultipleChoiceField): def label_from_instance(self, obj): return '%s' % _(obj.name) # settings.py LANGUAGE_CODE = 'pt-br' USE_I18N = True USE_L10N = True -
url encoded characters on clicking link and page not found
I am getting the following error using Django 2.1: Page not found (404) Request Method: POST Request URL: http://localhost:8000/user-accounts/%5Eregister/ Using the URLconf defined in my_project.urls, Django tried these URL patterns, in this order: admin/ user-accounts/ ^register/$ [name='register'] user-accounts/ ^login/$ [name='login'] user-accounts/ ^logout/$ [name='logout'] bank-accounts/ The current path, user-accounts/^register/, didn't match any of these. When I click a link in the header set in my base.html, I get the strange url http://localhost:8000/user-accounts/%5Eregister/ in browser. The links in base.html are: <li class="dropdown-header"><a href="{% url 'user-accounts:register' %}">Register</a></li> <li class="dropdown-header"><a href="{% url 'user-accounts:login' %}">Login</a></li> The user accounts app urls.py: from django.urls import path from django.contrib import admin from . import views app_name = 'user-accounts' urlpatterns = [ path(r'^register/$', views.register, name='register'), path(r'^login/$', views.user_login, name='login'), path(r'^logout/$', views.user_logout, name='logout'), ] The project urls.py: from django.contrib import admin from django.urls import path, include from user_accounts.views import register urlpatterns = [ path('admin/', admin.site.urls), path('', register), path(r'user-accounts/', include('user_accounts.urls')), path(r'bank-accounts/', include('bank_accounts.urls')), ] Thank you -
Unpacking a JSONField into multiple django form fields
I am using a JSONField from django.contrib.postgres.fields in my Django model. I want to set up my update form so that it looks at the object being passed into it, iterates through the JSON from the JSONfield, and dynamically creates the right amount of CharFields. models.py: class myclass(models.Model): purpose_section = JSONField() forms.py: class myclassForm(forms.ModelForm): class Meta: model = myclass fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields['purpose_section'].initial: self.fields['purpose_section_%s' % i] = forms.CharField(label="purpose_section_" + i,value=i.content) When I try to access the page, I receive an error: 'NoneType' object is not iterable Any ideas on what I'm missing? -
pip Installing old version of Django
I am creating a new virtual env to make some Django apps. When I create the environment I try to install Django 2.1.1 with pip but it keeps installing 1.11.15. I have tried forcing it with => pip install django==2.1.1 Collecting django==2.1.1 Could not find a version that satisfies the requirement django==2.1.1 (from versions: 1.1.3, 1.1.4, 1.2, 1.2.1, 1.2.2, 1.2.3, 1.2.4, 1.2.5, 1.2.6, 1.2.7, 1.3, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 1.3.6, 1.3.7, 1.4, 1.4.1, 1.4.2, 1.4.3, 1.4.4, 1.4.5, 1.4.6, 1.4.7, 1.4.8, 1.4.9, 1.4.10, 1.4.11, 1.4.12, 1.4.13, 1.4.14, 1.4.15, 1.4.16, 1.4.17, 1.4.18, 1.4.19, 1.4.20, 1.4.21, 1.4.22, 1.5, 1.5.1, 1.5.2, 1.5.3, 1.5.4, 1.5.5, 1.5.6, 1.5.7, 1.5.8, 1.5.9, 1.5.10, 1.5.11, 1.5.12, 1.6, 1.6.1, 1.6.2, 1.6.3, 1.6.4, 1.6.5, 1.6.6, 1.6.7, 1.6.8, 1.6.9, 1.6.10, 1.6.11, 1.7, 1.7.1, 1.7.2, 1.7.3, 1.7.4, 1.7.5, 1.7.6, 1.7.7, 1.7.8, 1.7.9, 1.7.10, 1.7.11, 1.8a1, 1.8b1, 1.8b2, 1.8rc1, 1.8, 1.8.1, 1.8.2, 1.8.3, 1.8.4, 1.8.5, 1.8.6, 1.8.7, 1.8.8, 1.8.9, 1.8.10, 1.8.11, 1.8.12, 1.8.13, 1.8.14, 1.8.15, 1.8.16, 1.8.17, 1.8.18, 1.8.19, 1.9a1, 1.9b1, 1.9rc1, 1.9rc2, 1.9, 1.9.1, 1.9.2, 1.9.3, 1.9.4, 1.9.5, 1.9.6, 1.9.7, 1.9.8, 1.9.9, 1.9.10, 1.9.11, 1.9.12, 1.9.13, 1.10a1, 1.10b1, 1.10rc1, 1.10, 1.10.1, 1.10.2, 1.10.3, 1.10.4, 1.10.5, 1.10.6, 1.10.7, 1.10.8, 1.11a1, 1.11b1, 1.11rc1, 1.11, 1.11.1, 1.11.2, 1.11.3, 1.11.4, 1.11.5, 1.11.6, 1.11.7, 1.11.8, 1.11.9, 1.11.10, …