Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - cannot assign - must be an instance
I tried phrasing this question recently and got totally confused. I've extended the default user model with this in my models.py: class Biography(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) biography = models.TextField(max_length=500, blank=True,default='Details') I've included this in the forms.py: class EditProfileForm(forms.Form): first_name = forms.CharField(label='First Name') last_name = forms.CharField(label='Last Name') biography = forms.CharField(label='Biography', widget=Textarea(attrs={'rows': 5})) I have a view to edit the profile and want to add "biography" to it, but have absolutely no clue where to start. Here's the view: def edit_profile(request): user = request.user products = Product.objects.filter(user=user) form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.save() return render(request, 'profile.html', {'user':user, 'products':products}) context = {"form": form} return render(request, "edit_profile.html", context) I tried to replicate what is already there with this: def edit_profile(request): user = request.user products = Product.objects.filter(user=user) biography = Biography(user=user) form = EditProfileForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'biography':user.biography}) if request.method == 'POST': if form.is_valid(): user.first_name = request.POST['first_name'] user.last_name = request.POST['last_name'] user.biography = request.POST['biography'] user.save() return render(request, 'profile.html', {'user':user, 'products':products}) context = {"form": form} return render(request, "edit_profile.html", context) I definitely missed the point somehow. The last time I asked this question I was somewhat chastised for not knowing how to solve … -
Django Social Auth not adding new user with saved Google credentials to the database
Scenario: Whenever a user tries to login via Google, if they're not already in the database, they're redirected back to an anon user state when they shouldn't be. If the user tries to login via Google with an existing email address (they're already in db), then they're authenticated just fine. In the request, even if the user authenticates via Google and is successful (gets an access token and everything), the request still believes it's an anonymous user. Working with Django Social Auth, and before this used to work but it doesn't any more. Code: views.py def index(request): try: # print(request.user) returns AnonymousUser even after authenticating profile = Profile.objects.get(email=request.user.email) return render(request, 'tablefor2/index-logged-in.html') except: return render(request, 'tablefor2/index-logged-out.html') HTML <a href="{% url "social:begin" "google-oauth2" %}"><button class="save btn btn-default">GET STARTED</button></a> settings.py MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'tablefor2.urls' SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', ], 'debug': DEBUG, }, }, ] LOGIN_URL = '/' LOGIN_REDIRECT_URL = '/' WSGI_APPLICATION = 'tablefor2.wsgi.application' SOCIAL_AUTH_ADMIN_USER_SEARCH_FIELDS = ['username', 'first_name', 'email'] SOCIAL_AUTH_USER_MODEL = 'tablefor2.Profile' … -
Cannot query field "furniture" on type "RootMutation"
I am wanting to create a furniture object in graphiql by using following query where I get an error Cannot query field "furniture" on type "RootMutation". This is the query I did for creating a furniture object mutation { newFurniture(input: {name: "graphFurniture", content: "This furniture is cool", category: "Bedroom Items"}) { clientMutationId } furniture{ // error is shown here name content category { name } } } Here is my code for mutation class FurnitureNode(DjangoObjectType): class Meta: model = Furniture class NewFurniture(graphene.ClientIDMutation): furniture = graphene.Field(FurnitureNode) class Input: name = graphene.String() content = graphene.String() category = graphene.String() @classmethod def mutate_and_get_payload(cls, input, context, info): furniture = Furniture(name=input.get('name'), content=input.get('content'), category=Category.objects.get(name=input.get('category'))) furniture.save() return NewFurniture(furniture=furniture) class NewFurnitureMutation(graphene.ObjectType): new_furniture = NewFurniture.Field() Why am i getting such error? -
How to use Django Subquery inside Annotate and Sum
I am trying to calculate total revenue for a day. Each DailyTotal contains a count of items sold (items_sold) and a Price those items were sold that day (items_price) (every items is sold for the same price all day). That part is working, but now I need to convert multiply that value by the exchange rate for that day/country. rate = ExchangeRate.objects.filter( date=OuterRef('date'), country=OuterRef('country'))) calc_with_rate = Sum(F('items_sold') * F('items_price') * Subquery(rate.values('rate')), output_field=FloatField(),) results = DailyTotal.objects.filter(**query_filters).annotate( revenue=calc_with_rate) but I get: unsupported operand type(s) for +=: 'int' and 'NoneType I assume it is because rate.values('rate') is not returning a an int.. but I can't do rate.values('rate')[0] or I get: This queryset contains a reference to an outer query and may only be used in a subquery. so I am not sure how to complete this query? -
difference between Response and HttpResponse django
What is the difference between Response and HttpResponse in django i am kinda confusing. Return Respose and return HttpResponse -
Django MySQL connection too slow
My django app is slow. So I profiled that. 69066 function calls (67072 primitive calls) in 0.206 seconds Ordered by: internal time List reduced from 734 to 147 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 2 0.081 0.040 0.101 0.051 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 6 0.043 0.007 0.043 0.007 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 4 0.017 0.004 0.017 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 2 0.013 0.006 0.013 0.006 {function Connection.set_character_set at 0x10622d6a8} I think query is not problem. But connections.__init__ is take a lot of times. So I test very simple function. This is the same function with above profile. But I change auth token to wrong. 2244 function calls (2175 primitive calls) in 0.119 seconds Ordered by: internal time List reduced from 426 to 85 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 2 0.079 0.040 0.095 0.047 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:81(__init__) 4 0.015 0.004 0.015 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:254(autocommit) 3 0.013 0.004 0.013 0.004 /Users/jyj/.pyenv/versions/logispot_app_env/lib/python3.6/site-packages/MySQLdb/connections.py:268(query) 2 0.008 0.004 0.008 0.004 {function Connection.set_character_set at 0x10622d6a8} Still connections.__init__ take long. This is another simple function to get user list 9818 function calls (9552 primitive calls) in 0.101 seconds Ordered by: internal time List reduced from 553 to 111 due to restriction <0.2> ncalls tottime percall cumtime percall filename:lineno(function) 1 0.041 … -
django allauth bootstrap - TemplateDoesNotExist
I am trying to get the bootstrap forms working for Django-Allauth, but I cannot get it working, and I cannot find much documentation on it. It references these bootstrap forms in the example of the django-allauth repo located at https://github.com/pennersr/django-allauth/tree/master/example. In the directions, it states that all you have to do to get the bootstrap forms working is install django-bootstrap-form and include "bootstrapform" in your INSTALLED_APPS in your settings file. I have done this in my project, but it still appears to be pulling templates from the /account folder instead of the /bootstrap folder. While debugging, I tried just replacing the login.html form in the /account folder with the one from the /bootstrap folder. In this case, I get a TemplateDoesNotExist exception at /accounts/login/ bootstrapform/form.html I figure if I can at least get the bootstrapform stuff working I can just replace the templates inside the /account folder and be fine... Any idea what may be happening? -
Django/MySQL: Making non-unique field unique fails even if field values are unique
I currently have this: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField() I need to make the field committee_xml_id unique, i.e. make it so: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField(unique=True) I have also tried making it so: class Committee(models.Model): # ...some fields... committee_xml_id = models.IntegerField(unique=True, db_index=False) Alas, the result is the same. Having run ./manage.py makemigrations and subsequently, ./manage.py migrate, the problem is this: django.db.utils.OperationalError: (1061, "Duplicate key name 'appname_committee_committee_xml_id_d1210032_uniq'") At first glance, it seems like the problem is that there is already non-unique data in the table, but the problem is precisely that there isn't. There are only 45 rows in the table, and the field committee_xml_id contains only unique entries. The following query gives no results, as expected when there are no duplicates: SELECT com.committee_xml_id, COUNT(*) FROM appname_committee AS com GROUP BY com.committee_xml_id HAVING COUNT(*) != 1 For rigor, here is the same query without the HAVING-condition, showing clearly that there are indeed no duplicates: SELECT com.committee_xml_id, COUNT(*) FROM appname_committee AS com GROUP BY com.committee_xml_id Result is: # committee_xml_id, COUNT(*) 78, 1 79, 1 124, 1 125, 1 129, 1 130, 1 131, 1 132, 1 133, 1 134, 1 137, 1 139, 1 140, 1 … -
NoReverseMatch: Reverse for 'deleted' with no arguments not found. - Django
I'm a new face to Django so please be considerate to if ever my problem is something stupid. So I have been practicing Django, and currently making a CRUD, however I've run into problems with tegards to NoReverseMatch, I went through answers in stackoverflow but still I couldn't find where I went wrong. Can you help me a bit guys? Actually it was working, when I resetted the DB, somehow it had the error, maybe i moved something or whatever unlucky thing i did. I've been at it for 3 hours actually. Just this error. So please help me: The traceback says that the NoReverseMatch is on this url Delete which i properly partnered and connected with url(r'^delete/(?P\d+)/', Delete.as_view(), name="deleted"), in my urls.py. Here's the gist of the code: First here's the urls involved. deleteupdate/urls.py (Delete and Update are from models imported to the file) urlpatterns = [ url(r'^', views.list, name='list'), url(r'^delete/(?P<pk>\d+)/', Delete.as_view(), name="deleted"), url(r'^update/(?P<pk>\d+)/', Update.as_view(), name="updated"), url(r'^(?P<student_id>)/', views.detail, name='detail'), ] main/urls.py urlpatterns = [ url(r'^$', include('index.urls')), url(r'^admin/', admin.site.urls), url(r'^list/', include('deleteupdate.urls')), ] Here's the HTML: {% if all_students %} <ul> {% for user in all_users %} <li><a href="/list/{{ user.id }}"></a> <button type="button"> <a href="{%url 'deleted'%}">Delete</a> </button> <button type="button"> <a href='{% … -
Is there a way to raise Permission Denied without rendering 403.html?
I'm trying to raise just the status of the error. PermissionDenied automatically renders 403.html for me. Is there a way to just raise the status without this? class IsMemorandumAdmin(UserPassesTestMixin): def test_func(self,user): permission = Permission.objects.get(name="Can CRUD Memorandums") return permission in user.user_permissions.all() def handle_no_permission(self,request): raise PermissionDenied the mixin API requires me to throw an exception of BasePermission type. If possible, an HttpResponse(status=401) would be nice -
Django save related ManyToMany model
I have two models with ManyToMany relationship as this: class Subject(models.Model): teachers = models.ManyToManyField( Teacher ) subject = models.CharField( 'Materia', max_length = 50, unique = True ) level = models.CharField( 'Nivel', max_length = 3, choices = LEVEL_CHOICES ) class Teacher(Person): # fields definition Following the docs I know I can save Subject model without saving Teacher field. That's fine. Now I want to add a Subject to Teacher, so I need a form with selected teacher, and a choice field with all the subjects. I found this question that relates to what I want to accomplish, but I think it doesn't address what I'm looking for. First I populate the subject choice filed, as shown in the ModelForm code below. forms.py class SubjectTeacherForm(ModelForm): subject = forms.ChoiceField(choices=[(m.id, m.subject) for m in Subject.objects.all()]) class Meta: model = Subject fields = ['teachers', 'subject'] urls.py #here I send the teacher id to the view url(r'^materias/asignar/profesor/(?P<teacher_id>\d+)/$',MateriaTeacherCreateView.as_view(), name='materia-create-teacher'), views.py class SubjectTeacherCreateView(SuccessMessageMixin, CreateView): model = Subject template_name = 'edu/subject/subject_create.html' form_class = SubjectTeacherForm def form_valid(self, form): # here I want to add the relation teacher = Teacher.objects.get(pk=self.kwargs['teacher_id']) self.object.teachers.add(teacher) return redirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(SubjectTeacherCreateView, self).get_context_data(**kwargs) # here I define the selected teacher to pass to the … -
Widgets in django smart-selects
Someone knows how to use widgets with smart-selects in Django? Is there any special widgets? The default forms.Select is not working correctly. -
Django: Best way to retrieve object
Lets assume that I have a class Person with a field email. I want to get a single record based on queryset and assign it to variable person. Sadly I cannot do person = Person.objects.filter(email="xxx@xxx.xxx")[0] because I might get an exception. So: Scenario 1: Include the above code in a try-except. Scenario 2 (which I'm currently using): person_arr = Person.objects.filter(email="xxx@xxx.xxx") if person_arr.exists(): person = person_arr[0] .... Scenario 3 for person in Person.objects.filter(email="xxx@xxx.xxx"): .... Scenario 4: You suggest something else. -
What should the page_name be in login.html?
I put the following in my user/templates/user/login.html: {% url 'social' page_name='what_should_this_say?' %} href="{% url 'social:begin' 'github' %}">Login with GitHub what should page_name be? http://github.something...? Thanks in advance. -
Django - Pass a model instance specified by template tags into view
On my HTML page, I have a list of Agent's (Agent is my custom User model). Beside each agent is a 'Send Invite' button. To create a TeamInvitation, I need to specify which Agent is attached to its receiver_agent field (a OneToOneField with Agent) There are multiple Agents displayed on the HTML page, and they are listed in order with template tags. I need to input something after pk at receiver_agent = Agent.objects.get(pk = ???), but I don't know what to input. views.py class InviteAgentSearchResults(ListView): model = Agent form_class = AgentSearchForm template_name = 'invite_agent_search_results.html' def get_queryset(self): # ... Code to find correct list of agents def post(self, request, *args, **kwargs): invite = TeamInvitation.objects.create(receiver_agent = Agent.objects.get(pk = ???)) return HttpResponse('Invite successfully sent.') HTML: {% for agent in agent_list %} <div class="agent"> # ... Some code here <form method="post"> # The "Send Invite" button {% csrf_token %} <button class="button1"><span>Send Invite</span></button> </form> </div> {% endfor %} -
Retrieving active user's username is not working in Django Rest Framework and Django
This is something that seems to painfully easy, but I can't get it working so have to ask. This is after reading the first few pages of Googling "django get username", or "django rest get username", and reading the several dozen SO answers on the subject. Simple enough: trying to get the name of the active user so I can retrieve records relevant to them. This is in my views.py where I am currently testing it and just trying to get it print(user) to console which isn't happening. # ./home/views.py from rest_framework.generics import ListAPIView from rest_framework.permissions import IsAuthenticated from django.contrib.auth.models import User from .serializers import GetHomeSerializer from .models import Home # Create your views here. class GetHomeAPIView(ListAPIView): queryset = Home.objects.all() serializer_class = GetHomeSerializer permission_classes = [IsAuthenticated] def get_username(self, request): user = request.user print(user) return user # ./home/serializers.py from django.utils.safestring import mark_safe from rest_framework.serializers import ( ModelSerializer, ) from .models import Home class GetHomeSerializer(ModelSerializer): class Meta: model = Home fields = '__all__' Everything is being returned to the React front-end as it should which is to render what is in the Home model, which is not user specific (basically a "welcome" message), but nothing indicating who the user is in console … -
Django Error Reporting ignore certain exception
When unhandled exception is raised, Django sends email with stacktrace. Is it possible to exclude certain exceptions from sending? For example, I don't want emails to be sent, when KeyError is raised. -
ajax post returns 404 for url in django 1.10
Im trying to post a simple ajax to 'signup' function in django but keep getting 404, I think it has to do with my url dispatcher and I need some help please.. my ajax looks like this: $('#signupBtn').click(function() { $.ajax({ type: 'POST', url : '/signup', dataType: "json", data : { userId : $('#signupEmail').val(), userPassword : $('#signupPassword').val() }, beforeSend: function() { $('#signupBtn').hide(); }, error: function(xhr,errmsg,err) { $('#signupBtn').show(); $('#signupEmail').val(""); $('#signupPassword').val(""); alert(xhr.status); }, success : function(json) { $('#signupBtn').show(); $('#signupEmail').val(""); $('#signupPassword').val(""); alert(json['u']); } }); return false;}); my views.py lookes like this: def signup(request): userid = request.POST.get('userId') userpass = request.POST.get('userPassword') data = { 'u' : userid, 'p' : userpass} return JsonResponse(data) and my app urls lookes like this: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^signup$', views.signup, name='signup'),] what is my problem? and how do i fix it? thanks. -
Django Python change user default attributes for authentication
In Django, the default attributes for user: username password email first_name last_name I would like to remove email, first_name, last_name and replace it with company Is that possible ? Can someone show me the process of performing an authentication session with these 3 modified attributes: - company - username - password Thanks. -
Incrementing a variable to use as serial number in django
I am currently using forloop.counter to display serial number but it skips the number when if condition is not satisfied. That is why I am not able to print the serial number. I need a way to increment a variable and then use it for serial number templates.html {% for all in all_lockscreens %} {% if all.media_type == "image" %} <tr> <td>{{ forloop.counter }}</td> <td>{{ all.media_name }}</td> <td>{{ all.description }}</td> <td>{{ all.date_added }}</td> </tr> {% endif %} {% endfor %} Need to increment a variable inside if loop which can be used for serial number -
Pycharm Django Supervisor Manage.py
I'm using Pycharm Professional edition to maintain a Django web application hosted on a remote Linux OS. Until now I've used Expandrive to mount the remote volume as a local windows mapped drive and can use remote debugging but would ideally like to develop locally and deploy to the server which I've got working but struggling to configure the run/debug configuration in conjunction with the Django settings in preferences considering I use supervisor to control all the processes. -
Using github to update website without re-deployment
I need to know how to update a website using github. Can't seem to find a clear example of that on the web. I have a djano project installed on my server. The app is in production. I basically need to know how I can connect it to my repository for my updates -
Installing mysql-python or mysqlclient for Django using pip throws error
I am starting to Learn python and Django framework. I already installed Django project and can run it. I am newboe to Python and Django. What I want to do is I want to connect to MySQL database of PhpMyadmin. I am using Xampp on windows for that. I followed this link - django, phpmyadmin and mysql?. But it throws error and saying I need to install python-mysql or mysqlclient. So I tried to install like this I also tried to install mysqlclient too. But both throwing following error. I searched solution and most of them say I need to update pip. I did it and my pip version is now latest and up-to-date. But it is still throwing that error when I install mysql-python and mysqlclient. Please how can I solve that error or how can I install in other way please? -
Django Admin Inlines for Indirectly Related ManyToMany Field
I have a few models as below and in the admin change form for Scenario I'd like to list, inline, all Users (i.e participants) that have "seen" that scenario through Simulation. models.py class Scenario(models.Model): name = models.CharField('Scenario', max_length=100) class Simulation(Event): scenario = fields.ForeignKey(Scenario, related_name='simulations') participants = fields.ManyToManyField(User, through='Participation') class Participation(models.Model): participant = fields.ForeignKey(get_user_model()) simulation = fields.ForeignKey(Simulation) How can I build or populate the ParticipationInline? What should the model be? admin.py class SimulationInline(admin.TabularInline): model = models.Simulation class ParticipationInline(admin.TabularInline): model = ...? class ScenarioAdmin(admin.ModelAdmin): inlines = (SimulationInline, ParticipationInline) I've tried a few things such as get_queryset and various 'dot' or 'dunderscore' joins... but I can't get it to work. The full queryset, if it can be done, would most likely have to be filtered as some Users would appear more than once. Thanks in advance for any help. Also if anyone can suggest a better way of phrasing the question/title... -
Simple log to console in Django 1.7.11
I've been breaking my head over creating a simple logfile within my django application. I've tried applying this question, as well as the examples on the docs, but it simply doesn't seem to work and I don't know what is going wrong. My current logfile, second example straight from the doc: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': os.getenv('DJANGO_LOG_LEVEL', 'INFO'), }, }, } The docs states the following: "this config only sends messages of level INFO or higher to the console" In my understanding, if I were to place this into my home.view.py file... import logging log = logging.getLogger(__name__) log.debug("Hey there it works!!") log.info("Hey there it works!!") log.warn("Hey there it works!!") log.error("Hey there it works!!") ...i should get the info, the warn and the error message printed to my console, whenever a call is made to home.views.py, which I thought happens when I visit the correct url. This appears to be false. It seems however that only warn and error is printed, and only when I run manage.py collectstatic. WARNING:home.views:Hey there it works!! ERROR:home.views:Hey there it works!! I want to receive the log messages in …