Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting fullcalendar javascript click data to django modelform
i want to click event on Fullcalendar, then it open another page, like this <script> document.addEventListener('DOMContentLoaded', function() { var calendarEl = document.getElementById('calendar'); var calendar = new FullCalendar.Calendar(calendarEl, { dateClick: function(info) { window.open("{% url 'create-book' %}","_self"); }, . but how to get data from fullcalendar ? there are function dateStr for show date, and resource.id, to show resource in timeline view(fullcalendar) alert('clicked ' + info.dateStr + ' on resource ' + info.resource.id); . what i want is bring dateStr and resource.id clicked data to django modelform, here views.py @login_required(login_url='login') def create_book(request): booking_forms = BookingForm(initial={ 'resourceId':'xxxx', 'startdate':'xxxx' }) im not sure what should i put on xxxx to get this through url on other page.. Thanks.. -
How to sort the fields in CreateView of Django?
I just learned django last January and I'm currently working on website to store and show lyrics. My problem is that in createview the fields are not sorted. Here is my models.py: class Lyrics(models.Model): title = models.CharField(max_length=50) singer = models.ForeignKey(Singer, on_delete=models.RESTRICT) type = models.ForeignKey(Type, on_delete=models.RESTRICT) lyrics = models.TextField() Views.py: class AddSongView(LoginRequiredMixin, CreateView): model = Lyrics fields = ['title', 'singer', 'type', 'lyrics'] Screenshot in the browser As you can see in the attached screenshot, the choices from singer field is not sorted. How to sort those choices? Thank you! -
A guidance for a mechanical bachelor student for getting start
I'm a undergraduate mech student and my first coding experience is learning python(in my 20th) that made me get over mech. Now I am looking for best process I can go through to become a django coder, front_end , back_end developer and things related on. What should I start to learn now?(your suggestion depend on what skill is suitable for a beginner to find a average job) -
Misaka Installation Error in a Django Project
I am using python 3.8. Whenever I try to install misaka in my Django project, it shows this error message: fatal error C1083: Cannot open include file: 'basetsd.h': No such file or directory I tried to clone the misaka repository from github but still this error persists. What should I do? -
Problem with connecting to localhost on Ubuntu WSL3
I set up locally Apache2 server for django project, and it worked perfectly well. The problem is that after one day off i got back to it and tried getting on server, and somehow i couldn't connect to it, even after checking if apache service is running, and reloading configuration just to be sure. I couldn't access it from localhost, and any other local tag. So after that i tried with django runserver command. Server was running, but i couldn't get on it as well. 2 days before, it worked without any issues. I'm using Ubuntu on WSL 3, and on windows i can run server without any problems. Tried pinging localhost and got 100% package loss. What i did then was restarting whole Ubuntu service with wiping all data. After setting up system everything worked again. The thing is that this is second time that this problem is occuring, and last time i get rid of it the same way, just restarting whole Ubuntu with removing all data. Second time after setting everything up and running server i tried restarting my computer to check if this problemm occurs, after windows restart, but it worked. -
Django-Snowflake external Browser connection issue when hosting in IIS Server
I have connected Snowflake from Django using authenticator as external browser.But when I hosted the application in IIS Server am not able to connect snowflake, Its not going for external browser and showing error like this HTTP Error 500.0 - Internal Server Error C:\TESTCASE_AUTOMATION-PYTHON-featue_UI\venv\Scripts\python.exe - The FastCGI process exceeded configured request timeout -
how i can assign a specific link to every user by which i can visit his profile
i want to assign a link for every user by which anyone can visit his profile i did this to achieve that hting but it doesn't work how i can do that my urls.py from django.conf.urls import url from django.urls import path from django.contrib.auth import views as auth_views from . import views from .views import SearchResultsView # Template Urls! app_name = 'accounts' urlpatterns = [ path('Skolar/',views.base, name= 'base'), path('Register/',views.register,name='register'), path('login/', views.my_login_view, name='login'), path('logout/',views.user_logout,name='logout'), path('<slug:username>/',views.profile, name='profile'), path('EditProfile/',views.update_profile,name='editprofile'), path('search/', SearchResultsView.as_view(), name='search'), ] my models.py for every user it created automatically with the help of signal from django.db import models from django.contrib.auth.models import User from django.utils import timezone from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Profile(models.Model): user = models.OneToOneField(User ,on_delete=models.CASCADE,) profile_pic = models.ImageField(upload_to='profile_pics',default='default.png',) twitter = models.URLField(max_length=80, blank=True,) facebook = models.URLField(max_length=80, blank=True,) about = models.CharField(max_length=1500, blank=True,) joined_date = models.DateTimeField(default=timezone.now,editable=False) dob = models.DateField(blank=True,null=True) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, *args, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() how i can assign that by which that link ony open that user profile which is assigned to it please help if you know how to do it -
Why can't I put values from database into "time" with python
I can't put values from database into type="time" please help me. {% for round in room_round %} <tr> <td> <div class="col-sm-6"> <input type="time" class="form-control" id="room_start" name="room_start[]" value={{round.room_start}} required>{{round.room_start}} </div> </td> <td> <div class="col-sm-6"> <input type="time" class="form-control" id="room_stop" name="room_stop[]" value={{round.room_stop}} required>{{round.room_stop}} </div> </td> <td><button type="button" class="btn btn-danger remove"><i class="glyphicon glyphicon-remove">Delete</i></button></td> </tr> {% endfor %} -
How to serialize a dataframe in django? Is there a way to return dataframe along with queyset in django?
What I'm trying to do here is get a query based on users' choices like date, group, and symbol. I would like to convert this queryset to a data frame using django_pandas. I tried to convert the data frame generated to JSON object but it gives some errors like: TypeError: Object of type 'DataFrame' is not JSON serializable. My viewset looks like this: class StockPriceDataViewSet(mixins.ListModelMixin, viewsets.GenericViewSet): queryset = StockPriceData.objects.all() serializer_class = StockPriceDataSerializer filter_backends = [DjangoFilterBackend, SearchFilter] filterset_fields = { 'date':['gte','lte'], 'org__symbol':['exact'], 'org__group':['exact'], } permission_classes = (AllowAny,) def get_queryset(self): queryset = super(StockPriceDataViewSet, self).get_queryset() result = generate_df(queryset=queryset) return queryset, result def generate_df(queryset): df = queryset.to_dataframe() df = df.drop(['s_n'], axis=1) df = df.set_index(['org','id'],inplace=True) result = df.to_json() return result When I run the above code in an interactive shell it runs smoothly without any errors but when Django handles the request an error pops up: 'NoneType' object has no attribute 'to_json' Also, the format of JSON is not standard as I was expecting. What am I doing wrong here? Can anyone explain. Any help will be appriciated. -
Session is not working in django restviews
Hi i am trying to set a value in session but not getting the value, I don't know what I am doing wrong. Setting Value class ClView(GenericAPIView): def get(self, request, *args, **kwargs): # Get Method Code def post(self, request, *args, **kwargs): cid = request.data['id'] request.session['myid'] = cid request.session.modified = True return Response(status=status.HTTP_202_ACCEPTED) Getting Value class MainView(APIView): def get(self, request, *args, **kwargs): cid = self.request.session.get('myid') return Response({"id":cid}) 'django.contrib.sessions.middleware.SessionMiddleware', in the middlewares -
Django Nested Annotate
I have 3 models class QuestionsModel(models.Model): created = models.DateTimeField(auto_now_add=True) Question = models.CharField(max_length=200) class AnswersModel(models.Model): Question = models.ForeignKey(QuestionsModel, related_name='QuestionAnswer') Answer = models.CharField(max_length=200) class UsersAnswerModel(models.Model): Answer = models.ForeignKey(AnswersModel, related_name='UsersAnswer') RegistrationID = models.CharField(max_length=200) I am trying to Count How many UsersAnswer the Question what I tried : class DashboardAdmin(admin.ModelAdmin): class Meta: model = QuestionsModel change_list_template = 'admin/Dashboard_change_list.html' date_hierarchy = 'created' def has_add_permission(self, request): return False def changelist_view(self, request, extra_context=None): response = super().changelist_view( request, extra_context=extra_context, ) try: qs = response.context_data['cl'].queryset except (AttributeError, KeyError): return response metrics = { 'totalAnswers' : models.Count('QuestionAnswer'), 'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer')) } response.context_data['summary'] = list( qs .values('Question') .annotate(**metrics) .order_by('-totalUsersAnswer') ) return response admin.site.register(DashboardModel, DashboardAdmin) I could not solve 'totalUsersAnswer' : models.Count(UsersAnswer=OuterRef('QuestionAnswer')) how to count nested foreign key any help please -
Django Rest Framework serializer is printing tuples instead of json
I've got the following serializer: from rest_framework import serializers from .models import Product class ProductSerializer(serializers.ModelSerializer): """ Serializer for Product object """ class Meta: model = Product fields = ['name', 'slug', 'description', 'image', 'price', 'active',] and the following test: from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient from rest_framework import status from .factories import ProductFactory from .models import Product from .serializer import ProductSerializer PRODUCTS_URL = reverse('product-list') def create_product(**params): """ Helper function to create a new product """ return Product.objects.create(**params) class PublicProductApiTests(TestCase): """ Test the public products' API """ def setUp(self): self.client = APIClient() def test_only_active_products_are_returned(self): ProductFactory.create_batch(2) products = Product.objects.all() serializer = ProductSerializer(products, many=True) print(serializer.data) When I print serializer.data on the screen, I'm getting: [OrderedDict([('name', 'Shane Fields'), ('slug', 'shane-fields'), ('description', 'Chance yourself conference.'), ('image', '/media/position/school.tiff'), ('price', '2.66'), ('active', False)]), OrderedDict([('name', 'Michael Hall'), ('slug', 'michael-hall'), ('description', 'Office city material room character number cause way.'), ('image', '/media/American/know.txt'), ('price', '-90244357.41'), ('active', True)])] after passing the queryset to the serializer and printing its data, isn't supposed to print in JSON format? what am I missing? -
Django: User not authenticating correctly
When logging into my app, the user is not authenticating correctly. Views.py ''' from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth import authenticate, login from django.urls import reverse from users.forms import CustomUserCreationForm from django.http import HttpResponse from users.models import Blog from django.contrib.auth.decorators import user_passes_test from django.contrib.auth.decorators import login_required # Create your views here. def intro(request): return render(request, "intro.html") def logmein(request): return render(request, "logmein.html") def login(request): username1 = request.POST.get('username') password1 = request.POST.get('password') user = authenticate(request, username=username, password=password) login(user, request) if user.is_authenticated: return render(request, "users/mainmenu.html") else: return render(request, "intro.html") def mainmenu(request): return render(request, "users/mainmenu.html") ''' Mainmenu.html ''' {% extends 'base.html' %} {% block content %} <h2>MainMenu</h2> Hello, {{ user.username }} {% endblock %} ''' When mainmenu.html is displayed following login, the user.username is showing as the SuperUser, regardless of what username and password is used to login. -
Access Django server running on local host from a computer with a certain IP address . Computers not on same network
I am a full stack engineer but know very little about networking. I have a django application running on my local host. I am interested in allowing only a specific IP address to be allowed access to my django server running on my computer. This computer is not on the same network as mine, so it would be a connection across the internet. Is such a thing possible? how is it done? my research so far shows me ways to do what I am trying to do, but to access my django server from a computer on the same network, and also does not restrict access to a certain IP address -
Django Application on Kubernetes is unable to send e-mails
I have a problem! I created an application (Python / Django) that is running on Linode with Kubernetes. Everything there is working perfectly, however, I can't send emails. I did tests using TLS (587) / SSL (465) and in the Dev environment (which I don't use Kubernetes) everything works with excellence, but, in Production my application doesn't send the e-mail and keeps processing without stopping until then showing error 502 (Bad Gateway | nginx / 1.19.2). What should I do? Thanks! -
Django object into JSON array into coordinates on a map
I'm just confused about one part here for JSON keys and values. So I have calculated a list of stores that is closest to my user's location shown below storages = Storage.objects.annotate(distance=Distance("location", user_location)).order_by("distance")[0:6] print(storages) data = serializers.serialize('json', storages) return JsonResponse(data, safe=False) next step I did is to convert it back into key value pairs. }).then(response => response.json()) .then(response => JSON.parse(response)) This way I can access the variables that I want through a code like so console.log(response[0].fields.location) however, my location data is stored as location: "SRID=4326;POINT (-122.9498219318841 49.21875514983133)" I want to loop through the array through first the response,fields, and then into locations, but the value has both long and lat. My initial thought is to perhaps created another nested element within location with long and latitude, not sure what is the correct way to do this. I followed a tutorial that was able to convert the django object into the template, but since this is an xmlhttprequest and also more dynamic, I cannot do that. Thank you! -
Django unit test fails on unique constraint
I'm writing a test to validate the uniqueness of a field. In this test, I'm trying to validate that a Product's slug is unique. My initial test was the following: from django.test import TestCase from django.urls import reverse from django.forms import ValidationError from django.db.utils import IntegrityError from rest_framework.test import APIClient from rest_framework import status from .factories import ProductFactory from .models import Product from .serializer import ProductSerializer PRODUCTS_URL = reverse('product-list') def create_product(**params): """ Helper function to create a new product """ return Product.objects.create(**params) class PrivateProductsTests(TestCase): def setUp(self): self.client = APIClient() def test_an_error_occurs_when_forcing_the_same_slug_for_different_products(self): product1 = ProductFactory.create(slug='') serializer1 = ProductSerializer(product1) product1_data = serializer1.data product1 = create_product(**product1_data) product2 = ProductFactory.create(slug=product1.slug) serializer2 = ProductSerializer(product2) product2_data = serializer2.data self.assertRaises(IntegrityError, create_product(**product2_data)) But it was failing with the following error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "products_product_slug_key" DETAIL: Key (slug)=(james-maxwell) already exists. looking around I found the following question which provided an answer: Fail on Testing IntegrityError UNIQUE constraint now my test looks like: def test_an_error_occurs_when_forcing_the_same_slug_for_different_products(self): product1 = ProductFactory.create(slug='') serializer1 = ProductSerializer(product1) product1_data = serializer1.data product1 = create_product(**product1_data) product2 = ProductFactory.create(slug=product1.slug) serializer2 = ProductSerializer(product2) product2_data = serializer2.data # there are two kinds of IntegrityError classes at play here, one # that's imported from the test and one … -
Difference between app_secret_key and secret_key for Django-Auth-App
For the python django package, django-duo-auth, the README shows the proper DUO CONFIG to be like so in settings.py: DUO_CONFIG = { 'DEFAULT': { 'HOST': '<api-host-url>', 'IKEY': '<integration_key>', 'AKEY': '<app_secret_key>', 'SKEY': '<secret_key>', 'FIRST_STAGE_BACKENDS': [ 'django.contrib.auth.backends.ModelBackend', ] } } HOST, IKEY, and SKEY make sense as they are attributes found in the Duo AUTH API, but I am confused as to what app_secret_key would mean. Any suggestions? -
Flushing a Database in Django
I'm setting up a database in django, while trying to flush the database i get the following error: `https://pastebin.com/Ktc203Rv.` While trying to migrate, the following error occured: `https://pastebin.com/Sc9rFQaT` I'm using django version 3.1.6 -
Django REST Framework: validated_data missing certain fields
I'm in the process of creating a registration process for my app. I'm having issues getting things running correctly. My intention is to send off one POST request with all of the necessary JSON to create the various models in Django. My error is that there is a KeyError for 'lat_long' when handling the coordinates. I checked validated_data to find that the data from my JSON body is not making it to the validated_data and neither is distance limit? However, bio, exp, age and town are all there in validated_data. Why is this? Both are declared in the ProfileSerializer and the models seem correct. However both of these fields are not present. In validated_data: 'genres' is just OrderedDict() with nothing inside so it isn't going to create the desired UserGenre instances either. Any help with this would be greatly appreciated, I've been trying to fix this for 4 days to no avail! P.S. If people could take a look at the serializers in particular and tell me am I going about creating multiple models/objects in one request correctly? Or is there a better way of doing it? Here is models.py (I'm using Djangos standard User object and have a Genre … -
Redirect page to dynamic URL Django
I'm a beginner on using django platform to create a mini project website and use a function based view. One of the feature in my project is a profile page that allowing user to edit the personal information. Here is my user profile models.py: class UserProfile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, blank=True) company_name = models.CharField(max_length=50, blank=True) company_url = models.URLField(max_length=50, blank=True) country = CountryField(null=True) AFF_CHOICES = (('Academic','Academic'), ('Bussiness','Bussiness'), ('Non-profit','Non-profit'), ('Industry/Government','Industry/Government')) affiliation = models.CharField(max_length=50, choices=AFF_CHOICES, null=True, blank=True) profile_picture = models.ImageField(upload_to='profile_picture', null=True, default='profile_picture/defaultphoto.png') def __str__(self): return str(self.user) Here is my urls.py app_name = 'dashboard' urlpatterns = [ path('', dashboard, name='dashboard'), path('<int:pk>/profile/',profile, name='profile'), path('<int:pk>/edit_profile/',edit_profile, name='edit_profile'), as you can see it will pass user PK so it will look like this (example on profile page) http://127.0.0.1:8000/dashboard/42/profile/ and it's already works. Here is my edit_profile views.py: def edit_profile(request, pk): user = request.user form = UserProfileForm(instance=user) if request.method == 'POST': form = UserProfileForm(request.POST, request.FILES, instance=user,) if form.is_valid(): form.save() messages.success(request, 'Your profile has been updated.') return redirect('/profile/dashboard/') #The problem is here #Still static else : form = UserProfileForm() context = {'editform':form} return render(request, 'dashboard/editprofile.html', context) i've tried this case with static url (not passing the user PK on url) and it is already works. How do i pass the … -
Django Display latest emails to certain user in Template
My django app I have created relies heavily on emails that are sent like this: from django.core.mail import send_mail send_mail( 'Subject here', 'Here is the message.', 'from@example.com', ['to@example.com'], fail_silently=False, ) Lets say that I keep sending an email to an user's email like this: post = get_object_or_404(Post, pk=pk) post_title = post.title author_of_post = post.author post_email = author_of_post.email send_mail( 'An User Comment on Your Post', '''Dear User, ''' ''' Your post, ''' + post_title + ''' was comment on by an user. Want to reply and check it out? --From the People at Red Man 2''' , 'redman2customerservice@gmail.com', [post_email], ) Now I want to add a notifications area, where it will display all the latest emails sent to the user, in the example of above post_email. So how would I do this. To sum up, I want to have a template where an user can see the latest emails sent to their account, sort of like a notification area. Thanks. -
ValueError: signal only works in main thread - Django, Scrapy celery
I am trying to implement a web scraper in my django app using scrapy in a celery task. I keep getting this error. I have tried every solution on here but can't figure it out. I followed this tutorial for my crawl file My crawl.py file from multiprocessing import Process from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from .spider import AliSpider settings = get_project_settings() class UrlCrawlerScript(): def __init__(self): self.crawler = CrawlerProcess(settings) self.crawler.install() self.crawler.configure() def _crawl(self, url): self.crawler.crawl(AliSpider(url)) self.crawler.start() self.crawler.stop() def crawl(self, url): p = Process(target=self._crawl, args=[url]) p.start() p.join() crawler = UrlCrawlerScript() def url_crawl(url): crawler.crawl(url) My Spider file import scrapy class AliSpider(scrapy.Spider): name = 'ali' def __init__(self, *args, **kwargs): self.url = kwargs.get('url') self.start_urls = [self.url] super(AliSpider, self).__init__(*args, **kwargs) def parse(self, response): title = response.css('.module-pdp-title ::text').extract() images = response.css('.main-image-thumb-ul img::attr(src)').extract() price = response.css('.ma-ref-price span::text').extract() types = response.css('.sku-attr-val span::text').extract() i = {} i['url'] = response.url i['title'] = title i['images'] = images i['price'] = price i['types'] = types return i -
Django Remove Allauth Custom HTML Forms
Hi Guys I'm using Allauth to login with Facebook. I developing the website using Django However it seems that if there is an issue with trying to login with my facebook account. The website is automatically being redirect to the default cancelled html page. Any idea how I can remove such redirection? Thanks -
get the id of the clicked instance in a django panel
I created two buttons and I am going to describe you the creation process and the functionality and finally I will ask my question. I have a django class of heroes. One button makes all heroes mortal, and one which makes all immortal. Since it affects all heroes irrespective of the selection, this needs to be a separate button, not an action dropdown. First, we will change the template on the HeroAdmin so we can add two buttons: @admin.register(Hero) class HeroAdmin(admin.ModelAdmin, ExportCsvMixin): change_list_template = "entities/heroes_changelist.html" Then we will override the get_urls, and add the set_immortal and set_mortal methods on the model admin. They will serve as the two view methods: def get_urls(self): urls = super().get_urls() my_urls = [ path('immortal/', self.set_immortal), path('mortal/', self.set_mortal), ] return my_urls + urls def set_immortal(self, request): self.model.objects.all().update(is_immortal=True) self.message_user(request, "All heroes are now immortal") return HttpResponseRedirect("../") def set_mortal(self, request): self.model.objects.all().update(is_immortal=False) self.message_user(request, "All heroes are now mortal") return HttpResponseRedirect("../") Finally, we create the entities/heroes_changelist.html template by extending the admin/change_list.html: {% extends 'admin/change_list.html' %} {% block object-tools %} <div> <form action="immortal/" method="POST"> {% csrf_token %} <button type="submit">Make Immortal</button> </form> <form action="mortal/" method="POST"> {% csrf_token %} <button type="submit">Make Mortal</button> </form> </div> <br /> {{ block.super }} {% endblock %} And …