Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Loading HTML into <div> element in Electron app, then loading subsequent links into same <div>
I'm developing an app for basic student management. I have an Electron app with a main content <div>, and I have jQuery load the response from "http://127.0.0.1:8000" (localhost). I'm running Django (back-end is being made in Python) for my back-end, and since it's a local app, there's no need to change the request to an actual website. Once the jQuery loads the initial page, with the login and such, I need subsequent links (the login button, home button, any link that's shown on the app) to be loaded into the main content <div> instead of redirecting the entire Electron app to that URL. I've tried running it in a web browser as opposed to in the Electron app, and everything works as intended. My code in the Electron app for loading the app: <div id="content" class="bg-light"> <div id="app-container"> <div id="page" style="z-index: 10;"></div> <script> // load page using jQuery $("#page").load("http://127.0.0.1:8000"); </script> </div> </div> I expect the content to update with the response from a link, instead of the Electron app's URL being redirected to it. Thanks in advance guys! -
Chrome err_connection_reset on lte connection
So I have very weird problem. So I have website and when I'm connected through wifi everything is fine, chrome and mozilla are loading my website. But when I switch to LTE internet my website is working fine only on mozilla. Chrome is throwing ERR_CONNECTION_RESET error. I tried turning off firewall and restarting server, but it doesn't change anything. Website was made in django. On the other hand when I'm connecting directly to ip, it's working (I see 404 from apache, but that's becouse it's configurated to work with domain). I'm using also certbot, but it's not looking like certbot fault. It's rather something connected with domain conguration. I'm using OVH services both for server and domain. In domain I added only ip4 and ip6, dns servers were left in default configuration. -
Difference between different ways to create celery task
I am very confused by looking at different ways of creating a celery task. On the surface they all work the same So, Can someone explain what is the difference between these. 1. from myproject.tasks import app @app.task def foo(): pass 2. from celery import task @task def foo(): pass 3. from celery import import shared_task @shared_task def foo(): pass I know by a little bit of googling that the difference between the 1nd and 3rd one is shared_task is used when you don't have a concrete app instance. Can someone elaborate more on that and when is the second one is used? -
Django Admin "__str__ returned non-string (type User)" error
I have 2 models named "Bid" and "Bidder" . I can not reach my table data when i click on data link on Admin Page for both models. It gives "str returned non-string (type User)" error. I think it s about my model code. class Bid(models.Model): main_contractor = models.ForeignKey("auth.User",on_delete = models.CASCADE,verbose_name = "Main Contractor ") work_title = models.CharField(max_length = 150,verbose_name = "Title") content = models.TextField(max_length = 500,verbose_name = "Content") created_date = models.DateTimeField(auto_now_add=True,verbose_name="Created date") bond = models.IntegerField(null=True , blank=True , verbose_name = "Bond",default='0') country = models.CharField(max_length = 2, choices=COUNTRY_CHOICES , default="United States") sector=models.CharField(max_length = 2, choices=SECTOR_CHOICES , verbose_name = "Sector") business_type=models.CharField(max_length = 2, choices=BUSINESS_TYPE_CHOICES ,verbose_name = "Business Type") bid_date=models.DateField(auto_now_add=False,verbose_name="Bid Date (Year-Month-Day)") est_start_date=models.DateField(auto_now_add=False,verbose_name="Est Start Date (Year-Month-Day)") end_date=models.DateField(auto_now_add=False,verbose_name="End Date (Year-Month-Day)") work1_description=models.CharField(max_length = 200,verbose_name = "Work 1 Description") work1_quantity=models.IntegerField(verbose_name = "Work 1 Quantity") work1_unit=models.CharField(max_length = 200,verbose_name = "Work 1 Unit") work2_description=models.CharField(max_length = 200,blank=True, null=True , verbose_name = "Work 2 Description",default='' ) work2_quantity=models.IntegerField(null=True , blank=True , verbose_name = "Work 2 Quantity",default='0') work2_unit=models.CharField(null=True , blank=True , max_length = 200,verbose_name = "Work 2 Unit",default='') work3_description=models.CharField(max_length = 200 , blank=True, null=True , verbose_name = "Work 3 Description", default='' ) work3_quantity=models.IntegerField(verbose_name = "Work 3 Quantity",default='0', null=True , blank=True) work3_unit=models.CharField(max_length = 200,verbose_name = "Work 3 Unit",default='', null=True , blank=True) work4_description=models.CharField(max_length … -
Why instance in django dosen't work with me?
I tried with This function for return with it the fields but it dose not return anything :) How I can fix that? code def edtiNote(request , slug): if slug: n = get_object_or_404(addNote , slugUrl=slug) if request.method == 'POST': form = addNoteForm(request.POST or None , instance=n) if form.is_valid(): new_edit_form = form.save(commit=False) new_edit_form.user = request.user new_edit_form.save() return redirect('../../../notes/'+str(new_edit_form.slugUrl)) elif request.method == 'GET': return redirect('../../../notes/'+str(form.slugUrl)) else: form = addNoteForm() context = {'formViews':form} return render(request , 'edit_Note.html' , context) -
How to render ModelForm data into HTML template?
I'm trying to display user info from my model named Listing that's in the django admin into my HTML template named myaccount.html and I have not had any success. What am I doing wrong with my current code? Any help is gladly appreciated. Cheers. user_profile/models from django.contrib import auth from django.db import models from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings class Listing (models.Model): image = models.ImageField(default='default.jpg', upload_to='profile_pics') user = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True, null=True) updated = models.DateTimeField(auto_now=True) rank = models.CharField(max_length=100, null=True) name = models.CharField(max_length=100) address = models.CharField(max_length=100) zip_code = models.CharField(max_length=100) mobile_number = models.CharField(max_length=100) def create_profile(sender, **kwargs): if kwargs['created']: user_profile = Listing.objects.create(user=kwargs['instance']) post_save.connect(create_profile, sender=CustomUser) user_profile/views.py from django.http import HttpResponse, HttpResponseRedirect from django.http import HttpResponseNotFound from django.shortcuts import get_object_or_404 from django.shortcuts import render, redirect from django.conf import settings from .forms import HomeForm from .models import Listing from users.models import CustomUser def change_view(request): form = HomeForm(request.POST or None, request.FILES or None,) user_profile = Listing.objects.all user = request.user if request.method == "POST": if form.is_valid(): listing_instance = form.save(commit=False) listing_instance.user = user listing_instance.save() return redirect("myaccount") context = { 'form': form, 'user_profile': user_profile } return render(request, "myaccount.html", context) HTML {% extends 'base.html' %} {% load static %} <p>{{ Listing.name }}</p> … -
Hide access token in django templates
Im using maps api in my django project and here is one of my template scripts : <script> function loadMap() { window.L.maps('map_id', '..../access_token=ACCESS_TOKEN'); } </script> The problem is by clicking on inspect or view page source on browser , the access_token is visible for anyone . I tried to add this token in environment vars and pass os.environ.get('access_token') as context to my template but its not working and access_token is visible again . How can i hide this token from my code ? -
Implementing Vue into existing django app
I have an existing django app built but I am trying to implement vue js into the project. I habe tried some tutorials online but none seem to work of fulfill my needs. Can anybody recommend a good resource or tutorial to follow? -
Dynamically populated Django field does not display choices
I want to dynamically populate a Django ChoiceField from a stored procedure. However, I cannot get the results to display in the Django admin. It comes up blank. What am I missing? Sorry if I've asked a question that's already been answered. I've already looked and looked... class Plot(models.Model): plot_claim_type = models.CharField('Plot Claim Type', max_length=7) class PlotAdminForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(PlotAdminForm, self).__init__(*args, **kwargs) c = connection.cursor() try: c.execute("BEGIN") c.callproc("udf_getcodetypes", "1") results = c.fetchall() for o in results: self.base_fields['plot_claim_type'].choices = forms.MultipleChoiceField(choices=(o[0], str(o[1]))) finally: c.close() @admin.register(Plot) class PlotAdmin(admin.ModelAdmin): form = PlotAdminForm -
Override Wagtail Admin login with AllAuth
I am trying to override the Django Wagtail admin login with my AllAuth Login page. I've tried adding the following line from the Documentation to my settings.py WAGTAIL_FRONTEND_LOGIN_URL = '/accounts/login/' I am currently using this mixin to override the django-admin login admin.site.login = login_required(admin.site.login) How do i properly override the wagtail admin login with Allauth login? -
How to assign default values to a Django path
I am building a Django API where one of my paths in urls.py is: path('device_id/<str:device_id>/readings/<int:num_readings>, views.results, name='results') I want to avoid getting a 404 if a user specifies a device id but does not enter a number of readings. I'd like the assign a default value of readings to 10. This url is connect to a view called results def results(request, device_id, readings): For example, if a user goes to: device_id/2132/readings/ I would like device_id = 2132 and readings=10 in the results view device_id/2132/readings/24 I would like device_id = 2132 and readings=24 in the results view -
How should I link a Django (2.1.4, Python 3.7) User and a Discord Account?
I am creating a Django website and trying to link a Discord account to the user, for listening to when the user is mentioned on the associated Discord server. This is to be run with: Python 3.7 Django 2.1.4 Discord.py 1.0.0(a) Being still quite new to Django, I do not really know where to start (I have looked on Google but can't find anything helpful). Here is the code for views.py: import discord token = open('token.txt', 'r').read() client = discord.Client() @client.event async def on_ready(): print(f'We have logged in as {client.user}') @client.event async def on_message(message): print(f'{message.channel}: {message.author.name} ({message.author}): \n {message.content}') client.run(token) I have not been able to run it yet, not being able to figure out the Discord account linking. -
How to make upload multiple files in single form at Django?
I have product form that adding new item for sale in my e-commerce project, It has title, description, price, brand, size areas and I want add area for putting product images, I can upload single file with filefield in form but I need upload multiple files and insert to different relationship file model with my product model (product class gets images from different related class). How can I do it with single form? I think I am so close to solving but I am not right way. I used betterforms module but I couldn't it. model.py from django.db import models from django.db.models import F from ckeditor.fields import RichTextField class ProductImage(models.Model): product_id = models.ForeignKey("Product", on_delete = models.CASCADE, verbose_name = "Product") product_image = models.FileField(upload_to='product_images/') cover_image = models.BooleanField(default=False) upload_date = models.DateTimeField(auto_now_add = True, verbose_name="Upload Date") class Product(models.Model): seller = models.ForeignKey("auth.User", on_delete = models.CASCADE, verbose_name = "Seller") category = models.ForeignKey("Category", on_delete = models.CASCADE, verbose_name = "Category Name") title = models.CharField(max_length = 50, verbose_name="Product Title") size = models.ForeignKey("Size", on_delete = models.CASCADE, verbose_name = "Size") color = models.ForeignKey("Color", on_delete = models.CASCADE, verbose_name = "Color") last_used_date = models.DateTimeField(verbose_name="Last Used Date") description = RichTextField() created_date = models.DateTimeField(auto_now_add = True, verbose_name="Created Date") product_image = models.ManyToManyField("ProductImage", verbose_name = "ProductImages") I … -
Django Admin error no such column: bid_bidder.apply_id
When i try to reach djanfo admin panel bidder app . It gives "no such column: bid_bidder.apply_id" error . I think i have a problem about model . I ve exactly 2 chained custom models name "Bid" and "Bidder" . "Bidder" is a model to apply to "Bid" model . ( it s like "Article" and it's "Comment"s models ). I ve problem with Bidder model . When i try to reach admin page bidders model it gives error. I ll show you models.py i dont know what s problem ... class Bid(models.Model): main_contractor = models.ForeignKey("auth.User",on_delete = models.CASCADE,verbose_name = "Main Contractor ") work_title = models.CharField(max_length = 150,verbose_name = "Title") content = models.TextField(max_length = 500,verbose_name = "Content") created_date = models.DateTimeField(auto_now_add=True,verbose_name="Created date") bid_file = models.FileField(blank=True,upload_to="bid_file/",verbose_name="Contract Files") bond = models.IntegerField(null=True , blank=True , verbose_name = "Bond",default='0') country = models.CharField(max_length = 2, choices=COUNTRY_CHOICES , default="United States") sector=models.CharField(max_length = 2, choices=SECTOR_CHOICES , verbose_name = "Sector") business_type=models.CharField(max_length = 2, choices=BUSINESS_TYPE_CHOICES ,verbose_name = "Business Type") bid_date=models.DateField(auto_now_add=False,verbose_name="Bid Date (Year-Month-Day)") est_start_date=models.DateField(auto_now_add=False,verbose_name="Est Start Date (Year-Month-Day)") end_date=models.DateField(auto_now_add=False,verbose_name="End Date (Year-Month-Day)") work1_description=models.CharField(max_length = 200,verbose_name = "Work 1 Description") work1_quantity=models.IntegerField(verbose_name = "Work 1 Quantity") work1_unit=models.CharField(max_length = 200,verbose_name = "Work 1 Unit") work2_description=models.CharField(max_length = 200,blank=True, null=True , verbose_name = "Work 2 Description",default='' ) work2_quantity=models.IntegerField(null=True , … -
Django Contact Form
i created a contact form using django that sends name, email and message. The form goes through successfully with the name, subject attach however only a portion of the message arrives to gmail instead of the whole message. how can i get the full message to show you on the gmail account? from django.db import models Create your models here. class Contact(models.Model): name = models.CharField(max_length=30) email = models.EmailField() message = models.TextField() def __str__(self): return self.name Forms from django import forms from django.forms import ModelForm from .models import Contact class ContactForm(forms.ModelForm): class Meta: model = Contact fields = ('name', 'email', 'message',) widgets = { 'name': forms.TextInput(attrs={'':''}), 'email': forms.TextInput(attrs={'':''}), 'message': forms.TextInput(attrs={'': ''}), } -
the amount of questions generated by an app is based on the amount of tickets he/she has in a cart app. How could I make this work?
Hi I'm setting up a site where a users can purchase tickets for a raffle. Before they get to be entered, they have to answer questions. the amount of go's at the question they can have has to be depended on the amount of tickets they are trying to purchase. If a ticket is delated or added from the cart so will the question. I have already created a cart app and the quiz app but I have an issue with conntecting them together. Any advice would be much appreciated! -
Make migrations in Djnago doesn't create the ForeignKey and OneToOneFields and adds them after the creation of models. Cannot migrate
Thanks in advance for taking you time to look over my question. I am developing a small Project Management app using: Python 3.6 with Django 2.1.5 I have some issues when I am making the migrations for my models. Basically, I am building a main Project Model and to this I am linking other activities to it. When I am making the migrations I have to following output in the Terminal: NOTE that: For the "project_creator" migrations, the OneToOneFields and ForeignKeys are added after the models are created (env) $ python manage.py makemigrations Migrations for 'authentication': authentication/migrations/0001_initial.py - Create model User - Create model Profile - Create model Roles Migrations for 'project_creator': project_creator/migrations/0001_initial.py - Create model ProjectBudgetModel - Create model ProjectDatesModel - Create model ProjectDescriptionModel - Create model ProjectMember - Create model ProjectModel - Create model ProjectProblemsToDescriptionModel - Create model ProjectTasksToDescriptionModel - Add field project to projectmember # - Add field project_member to projectmember - Add field project to projectdescriptionmodel - Add field updated_by to projectdescriptionmodel - Add field project to projectdatesmodel - Add field updated_by to projectdatesmodel - Add field project to projectbudgetmodel - Add field responsible to projectbudgetmodel - Add field updated_by to projectbudgetmodel When I migrate to … -
Why is my ModelChoiceField showing three forms instead of two and why is it not reading my choices?
First of all, I have two model forms fused into one form and they are supposed to show topic name and question type, but for some reason, three forms are showing up and the first one is not showing choices where the second one is showing up two times, and I don't want the second one which is the one with the choices showing up in it because my CSS are not applied on it. Choices are not showing up. Three forms instead of two. This is my model.py from django.db import models from home.choices import * # Create your models here. class Topic(models.Model): topic_name = models.IntegerField( choices = question_topic_name_choices, default = 1) def __str__(self): return '%s' % self.topic_name class Image (models.Model): image_file = models.ImageField() def __str__(self): return '%s' % self.image_file class Question(models.Model): questions_type = models. IntegerField( choices = questions_type_choices, default = 1) question_topic = models.ForeignKey( 'Topic', on_delete=models.CASCADE, blank=True, null=True) question_description = models.TextField() question_answer = models.ForeignKey( 'Answer', on_delete=models.CASCADE, blank=True, null=True) question_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.question_description class Answer(models.Model): answer_description = models.TextField() answer_image = models.ForeignKey( 'Image', on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return '%s' % self.answer_description This is my forms.py from django import forms from … -
Django queries using a list
I would like to run a query in django using a list. I found a similar post on stack overflow that got me to where I am now, but I can't seem to get my code to work. I think the only difference is that I am using REST. My code below is throwing the error unsupported operand type(s) for &: 'Build' and 'Build' What I am expecting is that the query will return all entries where the author_id matches any value in the machinesOwned list. from .models import Build import operator from functools import reduce class buildStatsAPI(generics.ListCreateAPIView):#for build stats permission_classes = (permissions.IsAuthenticated,) serializer_class = buildStatsAPI_serializer def get_queryset(self): machinesOwned = [4,5,7,9] query = reduce(operator.and_, (Build(author_id= item) for item in [machinesOwned])) return Build.objects.filter(query,deleted = 0,).values() -
Saving edited data via formsets
I am trying to edit multiple rows of data in a model via formsets. In my rendered form, I use javascript to delete (hide and assign DELETE) rows, and then save changes with post. My view: def procedure_template_modification_alt(request, cliniclabel, template_id): msg = '' clinicobj = Clinic.objects.get(label=cliniclabel) template_id = int(template_id) template= ProcedureTemplate.objects.get(templid = template_id) formset = ProcedureModificationFormset(queryset=SectionHeading.objects.filter(template = template)) if request.method == 'POST': print(request.POST.get) # Create a formset instance with POST data. formset = ProcedureModificationFormset(request.POST) if formset.is_valid(): print("Form is valid") instances = formset.save(commit=False) print(f'instances:{instances}') for instance in instances: print(f'Instance: {instance}') instance.template = template instance.save() msg = "Changes saved successfully." print("Deleted forms:") for form in formset.deleted_forms: print(form.cleaned_data) else: print("Form is invalid") print(formset.errors) msg = "Your changes could not be saved as the data you entered is invalid!" template= ProcedureTemplate.objects.get(templid = template_id) headings = SectionHeading.objects.filter(template = template) return render(request, 'procedures/create_procedure_formset_alt.html', { 'template': template, 'formset': formset, 'headings': headings, 'msg': msg, 'rnd_num': randomnumber(), }) My models: class ProcedureTemplate(models.Model): templid = models.AutoField(primary_key=True, unique=True) title = models.CharField(max_length=200) description = models.CharField(max_length=5000, default='', blank=True) clinic = models.ForeignKey(Clinic, on_delete=models.CASCADE) def __str__(self): return f'{self.description}' class SectionHeading(models.Model): procid = models.AutoField(primary_key=True, unique=True) name = models.CharField(max_length=200) default = models.CharField(max_length=1000) sortorder = models.IntegerField(default=1000) fieldtype_choice = ( ('heading1', 'Heading1'), ('heading2', 'Heading2'), ) fieldtype = models.CharField( choices=fieldtype_choice, … -
I can not show the saved images in the database
I am not able to show the images saved in the database, all other data appears, the only problem is in the images, in the html put the 3 commanders I tried to load the images. I am very beginner in python and django any help would be very welcome xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx models.py: class Usuario(models.Model): foto = models.ImageField( blank=False, verbose_name="Foto para seu perfil", upload_to='sistema/img') settings.py: import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '$n+6cd+9w+44=z*0o=8b#t&9*i!_ay%&6+kl=_cbq0%*sm0)c(' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['.127.0.0.1',] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'sistema', 'PetAqui', 'bootstrapform', 'widget_tweaks', 'crispy_forms', 'multiselectfield', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', ] SITE_ID=1 CRISPY_TEMPLATE_PACK = 'bootstrap4' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'PetAqui.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], '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', ], }, }, ] WSGI_APPLICATION = 'PetAqui.wsgi.application' # Database # https://docs.djangoproject.com/en/2.1/ref/settings/#databases DATABASES = { 'default': … -
Pagination for multiple query set from different models
I'm trying to get data from multiple models from multiple serializers. and I got the response and data but what is happen it didn't gives me the "count", "next" , and "previous" keys to use it for pagination. and I created a view as following: views.py class PlayerNotificationView(generics.GenericAPIView): def get_queryset(self): return def get(self, request, *args, **kwargs): activity_invitation_to_join = ActivityInvite.objects.filter(to_user=self.request.user, active=True, status__in=('P', 'k',)) team_invitation_to_join = TeamInvite.objects.filter(to_user=self.request.user, active=True, status__in=('P', 'k',)) team_player_left_team = TeamInvite.objects.filter(team__admin=self.request.user, active=True, status="L") activity_unread = ActivityInvite.objects.filter(to_user=self.request.user, read="False").count() team_unread = TeamInvite.objects.filter(to_user=self.request.user, read="False").count() total = activity_unread + team_unread un_read = [{'activity_unread': activity_unread, 'team_unread': team_unread, 'total': total}] context = [{ "request": request, }] activity_serializer = MyActivityInviteSerializer(activity_invitation_to_join, many=True, context=context) team_serializer = MyTeamInviteSerializer(team_invitation_to_join, many=True, context=context) team_player_left_serializer = MyTeamInviteSerializer(team_player_left_team, many=True, context=context) un_sorted_queryset = activity_serializer.data + team_serializer.data + team_player_left_serializer.data from operator import itemgetter response = sorted(un_sorted_queryset, key=itemgetter('updated_date'), reverse=True) + un_read context = { "notifications": response, } return Response(context) and it return response like this: { "notifications": [ { . . . }]} and what i need exactly is paginate the result to be like this: { "count": 2, "next": next, "previous": previous, "notifications": [ {.. }]} } So, how can I do this ? Please any one can help me? and if there any solution for this … -
Undefind path shows when trying to log in via email or username in Django
I am making a login page with Django to log in via either username or email. I start a app users, in this app, I have customized the users/model.py class UserProfile(AbstractUser): pass in my users/views.py, I have code to read input name="username" from .models import UserProfile from django.contrib.auth import authenticate from django.contrib.auth import login as auth_login from django.contrib.auth.backends import ModelBackend from django.db.models import Q class CustomBackend(ModelBackend): def authenticate(self, request, username=None, password=None, **kwargs): try: user = UserProfile.objects.get(Q(username=username)) | Q(email=username)) if user.check_password(password): return user except Exception as e: return None def login(request): if request.method == "POST": user_name = request.POST.get('username', '') password = request.POST.get('password', '') user = authenticate(username=user_name, password=password) if user is not None: auth_login(request,user) return render(request, 'index.html') else: return render(request, 'login.html',{}) elif request.method == 'GET': return render(request,"login.html",{}) in settings.py AUTH_USER_MODEL = 'users.UserProfile' AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", 'users.views.CustomBackend', ] As a result, I can log in using the username and password, it prints: [03/Feb/2019 23:40:06] "POST /login/ HTTP/1.1" 200 37066 # but when I log in with email and password, nothing change in my browser. On the terminal, it prints: Not Found: /user/login/ [03/Feb/2019 23:41:30] "POST /user/login/ HTTP/1.1" 404 2213 I don't know where this path "/user/login/" comes from, it's different from the … -
Django: Method Not Allowed (POST):
I am trying to create an event in FullCalendar by passing a timestamp into the url of a Django CreateView. However, after pressing submit on my form I keep getting a blank page and the error: Method Not Allowed (POST): /fullcalendar/ambroses-calendar/ html: dayClick: function(date, jsEvent, view) { if($('#calendar').fullCalendar('getView').type != 'month') { $("#occDiv").load("{% url 'edit_occurrence_short' 1234567898765 %}".replace(1234567898765, (new Date(date)).getTime())).dialog({ autoOpen: false, modal: true, bgiframe: true, width: 800 }); $("#occDiv").dialog('open'); } urls.py url(r'^occurrence/add/(?P<date>\d+)/$', ShortCreateOccurrenceView.as_view(), name='edit_occurrence_short') Views.py: class ShortOccurrenceMixin(CalendarViewPermissionMixin, TemplateResponseMixin): model = Occurrence pk_url_kwarg = 'occurrence_id' form_class = ShortOccurrenceForm class ShortCreateOccurrenceView(ShortOccurrenceMixin, CreateView): template_name = 'schedule/edit_occurrence_short.html' def form_valid(self, form): occurrence = form.save(commit=False) start = datetime.datetime.fromtimestamp(self.kwargs.get('date', None)/1000.0) end = start + datetime.timedelta(hours=1) occurrence.start = start occurrence.end = end occurrence.save() return HttpResponseRedirect('home') Models.py: class Occurrence(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE, verbose_name=_("event")) title = models.CharField(_("title"), max_length=255, blank=True) description = models.TextField(_("description"), blank=True) start = models.DateTimeField(_("start"), db_index=True) end = models.DateTimeField(_("end"), db_index=True) cancelled = models.BooleanField(_("cancelled"), default=False) original_start = models.DateTimeField(_("original start"), auto_now=True) original_end = models.DateTimeField(_("original end"), auto_now=True) created_on = models.DateTimeField(_("created on"), auto_now_add=True) updated_on = models.DateTimeField(_("updated on"), auto_now=True) Forms.py: class ShortOccurrenceForm(forms.ModelForm): class Meta(object): model = Occurrence fields = ('title', 'event') -
Deeping in M2M Queries
I have the following queryset which retrieves publications of the followers of the current user. followers is a M2M field of User to itself (many users to many users). Publication.objects.filter(user__in = self.request.user.followers.all()).order_by('created') As a recommendation system, I want to retrieve by a similar query the publications of followers of followers of a user, or followers of followers of followers of [...nsteps] of him. How can I do that? The idea would be something like this: Publication.objects.filter(user__in = self.request.user.followers.all().followers.followers).order_by('created') If possible, a would like to not evaluate querysets or evaluate as less of them as possible for efficiency.