Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
python language change telegram-bot
I have any trouble: I write telegram-bot on Python+django by helps python-telegram-bot. In this bot me need trigger between languages and I stuck(( I have keyboard: def get_language(self): keyboard = [[u"Русский"], [u"English"]] return ReplyKeyboardMarkup(keyboard, resize_keyboard=True) And I have hadler: elif state == LANGUAGE_WAIT_STATE: if text == u"Русский": profile = Profile.objects.get(telegramid=chat.profile.telegram_id) profile.locale = "ru" profile.save() chat.state.set(MENU_WAIT_STATE) chat.send_message(chat.l(u"WELCOME_MESSAGE"), keyboard=keyboard.get_menu()) elif text == u"English": profile = Profile.objects.get(telegram_id=chat.profile.telegram_id) profile.locale = "en" profile.save() chat.state.set(MENU_WAIT_STATE) chat.send_message(chat.l(u"WELCOME_MESSAGE"), keyboard=keyboard.get_menu()) else: chat.send_message(chat.l(u"USE_MENU")) This handler catch what button pushed and change profile.locale in DB. It's works. profile.locale is changing. But..... Labels on buttons don't changes, without "/start". Although all chat messages change their locale. But not buttons( I catch, what buttons pressed by "keyboard.BACK_BTN.text" and not understand what's wrong. What I must doing with it??? How to refresh button-labels without "/start"? -
Django - prefetch_related isn't working
I can't find a way to reduce a number of queries in my view/template. There is a Trip model which has a foreign key to City and the City has many GoogleApiCityCache objects - so GoogleApiCityCache has a foreign key to City. The important thing is that GoogleApiCityCache stores a formatted_address of the City object. I'm trying to prefetch GoogleApiCityCache to prevent querying database in each loop but according to Django-debug-toolbar, it access the database in every iteration. As you can see I'm trying to prefetch city__city_caches (city_caches is the related name) in TripManager's get_queryset method. And I'm trying to do the same thing in a view. None of them works. Please, note that city.formatted_address get one of it's city_caches which stores the formatted_address This is a structure: class TripManager(models.Manager): def get_queryset(self): return super(TripManager,self).get_queryset().prefetch_related('city__city_caches') .... def ordered_by_date_to_reverse(self): queryset = self.get_queryset() return queryset.order_by('-date_to') class Trip(models.Model): user = models.ForeignKey('auth.User', related_name='trips') city = models.ForeignKey('locations.City', related_name='trips') date_from = models.DateField() date_to = models.DateField() detail = models.TextField(null=True, blank=True) objects = TripManager() City model property: @property def formatted_address(self): return self.get_cache_by_lang().formatted_address This is a view: def profile(request, slug): owner = User.objects.filter(userprofile__slug=slug).prefetch_related('trips__city__city_caches').first() return render(request, 'profiles/profile/profile.html', {'owner': owner}) The problematic part of template: {% for trip in owner.trips.ordered_by_date_to_reverse %} {{ … -
PostgreSQL + Django AutoField id doesn't get restarted after flush
I am currently testing Django project using django-nose. I use PostgreSQL for my DB. The problem I am facing is: In test setUp method I create one Emp instance and save it. Then I execute this: Emp.objects.filter(empId=1) but this doesn't exist. During debugging I figured that the Emp instance exists in DB but its ID is 137. I presume that is the issue with django-nose as it flushes DB after every test, however previous empId's seem to remain. Note: I am using: class Emp(models.Model): empId = models.AutoField(primary_key=True) My question is, how do I resolve this issue? Is there a way to restart id auto-increment routine after every setUp call? -
Get and subscribe value from another model in case of ManyToManyField
I want to get value from foreign key from another model and subscribe it. It works when field is declared as ForeignKey but when field is declared as ManyToManyField it not works. How can I do it? Please help. class Document(models.Model): project = models.ForeignKey(Project) text = models.ForeignKey(Text, null=True, blank=True) language = models.ManyToManyField(Language, null=True, blank=True) def save(self, *args, **kwargs): self.text = self.project.text #WORKS self.language = self.project.language.all() #NOT WORKS super(Document, self).save(*args, **kwargs) -
Django saving to public media folder , error 403
So i have Angular + Django REST API applications hosted on nginx + gunicorn setup. I'm facing a weird problem . I have my media folder permisssions set to 777 and in my nginx config: location /media { alias /home/shalin95/zona_project/zona_api/media; expires 20m; } I have a model Product with main_picture field ( ImageField saving the files to /media/photos/) . When i create new instance ( new product ), and sometimes when i want to open the image in the browser i get 403 Forbidden error. NOTE: This happens occasionally , not on every instance saved ( no specific pattern , just randomly) Thank if i go and chmod -R 777 the media folder everything is okay ( i can see the picture ) , but why this happens ( on some occasions ) ? -
Trouble in learning Django
I'm learning Python Django, but I find it difficult to understand.but i need to learn it. I tried to learn from codingforentrepreneurs.com, www.lynda.com, and https://stackskills.com they all is very good recources but i didnt understand it. Can you help us with how can i learn it ? Knowing that i'm PHP developler but i must change to Django. -
Django Rest Framework HTTP Post Calls and Authentication with Ionic Framework
I implemented the Django Rest Framework into my Django project so I could use Django as a backend to my Ionic Framework app while maintaining the web app that I can make with Django. I went through the process to OAuth2, using the oauth toolkit, but now I am unsure on how to make the http request calls from the ionic framework side to authenticate a user and get a token. So far on the Ionic side I have the http request as: login(username, password, url) { let headers = new Headers() headers.append("Content-Type", "application/x-www-form-urlencoded"); return this.http.post(url, {"username": username, "password": password, }, {headers: headers}) .map(res => res.json()); } But when I run it in my browser, I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 500. On the server side the curl command curl -X POST -d "grant_type=password&username=USERNAME&password=PASSWORD" -u "CLIENT ID:CLIENT SECRET" https://www.example.com/o/token/ works perfectly fine and returns a token, where USERNAME, PASSWORD, CLIENT ID, and CLIENT SECRET are all the respective values. I'm not sure if this is the right question, but how do I turn the cURL command into something I can use in … -
How can i pass data from django template to angular 4?
I am having angular 4 application integrated with django. Angular 4 is just for showing some data in django template and i am having some RESTful api in django.I have used webpack to compile .ts files to js and included in django templates.I am getting the angular content in django templates and it works fine. I am having angular component code import { Component,OnInit } from '@angular/core'; import {Http, Response} from '@angular/http'; @Component({selector: 'my-component', template: '<ul> <li *ngFor="let res in results"> {{res}} </li></ul>' }) export class MyComponent { results: {}; constructor(private http: Http) { } app_func(){ this.http.get('http://someurl/id/test.json').subscribe( res => { this.results = res.json(); }) } ngOnInit(): void { this.app_func(); } And django template {% block bundles %} {% render_bundle 'main' %} {% endblock bundles %} {% block breadcrumbs %} {{ block.super }} {% breadcrumb test.name 'detail' test.id %} {% endblock breadcrumbs %} {% block content %} <div class="row"> <div class="col-md-12 col-md-offset-0"> <div class="test" id="results"> <my-component>Loading...<my-component> </div> </div> </div> {% endblock content %} I am getting the angular templates when i am using the static url (i.e exact url) in angular component. But i need to pass the {{test.id}} (which is from django views) value to angular component and use this … -
Django REST Framework doesn't display value in PUT form
Yesterday I posted a question and found a solution to that problem. The solution however caused another issue. Please take a look at the question, so I don't have to duplicate the contents. In the Browsable API the value for 'class_name' is not displayed in the PUT form. The rendered HTML looks like this: <div class="form-group "> <label class="col-sm-2 control-label "> Class </label> <div class="col-sm-10"> <input name="class_name" class="form-control" type="text"> </div> </div> For the other fields it displays the value properly, for example: <div class="form-group "> <label class="col-sm-2 control-label "> Order </label> <div class="col-sm-10"> <input name="order" class="form-control" value="Artiodactyla" type="text"> </div> </div> I poked around the source code and found out that the form is rendered in the file renderers.py in the following order: In the class BrowsableAPIRenderer the method get_context creates the form and calls the method get_rendered_html_form. The method get_rendered_html_form calls the method render_form_for_serializer. The method render_form_for_serializer calls the method render of the class HTMLFormRenderer. But I still don't know where to interfere and what should I change. Also I tried to implement the method to_internal_value in the serializer, but this is only for the deserialization and has nothing to do with the form rendering. Does anyone has an idea … -
How to register DRF router url patterns in django 2
My DRF routers specify a namespace so that I can reverse my urls: urls.py: router = DefaultRouter() router.register('widget/', MyWidgetViewSet, base_name='widgets') urlpatterns =+ [ url(r'/path/to/API/', include(router.urls, namespace='widget-api'), ] Which, when upgrading to django 2, gives: django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead. Django 2 now requires app_name if the namespace kwarg is specified when using include. What's the right way to specify app_name when the url patterns are constructed by a DRF url router? I don't think the documentation is up-to-date for django 2 on this subject. -
Django project, aggregate(Sum) adding too much
I have a django project using views, models and forms. In forms I have a field called 'closed_cnt' that is supposed to add up all closed things. That is supposed to match against 'opened_cnt' and it usually works fine. But the thing is this is documented on different occasions and over a period of time. F.ex. a month ago I put 110 as opened_cnt and 30 as closed_cnt Then today I accidentally closed 8 instead of 80, and when I go back to fix it, it complains that the sum is too much, so what I have to do is put the value as 0, save it, then open again and put the value as 80. The code example for the field in models.py @property def closed_cnt(self): finished = self.finished() total_closed = finished.aggregate(Sum(closed_cnt)) So what I need is to not read the number I am overwriting and only read the new number. Is it possible to achieve this? -
How can I display this nested json object neatly and structured for the results object in django?
Here is my view.py: def dublinbus(request): template = loader.get_template('park_at_dcu/dublinbus.html') busstop = request.GET.get('busstop', '') busstop_url = 'https://data.dublinked.ie/cgi-bin/rtpi/realtimebusinformation?stopid='+busstop+'&format=json' bus_time_info = requests.get(busstop_url) return HttpResponse(template.render(bus_time_info.json(), request)) Here is the json data: {"errorcode":"0","errormessage":"","numberofresults":1,"stopid":"1644","timestamp":"05\/12\/2017 12:22:09","results":[{"arrivaldatetime":"05\/12\/2017 13:11:49","duetime":"49","departuredatetime":"05\/12\/2017 13:11:49","departureduetime":"49","scheduledarrivaldatetime":"05\/12\/2017 13:12:00","scheduleddeparturedatetime":"05\/12\/2017 13:12:00","destination":"Clontarf Road ","destinationlocalized":" ","origin":"DCU","originlocalized":"DCU","direction":"Inbound","operator":"bac","additionalinformation":"","lowfloorstatus":"no","route":"104","sourcetimestamp":"05\/12\/2017 12:15:24","monitored":"true"}]} -
Django obtain query when calling function
i search a method to obtain query set when i calling sql function in my django's view : def gestionpaquet(request): try: cars=Car.objects.using("default").all() c=connection.cursor() c.execute("BEGIN") c.callproc("p_web_get_trunk") results=c.fetchall() c.execute("COMMIT") c.close() trunk="" trunks=[] for item in results: data=item[0] trunks.append(data) html = render_to_string("py/myhtml.html", locals()) except Exception as e: logger.warning("Error:" + e.message) return HttpResponse(html) In my template i correctly see cars but trunks doesn't work because trunks is not a query set, how can i obtain a query set when i execute function? Thanks. -
Gunicorn Error: HTTP_HOST header: 'wordist.org' (Django Project)
I'm developing a system through the django framework with gunicorn and nginx. But lately I realized that my system may be being hacked, because, I do not know how, the host www.wordist.com is infiltrated in my project. I've never seen this host in my life, but a error tells me to insert it into my ALLOWED HOSTS, and what's crazier, if I enter this host www.wordist.com into my ALLOWED HOSTS, then when I type this link in the url browser, this domain points to my project and shows my system, as if this domain www.wordist.com were mine, but I never saw this domain in my entire life. I suspect it's a hack or something malicious. Someone could help me unravel this case, and fix it. Thanks. -
Two Django projects with same database - permission denied for relation django_migrations
I have two django projects that are not connected in any way, both on localhost. I want to have them both use the same database. I am trying to create migrations on the second project after the first one succeeded but, I am getting an exception: django.db.utils.ProgrammingError: permission denied for relation django_migrations My setup is as follows: //First project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'srt_side_by_side', 'USER': 'srt_side_by_side_admin', 'PASSWORD': '******************', 'HOST': 'localhost', 'PORT': '', } } //Second project DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'srt_side_by_side', 'USER': 'srt_side_by_side_admin_2', 'PASSWORD': '**************', 'HOST': 'localhost', 'PORT': '', } } I have granted SUPERUSER privileges to both users. I have tried to set individual privileges while being connected as the corresponding user in the psql shell. GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA public to srt_side_by_side_admin_2; GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA public to srt_side_by_side_admin_2; GRANT ALL PRIVILEGES ON ALL FUNCTIONS IN SCHEMA public to srt_side_by_side_admin_2; The DB access privileges in the psql shell: =Tc/simeonparvanov simeonparvanov=CTc/simeonparvanov srt_side_by_side_admin=CTc/simeonparvanov srt_side_by_side_admin_2=CTc/simeonparvanov Any idea what am I doing wrong? -
Find all items that are selected in a series of select lists
I currently have a page in my application that contains a Django formset. Each form in said formset consists of a Select2 field, rendered using django-autocomplete-light. I am using jQuery to make the formset dynamic (i.e. you can add and delete forms). The problem I am currently trying to solve is that I want to capture the value of the all the selected options from all the forms in the formset when the select2:open event is called when you click on the Select2 field. I have been having trouble doing this, as everything I have tried only returns the value for the current field and not all of them. I.e. I have been trying things like this: $('.s2mutex.keychar').on('select2:open', function (e) { let values = $('s2mutex.keychar').find('option:selected').val(); }); How can I find the values of all the options that have been selected? Here is my template as it stands: {% extends 'pages/dashboard.html' %} {% load i18n crispy_forms_tags static widget_tweaks %} {% block content %} <div> <h1 class="text-center">Create cost group - Set Key characteristics and Value fields</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <h3>Name: {{ object.eventconfig.eventconfigstepinitial.name }}</h3> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} <div id="formset"> {{ keycharacteristicfield_inline.management_form }} {{ … -
Django - JQuery AJAX : How to filter "POST"-ed json on "GET"?
When passing a JSON to Django views, it's supposed to be using POST. Using GET will append a long URL that would throw a long URI error. I am trying to implement a filter on objects in JSON type of functionality using ajax. I have two filter options, by text and by dropdown, where the users can filter one or the other or both. To do this I pass these two data using GET. So essentially its: JSON : POST filter1 & filter2 : GET Script $('#select_type').on('change', function () { filterGeoJson(); filterSearch(); }); $(function() { $('#search').keyup(function() { filterGeoJson(); filterSearch(); }); }); function filterSearch(){ $.ajax({ type: "GET", //url: "/search/get_routes/", url: "/search/routes/bounds", data: { 'search_text' : $("#search").val(), 'filter_type' : $("#select_type option:selected").val() }, success: function(data){ var result = $('<div />').append(data).find('#list-group').html(); $('#list-group').html(result); }, dataType: 'html' }); } function filterGeoJson(){ $.ajax({ type: "POST", //url: "search/get_routes/", url: "/search/routes/bounds/", contentType: 'application/json; charset=utf-8', data: { 'routes_geojson' : JSON.stringify(geojsonFeature) }, success: function(data){ var result = $('<div />').append(data).find('#list-group').html(); $('#list-group').html(result); }, dataType: 'html' }); } The main problem is, where I can't keep the POST-ed json (ofcourse, since its POST) but its also unconventional to make a global variable in Python (not like in Java) so I can't keep it until … -
what is detail_route and list_route in django rest framework
what is detail_route and list_route in django rest framework. i am new to django and its tough to understand from drf docs http://www.django-rest-framework.org/api-guide/routers/ -
Neovim pylint & pylint-django
I'm using pylint along with w0rp's ale vim/neovim plugin. I use it for django development. But I'm unable to configure pylint-django plugin. Every single time it shows a model doesn't have objects member. Thanks in advance. -
django rest framework, not serializable
I am new at using the django REST framework and I am having trouble to import a list of the members of a team my query is team_name_list = Project.objects.get(id=kwargs['pk1']).team_id.members.all() which give an output : <QuerySet [<MyUser: johndoe@gmail.com>, <MyUser: johndoe2@gmail.com>, <MyUser: johndoe3@gmail.com>, <MyUser: johndoe4@gmail.com>]> The thing is when I try to import it in my context I get an error Object of type 'MyUser' is not JSON serializable I guess because the output of my query should be something ["johndoe@gmail.com","johndoe2@gmail.com","johndoe3@gmail.com","johndoe4@gmail.com"] How can I make it work -
Django getting csrf error
I've made a register form, usually it works, but sometimes it gives me the csrf error, after i go back to the register page, it works again: Forbidden (403) CSRF verification failed. Request aborted. This is the register form i've made: def register(request): data = dict() if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): cd = form.cleaned_data email = cd['email'] password = cd['password1'] new_user = CustomUser.objects.create_user( email=email, password=password, ) new_user.valid_email = False new_user.save() current_site = get_current_site(request) subject = 'Activate your account.' message = render_to_string('registration/account_activation_email.html', { 'user': new_user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(new_user.pk)), 'token': account_activation_token.make_token(new_user), }) new_user.email_user(subject, message) return redirect('account:account_activation_sent') else: form = RegistrationForm() data['form'] = form return render(request, 'registration/register.html', data) In register.html i am using {% csrf_token %}: <form method="POST" class="m-login__form m-form" action=""> {% csrf_token %} {{ user_form.non_field_errors }} {{ user_form.email.errors }} <div class="form-group m-form__group"> <input type="text" placeholder="E-mail*" name="email" autocomplete="off"> </div> {{ user_form.password1.errors }} <div class="form-group m-form__group"> <input type="password" placeholder="Parola*" name="password1"> </div> {{ user_form.password2.errors }} <div class="form-group m-form__group"> <input type="password" placeholder="Confirmati parola*" name="password2"> </div> <div class="m-login__form-action"> <button id="m_login_signup_submit" class="btn m-btn m-btn--pill m-btn--custom m-btn--air m-login__btn m-login__btn--primary"> Sign Up </button> </div> </form> What could be the problem? -
Is there is any phpmyadmin like alternative for python
Iam new to python, and i need to know is there any phpmyadmin like alternative for python. -
systemctl restart httpd failed, when I don't know why there is python/django related
I start my httpd failed: systemctl restart httpd Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details. [root@controller html]# journalctl -xe 12月 05 18:22:17 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:18 controller sshd[16444]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:20 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:20 controller sshd[16444]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:22 controller sshd[16444]: Failed password for root from 182.100.67.120 port 32032 ssh2 12月 05 18:22:22 controller sshd[16444]: Disconnecting: Too many authentication failures for root [preauth] 12月 05 18:22:22 controller sshd[16444]: PAM 5 more authentication failures; logname= uid=0 euid=0 tty=ssh ruser= rhost=182.100.67.120 user=root 12月 05 18:22:22 controller sshd[16444]: PAM service(sshd) ignoring max retries; 6 > 3 12月 05 18:22:24 controller sshd[16463]: pam_unix(sshd:auth): authentication failure; logname= uid=0 euid=0 tty=ssh ruser= rhost=182.100.67.120 user=root 12月 05 18:22:24 controller sshd[16463]: pam_succeed_if(sshd:auth): requirement "uid >= 1000" not met by user "root" 12月 05 18:22:26 controller sshd[1646 In my /var/log/messages: Dec 5 18:27:45 controller systemd: Starting The Apache HTTP Server... Dec 5 18:27:46 controller … -
Django: string representation from choices list [duplicate]
This question already has an answer here: Django: Display Choice Value 3 answers Is there a way to use django's model choices to obtain a string representation? I am trying to avoid having to write a long series of if-thens or switch conditions. I have many lists of tuples for various choices in my models.py, like this: FOOD_CHOICES = ( ("1", "Pizza"), ("2", "Hamburger"), ("3", "Hoagie"), ) The point was to obtain a quick numeric representation of each choice, while allowing admins to see the actual choices on the admin page. But now I would also like to get "Pizza" instead of "1" when I pass a query to a web page. It seems like the only way to do this is to use a series of If-thens, and I would really like to avoid that because there are dozens of choices that are only going to increase as time goes on. -
Django Rest Framework API in AWS cant use user token
So i have created a database and API for user to use it to register, login, see current user profile and log out. This work perfectly locally so i uploaded it into AWS. The register and login works but when using the token from the login. the data i get is blank. Even using the token for logout also got error. I am not sure what is the problem as it was perfectly fine when using it locally. Please help Here is the screenshot taken from Postman on both locally and AWS Expected - Local: https://imgur.com/a/HQKtt Result - AWS: https://imgur.com/a/hwjKt models.py class CustomUserManager(UserManager): def get_by_natural_key(self, username): return self.get( Q(**{self.model.USERNAME_FIELD: username}) | Q(**{self.model.EMAIL_FIELD: username}) ) class MyUser(AbstractUser): userId = models.AutoField(primary_key=True) gender = models.CharField(max_length=6, blank=True, null=True) nric = models.CharField(max_length=9, blank=True, null=True) birthday = models.DateField(blank=True, null=True) birthTime = models.TimeField(blank=True, null=True) ethnicGroup = models.CharField(max_length=30, blank=True, null=True) mobileNo = models.IntegerField(blank=True, null=True) favoriteClinic = models.CharField(max_length=50, blank=True, null=True) # displaypicture = models.ImageField objects = CustomUserManager() def __str__(self): return self.username class Session(models.Model): userId = models.ForeignKey(MyUser) token = models.CharField(max_length = 255) firstActive = models.DateField(auto_now=True) lastActive = models.DateField(auto_now=True) class Relation(models.Model): # relationId = models.AutoField() userId = models.ForeignKey(MyUser) relativeId = models.ForeignKey(MyUser, related_name='relative') relationship = models.CharField(max_length = 20) dateEst = models.DateField(auto_now_add=True) class …