Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named 'chartit';
I am trying to use chartit in django and in its documentation it says add chartit to INSTALLED APPS in "settings.py". When I try to do that, it gives this error: ImportError: No module named 'chartit' How do I import it? Thank you. PS-Sorry, it's a silly question. -
Error when connecting to MySQL database Python
I m trying 2 connect mysql database 2 python,but m getting a an error Code== import mysql.connector; from mysql.connector import errorcode; user="root"; password="toor"; host="localhost"; database="pydb"; try: print("Hello") conn=mysql.connector.connect('root','toor','localhost:8000','pydb');//have also tried localhost only still same error print("Hello2"); mycursor=conn.cursor(); print("Hello3"); mycursor.execute("show tables;"); print("Hello4"); print(mycursor.fetchall()); print("Hello5"); conn.close() except mysql.connector.Error as err: print("Something went wrong: {}".format(err)) Error == C:\Python34\python.exe C:/Users/vaibhav2/PycharmProjects/MyUniversityResult/MyUniversityResult/mysqlconnectt.py Hello Traceback (most recent call last): File "C:/Users/vaibhav2/PycharmProjects/MyUniversityResult/MyUniversityResult/mysqlconnectt.py", line 11, in conn=mysql.connector.connect('root','toor','localhost:8000','pydb'); File "C:\Python34\lib\site-packages\mysql\connector__init__.py", line 179, in connect return MySQLConnection(*args, **kwargs) File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 57, in init super(MySQLConnection, self).init(*args, **kwargs) TypeError: init() takes 1 positional argument but 5 were given Process finished with exit code 1 -
Django - Using multiple models for authentication
I am kind of new to django and I am concerned about can we use multiple models for authentication for different types of users for our application e.g for Customers use Customer model, for Suppliers use Supplier model and also keep default User registration model for administration use only? If so can you point me in the right direction, how it can be done? Which package should be used? There is one way that I came around is by adding a foreign key to each model viz needed for authentication but that will involve joins in every query which could result in performance issues. I need to know if there is a better way. An also these custom models can benefit for all permissions stuff available in admin panel. Expert opinion will be really appreciated. -
Building a Back-end Server in Django
I want exact step by step process to building a back-end server. I am building a GPS tracking app and I need the back-end server to collect the data from the android phone and plot them on a map. I have no idea of how to start building a back-end server and I need a little guidance. I know that I have to use the Django REST framework, this is because I am better at python programming. Does anyone know how to use this framework and could you please give me specific instructions on how to build and run a back-end server. -
Is it possible column-wise filter in django admin table?
We are working on Django and Django Rest Framework around a year. I never find the example of column wise filter in Django admin panel's table (ex. column-wise-filter-datatables). Right now we are using list_filter and search_fields and customization list_filter. I don't know column wise filter is possible in built-in Django admin panel or not. Please give us the url or suggestions. -
Store class info in a DB then instantiate the class in your code?
In my poll app, I have a Controller class that examines a UserProfile, and depending on the profile satisfying certain conditions, returns a FormView class called ShowQuestion. As I've presently designed it, the UserProfile has a ForeignKey to a ProfileQuestion, so I can know progress in the sequence of questions without having to do many database hits. ShowQuestion fetches the ProfileQuestion from the database, which tells the class which ProfileQuestion.template_name and ProfileQuestion.form_class to render. So far so good. However both those template_name and form_class properties are stored as strings (who can't be called; eg this question). If I declare them (in say profilequestions.py and then import), I lose the foreign key relationship that allows me to track progress without sequentially going though the database to see which questions have been answered. I could have the ProfileQuestion table, and import profilequestions.py with the dictionary mapping to the actual classes, but that seems brittle to have code like that in two places. What's the correct way to record Form classes somewhere so that you can call them and do DB queries on them? -
How to cache query sets across requests in Django?
I want to cache an entire table in memory. Default Django QuerySets are cached within a view but I want an entire table to be cached in memory so that I can look at the table again and again across various requests. I tried using Redis/Memcached but serialization/deserialization is consuming a lot of time because of large table size (1,00,000 entries). Any neat solutions for this problem? -
Task do not show up in celery using gunicorn
I want to add Tasks to the task queue in celery. Using the django development server the tasks show up and are executed. When running in gunicorn nothing happens. I use nginx as reverse proxy with socket connection to gunicorn calery.py from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'energiemanagement.settings') from django.conf import settings # noqa app = Celery('energiemanagement') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) the task @shared_task(serializer="json") def automatische_messung(pk): messpunkt = get_object_or_404(Messpunkt, pk=pk) if messpunkt.active: get_automatische_messung(pk) the view def add_messpunkt(request): form = MesspunktForm(request.POST or None) if form.is_valid(): messpunkt = form.save() result = tasks.automatische_messung.apply_async(args=[messpunkt.pk]) print(result) return redirect('monitoring:messpunkt_detail', messpunkt.pk) context = { 'form': form, } return render(request, 'generic_form_view.html', context) the log when running from the dev server [tasks] . energiemanagement.celery.debug_task . monitoring.tasks.automatische_messung [2016-09-30 12:29:43,373: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2016-09-30 12:29:43,401: INFO/MainProcess] mingle: searching for neighbors [2016-09-30 12:29:44,415: INFO/MainProcess] mingle: all alone [2016-09-30 12:29:44,425: WARNING/MainProcess] celery@lvps92-51-149-128.dedicated.hosteurope.de ready. [2016-09-30 12:32:56,586: INFO/MainProcess] Received task: monitoring.tasks.automatische_messung[6078d8fc-12a7-4e29-ba22-60c2befc3fb3] [2016-09-30 12:33:56,679: ERROR/Worker-1] Could not read from http://192.168.2.106/values.xml [2016-09-30 12:33:56,683: INFO/MainProcess] Task monitoring.tasks.automatische_messung[6078d8fc-12a7-4e29-ba22-60c2befc3fb3] succeeded … -
Docker for windows10 run django fail: Can't open file 'manage.py': [Errno 2] No such file or directory
I just start a sample django app. And use docker to run it. My docker image like: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ My docker-compose.yml file: version: '2' services: django: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" When I run docker-compose up command,it build successfully but failed in running command: python manage.py runserver 0.0.0.0:8000,it complained thon: can't open file 'manage.py': [Errno 2] No such file or directory. Is this a bug in docker for windows? Because I just follow the docks of docker Quickstart: Docker Compose and Django Thank for you help! -
Is multi choice django admin filters possible..?
Suppose if there is a model named 'Cities' and at admin side there is a filter 'city_name' to filter model based on city names. By default django only allows to choose one city name from the django admin filter. But I need to choose multipile city names in django admin filter.How can i do that.?? -
How to make Django generic views accessible to logged in users only?
I've implemented the social-auth for Google for users to log in. I cannot understand how to restrict the visitors from accessing the generic views like UpdateView, ListView or CreateView, if they are not logged in with the social-auth system. Here is the code. views.py class AchievementCreate(CreateView): form_class = AchievementForm2 model = Achievements def form_valid(self, form): achieves = form.save(commit=False) achieves.resume = Resume.objects.get(pk=2) return super(AchievementCreate, self).form_valid(form) def home(request): #logout(request) uname="" if request.method == 'POST' and 'submit' in request.POST: submit = request.POST['submit'] if submit=="sign-out": logout(request) if '_auth_user_id' in request.session: uname=sm.UserSocialAuth.objects.get( user_id=int(request.session['_auth_user_id']) ).user request.session['uname']=str(uname) return render(request,'cv/home.html',{'uname': uname}) home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"/> <title>Home</title> </head> <body> <form method="post" action="{% url 'cv:home' %}">{% csrf_token %} {% if uname %} Helo, {{uname}}<br> The user already signed in. He may need to sign out<br> <input type="submit" name="submit" value="sign-out"> {% else %} Please sign-in<br> <a href="{% url 'social:begin' 'google-oauth2' %}">Google login</a> {% endif %} </form> </body> </html> urls.py urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^achievements/(?P<pk>[0-9]+)/delete/$', views.AchievementDelete.as_view(), name='achievement-delete'), url(r'^achievements/(?P<pk>[0-9]+)/$', views.AchievementUpdate.as_view(), name='achievement-update'), url(r'^achievements/add/$', login_required(views.AchievementCreate.as_view()), name='achievement-add'), url(r'^home/$', views.home, name='home'),] I want the "AchievementCreate" class to be accessible only if the user has logged in. But I don't understand how. Is it possible to use sessions? How, in this case? -
Call admin function from another admin in django
I have a products/admin.py as follows # django imports from django.contrib import admin # model imports from products.models import Product from inventory.models import Inventory class ProductAdmin(admin.ModelAdmin): list_display = # some fields in a tuple readonly_fields = # some more fields in a tuple def save_model(self, request, obj, form, change): if 'is_active' in form.data: if form.data['is_active'] == 'on': # create an Inventory if product doesn't exists. obj.created_by = request.user obj.updated_by = request.user if change: obj.updated_by = request.user obj.save() admin.site.register(Product, ProductAdmin) I have a inventory/admin.py as follows # django imports from django.contrib import admin # models imports from inventory.model import Inventory, DispatchedInventory class InventoryAdmin(admin.ModelAdmin): def save_model(self, request, obj, form, change): obj.created_by = request.user obj.updated_by = request.user if change: obj.updated_by = request.user obj.save() readonly_fields = ['created_by', 'updated_by'] Now I want to call InventoryAdmin.save_model() inside ProductAdmin.save_model() when if form.data['is_active'] == 'on': is true. My motivation behind it is that to create an inventory for the product when product is made active. I know how to create by taking an instance of Inventory model itself like as follows( which will be last resort): inventory_instance = Inventory.objects.get_or_create(product=product) But calling the admin functions does all the job for me so I want to figure out a way … -
Could not parse the remainder: '/{{menu.Info.page}}' from ''item'/{{menu.Info.Page}}'
<a href="{% url 'page' %}"><img id="page" class="abc" src="{{STATIC_URL}}page/code_251.png" style=""/></a> Hitting this url like localhost:8000/app/page works fine. If I want something from views and append that pageid with url then showing error as Couldn't parse. From views:{{page.pageid}} output url should be :localhost:8000/app/?pageid=xx for this i tried with below syntax: <a href="{% url 'page'/?pageid={{page.pageid}} %}"><img id="page" class="abc" src="{{STATIC_URL}}page/code_251.png" style=""/></a> But above syntax did't worked for me. Can someone share some idea!! -
moment.js date in Django template
I want to display the date of the relevant text (for example, 3 days ago) using the moment.js. But my code does not work. My code, but it does not work: <div class="base"> <script type="text/javascript"> var time = {{ obj.pub_date|date:'Ymd' }}; moment(time, "YYYYMMDD").fromNow(); </script> <p>{{ obj.text }}</p> </div> -
cx_oracle Unable to acquire Oracle environment handle
When trying to get a connection to an Oracle Database I´m getting the following error: File "test.py", line 5, in <module> conn = cx_Oracle.Connection('dbuser/dbpass@fqdn') cx_Oracle.InterfaceError: Unable to acquire Oracle environment handle The Test code: import os #os.environ['ORACLE_HOME']='/oracle/client/112_64/' import cx_Oracle conn = cx_Oracle.Connection('dbuser/dbpass@fqdn') My Paths are set like this: ORACLE_BASE=/oracle/oracle-client ORACLE_HOME=/oracle/oracle-client/112_64 LD_LIBRARY_PATH=/oracle/client/112_64/:/oracle/oracle-client/112_64/lib/ PATH=/oracle/oracle-client/112_64/bin:/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/home/my_user/bin The installed Oracle Version is 11g according to libocci.so.11.1 and the cx_Oracle Version is 5.2.1 I dont´t know what the problem could be. Can some give me a hint? -
Django ListView with filter form and datatables
I have a simple ListView which displays a model called Event. The page also contains a form (via FormMixin) which the user can use to filter the queryset of Events returned to the list. So something like this:- class EventListView(FormMixin, ListView): model = Event form_class = EventFilterForm context_object_name = 'events' def get_form_kwargs(self): return { 'initial': self.get_initial(), 'data': self.request.GET or None} def get_context_data(self, *args, **kwargs): context = super(EventListView, self).get_context_data(*args, **kwargs) context['form'] = self.get_form(self.get_form_class()) return context All fine so far. However, I want to display these results in a datatable (https://datatables.net/) and get the results using the server side processing in order to make the page load faster. At the moment, I do this:- $('#events_table').DataTable({ dom: 'lrtip', processing: true, serverSide: true, ajax: "{% url 'event_list' %}", ordering: false }); This makes things tricky because the ajax call to the URL that fetches the next set of results for the table is a separate HTTP request so it loses the sense of any filters that may have been input via the form and therefore always uses the full queryset of all events. My latest thought is that I might be able to get around this by turning the ajax call into a POST … -
What should I put inside "SPATIALITE_LIBRARY_PATH"? Django
I'm trying to make Django's SQLite3 accept spatial queries. This tutorial suggests that I add this to settings: SPATIALITE_LIBRARY_PATH = 'mod_spatialite' Which produces this error: django.core.exceptions.ImproperlyConfigured: Unable to load the SpatiaLite library extension "mod_spatialite" because: The specified module could not be found. I also tried doing this: SPATIALITE_LIBRARY_PATH = r'C:\Program Files (x86)\Spatialite\mod_spatialite-4.3.0a-win-x86\mod_spatialite-4.3.0a-win-x86\mod_spatialite.dll' If I don't add this variable I receive this error when I migrate: django.core.exceptions.ImproperlyConfigured: Unable to locate the SpatiaLite library. Make sure it is in your library path, or set SPATIALITE_LIBRARY_PATH in your settings. Thank you. -
Confusing Jquery Filter, Bug
I have created a calendar and i would like to have a filtering affect that is easy and user friendly. so i sent up a fast filter with Jquery. $(document).ready(function() { $('input[type="checkbox"]').change(function() { var filters = $('input[type="checkbox"]:checked'); if (filters.length) { $('.alert').hide(); $('.more').hide(); $('input[type="checkbox"]:checked').each(function() { $('.alert.' + $(this).data('type')).show(); }); } else { $('.alert').show(); $('.more').show(); } }); }) It's very simple and dull, working with a check box of all the category's. Depending on the category's that are selected it will hide them or show them. Now this was fine until i added some Drop-Down boxes. The reason for this is the template is pretty static and will only allow 3 events within any day. So i added a 'More' option if the loop returns more than 3 events that creates a Drop-Down and displays the other events in that drop box. Drop-Down Now this drop-down holds events and these events will not show when i filter! i don't understand why because the 'more button' will move up the page. Showing Filter options and whole cal,, More Is also moved up under 2 events When i select this more button nothing happens, it changes to 'Close' but no events show hell he … -
how to upload image file to mysqldb through ajax request in django without using directly form data
am trying to upload image but in table it is saving path of file of local system like:C:\fakepath\kerala-tour.png, i cant retrive the image file can anyone figure it out and help me. my code is : html page: <form enctype="multipart/form-data"> <input type="button" class="button" value="ADD HOTEL" onclick="addnewhotel()"> </form> js file: function addnewhotel() { var image=$('#imagefile').val(); ajaxsetup(); $.ajax({ type:'POST', url:'/add_hotel', data:{'image':image}, success:function (data) { $('#hotel_result').html(data); } }) } veiws.py: def add_hotel(request): if request.method == 'POST': image=request.FILES.get('image') Hotel(image=image).save() return HttpResponse('ADDED') models.py: class Hotel(models.Model): image=models.ImageField(upload_to="/media") -
Get value from model
I have 2 issues. First, I have the model with field obj_id, text, creation_date. In table it looks like: obj_id text creation_date 1 '1' 01.01.2016 1 '2' 01.02.2016 2 '3' 01.03.2016 2 '4' 01.04.2016 I need return list of 'obj_id' with MAX 'creation_date'. After that I need execute SQL select * from someModel where obj_id in (list) How I can do it using best Django practices? P.S. There aren't any relations between two models. -
Django Serializer - Create object with relations
I'm really stuck with this.. so any help would be great! I have a Django with the Django Rest Framework installed. What I'm trying to accomplish is to create and App object through the REST API, with the nested Version object and relate this to a already existing client. This is the model that I have, so you could get a better idea: class Client(models.Model): client = models.CharField(max_length=200) mail = models.CharField(max_length=200, null=True) class Keyword(models.Model): keyword = models.CharField(max_length=200) client = models.ForeignKey(Client, related_name='client_keywords',on_delete=models.CASCADE) class App(models.Model): client = models.ForeignKey(Client, related_name='client_apps', on_delete=models.CASCADE) appname = models.CharField(max_length=200, unique=True) class Version(models.Model): apps = models.ForeignKey(App, related_name='version',on_delete=models.CASCADE) version = models.CharField(max_length=20, null=True) As you can see Clients can have multiples Apps(1->N), and Apps can have multiple versions (1 -> N) I've implemented the following serializer so I can create the App object with the necessari relations but I must be doing something wrong: class AppSerializer(serializers.ModelSerializer): version = VersionSerializer(many=True) client = ClientSerializer() class Meta: model = App fields = ('pk','client',..., 'version') def create(self, validated_data): versions_data = validated_data.pop('version') clients_data = validated_data.pop('client') app = App.objects.create(**validated_data) app.client = Client.objects.get(pk=clients_data['client']) for version_data in versions_data: Version.objects.create(apps=app, **version_data) return app My idea here is to get the pk from "clients_data['client']" which i'm sending in the POST, get … -
How can I call render_option() of forms.Select in Django?
class MySelect(forms.Select): def __init__(self, *args, **kwargs): self.variations = kwargs.pop('variations') super(MySelect, self).__init__(*args, **kwargs) def render_option(self, selected_choices, option_value, option_label): return '<option whatever> {} </option>'.format(self.variations[0]) class CartItemForm(forms.ModelForm): class Meta: model = CartItem fields = ( 'variation', 'width', 'height', 'quantity', ) # widgets = { # 'variation': MySelect(variations=self.variation_query) # } def __init__(self, *args, **kwargs): product = kwargs.pop('product') try: cart = kwargs.pop('cart') self.cart = cart except: pass super().__init__(*args, **kwargs) variation_field = self.fields['variation'] variation_field.queryset = Variation.objects.filter( product=product ) variation_field.widget = MySelect(variations=variation_field.queryset) def save(self): cart_item = super().save(commit=False) cart_item.cart = self.cart cart_item.save() return cart_item But it doesn't call render_option() so it doesn't show anything in template... What's wrong with that? -
Django: NoReverseMatch at /courses/2/
Getting this error: Reverse for 'step' with arguments '()' and keyword arguments '{'course_pk': 2, 'step_pk': ''}' not found. 1 pattern(s) tried: ['courses/(?P\d+)/(?P\d+)/'] /urls.py ... url(r'^courses/', include('courses.urls', namespace='courses')), ... /courses/urls.py ... url(r'(?P<course_pk>\d+)/(?P<step_pk>\d+)/$', views.step_detail, name='step'), ... Error during template rendering: The html line generating the error is: ... <a href=" {% url 'courses:step' course_pk=step.course.pk step_pk=step_pk %} ">{{ step.title }}</a> ... courses/models.py class Course(models.Model): created_at = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=255) description = models.TextField() def __str__(self): return self.title class Step(models.Model): title = models.CharField(max_length=255) description = models.TextField() content = models.TextField(blank=True, default='') order = models.IntegerField(default=0) course = models.ForeignKey(Course) class Meta: ordering = ['order',] def __str__(self): return self.title courses/views.py def course_detail(request, pk): #course = Course.objects.get(pk=pk) course = get_object_or_404(Course, pk=pk) return render(request, "courses/course_detail.html", {"course": course}) def step_detail(request, course_pk, step_pk): step = get_object_or_404(Step, course_id=course_pk, pk=step_pk) return render(request, "courses/step_detail.html", {"step": step}) I can't seem to understand where the problem is as I'm currently new to django. Much help would be appreciated. -
custom decorator for class viewsets
I have a view set like this class NeProjectsViewSet(viewsets.ViewSet): def list(self, request,org_unique_id): ''' something ''' def create(self, request,org_unique_id): ''' something ''' def retrieve(self): ''' something ''' def update(self, request, pk): ''' something ''' def partial_update(self, request): ''' something ''' def destroy(self, request): ''' something ''' and i've a method like this def check_session(self,request): current_datetime = datetime.now() if ('last_login' in request.session): last = (current_datetime - datetime.strptime(request.session['last_login'], "%Y-%m-%d %H:%M:%S.%f")).seconds if last > base.SESSION_IDLE_TIMEOUT: del request.session['token'] raise ValueError('Session Expired') else: request.session['last_login'] = str(current_datetime) return (request.session['token'] == request.META['HTTP_AUTHORIZATION']) to validate session for every request, for that i need to call this method before every method in the viewset. I read somewhere writing custom decorator is better way, so how to implement custom decorator for my view set to check session for request -
How to get logged in username in views.py in django
Actually i'am very new to django and python. In /templates/home.html, added {{ user.username }} it's showing currently logged in username <p>Welcome {{ user.username }} !!!</p> I want to get currently logged in username in views.py file. How to get username? i tried different way but i am not get the result user = User.objects.get(username=request.user.username) username = request.GET['username'] def sample_view(request): current_user = request.user print(current_user) Please tell me, How to achieve my result.