Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a soap server to expose an api using pysimplesoap on django
I am new to django. I would like to know how to exopse my django application api as soap service to my client using pysimplesoap. Any help is appreciated. -
Django: DjangoTables - Could not parse remainder
I am having some difficulty with making a Django table and an MPLD3 graph. I am passing in a dictionary which contains a JSON representation of a Matplotlib graph and as a list of objects. There doesn't seem to be an issue with the graph, but I run into the following error: Could not parse the remainder: '{Observations}' from '{Observations}' I'm not exactly sure what the error is telling me, and other answers for similar questions haven't helped. It's a syntax error, but it's for a rule that I'm unaware of. Could somebody please explain where the issue is? Here is my views.py: Observations = [] #observations is an array of objects created and added to the database def display(request): js_data = json.dumps(mpld3.fig_to_dict(fig)) info = { "Graph": js_data, "Observations": Observations } return render_to_response('layout.html', info) Here is my template: {% load render_table from django_tables2 %} <!doctype html> <html> <head> <link rel="stylesheet" href="{{ STATIC_URL }}django_tables2/themes/paleblue/css/screen.css" /> </head> <div> graph = {{ Graph|safe }} mpld3.draw_figure("Figure", graph) </div> <div> {% render_table {Observations} %} </div> </html> -
Python Django : Saving a Version model that references other current models saved
I'm really new to Python and Python Django. I'd like to ask if there's a possibility that I create a Version model that saves the state of the other current models that it uses. For example, there are already entries in models Point and Line once I click on a save button, it should create the Version model that will contain the state of the current Point and Line data entries, name, date it was saved. Which, after saving the version, I can still modify my Point and Line. It should be able to create a lot of Versions. Not override one another. What is the best way to do this? Is this even possible? -
Django Signal or Callback from Mysql Events and Trigger
I have MySQL event running on every month and deletes the old records. While deleting the records I want to send the push notifications to the user. Is there any way we can define it in Django to receive the deleted records ids from Mysql to send push notification to the associated users? -
Does Django used the same instance of class views per request?
In django, when using class based views, it is commonplace to set class-level variables such as template_name class MyView(View): template_name = 'index.html' def get(self, request): ... I am wondering if modifying these variables during runtime class MyView(View): template_name = 'index.html' def get(self, request): if some_contrived_nonce_function(): # JUST SO IT ONLY RUNS ONCE self.template_name = 'something.html' ... will last only for that request (a new instance of MyView is created per request), or will it last for all subsequent requests (the same instance of MyView is used) -
Django: How can I store session data in unit test?
This is part of my views.py views,py . . def get(self, request, *args, **kwargs): if request.session['from_product'] = True: blah blah . . For passing this if statement, I tried to store session data in test code like this: class OrderViewFromProductWithLoginTest(OrderSetupTestCase): def setUp(self): self.login() self.client.session['from_product'] = True self.client.session.save() But it doesn't work. This is how I verified: from django.contrib.sessions.models import Session session = Session.objects.first() sessoin.get_decode() >> {'_auth_user_backend': 'django.contrib.auth.backends.ModelBackend', '_auth_user_hash': 'ffd87a41ff1e77abcbd78724f4b5b5133c67a08f', '_auth_user_id': '1'} How can I implement this? -
customization of the django admin page
#admin.py from django.contrib import admin from django.contrib.auth.models import User from django.contrib.auth.admin import UserAdmin #from django.contrib.auth.models import AbstractUser from models import UserProfile from models import country admin.site.register(country) class UserProfileAdmin(admin.ModelAdmin): #model = UserProfile can_delete = False verbose_name_plural = 'userprofile' model = Userprofile list_editable = ('country','state') list_display = ('state') #admin.site.unregister(User) admin.site.register(UserProfile,UserProfileAdmin) #models.py from django.db import models from django.conf import settings from django.utils.encoding import python_2_unicode_compatible from django.contrib.auth.models import User from django.contrib.auth import models as auth_models from django.contrib.auth.models import AbstractUser from django.db.migrations.migration import Migration class country(models.Model): #id = models.IntegerField() country_id = models.IntegerField() country_a2_code = models.CharField(max_length=255) country_a3_code = models.CharField(max_length=255) country_name = models.CharField(max_length=255) #created_date = models.DateTimeField('date published'). def __unicode__(self): return self.country_name class state(models.Model): #id= models.IntegerField() state_id = models.IntegerField() state_code = models.CharField(max_length=255) country_id = models.ForeignKey(country, blank=True, null=True) #created_date = models.DateTimeField('date published') def __unicode__(self): return self.state_code #def __str__(self): #return self.country_a3_code class UserProfile(AbstractUser): url = models.URLField() home_address = models.CharField(max_length=255,default="") phone_numer = models.CharField(max_length=255,default="") country = models.ForeignKey(country, blank=True, null=True) state = models.ForeignKey(state, blank=True, null=True) If i select the country the corresponding state should be displayed in the state field. i need to know how to do it in models to achieve that. The foreign key automatically converts into select box.. How should we extract foreign key values if i select the country … -
Django Oscarapi for Mobile endpoints
I am working on a django oscar ecommerce application. I have successfully installed the default oscar application following the documentation. I want to test the same functionality of oscar through oscarapi (for mobile endpoints) using the RESTful Api. I followed the following steps as mentioned below: Add rest_framework and oscarapi to your INSTALLED_APPS section in settings.py Add the application’s urls to your own app’s url.py: from oscarapi.app import application as api urlpatterns = patterns('', # ... all the things you allready got url(r'^api/', include(api.urls)), ) I have added the following to my settings.py: INSTALLED_APPS= [ .... 'oscarapi', 'rest_framework', 'corsheaders', ] MIDDLEWARE_CLASSES= [ 'corsheaders.middleware.Corsmiddleware', ] REST_FRAMEWORK = { 'CHARSET': 'utf-8', 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', 'rest_framework.renderers.BrowsableAPIRenderer', ) } My sample application now has url-> http://localhost:8000/api/ But I am not able to understand how to add the JSON data and integrate with the mobile app. Any help will be much appreciated! Thanks -
DRF default_manager error?
My DRF based API is throwing an error which I can't seem to resolve as its not directly linked to my code. Traceback (most recent call last): File "/opt/venv/drf_app/lib/python3.5/site-packages/django/core/handlers/exception.py", line 39, in inner response = get_response(request) File "/opt/venv/drf_app/lib/python3.5/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/opt/venv/drf_app/lib/python3.5/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/venv/drf_app/lib/python3.5/site-packages/django/views/decorators/csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/viewsets.py", line 83, in view return self.dispatch(request, *args, **kwargs) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/views.py", line 477, in dispatch response = self.handle_exception(exc) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/views.py", line 437, in handle_exception self.raise_uncaught_exception(exc) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/views.py", line 448, in raise_uncaught_exception raise exc File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/views.py", line 474, in dispatch response = handler(request, *args, **kwargs) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/mixins.py", line 40, in list queryset = self.filter_queryset(self.get_queryset()) File "/opt/venv/drf_app/lib/python3.5/site-packages/rest_framework/generics.py", line 151, in filter_queryset queryset = backend().filter_queryset(self.request, queryset, self) File "/opt/venv/drf_app/lib/python3.5/site-packages/django_filters/rest_framework/filterset.py", line 28, in __init__ super(FilterSet, self).__init__(*args, **kwargs) File "/opt/venv/drf_app/lib/python3.5/site-packages/django_filters/filterset.py", line 284, in __init__ queryset = self._meta.model._default_manager.all() AttributeError: 'NoneType' object has no attribute '_default_manager' Is the error in the rest-framework code or is it coming from elsewhere? FYI, the django admin side works okay. Below are the models and serializers am using: class ListCreateRetrieveUpdateViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.RetrieveModelMixin, mixins.UpdateModelMixin, viewsets.GenericViewSet): """ A viewset that provides `list`, `create`, `retrieve`, `update` actions. … -
Django QuerySet union throws TypeError
I am trying to populate a Django dropdown list using a QuerySet. forms class PropertyForm(forms.Form): prop1_names = Property.objects.values_list('prop1_name', flat = True).order_by('-prop_score')[:1] prop2_names = Property.objects.values_list('prop2_name', flat = True).order_by('-prop_score')[:1] props_queryset = prop1_names | prop2_names properties = forms.ModelChoiceField(queryset = props_queryset) Both 'prop1_names' and 'prop2_names' query sets are based on the same model and both columns prop1_name and prop2_name have the same data type. Error message: File "/usr/local/lib64/python3.4/site-packages/django/db/models/query.py", line 1115, in _merge_sanity_check % self.__class__.__name__ TypeError: Merging 'QuerySet' classes must involve the same values in each case. Appreciate any help. -
Django admin login redirect to two factor auth
I have a Django site where I need to implement the two factor authentication. Here is the flow that needs to be done- The user logins with username/password(which is manually created using manage.py superuser). Redirect the user to two factor auth page. Where he will have two boxes(phone number and random six digit), one to enter his phone number. Once he enters the phone number, ajax call his done to send him a SMS with a random six digit. He enters the six digit number and it takes him to the actual admin site. Currently, by default once the username/password is validated he his taken to the admin site. I need to add two factor between these two. Right now, im planning to override the admin view something like this. How to override Django admin's views? Is there a way better to accomplish this. Also, im running on Django==1.6 and can't use two factor auth app... Django-otp looks prospective but there is no good documentation for its implementation. Any inputs would be useful... -
How to set PK in Django on one hand I can set PK value in my form on the other hand if i not set it can increase auto?
I create a form to ctroll database table data,I want to add a record on the condition that I can set the PK value at the same time the PK value auto increase if not set the PK value.The model is below: class Offerlist(models.Model): id = models.AutoField(primary_key=True) ...... If I want to acheieve my expected effect how to set the PK in model? -
How to resolve Forbidden 403 error when making a urllib request with POST data in Django using Docker?
I have a three layer Django project that uses Docker. The first container is the front end and does all of the rendering, the second layer deals with logic for what to display on the front end and interacts with the database layer (third) by requesting JSON, and the third container/layer interacts directly with the database. I have a form in the front end where a user tries to sign up. However, when I make an API call to my second layer using POST and passing the form values, I keep receiving a 403 Forbidden Error. I am using a CSRF token in my form. How can I remove the 403 Forbidden Error? Some code in my views.py at the front end level: def signup(request): #more code username = form.cleaned_data["username"] #and some more fields data = {"username": username, "password":password, ... "location": location} postData = urllib.parse.urlencode(data).encode('utf-8') try: req = urllib.request.Request("url to API in 2nd layer", postData) #more code Django attempts to execute the try statement, but I am getting a 403 Forbidden Error. -
Django: Creating default value with post_save and Admin Inline
I have two objects, Product and Variation. Variation is defined as ForeignKey at product table. I want to set a default value for variation which will be used if I don't create a product object with a variation value. If a product is created with a variation value, it shouldn't use the default value. But when I run the code below, it always creates an object with using default variaton. models.py class Variation(models.Model): product = models.ForeignKey(Product) ... def product_post_saved_receiver(sender, instance, created, *args, **kwargs): product = instance variations = product.variation_set.all() if variations.count() == 0: new_var = Variation() new_var.product = product new_var.title = "Default" new_var.price = product.price new_var.save() post_save.connect(product_post_saved_receiver, sender=Product) I am trying to get this output: MacBook Pro - Default iPhone 7 - 16 GB, 32 GB Instead of that it returns this output: Macbook Pro - Default iPhone 7 - Default, 16 GB, 32 GB -
Django : How can I mock request.session of view?
I'm using mocking to test views. tests.py @patch('orders.views.OrderView.generate_merchant_uid') def test_expected_price_is_registered_on_GET_request(self, mock_generate_merchant_uid): self.client.get(reverse('orders:order')) views.py class OrderView(LoginRequiredMixin, View): def generate_merchant_uid(self): merchant_uid = "blah_blah_blah" return merchant_uid def get(self, request, *args, **kwargs): merchant_uid = self.generate_merchant_uid() request.session['merchant_uid'] = merchant_uid return HttpResponse('a') It occurs errors: TypeError: <MagicMock name='generate_merchant_uid()' id='4431843456'> is not JSON serializable It occurs error because I mocked generate_merchant_uid and it returns MagicMock and View trying to store this MagicMock in the request.session. I think what I have to do is to mock request.session. But have no idea how I can do that. Need advices. Thanks. -
System architecture : design considerations. Java vs Django vs RoR
I'd like to designing new web application with few requirements and considering which language/framework I should choose. Requirements: Web based solution (web UI and backed) Fast deployment and setup <- by this I mean just run by single command, no configuration needed for total beginner. Similar to Jenkins java -jar jenkins.war or Gerrit. Some kind of que to run tasks asynchronously. No code protection Due to the fact that I want to be simple to run and deploy (without initial configuration needed) I am considering using Java EE/Spring framework. Initially I was considering Django or RoR since deploy is pretty easy and development is way faster than Java but those frameworks need some kind of scheduling framework like Celery + some kind of broker so additional configuration is needed. I am not limited to any language,(besides PHP since I just do not like it :P) If any of you have any thoughts about my design and want to share let's do it. Thanks a lot for any kind of question/ answers. -
django multiple database: could not detect the changes in model while makemigrations
I am developing an app that need to deal with two databases and I could get the two database setup running however while makemigrations it is not detecting the changes made in the model which are not associated with default database: Here is the code snippet of what I am doing: settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': "name", 'USER': "user", 'PASSWORD': "pass", 'HOST': "", 'PORT': '', }, 'mysqlData': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name2', 'USER': 'user2', 'PASSWORD': 'pass2', 'HOST': "", "PORT": '' } } DATABASE_ROUTERS = ['router.DataRouter', ] DATABASE_APPS_MAPPING = {'mysql-data': 'mysqlData', } router.py: class DataRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'mysql-data': return 'mysqlData' return 'default' def db_for_write(self, model, **hints): if model._meta.app_label == 'mysql-data': return 'mysqlData' return 'default' def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'mysql-data' and obj2._meta.app_label == 'mysql-data': return True elif 'mysql-data' not in [obj1._meta.app_label, obj2._meta.app_label]: return True return False def allow_migrate(self, db, model): if db == 'mysqlData' or model._meta.app_label == "mysql-data": return True else: return True models.py: class data(models.Model): x = models.FloatField(default=0) y = models.FloatField(default=0) class datamysql(models.Model): x = models.FloatField(default=0) y = models.FloatField(default=0) class Meta: app_label = 'ML-data' the problem is it only detects the changes in model data which corresponds to … -
In Django, how do I move a file from a model to a directory on disk?
I have a model which stores a .exe file. I want to take that file out of the model and paste it in a specific folder without altering the model. Any ideas? The model is something like this: class Program(models.Model): program_name = models.CharField(...) program_version = models.CharField(...) program_installer = models.FileField(...) I need to be able to extract the program installer from the model, sever any connection it has with the model itself and then put a new file in the model (while keeping the older installer i a separate place). -
How to extend django auth user page in the admin site
I know how to extend the change_form.html for my app's models. For instance, I have an app called 'sales' - to modify the admin change form I have a template in [PROJECTDIR]/templates/admin/sales/customer/change_form.html and I do what I need overriding the various blocks as necessary. This works well. What I can't figure out, however, is how to modify the admin page for User objects in the same way. I've tried a variety of directory naming structures but none work: [PROJECTDIR]/templates/admin/auth/user/change_form.html [PROJECTDIR]/templates/admin/contrib/auth/user/change_form.html [PROJECTDIR]/templates/admin/django/contrib/auth/user/change_form.html [PROJECTDIR]/templates/admin/django.contrib.auth/user/change_form.html I'm likely missing something really simple, but I can't find any docs and my Google-fu is failing to find anything. -
Converting from <day> <time> to DateTime in python and Django, and back
Im trying to use strptime to convert a day and time into a DateTime field. That is, convert input like "Friday 3:00 PM" to a datetime field. The event this is for takes place over three consecutive days, so I know that Friday will be a specific day in February, and so on. My question, is how do I go about doing this? How do I convert, for example, Friday 3:00 PM into 2017-02-24 15:00:00? What I have right now in my Django project, in views.py is: new_request.start = time.strptime(form.cleaned_data['start'], '%A %I:%M %p') Then, I have to print out "Friday 3:00 PM" from the datetime field later, using strftime, which I would assume is the reverse of the above? Thanks! -
The view manager.views.Login didn't return an HttpResponse object. It returned None instead
I m using this code for a login form. But the post request aint working i m getting this error: ValueError at /home/login/ The view manager.views.Login didn't return an HttpResponse object. It returned None instead. Views.py class Login(View): form = LoginForm template_name = 'login.html' def get(self, request): form = self.form(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] auth_user = authenticate(username=username, password=password) if auth_user is not None: if auth_user.is_active: login(request, auth_user) return render(request, 'home.html') else: template_name = 'invalid_login.html' return render(request, template_name) urls.py from django.conf.urls import include, url from .views import register,home, contact, contactList, Login, Logout app_name = 'manager' urlpatterns = [ url(r'^$', home.as_view(), name='home'), #REGISTRATION url(r'^register/$', register.as_view() , name='register'), url(r'^login/$', Login.as_view() , name='login'), url(r'^logout/$', Logout , name='logout'), ] login.html <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="submit">SUBMIT</button> </form> The complete code is on Github for any further reference: GITHUB -
'ReverseManyToOneDescriptor' object has no attribute 'latest'
I have received this error when trying to run a function. This is my first django/python project so I am not experienced in this. I have searched for this error but not found anything similar. def getpriority(chunks): p = 0 for chunk in chunks: a = chunk.result_set.all() l = a.latest() if pytz.utc.localize(datetime.now()) - l.timestamp > datetime.timedelta(days=3): x = getresult(chunk) print(x) I am trying to assign priorities to my Chunk model so I can select the Chunk with the highest priority to use the object. I believe that my error is in calling latest() on 'a'. When I run Chunk.result_set.latest() in a django shell I get the following error: Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'ReverseManyToOneDescriptor' object has no attribute 'latest' In my Result model, I have set get_latest_by which I believe is required to run .latest(): class Result(models.Model): rel_chunk = models.ForeignKey(Chunk, on_delete=models.CASCADE) score = models.IntegerField() timestamp = models.DateTimeField(auto_now_add=True) class Meta: get_latest_by = 'timestamp' I believe that the error lies in the fact that I'm calling latest on a related object set but if this can't be called on a related object set then how can I find the latest related Result? -
Right django decorator
I have copied code of django decorator, and changed it for my purposes def valid_token_required(function=None): def _dec(view_func): def _view(request, *args, **kwargs): if 'token' in request.session: try: conn = server.GetTokenCon(request.session['token']) if conn.get_api_status().status == 'good': kwargs['Connection'] = conn return view_func(request, *args, **kwargs) except RateLimitExceededException as e: return HttpResponseForbidden('token_limit') except BadCredentialsException as e: return HttpResponseForbidden('badkey') return HttpResponseForbidden('require_token') _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ return _view if function is None: return _dec else: return _dec(function) All is OK, but I can't understand the sense of this lines, I have tried to delete them and code continue work. Can somebody explain the meaning of this lines? _view.__name__ = view_func.__name__ _view.__dict__ = view_func.__dict__ _view.__doc__ = view_func.__doc__ -
TypeError at /home/register/ __init__() takes 1 positional argument but 3 were given
I m trying to register the user using a registration form.When I hit the register button the user gets registered but the redirection doesn't happen instead i m getting the error: TypeError at /home/register/ __init__() takes 1 positional argument but 3 were given views.py class register(View): form_class = UserForm template_name = 'register.html' def get(self, request): form = self.form_class(None) return render(request, self.template_name, {'form': form}) def post(self, request): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user.set_password(password) user.save() auth_user = authenticate(username=username, password=password) if auth_user is not None: if auth_user.is_active: login(request, auth_user) return redirect('manager:home') return render(request, self.template_name, {'form': form}) register.html REGISTRATION <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <button type="sbumit">REGISTER</button> </form> link to the whole code: Github -
Docker Container for a Django app using uwsgi + nginx
So I am trying to get my django app to work in a Docker container. However it seems that I am not even close to success... The error, that I keep getting is: You're accessing the development server over HTTPS, but it only supports HTTP. My Dockerfile looks as follows: FROM ubuntu:14.04 # Install required packages and remove the apt packages cache when done. RUN apt-get update && apt-get install -y libldap2-dev libsasl2-dev libssl-dev RUN apt-get update && apt-get install -y \ libmysqlclient-dev \ # mysql-server \ nginx \ python-dev \ python-mysqldb \ python-setuptools \ supervisor \ vim \ && rm -rf /var/lib/apt/lists/* RUN easy_install pip RUN mkdir /app # install uwsgi now because it takes a little while RUN pip install uwsgi # setup all the configfiles RUN echo "daemon off;" >> /etc/nginx/nginx.conf RUN rm /etc/nginx/sites-enabled/default RUN ln -s /app/nginx-app.conf /etc/nginx/sites-enabled/ RUN ln -s /app/supervisor-app.conf /etc/supervisor/conf.d/ # COPY requirements.txt and RUN pip install BEFORE adding the rest of your code, this will cause Docker's caching mechanism # to prevent re-installinig (all your) dependencies when you made a change a line or two in your app. COPY requirements.txt /app/ RUN pip install -r /app/requirements.txt # add (the rest of) our …