Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Third party authentication using Django and Phonegap
In my mobile app, i need to provide signup or sign using Facebook, Twitter, and Google.I checked third-party authentication using Django but I can't be used Django template in my mobile application.Can someone please suggest how to implement this.I am quite new to both Django and PhoneGap technology -
How to run Celery Periodic task at every end of the month
Basically, I have a task to generate Invoice. So I have created a function generate_invoice() in my tasks.py file. Now, I am using @periodic_task to call the function. But I need my task will run only on the last date of the month whether it is 31st, 30th, 29th or 28th depends on the month. I am getting the last date of month using this function: def get_last_date(): today = timezone.now() year = today.year month = today.month last_date = calendar.monthrange(year, month)[1] return str(last_date) My code for task looks like this: @periodic_task(run_every=(crontab(day_of_month=get_last_date())), name="invoice_simulation", ignore_result=True) def invoice_simulation(): generate_invoice() But this is not running! -
Same test for different states of the same object without persisting changes
I am trying to run the same exact test on a single obj which is a models.Model instance and has some relations with other models. I do not want to persist changes in that instance, so effectively I want the same effect of the tearDown method which rollbacks transactions. To illustrate this: class MyTestCase(django.test.TestCase): def test(): # main test that calls the same test using all # different states of `obj` that need to be tested # different values of data that update the state of `obj` # with state I simply mean the values of `obj`'s attributes and relationships data = [state1, state2, state3] for state in data: obj = Obj.objects.get(pk=self.pk) # gets that SINGLE object from the test db # applies the state data to `obj` to change its state obj.update(state) # performs the actual test on `obj` with this particular state self._test_obj(obj) def _test_obj(self, obj): self.assertEqual(len(obj.vals), 10) self.assertLess(obj.threshold, 99) # more assert statements... This design has two problems: The changes on obj persist on the test database, so on the next iteration the data would be tainted. I would want to rollback those changes and get a fresh instance of obj as if the test method was … -
Django model method to count method flag of foreignkeys
I have two models Assessment and Answer with a OnetoMany relationship. models.py class Assessment(models.Model): name = models.CharField(max_length=255, blank=False) def __str__(self): return "{}".format(self.name) def _all_answers_completed(self: #some how get all related answers #then see if "completed" = true #if all = true then return true #if any = false then return false completed = property(_all_answers_completed) class Answer(models.Model): assessment = models.ForeignKey(Assessment, null=True, blank=True, on_delete=models.CASCADE) score_risk = models.IntegerField(default=0) score_impact = models.IntegerField(default=0) score_occurrance = models.IntegerField(default=0) def __str__(self): return "Answer to Question:{} for Assessment {}".format(self.question, self.assessment) def _is_answered(self): if self.score_risk > 0 and self.score_impact >0 and self.score_occurrance > 0: return True else: return False completed = property(_is_answered) I want to set the assessment method completed based on the related answers property answer.completed I just don't know how to do this or do I have to do this in a view via looping through a queryset. -
django creating user fixtures get CommandError: Unable to serialize Nonetype
I'm trying to create some fixtures for a test in django and trying to dump a user from the db which has a few users in it. However when I try to use dumpdata admin command I get an error: CommandError: Unable to serialize database: 'NoneType' object has no attribute '_meta' Presumably one of the users has None in one of it's fields (?) which may be causing the issue? However the error doesn't show what user or field. Is there a simpler way to generate some user fixtures? I'm using a custom user model (and also django allauth): class User(AbstractUser): MR = 'Mr' MRS = 'Mrs' MISS = 'Miss' MS = 'Ms' DR = 'Dr' SIR = 'Sir' PROF = 'Prof' REV = 'Rev' TITLE_CHOICES = ( (MR, 'Mr'), (MRS, 'Mrs'), (MISS, 'Miss'), (DR, 'Dr'), (SIR, 'Sir'), (PROF, 'Prof'), (REV, 'Rev'), ) title = models.CharField(max_length=5, null=True, choices=TITLE_CHOICES) date_of_birth = models.DateField(null=True) primary_phone = PhoneNumberField(null=True) mobile_phone = PhoneNumberField(null=True) def __str__(self): return self.username def get_absolute_url(self): return reverse('users:detail', kwargs={'username': self.username}) -
Django CMS - How to make CKEditor automatically inherit HTML content inside the Placeholder tag?
I'm using CKEditor 4.7.3. I would like to be able to inherit the HTML content that is placed within the Placeholder tag automatically into CKEditor. My HTML code looks like this: <p class="info" data-aos="fade-down"> {% placeholder "test" or %} <i class="fa fa-circle-o" aria-hidden="true"></i> <span class="text-uppercase">Test:</span> Vestibulum tortor quam, feugiat vitae.{% endplaceholder %}</p> Currently Django CMS creates a 'Test' placeholder instance in Structure mode and when I add a 'Text' plugin to it I have to paste all HTML content manually to make it look like original site. Is there a way to make CKEditor automatically inherit the HTML content? -
Django custom decorator - function has no attribute get
I'm trying to create my own decorator based on @cache_page decorator. My decorator should work exactly like @cache_page except when slug attribute of the view matches request.user.userprofile slug, then normally process the view and return not cached response Pseudocode: def profile(request,slug): # if not request.user = User.objects.get(userprofile__slug=slug): # return cache # else compute response and return it My decorator: def exclude_cache_for_request_user(*args, **kwargs): def exclude_cache_for_request_user_decorator(func): def func_wrapper(*fargs,**fkwargs): request = fargs[0] if request: user = getattr(request,'user',None) owner_slug = fkwargs.get('slug') owner = User.objects.get(userprofile__slug=owner_slug) if user==owner: return func(*fargs, **fkwargs) else: if len(args) != 1 or callable(args[0]): raise TypeError("cache_page has a single mandatory positional argument: timeout") cache_timeout = args[0] cache_alias = kwargs.pop('cache', None) key_prefix = kwargs.pop('key_prefix', None) if kwargs: raise TypeError("cache_page has two optional keyword arguments: cache and key_prefix") return decorator_from_middleware_with_args(CacheMiddleware)( cache_timeout=cache_timeout, cache_alias=cache_alias, key_prefix=key_prefix ) return func_wrapper return exclude_cache_for_request_user_decorator This works if user matches the slug. Otherwise, it raises: Exception Value: 'function' object has no attribute 'get' Full traceback: File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/utils/deprecation.py" in __call__ 142. response = self.process_response(request, response) File "/home/milano/.virtualenvs/beduenovenv/local/lib/python2.7/site-packages/django/middleware/clickjacking.py" in process_response 32. if response.get('X-Frame-Options') is not None: Exception Type: AttributeError at /profiles/detail/cingo/ Exception Value: 'function' object has no attribute 'get' Do you know where is the … -
Django URL invalid literal for int() with base 10
I have a Location model setup in Django and I originally set it up so that the URL was /location/3/ using the primary key. but the client want to change it to use a slug of the location name. I created a slug field in the model. And changed the URL pattern in urls.py. urlpatterns = [ url(r'^(?P<pk>[\w-]+)/$', views.LocationsSingleView.as_view(), name='detail'), ] I can link to them fine. But when it tries to actually load that page I get an error: invalid literal for int() with base 10: 'eau-claire' Where eau-claire is the slug for that Location. Documentation doesn't say anything about this. A lot of people with this issue have issues with their view. But my view is super simple. So I don't know what's wrong. Here is my view: class LocationsSingleView(DetailView): model = models.Location -
How to save button value to databse in django?
I'm trying to create my first django app - sports predictions game. I want user to select from three possible results using 3 buttons (images) which pass 3 different values to the db: 1 - home team wins 0 - draw 2 - away team wins I am able to save data using forms when I type something into it, but how do I pass value of these buttons to my database? code on my game.html: {% csrf_token %} {{ form }} <input type="submit" value = 1> <input type="submit" value = 0> <input type="submit" value = 2> </form> and my view: def game(request, Game_id): thisgame = get_object_or_404(Game, pk=Game_id) nextgame = int(thisgame.id)+1 template = loader.get_template('polls/game.html') form = NewBetForm(request.POST or None) current_user = request.user allgames = Game.objects.all() betchoices = BetChoice.objects.all() context = { 'thisgame': thisgame, 'nextgame': nextgame, 'form': form, 'current_user': current_user, 'betchoices': betchoices,} if form.is_valid(): bet = form.save(commit=False) bet.gameid = Game.objects.get(id=Game_id) bet.userid_id = current_user.id bet.save() else: print (form.errors) and my form: class NewBetForm(forms.ModelForm): class Meta: model = GameBet fields = ['bet'] and the error I get is Bet - this field is required Thank you for all ideas! -
Can I use neomodel with Django's authentication system?
I want to use neomodel in my Django project. So I've created a simple User model like this to store users: class User(DjangoNode): uid = UniqueIdProperty() username = StringProperty(unique_index=True, required=True, label="Username") password = StringProperty(label="Password", required=True) name = StringProperty(label="Name", required=True) class Meta: app_label = "myapp" Now I need to authenticate the users. Can I use the standard Django's auth app for this or it only works with Django models? -
Django don't redirect to a external url
I have this view where I execute a redirect to an external site: def redpagopa(request): if request: return redirect('http://www.google.com/') else: return render_to_response('404.html') .... call=redpagopa(urlpa) # call of the redirect function, redirect doesn't work where urlpa is the url passed to the function redpagopa..in this code I explicited the address for example google. But the redirect doens't work. If I create an url entry in urls.py: url(r'^redpagopa/$', 'mopa.views.redpagopa', name='redpagopa') and in the browser I give the address: http://example.com/redpagopa the redirect works. I need when redirect is called, the browser be redirect on the specified url. There is some error in my code? I use Django v1.3, version mandatory. -
Authentication of different types of user of same name in django?
I have a model of teacher and student . If I created a Student and again create a teacher with same name and email and stuffs, It gets created .. Can't be a teacher and student of same people in a college. How to apply in rest api? -
Inplace edit form with Django + Bootstrap
Can someone guide me how can I create inplace edit forms for my table the easiest way? I have table with a lot of data. I want to edit that data directly from the table view just clicking on a row. I tried x-editable but it's not working with Bootstrap v4. -
why i am not able to view with classbased (list view )but for function based view it is working fine?
My question: why i am not able to view search only ayan rand's book with classbased list view? this is my function based view for store list, and i am retrieving all my book objects and rendering in HTML and it is working fine. But using classbasedview "SearchBookDetail" i am not able to get the specified book details as denoted . Views.py: from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse,HttpResponseRedirect from django.views.generic import TemplateView,ListView,DetailView def store_listView(request,): queryset=Book.objects.all() context={ "objects_list":queryset } return render(request,'bookstores/store.html',context) class SearchBookDetail(ListView): template_name = "bookstores/store.html" queryset = Book.objects.filter(author__icontains='Ayan Rand') print("Ayan Rand query set", queryset) Urls.py: from django.conf.urls import url from django.contrib import admin from django.views.generic import TemplateView from store.views import (Home,ContactView,LoginView, store_listView, SearchBookDetail, book_createview, QuoteslistView, AyanRandBookDetail, quotesFunctionView) urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$',Home.as_view()), url(r'^contact/$',ContactView.as_view()), url(r'^login/$',LoginView.as_view()), url(r'^store/$',store_listView), url(r'^store/AyanRandBookDetail/$',AyanRandBookDetail.as_view()), url(r'^store/SearchBookDetail/$',SearchBookDetail.as_view()), url(r'^quotes/$',quotesFunctionView)] -
I don't understand the meaning of "create new view as a subclass"?
DRF REST AUTH DOC <- I'm following Facebook social login implementation (Step 3 and 4) I'm building Social Login with django-rest-auth, and I can't follow this simple step. It says Create new view as a subclass of rest_auth.registration.views.SocialLoginView with FacebookOAuth2Adapter adapter as an attribute: And what does subclass mean????? I put FacebookLogin view in [project-name]/urls.py and it seems right. But I put these lines of example code as shonw below in [project-name]/views.py and the social login doesn't work. from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from rest_auth.registration.views import SocialLoginView class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter -
Django @cache_page based on condition
Can I specify a condition for cache_page decorator? I use @cache_page to cache userprofile detail page. The problem is that there is a different HTML for user about who is this detail page and for visitors. The particular user can update their profile picture etc. which visitors can't. if "peter" visits /userprofile/peter/ - he can change his profile picture if "andre" visits /userprofile/peter/ - it's readonly for him, so he can't change profile picture etc. If I use cache_page and the user "peter" is the first person who visited the page, it is cached, and another users/visitors like "andre" see this page like it was their profile. Can I cache for "peter", so owner==request.user and anybody else differently? @cache_page(1*60) @login_required def profile(request, slug): owner = User.objects.filter(userprofile__slug=slug).first() profile_picture_update_form = UserProfileUpdateProfilePictureForm(request.POST or None, request.FILES or None) return render(request, 'profiles/profile/profile.html',context={'owner': owner, 'profile_picture_update_form': profile_picture_update_form} ) EDIT: Moving @cache_page to URLConf won't help since it's the same url for user and for visitors. -
Django way to "Pre-cache" an existing database table?
I have a 200MB sized csv file containing rows where a key term is matched against a list of strings inside the second column. term_x | ["term_1","term_2"] term_y | ["term_1","term_2"] term_z | ["term_1","term_2"] My Django app is not configured to use any complex memory caching (Redis, Memcached) and in practice, I want to pass a term into the database table to retrieve the corresponding list value. Due to its size however, retrieving the list from the correct row takes around half a second to do, on top of other actions being performed while loading the page. Is it possible in Django to "pre-cache" this table upon server startup? i.e. add all of those values to the cache with the first column being the key? I have attempted something similar by overriding the "ready" method in my app.py to load the database table into the cache on startup, but I get null values when I try to use a term I know is in the table: print("Loading RS Lookup cache..."), #setup database connection.... cache_df = pd.read_sql_query("Select * from table_to_cache", engine) print("Table loaded") for index, row in cache_df.iterrows(): cache.set(row['term'], row['list_of_terms'], None) print("RS Table loaded") -
Django Rest Framework IsAuthenticated permission Error Anonymous user
I'm writing api using django rest framework using Token Authentication method written as below @api_view(['GET']) @permission_classes((IsAuthenticated, )) def ah(request, format=None): result = request.user.is_authenticated() content = {"hello":result} return Response(content) my settings are REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.IsAdminUser', 'rest_framework.permissions.IsAuthenticated', ], 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', #'rest_framework.authentication.BasicAuthentication', #'rest_framework.authentication.SessionAuthentication' ) } MIDDLEWARE_CLASSES = [ 'django.contrib.sessions.middleware.SessionMiddleware', #'middleware.FirstTokenAuth.AuthenticationMiddlewareJWT', #'middleware.TokenAuthTest.JWTAuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.security.SecurityMiddleware', #'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', #'django.middleware.csrf.CsrfViewMiddleware', #'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] When I call this API using IsAdminUserpermission class The django restframework returns: 403 response "detail": "Authentication credentials were not provided." if the token wasn't provided in the header 401 response "detail": "You do not have permission to perform this action." if the token was not for admin user but the main problem is here when I set @permission_classes((IsAuthenticated, )) The API is called normally without returning 403 or 401 even if i didn't add a token to the header and the user returned is anonymous user. How can I prevent anonymous user from calling API and return 403 response for him. Any help Please !! -
Django Allow current user to some if some other user is also online/logged in
I'm trying to figure out how to check if some other user is logged in. I'm able to check if the current user is logged in with request.user.is_authenticated(), however, I want my current user to be able to see all other users of the site that are also logged in at the same time. How can this be done? -
Pycharm and Django TypeError for request.GET[value]
This is more of an annoyance than a real problem, but when using the following code: if request.method == "GET": device_id = request.GET['id'] The request.GET has the following error: Class 'type' does not define 'getitem', so the '[]' operator cannot be used on it's instance. A really great description of the problem (although in a different situation) can be found here: Pycharm: Type hint list of items I am simply trying to get rid of the PEP errors in PyCharm without disabling them. Any thoughts on how to change the above code? Thanks! -
How to use Django ORM in Wagtail when querying outside of Page context?
I am using Wagtail with another cart application. They are using the same DB. By now I have been using def get_context(self, request): context = super(HomePage, self).get_context(request) blogs = Blogs.objects.all() context['blogs'] = blogs return context However, now I need data that is outside the context of the page and I am using a custom query e.g. def my_custom_sql(): with connection.cursor() as cursor: cursor.execute("SELECT * FROM product_product") row = cursor.fetchone() return row Is there a way to use the ORM instead and get a QuerySet? In other words I want to query the DB from all the page methods with the ORM agnostic of the context that I am in. -
uwsgi deploy django failed to open python file blog/wsgi.py
when i use uwsgi deploy my django application,occur this error your server socket listen backlog is limited to 100 connections your mercy for graceful operations on workers is 60 seconds mapped 71400 bytes (69 KB) for 2 cores *** Operational MODE: threaded *** failed to open python file blog/wsgi.py unable to load app 0 (mountpoint='') (callable not found or import error) *** no app loaded. going in full dynamic mode *** *** uWSGI is running in multiple interpreter mode *** spawned uWSGI worker 1 (and the only) (pid: 2040, cores: 2) (py3env) [root@host blog]# pwd /yuyang/djangoblog/djangblog/blog (py3env) [root@host blog]# ls celery.py __init__.py mywsgi.ini __pycache__ settings.py urls.pywsgi.py(py3env) -
Django-Sphinx RuntimeError: Model class models.Project doesn't declare
I am attempting to generate a html documentation with Sphinx of a django project. I am getting the following error when executing make html on windows cmd. > C:\django_project\docs\source\models.rst:4: WARNING: autodoc: failed to > import module 'models'; the following exception was raised: Traceback > (most recent call last): File > "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\sphinx\ext\autodoc.py", > line 658, in import_object > __import__(self.modname) File "C:\django_project\project_name\models.py", line 8, in <module> > class Project(models.Model): File "C:\Users\...\AppData\Local\Continuum\Anaconda3\lib\site-packages\django\db\models\base.py", > line 118, in __new__ > "INSTALLED_APPS." % (module, name) RuntimeError: Model class models.Project doesn't declare an explicit app_label and isn't in an > application in INSTALLED_APPS. Thanks for your help! -
How import a function from another view with Django?
I have this folder hierarchy: |---- saga |---- core |---- views.py |---- study_time |---- views.py On my study_time/views.py, I have this functions: def study_time(request): def tasks_subjects(week_day, key): #Code here return __tasks def day_studies(week_day): __tasks_subjects = tasks_subjects(week_day, 0) #Code here return __studies return render(request, 'study_time.html', context) On my study_time/views.py, I need the day_studies() function, so I'm importing like this: from saga.study_time.views import day_studies def home(request): day_progress = day_studies(datetime.date.today().isoweekday()) But I'm getting the error: ImportError: cannot import name 'day_studies' How can I make this importation? I don't want to reply all code. -
How to change the Column Names of a database created by Django (from models.py)?
So I have a MySQL Database in my local PHPMyAdmin with DBs and Tables already filled in with data. I have to now port that DB into django. For example, the name of a table in the DB is "ratings". So using django, I have to first create an app named something (let's say "website") and then I can add the model ratings to that app. This creates a table "website_ratings" in the DB. Which is not what I want, I want the name of the table to be just ratings. Is there any way to get this done?