Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django SiteTree: menu renders but breadcrumbs doesn't when variable is in url
I am using django==1.11 and django-sitetree==1.9.0, all links without url variables render both on menu and breadcrumbs but urls with variables only render on menu(with correct links) and not on breadcrumbs. Title: {{ object.title }} URL: products:detail object.slug object.pk URL as Pattern: Checked url(r'^products/(?P<slug>[-\w\d]+)~(?P<pk>\d+)/$', views.ProductDetailView.as_view(), name='products:detail) {% sitetree_breadcrumbs from "main-menu" template "sitetree/breadcrumbs_semantic.html" %} -
User Edit Profile Form won't edit all fields,Django
I have created a registration form using django's usercreation form. And have then created a EditProfileForm using the registration form. My Issue is that EditProfileForm uses User Model,and Birthdate field is in Profile Model,so I am able to edit all fields except Birthdate as it is not from the user model. How do I go about editing birthdate,or creating a form where I can edit all fields instead of only the user fields? My Model for Profile class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.PROTECT) def __str__(self): return self.user.username; USWEST = 'usw' USEAST = 'use' EUROPE = 'eu' OCEANIA = 'oce' ASIA = 'as' SOUTHAMERICA = 'sam' SOUTHAFRICA = 'saf' MIDDLEEAST = 'me' PREF_SERVER_CHOICES = ( (USWEST, 'US-West'), (USEAST, 'US-East'), (EUROPE, 'Europe'), (OCEANIA, 'Oceania'), (ASIA, 'Asia'), (SOUTHAMERICA, 'South America'), (SOUTHAFRICA, 'South Africa'), (MIDDLEEAST, 'Middle-East'), ) pref_server = models.CharField( max_length=3, choices=PREF_SERVER_CHOICES, default=USWEST, ) birth_date = models.DateField(null=True, blank=False,) sessions_played = models.IntegerField(null=False, blank=False, default='0',) teamwork_commends = models.IntegerField(null=False, blank=False, default='0',) communication_commends = models.IntegerField(null=False, blank=False, default='0',) skill_commends = models.IntegerField(null=False, blank=False, default='0',) positivity_commends = models.IntegerField(null=False, blank=False, default='0',) FORMS.PY from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from apps.api.models import Profile, Feedback from django.forms import ModelForm #form to create profile #RegistrationForm VIEW must be … -
Getting value error in django
this is my file on git I am trying to render flight from my database to HTML ,but unable to do so and getting an error ValueError at / invalid literal for int() with base 10: 'Mohani' Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.0.3 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'Mohani' Exception Location: C:\Users\RAVI SHANKAR SINGH\Python\lib\site-packages\django\db\models\fields\__init__.py in get_prep_value, line 947 Python Executable: C:\Users\RAVI SHANKAR SINGH\Python\python.exe Python Version: 3.6.4 Python Path: ['X:\\Virtual\\Django\\airline', 'C:\\Users\\RAVI SHANKAR SINGH\\Python\\python36.zip', 'C:\\Users\\RAVI SHANKAR SINGH\\Python\\DLLs', 'C:\\Users\\RAVI SHANKAR SINGH\\Python\\lib', 'C:\\Users\\RAVI SHANKAR SINGH\\Python', 'C:\\Users\\RAVI SHANKAR SINGH\\Python\\lib\\site-packages'] Server time: Wed, 4 Apr 2018 16:21:54 +0 I tried to find in file That Mohani error could not find in any file even init.py is empty. I am new Kindly guide me -
Django manytomany m2m_changed script works, but how?
I have a model: class Course(models.Model): class Meta: ordering = ['completion_order'] degree = models.ForeignKey(Degree, on_delete=models.CASCADE) name = models.CharField(max_length=30, null=False, blank=False) completion_order = models.PositiveSmallIntegerField(default=0,null=False, blank=False) required = models.ManyToManyField('Task', default=1, blank=True, symmetrical=False) And I have written a function to run on "m2m_changed" to automatically adjust the completion order to take into account any changes in prerequisites: def required_changed(sender, instance, **kwargs): degreecourses = Courses.objects.all().filter(degree=instance.degree) for zcr in degreecourses: #resets the order for the all the degree's course instances zcr.completion_order = 0 for cr in degreecourses: #assigns new completion_order values if cr.required.count() is 0: # if no requirements sets 'completion_order' to 1 cr.completion_order = 1 else: #sets 'completion_order' to the increment of the highest (max) value of this courses's required course mx = cr.required.all().aggregate(Max('completion_order')) neworder = mx['completion_order__max'] + 1 cr.completion_order = neworder cr.save() This is run after any change in the m2m thus: m2m_changed.connect(required_changed, sender=Course.required.through) I originally set this up iterating through multiple times, but then realised it was unnecessary -my (novice) question is: Can someone explain how this is able to resolve all of the "required" values in one pass, i.e. without having to iterate through the second loop multiple times? I'm guessing it's to do with python being object oriented - but … -
django queryset method on related model filter
I have the following set-up: class Person(models.Model): name class AppointmentQuerySet(models.QuerySet): def active(self): from datetime import datetime return self.filter(initial_date__date__lte=timezone.now().date()) class Appointment(models.Model): initial_date = models.DateTimeField() person = models.ForeignKey(Person, related_name='appointments', blank=True, null=True) objects = AppointmentQuerySet.as_manager() def active(self): from datetime import datetime return self.initial_date <= timezone.now().date() I fired up the shell to try some queries and created: 1 person with no appointments 2 person with 1 active appointment each and tried this: Person.objects.filter(appointments=True) # At some point yesterday, this was giving me results, # now it's returning an empty queryset this works as I thought it would: Person.objects.filter(appointments_isnull=False) # returns the 2 persons with appointments but # I have no clue from here if the appointments are active or not If I try Person.objects.filter(appointments__active=True), I get: FieldError: Related Field got invalid lookup: appointments If instead, I try Person.objects.filter(appointments.active()=True), I get: SyntaxError: keyword can't be an expression How can I filter from Person.objects.filter(appointments=?) the active appointments each person has? -
Validate csv file submitted with Django form without loading into memory
I'm building a django app that will let people upload CSVs that will be stored in S3 (based on django-storages) then processed by celery tasks which will then ingest them into the database. These CSVs can be any size, from a few rows (where Django would store it as a InMemoryUploadedFile) to hundreds of megabytes (where django would use aTemporaryUploadedFile.) I'm using a simple ModelForm on a generic CreateView, but I want to add a way to check the first row in the file (the header) to validate that the CSV has all the columns I need. This would be pretty simple if I knew the path of the file. I'd just use python's standard file and csv handling functionality to read the first line into the csv module and check the fields. But how do I do that using an uploaded file where it may be in memory or it may be a temporary file, inside the modelform? Without loading the file into memory? -
Jsonify an array of django object
Here is my actual code : def getObject(obj): data = serializers.serialize('json', [obj,]) struct = json.loads(data) data = json.dumps(struct[0]) return data result = [] i = 0 for data in c : try : i = Item.objects.get(barcode=data) result.append(getObject(i)) i = i + 1 except : pass print(i) import json with open('data.json', 'w') as outfile: json.dump(result, outfile) The problem is that at the end i have a jsonify array of stringified json django object. If you have any idea Thanks -
Cache in only in Django (as database caching) and not in browser
I've tried a lot of things, and they all failed. My Django (2.0) website has some pages which take a lot of time to generate. I want to keep this pages in the database cache of the Django server until the database changed. My goal: Have pages ready in database cache Serve users the cached pages Don't save these pages as cache in the browser (the browser can't know if the page needs to be re-generated) Keep .js files etc as cache in browser Don't use browser cache when using the browser 'back' button to go back to the calculation heavy page The closest I got was to enable database caching, enabled per-site caching, and using cache.clear() on receiving post_save and post_delete signals. But still, if I pressed 'back' in my browser, the local cache was used (so no request was send to the server). I tried to fix this by adding @never_cache to the view, but this also prevented caching in the middleware... -
Apps not ready yet, upgrading to Django 1.9 and then to 2.0
I am trying to upgrade my Django project to Django 2.0, currently the version is 1.8.19. I figured I would do it step by step, firstly upgrading to 1.9, then 1.10 and so on till 2.0. The problem is that I get error message Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line utility.execute() File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 302, in execute settings.INSTALLED_APPS File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/conf/__init__.py", line 55, in __getattr__ self._setup(name) File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/conf/__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/conf/__init__.py", line 99, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/home/riddle/tmp1/example-project/env/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/riddle/tmp1/example-project/app/ad_akumuliatoriai_lt/settings.py", line 140, in <module> from apps.frontend.ad_akumuliatoriai.models import Language File "/home/riddle/tmp1/example-project/app/apps/frontend/ad_akumuliatoriai/models.py", line 5, in <module> from ordered_model.models import OrderedModel File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/ordered_model/models.py", line 20, in <module> class OrderedModelBase(models.Model): File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/db/models/base.py", line 94, in __new__ app_config = apps.get_containing_app_config(module) File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/apps/registry.py", line 239, in get_containing_app_config self.check_apps_ready() File "/home/riddle/tmp1/example-project/env/lib/python3.6/site-packages/django/apps/registry.py", line 124, in check_apps_ready raise AppRegistryNotReady("Apps aren't … -
injecting code inside of code python django and q objects
This question gets me close to what I want to do but I am still in need of further understanding. Django. Q objects dynamicaly generate I have a view in django that looks to see if any query params have been sent to the url. I am expecting some query objects to have multipule values. ie. domain.com/?neighborhood=Logan Square&neighborhood=River North I grab queryparams and put them in a list. I am now trying to iterate through that list and filter through the query params using or logic. https://docs.djangoproject.com/en/1.11/topics/db/queries/#complex-lookups-with-q for this I know I need to use Q objects. the proper code for this is: Q(neighborhood='Logan Square') | Q(neighborhood='River North') so what I need to do is 1 adding a query Q object dynamically and then also adding the | operator dynamically for all objects in the for loop. -
Django queryset: Exclude all row(s) if any one row with same id is excluded
I am using Django query to filter out some transactions from table where one transaction might have multiple entries in the table. E.g. Sample table +---------------+---------+ | TransactionId | Status | +---------------+---------+ | Txn0 | Pending | | Txn0 | Success | | Txn1 | Fail | | Txn2 | Pending | | Txn3 | Fail | | Txn4 | Pending | | Txn4 | Fail | | Txn5 | Pending | +---------------+---------+ Current query : SampleTable.objects.exclude(status='Fail').exclude(status='Success') My current query returns Txn0, Txn2,Txn4, Txn5( because these are marked pending). I need a queryset which return only row Txn2, Txn5( because all other transaction has atleast one Fail or Success transaction). Also, tried using .distinct() but that didn't help. -
Django fixtures many to many natural keys
I'm writing some additional fixtures for a project, and I have a question about how to use the natural keys. In another fixture, the natural key for area is defined like so: "fields": { "area": [ "auckland", "NZ" ], However, I'm writing a fixture for a model with a ManyToMany relation, so how do I include multiple two object keys? the following doesn't seem to work. "fields": { "areas": [ "auckland", "NZ", "sydney", "AUS" ], -
django formsets & jquery : execute jquery on added formsets
Let's say I have the following formset. {% for form in formset %} <tr style="border:1px solid black;" id="{{ form.prefix }}-row" class="dynamic-form" > <td{% if forloop.first %} class="" {% endif %}></td> {% render_field form.choicefield1 class="form-control" %}{{form.typeTiers.errors}} </td> <td> {% render_field form.choicefield2 class="form-control" %}{{form.tiers1.errors}} </td> <td>{% render_field form.choicefield3 class="form-control" %}{{form.numfacture1.errors}} </td> </tr> {% endfor %} <td><input type="submit" name="ajoutligne" value="Ajouter une ligne" class="btn btn-primary" id="add-row" style="background-color: #8C1944; border-color: #8C1944; float:right;margin: 5px;" onclick="test()"></td></tr> the forms are added using dynamic-formset.js , which I call in the code bellow to create a new form when clicking on my button : $(function () { $('#add-row').click(function() { addForm(this, 'form'); }); }) and I need to applay jquery function on every row I add in my formset. That's why I created the function test called in onclickfunction: var jax= -1; function test(){ jax =jax+1; alert("hello"); alert($('#id_form-'+jax+'-typeTiers').attr('name')); //for(var i=0;i<) $("#id_form-"+jax+"-typeTiers").change(function () { alert($('#id_form-'+jax+'-typeTiers').attr('name')); x="<option>5</option>"; y="<option>0</option>"; $("#id_form-"+jax+"-tiers").html(x); $("#id_form-"+jax+"-numfacture").html(y); }); } what I need is to make my rows independent of each other, so if I change the field1 in my first row, only the second field in the same row changes, without affecting the other rows. however I have two problems : The first : when I load the page in … -
Django: How to override methods
In my Django app I have to override methods sometimes. My question is if there is something like a "best practice" in how to override a method. Example: In my project I have the following class. class AuthorCreate(CreateView): model = Author form_class = AuthorForm template_name = 'app/create_author.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.creator = self.request.user self.object.save() return super().form_valid(form) So here I have overridden the form_valid() method. It works and I think it's correct. However, is that good practice or not, e.g. I see something like this often: def overridden_method(self, *args, **kwargs): #Some logic here pass So, should have I done it this way? def form_valid(self, form, *args, **kwargs): self.object = form.save(commit=False) self.object.creator = self.request.user self.object.save() return super().form_valid(form) So my question is basically WHEN I should use WHICH "template" for overriding methods or WHEN not to use some specific form. I'd be glad about some detailed/explained best practices. Thanks a lot! -
How should I understand below codes in Django?
1. define a class in the models.py which was created in my own app. class Article(models.Model): headline = models.CharField(null=True,blank=True,max_length=200) content = models.TextField() def __str__(self): return self.headline 2. define a function in views.py from firstapp.models import People,Article def index(request): article_list = Article.objects.all() context = {} context['article_list'] = article_list index_page = render(request, 'first_web_2.html', context) return index_page The question is: how to is the article_list a list?how should I understand "context['article_list'] = article_list"? -
Django 2.0 - Not a valid view function or pattern name (Customizing Auth views)
I´m working on a course exercise and I'm stuck for a few hours and I'm not sure what is causing the app to break, next, you will find the files involved and perhaps you can find out the solution. Thanks for your help! Project structure This error is being thrown when I log in: Internal Server Error: /account/login/ ... django.urls.exceptions.NoReverseMatch: Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. [04/Apr/2018 17:12:15] "POST /account/login/ HTTP/1.1" 500 151978 At the end of the settings.py file from django.urls import reverse_lazy LOGIN_REDIRECT_URL = reverse_lazy('dashboard') LOGIN_URL = reverse_lazy('login') LOGOUT_REDIRECT_URL = reverse_lazy('logout') The urls.py file from django.contrib.auth import views as auth_views from django.urls import path from . import views app_name = 'account' urlpatterns = [ # path('login/', views.user_login, name='login'), path('', views.dashboard, name='dashboard'), # login / logout urls path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='registration/logged_out.html'), name='logout'), path('logout-then-login/', auth_views.logout_then_login, name='logout_then_login'), ] The views.py file from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.shortcuts import render @login_required def dashboard(request): return render(request, 'account/dashboard.html', {'section': 'dashboard'}) The base.html template {% load staticfiles %} <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>{% … -
email authentification doesn't work using django-allauth
I installed django-allauth and set it up to use it for the internet registration and authentication backend in order to have an email confirmation at registration and sign up the users using their email instead of their username. What is happening is that the registration works perfectly, the authentication using the email doesn't work whereas it's working with the username. I got the following error: The e-mail address and/or password you specified are not correct. Here my current configuration: Django-allauth: 0.35.0 Django: 1.11 Python: 3.6.4 mysql: 15.1 # settings.py SITE_ID = 1 DJANGO_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.sites', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] THIRD_PARTY_APPS = [ 'allauth', 'allauth.account', 'allauth.socialaccount', ] AUTHENTIFICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] LOGIN_REDIRECT_URL = 'main:home' LOGOUT_REDIRECT_URL = 'main:home' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(APPS_DIR, 'templates'), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.media', 'django.template.context_processors.i18n', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_CONFIRM_EMAIL_ON_GET = True # url.py urlpatterns = [ # Django admin url(settings.ADMIN_URL, admin.site.urls), url(r'', include('main.urls')), url(r'^accounts/', include('allauth.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I hope I gave all the useful information. I wonder if … -
How to make a file export in a Django FormView?
I'm strugling with overriding the right methods in a Django CBV FormView. The purpose is a to have a view with a simple form, and use the data of this form to generate an Excel export, and make the user download it. Here is what I have so far: class FinancesReportsView(PermissionRequiredCanHandleFinancialReports, FormMessagesMixin, FormView): form_class = DateRangeForm form_valid_message = MSG_EXPORT_OK form_invalid_message = MSG_EXPORT_KO template_name = 'finances/financial_exports.html' success_url = reverse_lazy('bo:financial-reports') def form_valid(self, form): start = form.cleaned_data['start'] end = form.cleaned_data['end'] # Create Excel filename = 'report.xlsx' workbook = xlsxwriter.Workbook(filename) worksheet = workbook.add_worksheet() worksheet.write('A1', start) worksheet.write('A2', end) workbook.close() # Response Headers XLSX_CONTENT_TYPE = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" CONTENT_DISPOSITION = f'attachment; filename="{filename}"' response = HttpResponse(content_type=XLSX_CONTENT_TYPE) response['Content-Disposition'] = CONTENT_DISPOSITION return super().form_valid(form) This obviously does not work, because the return of super().valid_form will bypass the response modifications made earlier. Should I override another method? Any simple code sample would be very appreciated. Thanks. -
django.urls.exceptions.NoReverseMatch for username but arguments are there.
i'm getting a no reverse match error however from what i can tell, all the necessary things are there. I have the url which has the username argument which is being given from the html and is being saved into the model and expressed through the view. im a still a django novice. all help is appreciated. file structure usertest - root -->accounts - appname -->questions - appname -->urls.py -->views.py -->model.py templates -->base.html urls.py url(r'by/(?P<username>[-\w]+)/$', views.UserQuestions.as_view(), name="for_user"), base.html <li><a href="{% url 'questions:for_user' username=question.user.username %}" class="glyphicon glyphicon-user"></a></li> model.py class Question(models.Model): class Meta: ordering = ['-date_updated'] user = models.ForeignKey(User, related_name="questions") question = models.TextField(blank=False, null=False) # unique=True, question_html = models.TextField(blank=False, null=False) answer = models.TextField(blank=False, null=False) answer_html = models.TextField(blank=False, null=False) date_created = models.DateTimeField(auto_now=True, null=True) date_updated = models.DateTimeField(auto_now=True, null=True) slug = models.SlugField(unique=True, default='') tags = TaggableManager() def __str__(self): return self.question # ^ to display an object in the Django admin site and # as the value inserted into a template when it displays an object. def save(self, *args, **kwargs): self.question_html = misaka.html(self.question) self.answer_html = misaka.html(self.answer) super().save(*args, **kwargs) def get_absolute_url(self): return reverse( "questions:detail", kwargs={ "slug": self.slug, "pk": self.pk, "username": self.user.username, } ) views.py class UserQuestions(generic.ListView): model = models.Question template_name = "questions/user_question_list.html" def get_queryset(self): try: self.question_user = … -
How to send images from Unity to Django through Json type
I want an image request between Django and Unity. So, I want to send the image data to Json type using UnityWebRequest. The source code below is Unity C # code. public void onClickSendButton(){ coroutine = ServerThrows(); StartCoroutine(coroutine); } IEnumerator ServerThrows() { string imageAsJson = File.ReadAllText(imagePath); byte[] bodyRaw = System.Text.Encoding.UTF8.GetBytes(imageAsJson); UnityWebRequest www = new UnityWebRequest(url, "POST"); www.uploadHandler = (UploadHandler) new UploadHandlerRaw(bodyRaw); www.downloadHandler = (DownloadHandler) new DownloadHandlerBuffer(); www.chunkedTransfer = false; www.SetRequestHeader("Content-Type","application/json"); yield return www.SendWebRequest(); if(www.isNetworkError||www.isHttpError){ Debug.Log(www.error); } else { GetResponse(www); } } Here is the Django Server Code: def fromunity(request): data = json.loads(request.body.decode('utf-8')) print(data) print(request.content_type) return HttpResponse() In Unity, when I send a request through onClickSendButton, Django Server shows the following results: enter image description here (json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)) Depending on the Django Server results above, what should I do? -
Django read 3 variables at once from list
Im doing the following right now: {% for user in user_list %} <div class="row"> <div class="col align-self-center"> <form> <button class="btn btn-outline-primary btn-sm btn-block" formaction="{% url 'interface:data' user.id %}">{{user.id}}</button> </form> </div> </div> {% endfor %} This generates a row with a single column. I would like to generate 3 columns per row, so I need to read 3 variables at once from that list. How can I do that? I need something like this: for user1,user2,user3 in user_list new row col for user1 col for user2 col for user3 end for -
AttributeError: 'list' object has no attribute 'set_canvas'
Hi I am getting the above mentioned error when trying to run the code on django in views.py The error is occuring at canvas = FigureCanvas(chart) -
return access_token when user login/ signup django-rest-framework-social-oauth2
when user login / signup the user is registered to database then redirected to http://localhost:8000/accounts/profile/ by default. this details were store in database, i want to return a json response with the backend, access token like this { backend: google-oauth2, token: 8PBzJsBqeCKq49kzp45THrB0GGY5E1QAnby5ttWmaGxroPIfKZ8qSujt, } i tried to get the userid of the logged in user but it throws a unauthenticated error class ldata(APIView): def get(self, request): if request.user.is_authenticated: user = request.user return Response(user.id) else: return Response("not logged in") -
How to split one app to two apps in Django?
I made an app(first app) with Django following a tutorial. And I finally completed a web server with AWS EC2, nginx, uwsgi, mySQL, and Django. Then I tried to make a new app(second app). But I found that I put account information(user model) in first app's model.py. Furthermore, I added something like notification functions in first app's model and view etc... I want to make new app with first app's account and notification, but I am not sure it's possible to split one app to two apps. I'd like to make a site(project) have three apps which are account apps(including user model, notification, etc.), first app, and second app. Then, I thought second app can use user info like first app. (Is there any better way?) I just have a questions, how can I split account app from first app without any data loss. Actually I afraid that if I make a problem, it's very hard to restore it. (model, view, url, ...) My model is following class Profile(models.Model) # I'd like to split into account app class Recruit(models.Model) # stay in first app class Apply(models.Model) # stay in first app class Comment(models.Model) # stay in first app I will … -
AttributeError: 'NoneType' object has no attribute 'app_label' when running python manage.py test
When I run python manage.py test from django I see below error AttributeError: 'NoneType' object has no attribute 'app_label' Here is the traceback of the error snippet. Traceback (most recent call last): File "manage.py", line 26, in <module> execute_from_command_line(sys.argv) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/__init__.py", line 359, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/base.py", line 294, in run_from_argv self.execute(*args, **cmd_options) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/commands/test.py", line 72, in handle failures = test_runner.run_tests(test_labels) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/test/runner.py", line 549, in run_tests old_config = self.setup_databases() File "/Users/abhilash1jha/PycharmProjects/Glue/ci/test/customtestrunner.py", line 56, in setup_databases self.parallel, **kwargs File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/test/runner.py", line 743, in setup_databases serialize=connection.settings_dict.get("TEST", {}).get("SERIALIZE", True), File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/db/backends/base/creation.py", line 70, in create_test_db run_syncdb=True, File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/__init__.py", line 130, in call_command return command.execute(*args, **defaults) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/base.py", line 345, in execute output = self.handle(*args, **options) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 224, in handle self.verbosity, self.interactive, connection.alias, apps=post_migrate_apps, plan=plan, File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/core/management/sql.py", line 53, in emit_post_migrate_signal **kwargs File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/dispatch/dispatcher.py", line 191, in send response = receiver(signal=self, sender=sender, **named) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/contrib/auth/management/__init__.py", line 63, in create_permissions ctype = ContentType.objects.db_manager(using).get_for_model(klass) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 60, in get_for_model self._add_to_cache(self.db, ct) File "/Users/abhilash1jha/projects_venv/glue/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 132, in _add_to_cache key = (ct.app_label, ct.model) AttributeError: 'NoneType' object has …