Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I am using Django 1.8(django-registration-redux==1.8) and keep getting redirected to /profile when trying to get to my registrations page.
I would like to be able to get to the registration page so that I can login. Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/profile/ Using the URLconf defined in bookstore.urls, Django tried these URL patterns, in this order: ^store/ ^accounts/ ^activate/complete/$ [name='registration_activation_complete'] ^accounts/ ^activate/resend/$ [name='registration_resend_activation'] ^accounts/ ^activate/(?P<activation_key>\w+)/$ [name='registration_activate'] ^accounts/ ^register/complete/$ [name='registration_complete'] ^accounts/ ^register/closed/$ [name='registration_disallowed'] ^accounts/ ^register/$ [name='registration_register'] ^accounts/ ^login/$ [name='auth_login'] ^accounts/ ^logout/$ [name='auth_logout'] ^accounts/ ^password/change/$ [name='auth_password_change'] ^accounts/ ^password/change/done/$ [name='auth_password_change_done'] ^accounts/ ^password/reset/$ [name='auth_password_reset'] ^accounts/ ^password/reset/complete/$ [name='auth_password_reset_complete'] ^accounts/ ^password/reset/done/$ [name='auth_password_reset_done'] ^accounts/ ^password/reset/confirm/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>.+)/$ [name='auth_password_reset_confirm'] ^admin/ The current URL, accounts/profile/, didn't match any of these. urlpatterns = [ url(r'^store/', include('store.urls'), name='store'), url(r'^accounts/', include('registration.backends.default.urls')), url(r'^admin/', include(admin.site.urls)), ] Above is what my urls.py in my base applicaiton looks like. I tried using redirect_url in settings.py but still was not able to get to the registration page I want. -
Problems with Django SSO implementation
Is there a pre-built solution floating around that not only implements single sign on (django-mama-cas + django-cas-ng) but also auto logs in and out across the services? Meaning the domains (not subdomains) seamlessly pick up the fact I've logged in or out. I have a cas server setup, but the problem is essentially this.... Lets say I login on one domain. The other domain (if I refresh the page) doesn't pick up the ticket created until I visit (server.com/login) and then redirects me back to my original page once it sees I'm already authenticated. SO..... let's say I have a navbar with your typical conditional logic that say display register / login if not authenticated or logout if authenticated. On my other domain using the same shared code base it will display login / register until I visit the login url (and get kicked back... since I've already logged in) despite having just authenticated on the other domain. Hence, I'm looking for a way to not only have SSO implemented but have my other domains seamlessly pick up the fact that I've been authenticated through the cas server even if I didn't visit the server (to login or logout) from … -
Django changing user created data to another user?
I am having a conceptual issue in my Django project. In my scenario I have a sales team, this sales team unfortunately has high turn-over. The database works like this: Salesman Alex (user_id PK) -> has_many Clients (user_id FK) -> has_many Jobs -> has_many Notes So I am trying to structure my model with the above relationship. However, what I can't wrap my head around is what if Salesman Alex and Salesman Bob SWAP clients? What if Alex quits? The obvious answer would be to update the user_id, however, I have been reading that causes major issues. Any insight into this would be most appreciated. -
Django prevent migrations on remote database
I have a Django app that connects to two databases. One of my DBs is on a different (production) server. I want to make very sure that in developing my app, I don't accidentally migrate models on the production server. My understanding is this: Suppose my settings.py DATABASES is this: DATABASES = { 'default': {}, 'remote_db': { 'NAME' : 'important_remote_db_name', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'someuser', 'PASSWORD': 'somepass', 'HOST': : 'some.production.host.com', 'PORT' : '3306', }, 'myapp_db': { 'NAME' : 'my_app_db_name', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'localuser', 'PASSWORD': 'localpassword' } } Now suppose I also have a router class called RemoteDBRouter. Like all routers, that class will have a method allow_migrate. Note that the remote DB uses Django auth models, so the User model will have app_label 'auth', and the remote DB also has its own models with app_label 'remoteapp'. With that info, I see two possibilities for the allow_migrate method: #OPTION 1 def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'auth' or app_label == 'remoteapp': return db == 'remote_db' return None #OPTION 2 def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == 'auth' or app_label == 'remoteapp': return False return None Which one should I use? Option 2 is … -
Django relation lookup not creating expected query
I'm using Django 1.11.6, python 3.4.2, postgresql, PyCharm 4.5.2, and windows 10 (only for development purposes). The goal is to utilize the 'Lookups that span relationships' from the Django docs. # models class AlphaType(models.Model): page_type = models.CharField(max_length=50, primary_key=True, null=False) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) class AlphaBoard(models.Model): title = models.CharField(max_length=50) alpha_text = models.TextField(max_length=30000) created_on = models.DateTimeField(auto_now_add=True) modified_on = models.DateTimeField(auto_now=True) fk_page_type = models.ForeignKey(AlphaType, on_delete=models.CASCADE, default='general') #views .... q = AlphaBoard.objects.filter(fk_page_type__page_type='general') print(q.query) .... Just fyi, the tables have the app name prepended to the model name and the foreign key has 'id' appended to the foreign key column name. Result of the query print. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" WHERE "alpha_alphaboard"."fk_page_type_id" = "general" What I was expecting. SELECT "alpha_alphaboard"."id", "alpha_alphaboard"."title", "alpha_alphaboard"."alpha_text", "alpha_alphaboard"."created_on", "alpha_alphaboard"."modified_on", "alpha_alphaboard"."fk_page_type_id" FROM "alpha_alphaboard" INNER JOIN "alpha_alphaboard" ON "alpha_alphatype" "alpha_alphaboard"."fk_page_type_id" = "alpha_alphatype"."page_type" WHERE "alpha_alphatype"."page_type" = "general" Questions Why is the query ignoring the page_type relation from the filter? Look at the result of the printed query and the filter within the views. I should also add that I had a related_name="fk_page_type" within the AlphaBoard.fk_page_type, but I removed it. So a follow up question is why is it still picking up the related_name? How do you use … -
Django: Class-based views, URL and template_name
I am trying to use something like polls:detailin a class-based view, such as this: class QuestionDetail(DetailView): template_name = 'polls:result' However, I get a TemplateDoesNotExist at /polls/2/result polls:result error... The urls.py is: from django.conf.urls import url from polls.views import IndexView, DetailView, ResultsView from . import views app_name = 'polls' urlpatterns = [ url(r'^$', IndexView.as_view(), name='index'), url(r'^(?P<pk>\d+)/$', DetailView.as_view(), name='detail'), url(r'^(?P<pk>\d+)/result$', ResultsView.as_view(), name='result'), url(r'^(?P<pk>\d+)/vote$', views.vote, name='vote'), ] I guess the main question is, how do I use the names of URLs in class-based views, instead of explicitly providing the template name, such as polls/question_results.html? Is there anything other than template_name? I was reading that it's a good practice to use names in URLS so in case the URL itself changes, the rest of the code still works, so that's what I'm trying to do. -
django with multiple databases and foreignkeys for User
Suppose I have a django app on my server, but I wish to do authentication using django.contrib.auth.models where the User and Group models/data are on another server in another database. In Django, my DATABASES setting would be something like this: DATABASES = { 'default': {}, 'auth_db': { 'NAME' : 'my_auth_db', 'ENGINE' : 'django.db.backends.mysql', 'USER' : 'someuser', 'PASSWORD' : 'somepassword', 'HOST' : 'some.host.com', 'PORT' : '3306', }, 'myapp': { 'NAME': 'myapp_db', 'ENGINE': 'django.db.backends.mysql', 'USER': 'localuser', 'PASSWORD': 'localpass', } } DATABASE_ROUTERS = ['pathto.dbrouters.AuthRouter', 'pathto.dbrouters.MyAppRouter'] First question: will this work, ie will it allow me to login to my Django app using users that are stored in the remote DB 'my_auth_db'? Assuming the answer to the above is yes, what happens if in my local DB (app 'myapp') I have models that have a ForeignKey to User? In other words, my model SomeModel is defined in myapp and should exist in the myapp_db, but it have a ForeignKey to a User in my_auth_db: class SomeModel(models.model): user = models.ForeignKey(User, unique=False, null=False) description = models.CharField(max_length=255, null=True) dummy = models.CharField(max_length=32, null=True) etc. Second question: Is this possible or is it simply not possible for one DB table to have a ForeignKey to a table in another … -
"Generate" client to use Django restful API
I have programmed a Django application that provides a RESTful API via Django Restful Framework. Now I need to create a "client" that uses the API. This client will also be written in Python but run on a different machine than the app. As the application I already have contains most of the required information how the API can be consumed (i.e. the Django model), it seems possible to "generate" the client code automatically to a large extent. Similar to how the Django Restful Framework "generates" the API code from the model. This would save me from having to use the (awesome, I admit) Request module and write a lot of code myself. I assume I could use the Django Restful Framework's Serializers, etc. to have a head start, but that would mean that the client must have Django installed. That is something that will not be possible. What is the best/easiest/preferred/pythonic way to write a (slim) client to consume a Django RESTful API? -
adding {% static '<File_Name>' %} to many entries in DJango
I need to add the "static" feature to a number of files in my DJango project as mentioned here: howto: static files It seems to work. But, the instruction says that one needs to make this change OLD: <img src="my_app/example.jpg" alt="My image"/> NEW: {% load static %} <img src="{% static 'my_app/example.jpg' %}" alt="My image"/> to every line that needs it. I have several hundred lines of already-existing code that is in the old format. How can one change so many lines so at one time so that they will be in the correct format? TIA -
is there a way to convert a view function to a celery task?
task.py @task(name="send_mail_to_custormer") def order_created(order_id): order = Order.objects.get(id=order_id) subject = 'Order nr. {}'.format(order.id) message = 'Dear {} {},\n\nYou have successfully placed an order. Your order id is {}'.format(order.first_name, order.last_name, order.id) from_email = settings.EMAIL_HOST_USER to_email = [order.email] mail_sent = send_mail( subject, message, from_email, to_email, fail_silently=False ) return mail_sent views.py def order_create(request): cart = Cart(request) if request.method == 'POST': form = OrderCreateForm(request.POST) if form.is_valid(): order = form.save() for item in cart: try: OrderItem.objects.create(order=order, product=item['product'], price=item['price'], quantity=item['quantity']) except: pass cart.clear() order_created.delay(order.id) return render(request,'orders/order_created.html', {'cart': cart, 'order': order}) else: form = OrderCreateForm() return render(request, 'orders/order_create.html', {'cart': cart, 'form': form}) cart.py class Cart(object): def __init__(self, request): self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def add(self, product, quantity=1, update_quantity=False): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0, 'price': str(product.price)} if update_quantity: self.cart[product_id]['quantity'] = quantity else: self.cart[product_id]['quantity'] += quantity self.save() def save(self): self.session[settings.CART_SESSION_ID] = self.cart self.session.modified = True Now the celery task sends mail and view function creates order after taking values from cart and order form. How I can change the task to create order? Is it a good practice doing so. Hope somebody can help me, thank you. -
Django save override recursion not working
I'm trying to set up a promo code system that automatically gets claimed by eligible users/students (specified either by a M2M or comma separated string of emails). Here's the relevant code from the model: class PromoCode(models.Model): students_claimed = models.ManyToManyField('Student', blank=True, related_name='promo_codes_claimed') claimable_by = models.ManyToManyField('Student', blank=True, related_name='claimable_promo_codes') claimable_by_emails = models.CharField(max_length=10000, null=True, blank=True) def save(self, *args, **kwargs): if self.claimable_by_emails: for email in self.claimable_by_emails.split(','): try: student = Student.objects.get(user__email=email) student.claim_promo_code(self) except Student.DoesNotExist: pass for student in self.claimable_by.all(): student.claim_promo_code(self) super().save(*args, **kwargs) The claim_promo_code method within Student is as follows: def claim_promo_code(self, promo_code): if promo_code.is_claimable_by(self): promo_code.students_claimed.add(self) promo_code.save() print('TEST') I know the claim_promo_code method is being called because the print statement is running; however, the user is not being added/saved to students_claimed. Calling the claim_promo_code method through other means (outside of the save method) works as intended. Is there a problem with calling an object's save method within itself, as is the case here? How should I approach solving this? -
CSS styling got ruined while sending html mail using python via sendgrid
When I send HTML template as a mail, all the styling got ruined. The html is created using sendgrid templating but all the styling got ruined when I send this email. Here is my code. main.py from django.template.loader import render_to_string def send_mail(receiver_email, subject, email_template): sendgrid_object = sendgrid.SendGridAPIClient(apikey = credentials.sendgrid_API_key) data = { "personalizations": [ { "to": [ { "email": receiver_email } ], "subject": subject } ], "from": { "email": "support@xyz.net", "name": "Support" }, "content": [ { "type": "text/html", "value": email_template } ] } response = sendgrid_object.client.mail.send.post(request_body=data) send_mail(email,subject, render_to_string("welcome.html")) -
AttributeError in views.py: type object 'Transaction' has no attribute 'objects'
I am a first-time poster here and I have run into an issue using Django. I am creating a finance app which tracks deposits and withdrawals.Unfourtanently I have run into an issue using models. Here is the relevant code Views.py from django.shortcuts import render from .models import Transaction # Create your views here. class Transaction: def __init__(self, name, description, location, amount): self.name = name self.description = description self.location = location self.amount = amount def sum(totals): sum = 0 for i in range(len(totals)): if totals[i].name.lower() == 'deposit': sum += totals[i].amount else: sum -= totals[i].amount return sum #transactions = [ # Transaction('Deposit', 'Allowance', 'Home', 25.00), # Transaction('Withdrawl', 'Food', 'Bar Burrito', 11.90), # Transaction('Withdrawl', 'Snacks', 'Dollarama', 5.71) #] def index(request): transactions = Transaction.objects.all() balance = sum(transactions) return render(request, 'index.html', {'transactions':transactions, 'balance': balance}) Models.py from django.db import models # Create your models here. class Transaction(models.Model): name = models.CharField(max_length = 100) description = models.CharField(max_length = 100) location = models.CharField(max_length = 100) amount = models.DecimalField(max_digits = 10, decimal_places = 2) def __str__(self): return self.name admin.py from django.contrib import admin from .models import Transaction # Register your models here. admin.site.register(Transaction) Let me know if there is any other code you need to look at and thanks in … -
Django login using email
I want to login on website, using user's email. I have: models.py class User(models.Model): email = models.EmailField() password = models.CharField(max_length=200) client_id = models.IntegerField() role = models.CharField(max_length=200) So, as far as I understand it will be hard to create Customer User model, after migrations to db. Can I just use this code to login, or I need to change user's model? P.s. It's not standart login user's model, can I logout using standart auth.logout? urls: url(r'^admin/', admin.site.urls), url(r'^main/$', MainPage, name="main"), url(r'^login/$', UserLogin, name="login"), url(r'^$', HomeView, name="home"), url(r'^logout/$', Logout, name="logout"), views.py def UserLogin(request): email = request.POST.get('email',False) password = request.POST.get('password',False) user = authenticate(email=email,password=password) if user is not None: return HttpResponseRedirect('Main.html') else: return HttpResponseRedirect('Index.html') def Logout(request): auth.logout(request) return render_to_response('Login.html') Html code: <form class="m-t" role="form" action="/login" method="post"> <div class="form-group"> <input type="email" class="form-control" placeholder="Username" required=""> </div> <div class="form-group"> <input type="password" class="form-control" placeholder="Password" required=""> </div> <button type="submit" class="btn btn-primary block full-width m-b">Login</button> <a href="password.html"> <small>Forgot password?</small> </a> <a class="btn btn-sm btn-white btn-block" href="reg.html">Create an account</a> </form> After running server with url .8000/login, every try program returns user = None, and redirects to Index.html. I thought, that I have this mistake because I'm already logged in, but now I'm not sure. Also, When I try to logout from … -
Error installing psycopg2==2.6.2
I have problems when I try installing psycopg2==2.6.2 . I have installed postgresql 9.6. and I am using a virtualenv.Any help is welcome. Collecting psycopg2==2.6.2 (from -r requirements.txt (line 21)) Downloading psycopg2-2.6.2.tar.gz (376kB) 100% |████████████████████████████████| 378kB 281kB/s Complete output from command python setup.py egg_info: running egg_info creating pip-egg-info/psycopg2.egg-info writing top-level names to pip-egg-info/psycopg2.egg-info/top_level.txt writing dependency_links to pip-egg-info/psycopg2.egg-info/dependency_links.txt writing pip-egg-info/psycopg2.egg-info/PKG-INFO writing manifest file 'pip-egg-info/psycopg2.egg-info/SOURCES.txt' Error: could not determine PostgreSQL version from '10.0' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-k7nulk7r/psycopg2/ -
DRF: Database not updating
Following are my files. It is simply adding products based on subcategories and categories. Everything is working fine but the data is not being saved in the database. I am not sure where I am going wrong. models.py from django.db import models class Category(models.Model): category = models.CharField(max_length=200) parent = models.ForeignKey('self', blank=True, null=True, related_name='children') class Meta: unique_together = ('parent' , 'category') def __str__(self): return self.category class SubCategory(models.Model): subcategory = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) parent = models.ForeignKey('self', blank=True, null=True, related_name='subchilren') class Meta: unique_together = ('parent' , 'subcategory') def __str__(self): return self.subcategory class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey('Category', null=True, blank=True) subcategory = models.ForeignKey('SubCategory', null=True, blank=True) def __str__(self): return self.name views.py class AddProducts(APIView): serializer_class = AddProductsSerializer def post(self, request, format=None): data = request.data serializer = AddProductsSerializer(data=data) if serializer.is_valid(raise_exception=True): new_data = serializer.data return Response(new_data) return Response(serializer.errors, status=HTTP_400_BAD_REQUEST) serializers.py class AddProductsSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'name', 'category', 'subcategory') def create(self, validated_data): return Product.objects.create(**validated_data) def update(self, instance, validated_data): instance.name = validated_data.get('name', instance.name) instance.category = validated_data.get('category', instance.category) instance.subcategory = validated_data.get('subcategory', instance.subcategory) instance.save() return instance -
Celery 4 not auto-discovering tasks
I have a Django 1.11 and Celery 4.1 project, and I've configured it according to the setup docs. My celery_init.py looks like from __future__ import absolute_import import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ['DJANGO_SETTINGS_MODULE'] = 'myproject.settings.settings' app = Celery('myproject') app.config_from_object('django.conf:settings', namespace='CELERY') #app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) # does nothing app.autodiscover_tasks() # also does nothing print('Registering debug task...') @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) However, when I launch a worker with: .env/bin/celery worker -A myproject -l info it shows no tasks being found except for the sample "debug_task", even though I have several installed apps with Celery tasks, with should have been found via the call to app.autodiscover_task(). This is the initial output my worker generates: -------------- celery@localhost v4.1.0 (latentcall) ---- **** ----- --- * *** * -- Linux-4.13.0-16-generic-x86_64-with-Ubuntu-16.04-xenial 2017-10-31 15:56:42 -- * - **** --- - ** ---------- [config] - ** ---------- .> app: myproject:0x7f952856d650 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: amqp:// - *** --- * --- .> concurrency: 4 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . myproject.celery_init.debug_task [2017-10-31 … -
Django Channel Group send then discard
I want to send a message to a Group and immediately afterwards discard one of the reply channels. It doesn't work due to the consumer_finished signal not sending until the incoming message is fully dealt with, I gather from debugging the code and witnessing when the message is sent to the frontend. The result is that my message doesn't get sent on the channel that I delete afterwards. Am I doing anything wrong, or is this a Channel bug/feature? Group(room_id).send({'text': json.dumps({'command': 'leave', 'room': {'id': room_id}, 'user': {'id': str(message.user.id)}})}) Group(room_id).discard(message.reply_channel) -
Django Rest Framework - 'ModelBase' object is not iterable
Struggling to understand this error message. I think it means that somewhere I'm trying to iterate over the Base class, instead of an instance or instances of the class? I also believe I wouldn't be able to iterate over a single instance anyway, but all I want to do is use DRF to show all Actions that FK to the object with the id in the URL. views.py: class ActionDetailListView(core.views.MixedListAPIView): resource_types_list = [ { "model": ActionDetail, "serializer": ActionDetailSerializer, "filter": ActionDetailFilter } ] def get_queryset(self, *args, **kwargs): pk = kwargs.get('pk', None) return ActionDetail.objects.filter(action__parent__grandparent_id=pk) filters.py class ActionDetailFilter(django_filters.FilterSet): pass serializers.py class ActionDetailSerializer(core.serializers.HalModelSerializer): class Meta: model = ActionDetail -
python 3.6 JsonResponse issue
So i recently migrated to Python 3.6 and Django 1.11 and my JsonResponse code looked like this: return JsonResponse({'status': '1'}) it worked fine but after the migration i started getting this error: TypeError: Object of type 'bytes' is not JSON serializable After printing the type of the data passed to JsonResponse i realized python 3.6 changed this from dict to byte. So i changed the code to make sure i was passing a dict. I still get the same error after trying all of this: data = dict([('status', 0)]) print(data) print(type(data)) # print(type(json.dumps(data))) # data = {"status": '0'} # data = json.dumps(data) # json.dumps(data.decode("utf-8")) #response = json.JSONEncoder().encode({"status": 0}) #JsonResponse(data, safe=False) # response = json.dumps(data) print(JsonResponse(data, safe=False)) return JsonResponse(data, safe=False) Prints: {'status': 0} <class 'dict'> <JsonResponse status_code=200, "application/json"> with the json.dumps options y get this error instead AttributeError: 'str' object has no attribute 'get' Any help would be much appreciated -
How to use mezzanine together with allauth?
I commented mezzanine mezzanine.accounts from settings.INSTALLED_APPS and use allauth as AUTHENTICATION_BACKEND settings.py AUTHENTICATION_BACKENDS = ( "django.contrib.auth.backends.ModelBackend", "allauth.account.auth_backends.AuthenticationBackend" ) urls.py: urlpatterns += [ url(r"^$", include("movies.urls")), url("^blog2", blog_post_list, name="home"), url(r"^admin/", include(admin.site.urls)), url(r"^movies/", include("movies.urls", namespace="movies")), url(r"^faq/", include("fack.urls")), url(r"^accounts/", include("allauth.urls")), url(r'^captcha/', include('captcha.urls')), url(r'^jsi18n/$', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^tz_detect/', include('tz_detect.urls')), url(r"^h/", include("home2.urls", namespace="home2")), url(r"^profile/", include("profile.urls", namespace="profile")), url("^", include("mezzanine.urls")), ] The problem is that when I go to https://localhost/blog2, that I see the base.html of allauth.accounts. Maybe mezzanine confuses allauth accounts/base.html with its own accounts/base.html? Or maybe I'm missing something else. -
ajax function throwing HTTP 200 immediately followed by HTTP 500 error
Why do I get a HTTP 200 followed immediately by a HTTP 500? I have the impression the Ajax function is called twice in a row. The objects that I expect to be created are actually created though... my ajax function is called on a form submit: $(document).on('submit','#like_form_reading_list{{ article.pk }}', function(e) { e.preventDefault(); $.ajax({ type: 'POST', url: '{% url "userprofile:like" %}', data: { journal: '{{ journal.pk }}', section: '{{ section.pk }}', article: '{{ article.pk }}', csrfmiddlewaretoken: '{{ csrf_token }}' }, success: function showAlertLike() { $("#success_like").show().delay(2000).fadeOut(); }, error: function showAlertPin() { $("#error_like").show().delay(2000).fadeOut(); } }); }); In my view: class LikeView(generic.FormView): """ A view that creates a LikedArticles object when a user clicks on the like badge under each article displayed. """ def post(self, request): if request.method == 'POST': user = request.user journal_pk = request.POST.get('journal') section_pk = request.POST.get('section') article_pk = request.POST.get('article') journal = Journal.objects.get(pk=journal_pk) section = Section.objects.get(pk=section_pk) article = Article.objects.get(pk=article_pk) print('IN LIKE VIEW ', user, journal_pk, section_pk, article_pk) LikedArticles.objects.create( user=user, journal=journal, section=section, article=article ) return HttpResponse('') In my terminal: Internal Server Error: /like/ Traceback (most recent call last): [SOME ERROR MESSAGE] "/Users/benoitkoenig/Desktop/projet_web/harrispierce_django/hpdjango/lib/python2.7/site-packages/django/db/models/fields/init.py", line 966, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' ('IN LIKE VIEW ', at … -
Extending User Model to an Existing DB table?
I'm having issues getting my User model to extend to an existing database table. I have a feeling i'm getting close. I don't receive any errors with my following code, but anytime I login it doesn't pull in the additional information. First of all I'm using LDAP authentication with python 3.6 and Django 1.11, once a user is validated as an AD user the username and password is written to my User table. Second my existing table is not to be changed or modified and its called AllEeActive. I have a primary key that is the username in my user table called employee_ntname. I'm trying to use a signal handler to write to connect the two models. Below is my code... What am I doing incorrectly?: from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, … -
which is the best way to deploy django web app
I have created one dummy test app in django python. So that how am I deploy on any web server in its cost free hosting. -
Cant access server media files in django + angular project
Because I wanted to do my routing in angular side I have added this url in my urls.py: url(r'^.*$', Home.as_view(), name='home'), in which my home view I just specify my base.html: class Home(TemplateView): template_name = "base.html" So that I can specify my <ng-view></ng-view> in base.html Now my issues the requests to get pictures in server side like localhost:8000/media/logo.png are going to the defined url for Home. How can I overcome this issue? Thank you.