Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display a ForeignKey field in a ModelForm with no default value?
I need to create a form for Player that has Role objects as choices in a dropdown field, but with their string field shown instead. models.py class Player(models.Model): role = models.ForeignKey(role) ... class Role(models.Model): designation = models.CharField() forms.py class PlayerForm(ModelForm): class Meta: model = Player fields = ['role'] Say I have three role objects with these as their designations, respectively: Warrior, Mage, Rouge, how can I display it in a PlayerForm instance as a dropdown, with no default value so the user has to choose one? Currently this code displays the objects as the objects themselves (Role object (1), Role object (2), ...) -
I have 2 classes Teams and ToDo, and 2 serializers and the code in View. In a query set i want as outcome "the team ID or PK which owns the Todo
class Teams(models.Model): name = models.CharField(max_length=20) file = models.FileField(upload_to='team_icons', null='True', blank='True') members = models.ManyToManyField(User, related_name='member') class ToDo(models.Model): title = models.CharField(max_length=200) description = models.TextField() owner = models.ForeignKey('auth.user', related_name='todos', on_delete=models.CASCADE) file = models.FileField(upload_to='uploads', null='True', blank='True') teamOwner = models.ForeignKey("Teams", related_name='team', on_delete=models.CASCADE) ==> the serializers class ToDoSerializer(serializers.ModelSerializer): class Meta: fields= ( 'id', 'title', 'description', 'owner', 'file', 'teamOwner', ) model = ToDo class TeamSerializer(serializers.ModelSerializer): # name = serializers.SerializerMethodField() class Meta: fields = ( 'id', 'name', 'file', ) model = Teams And finally the view code of the query: class ListTodo(generics.ListCreateAPIView): queryset = models.ToDo.objects.all() serializer_class = serializers.ToDoSerializer def get_queryset(self): owner_queryset = self.queryset.filter(Teams) return owner_queryset Every combination in .filter(xxx) fails. ik want as outcome the Team ID or PK number in the return queryset. Iam a beginner so i hope i explained my problem in a clear way -
Why django-rest-auth SocialLoginView is not working?
https://django-rest-auth.readthedocs.io/en/latest/installation.html here is the official docs about social login in django-rest-auth. they say the way to make the LoginView(GithubLogin, FacebookLogin, etc..) inheriting SocialLoginView like this. from allauth.socialaccount.providers.github.views import GitHubOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import OAuth2Client from rest_auth.registration.views import SocialLoginView class GithubLogin(SocialLoginView): adapter_class = GitHubOAuth2Adapter callback_url = CALLBACK_URL_YOU_SET_ON_GITHUB client_class = OAuth2Client but when i try to access the url with this as as.view(), they always say { "non_field_errors": [ "View is not defined, pass it as a context variable" ] } I tried the best. I have been suffering it for a few days. plz anybody save my life.. What's wrong with it? I've searched a lots but there wasn't any good answer for me. -
How do i get the context to test my view page?
I'm trying to test my search results to check the response when there are no results. this is the function in my view: def get_context_data(self, *args, **kwargs): result = super().get_context_data(**kwargs) query = self.request.GET.get('q') result['book'] = get_object_or_404(books,ISBN = query) return result this is my test class and function class Test_Search_results_view(TestCase): def test_no_results(self): response1 = self.client.get('/TextSearch/results1/?books=new&q=9780815345244') response2 = self.client.get('/TextSearch/results2/?books=new&author=Bruce+Alberts&Book+Name=Molecular+Biology+of+the+Cell&edition=6') self.assertEqual(response1.status_code, 404) self.assertEqual(response2.status_code, 404) self.assertQuerysetEqual(response2.context['book'],[]) but i keep getting this error self.assertQuerysetEqual(response2.context['book'],[]) File "C:----\context.py", line 83, in __getitem__ raise KeyError(key) KeyError: 'book' how do I check if my book query got empty results? -
Connect IIS FastCGIModule to Executable on NAS
I have a FastCGIModule handler that points to Python executables on a hard drive on the server. This works, and my Django site is displayed. When I change the executables section of the handler mapping to point to a NAS mapped to a drive on the server, I get this error when I navigate to the site: HTTP Error 500.0 - Internal Server Error An unknown FastCGI error occurred I am using the full DFS path in the path to the executable, because just using the mapped drive letter results in The specified executable does not exist on the server. How do I create a handler mapping in IIS that points to executables on a NAS? -
Django with Haskell
I have a program written in Haskell that does resource analysis, and I would like to build a web interface for this program. I will also start learning Django, for professional reasons, and it would be very convenient if I could combine both these goals, and build a web interface for this program using Django. What I would like to know is, is this even possible? At the moment I know nothing about Django, other than the fact that it is a python web framework. Keep in mind that this will be a very simple web interface, with almost no user interaction, it will be a simple "Insert you code here" and "This is the result". And because I have little hope that the above would work, what Haskell framework would you recommend to build this interface? Thank you! -
How to pass variables in a paramter of an html component with django
I'm today working on a django porject composed of only one application (an encyclopedia), but I am facing some struggles. I have a view named index that is displaying all the encyclopedias that the user can access to. On each file, I want to add a link to can redirect the user to the concerned encyclopedia. To do that, in my index view, I am calling a function that lists all the encyclopedias that we can have access to. This list will be used for rendering an html page. The problem that I am facing is on this html page named index.html. I am trying to pass the name of each encyclopedia in the href parameter for my link. Here is my html code: {% extends "encyclopedia/layout.html" %} {% block title %} Encyclopedia {% endblock %} {% block body %} <h1>All Pages</h1> <ul> {% for entry in entries %} <li><a href ="/{{entry}}">{{ entry }}</a></li> {% endfor %} </ul> {% endblock %} P.S: my django project is based on a base code provided by : https://cs50.harvard.edu/web/2020/projects/1/wiki/ -
How can solve a DeleteView problem in Django concerning a foreign key?
I have to apps (DMS and ObjPDW). The first one is for managing some files. In this I have a model DMS_Dokument, which includes a FileField and some more. Recently I added a new model to the latter app (ObjPDW) and I included a foreign key to Dokument_DMS: class Zahlungsstrom(models.Model): zahlung_bezeichnung = models.CharField(max_length=550, blank=False, null=False, verbose_name="Bezeichnung") zahlung_betrag = models.DecimalField(max_digits=7, decimal_places=2, default=None, blank=True, null=True) zahlung_dok_fk = models.ForeignKey(dmsdok.DMS_Dokument, on_delete=models.SET_DEFAULT, default=None, null=True, blank=True, verbose_name="Zahlungsdokument") Now I wanted to delete a DMS_Dokument object (using the DeleteView CBV), but it gives me a "prorammingerror": "(1146, "Table 'DB_DMS.ObjPDW_zahlungsstrom' doesn't exist")" I have no clue what the problem is. :( -
Django filters update query when user changes value in dropdown filter
I have a filter that is for my model that is a select of all the values in that columns. I would like to make it so that when the user select a value from the select it automatically filters the data without the need for a submit button. I believe I need an onclick attribute for the select field but I cant figure out how to set that up for filter forms. filters.py import django_filters from django_filters import CharFilter, AllValuesFilter from .models import * class SetFilter(django_filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains', label='', ) type = AllValuesFilter(field_name='type', choices=Set.objects.values_list('type', flat=True).distinct(), label='', ) class Meta: model = Set fields = '' exclude = [''] sets.html: <td class="d-none d-xl-table-cell">{{ myFilter.form.type }}</td> -
Django Model For An About Page
I have an about page which contains some information that I want editable through Django's admin interface, I created the following model for the page: from django.db import models class About(models.Model): office_address = models.CharField(max_length=100) phone_one = models.CharField(max_length=16) phone_two = models.CharField(max_length=16, null=True, null=True) mail_one = models.EmailField(max_length=40) mail_two = models.EmailField(max_length=40, null=True, blank=True) I have a couple of questions though. Number one, is what I am doing the right way? If it were you, how would you store those? What should I name my model? "About" is obviously not good, even in a plural case it will be Abouts! -
Execute function using curl
I have a function: def foo(request): qs = Example.objects.all() for query in qs: query.param += 10 query.save(update_fields=['param']) return redirect('main:index') urlpatterns = path('foo/', foo) When i use http://localhost:8000/foo in the browser, the function executes just fine, but when i try to execute it in the console using curl http://localhost:8000/foo, the function doesn't work, even though it accesses the server: * Trying 127.0.0.1:8000... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) * Server auth using Basic with user 'admin' > GET /foo HTTP/1.1 > Host: localhost:8000 > Authorization: Basic YWRtaW46TTd0d2E5bWo= > User-Agent: curl/7.68.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 301 Moved Permanently < Date: Mon, 26 Oct 2020 19:42:20 GMT < Server: WSGIServer/0.2 CPython/3.8.5 < Content-Type: text/html; charset=utf-8 < Location: /foo/ < Content-Length: 0 < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < * Connection #0 to host localhost left intact -
How to use Django model variable in form to set the input value in the HTML template
I have a database model called projects and a form model called project_id. I am looping through the projects in the database model -- {% for p in projects %}--to create bootstrap cards but I am trying to dynamically set the form's hidden input value to my project's primary key database id --{{ p.id }}--. The point here is to be able to click the view button to redirect to another page that will show the information of the project BUT that redirect is going to use the input value to run a database query in views.py. I've scoured the internet everywhere and can't find anything that doesn't use JS. project.html <div class="row"> {% for p in projects %} <div class="col-md-6"> <div class="card mb-4 box-shadow"> <img class="card-img-top" data-src="holder.js/100px225?theme=thumb&amp;bg=55595c&amp;fg=eceeef&amp;text=Thumbnail" alt="Thumbnail [100%x225]" src="{{p.showcase}}" data-holder-rendered="true" style="height: auto; width: 100%; display: block;"> <div class="card-body"> <h2 class="card-title">{{p.name}}</h2> <h6 class="card-subtitle mb-2 text-muted">{{p.contractor}}</h6> <p class="card-text py-3">{{p.description}}</p> <div class="d-flex justify-content-between align-items-center"> <form action="" method="POST">{% csrf_token %} <div class="form-group"> {{ form.project_id.value|deafult_if_none:{{p.id}} }} </div> <div class="form-group"> <input type="submit" value="View >>" class="btn btn-primary" /> <div class="submitting"></div> </div> </form> </div> <div class="text-right"> <small class="text-muted">{{p.date}}</small> </div> </div> </div> </div> {% endfor %} </div> -
Django: post form and post list on the same page
I make a site with multiple users, making posts with images and ability to add/remove friends. So it's easy to make two different pages for post list and creating a new one. But of course it looks better when you can read posts and make new at the same place. As I understand (learn django for less than a month), I can't connect 2 views to the same url, so the most logical way I see is to join 2 views in one, I also tried to play with template inheriting to render post form by including template, but actually it doesn't work. Below you can see my views, Post model, and templates. Thank you for attention. views.py: from braces.views import SelectRelatedMixin from . import models from django.views import generic from django.contrib.auth.mixins import LoginRequiredMixin class PostList(SelectRelatedMixin, generic.ListView): model = models.Post select_related = ('user',) class CreatePost(LoginRequiredMixin, SelectRelatedMixin, generic.CreateView): fields = ('post_message', 'post_image') model = models.Post select_related = ('user',) def form_valid(self, form): self.object = form.save(commit = False) self.object.user = self.request.user self.object.save() return super().form_valid(form) models.py: import misaka class Post(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, related_name = 'posts') posted_at = models.DateTimeField(auto_now = True) post_message = models.TextField() message_html = models.TextField(editable = False) post_image = … -
Clone model object values Django
i want to clone the values from existing model object and sanitize the values for special characters to provide a better search. So i already have values in the database that i want to sanitize and store in a new object after. This is a code example: class Entry(models.Model): headline = models.CharField(max_length=255) sanitized_headline = models.CharField(max_length=255) I would like populate all the sanitized_headline objects with the corresponding headline values after some character replacements like this re.sub('č', 'c', headline) applied to headline before cloning, as well as do this for every new entry. Im using Django for a GraphQl API character replacement can't be done through a view. Thank you -
Whats is the mean of getting {count: 0, next: null, previous: null, results: Array(0)} on console?
I am fetching the data from database in reactjs using axios below the code componentDidMount() { this.setState({ loding: true }); const token = getTokenu(); Axios.get(ApiUrlConstant.getApiFullUrl("bulletin.article"), { headers: { Authorization: "Token " + token, }, }) .then((res) => { console.log(res.data); this.setState({ data: res.data, loding: false }); }) .catch((error) => { this.setState({ error: error, loading: false }); }); } with django backend then I get below log on the console.. {count: 0, next: null, previous: null, results: Array(0)} note:-The data is there in our database. but still Im getting above log on console What is the mean of that? if we have data then why empty array showing on console? -
How to install pscopg2 on Python 3.9?
I have been trying to install psycopg2 (pip install psycopg2), but I keep getting error. I have also tried with: pip install psycopg2-binary but I'm getting the same error. Here is the error message: ERROR: Command errored out with exit status 1: command: 'c:\users\viktor\pycharmprojects\wemport\venv\scripts\python.exe' -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\Viktor\\AppData\\Local\\Temp\\pip-install-015ceiei\\psycop g2\\setup.py'"'"'; __file__='"'"'C:\\Users\\Viktor\\AppData\\Local\\Temp\\pip-install-015ceiei\\psycopg2\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"' "', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl' cwd: C:\Users\Viktor\AppData\Local\Temp\pip-install-015ceiei\psycopg2\ Complete output (23 lines): running egg_info creating C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info writing C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\PKG-INFO writing dependency_links to C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\dependency_links.txt writing top-level names to C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\top_level.txt writing manifest file 'C:\Users\Viktor\AppData\Local\Temp\pip-pip-egg-info-3shb13sl\psycopg2.egg-info\SOURCES.txt' Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. If you prefer to avoid building psycopg2 from source, please install the PyPI 'psycopg2-binary' package instead. For further information please check the 'doc/src/install.rst' file (also at <https://www.psycopg.org/docs/install.html>). ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. How to fix that? -
send_mail() in django is not sending. Command line sendmail is
I have a linux laptop. I am trying to test out some email functionality in my django app and I can't seem to get send_mail or EmailMessage to work. Here is my sendmail: def get(self, request, *args, **kwargs): send_mail( 'Subject here', 'Here is the message.', 'me@pop-os.domain', ['me@gmail.com'], fail_silently=False, ) return HttpResponse('Message sent') When I go to the page it prints a successful email message in the Terminal: Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Subject here From: me@po-pos.domain To: me@gmail.com Date: Mon, 26 Oct 2020 19:13:36 -0000 Message-ID: <160373961632.78488.2486155271127153156@pop-os.localdomain> Here is the message. I never receive the message in my gmail. I've changed to From and To to mask the actual email addresses. What could I be doing wrong? If I use the command line to sendmail like this it works. sendmail user@example.com < /tmp/email.txt -
Circular import error in wagtail.contrib.forms.models
I want to make sure that this is a bug before I submit it and not something I've configured incorrectly. I'm updating a website from Wagtail 2.5 to Wagtail 2.10.2 and I seem to have triggered a circular import into previously working code. The imports are as follows: from wagtail.core.models import Page, Orderable from wagtail.core.fields import RichTextField, StreamField from wagtail.admin.edit_handlers import FieldPanel, FieldRowPanel, MultiFieldPanel, \ InlinePanel, PageChooserPanel, StreamFieldPanel, TabbedInterface, ObjectList from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.documents import get_document_model from wagtail.documents.edit_handlers import DocumentChooserPanel from wagtail.snippets.models import register_snippet from wagtail.search import index from wagtail.snippets.edit_handlers import SnippetChooserPanel from wagtail.contrib.forms.models import AbstractForm, AbstractFormField, AbstractFormSubmission from wagtail.contrib.forms.edit_handlers import FormSubmissionsPanel from wagtail.contrib.forms.views import SubmissionsListView from wagtail.contrib.forms.forms import FormBuilder from wagtail.api import APIField The error I'm getting is: ImportError: cannot import name 'AbstractForm' from partially initialized module 'wagtail.contrib.forms.models' (most likely due to a circular import) I'm having a hard time sorting out where the issue is because it's hitting the import error at the start of the module. One thing I did try was to instead do from wagtail.contrib.forms import models as form_models and then use form_models.ModelName but that also resulted in a circular import error for AbstractFormField. However, that was triggered when the import is actually … -
Django - Is there a way to display a fa icon in a CreateView?
In my page, I have a notification system, which allows the admins to send custom notifications to a certain set of users. For now, it works correctly, creating a Notification object, which is then displayed to the users that need to see it. In my notifications bar in the UI, it displays a list of notifications, ordered by date, and each notification has an icon. For specific notifications (system-level notifications), there's specific fa icons being included <i class="fas fa-handshake"></i>, for instance. I'd like the admins to be able to include a specific icon from a set of icons I set. My relevant models look like this: class Icono(models.Model): name= models.CharField(max_length=100, null=False, blank=False) slug = models.CharField(max_length=100, null=False, blank=False) def __str__(self): return mark_safe('<i class="{}"></i>'.format(self.slug)) class Notificacion(models.Model): icono = models.ForeignKey(Icono, on_delete=models.CASCADE, null=True) # Other attributes I have a CreateView that creates the notification, that looks like this: class FormEnviarNotificacionView(LoginRequiredMixin, SuccessMessageMixin, SetUserEventoFormMixin, CreateView): model = Notificacion form_class = NotificacionForm template_name = 'eventos_admin/enviar_notificacion_a_asistentes.html' def get_success_url(self): return reverse_lazy('eventos_admin:send_notification', kwargs={'pk_evento': self.request.user.evento_activo.id}) def get_success_message(self, cleaned_data): if not self.object: return messages.warning(self.request, 'Hubo un error al enviar la notificación. Por favor, sólo envíe texto.') return 'Mensaje enviado correctamente.' And the form is just this: class NotificacionForm(AgregarNotificacionMixin, forms.ModelForm): class Meta: model … -
How to insert JSON file into django model to create an object
I have a huge json file like this and I cant enter it manually {"idmeasurements":2,"ip":"1.161.137.116","ip_decimal":27363700,"city":"Taipei","country":"Taiwan","latitude":25.04214,"longitude":121.51987,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.1,"continent":"Asia","region":null,"state":"Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} {"idmeasurements":3,"ip":"1.162.55.48","ip_decimal":27408176,"city":"Taipei","country":"Taiwan","latitude":25.04214,"longitude":121.51987,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.099887,"continent":"Asia","region":null,"state":"Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} {"idmeasurements":5,"ip":"1.163.233.221","ip_decimal":27519453,"city":"Sanchong","country":"Taiwan","latitude":25.06667,"longitude":121.5,"d_type":null,"dorgtype":"Telecommunications","naics":null,"isic":"Telecommunications","naics_code":517000.0,"isic_code":"J6100","data_source":"02-05-2018\/ddos1.csv","attack_type":"UDP Flood ","magnitude":0.094098,"continent":"Asia","region":null,"state":"New Taipei","isp":"HiNet","orgm":"HiNet","orgtype":"Telecommunications"} and a model like this class Data(models.Model): idmeasurements=models.IntegerField() ip=models.CharField(max_length=300) ip_decimal=models.IntegerField() city=models.CharField(max_length=300) country=models.CharField(max_length=300) latitude=models.FloatField() longitude=models.FloatField() d_type=models.CharField(max_length=300, null='TRUE') dorgtype=models.CharField(max_length=300) naics=models.CharField(max_length=300, null='TRUE') isic=models.CharField(max_length=300) naics_code=models.IntegerField() isic_code=models.CharField(max_length=300) data_source=models.CharField(max_length=300) attack_type=models.CharField(max_length=300) magnitude=models.FloatField() continent=models.CharField(max_length=300) region=models.CharField(max_length=300) state=models.CharField(max_length=300) isp=models.CharField(max_length=300) orgm=models.CharField(max_length=300) orgtype=models.CharField(max_length=300) I want to save this json data to create an object in this model -
Django WeasyPrint
I have a django template view that generates a bar chart: {% block pagecontent %} <script src="/static/javascript/jslib/highcharts.7.1.1/highcharts.7.1.1.js"></script> ... <link rel="stylesheet" href='/static/semantic/plugins/modal.css'> <h1>Test</h1> <div class="ui padded grid"> <div id="container" style="width:100%; height:400px;"></div> </div> <script type="text/javascript"> document.addEventListener('DOMContentLoaded', function () { var mainChart = Highcharts.chart('container', { animation: false, chart: { type: 'bar' }, title: { text: 'Fruit Consumption' }, xAxis: { categories: ['Apples', 'Bananas', 'Oranges'] }, credits: { enabled: false }, yAxis: { title: { text: 'Fruit eaten' } }, series: [{ name: 'Jane', data: [1, 0, 4] }, { name: 'John', data: [5, 7, 3] }] }); }); var demandChart; // globally available document.addEventListener('DOMContentLoaded', function() { demandChart = Highcharts.stockChart('container', { rangeSelector: { selected: 1 }, series: [{ name: 'USD to EUR', data: usdtoeur // predefined JavaScript array }] }); }); </script> {% endblock %} I'm using django-weasyprint to download the file but its not showing the javscript generated content. How can I do this via weasyprint? If its not possible, are there any packages that do support showing javascript content? Here is the weasyprint code: html = render_to_string(template_name=template_name, context=context) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = file_name pdf = weasyprint.HTML(string=html).write_pdf( stylesheets=[ weasyprint.CSS(base_url=base_url, string='body { font-family: Georgia, serif}'), ] ) -
Deploying Django + Next JS
I have built Django + Next JS website and now I want to deploy. I don't know which one to prefer hosting server or VPS. Website is simple, static and kind of catalogue. Next JS default homepage is pages/index.js. I mean it is not index.html, it is index.js Is it possible on hosting server? I'm asking because next js is also need to run node js server on development. On VPS plan does anyone know about how to dockerize exactly this things? Hosting or VPS? Which hosting server do you prefer? -
Calling javascript get from Django template does not fire
I'm trying to implement a simple like functionality on my Django site, should be straightforward enough. All of my code works fine except for the get() statement in the jquery code - it just doesn't do anything. I've looked through as many examples as I can and everything seems legit, but the get code just doesn't fire. I can manually put in the url, I reach my view function fine: the console output and the returning "hello" works when I do this. I've put in a call to update a test field to make sure the script is firing, that's ok. I'm stumped - any help would be greatly appreciated. I've stripped the code down to ensure it's just the .get() left tripping me up: In my template: <strong id="like_count">{%product.likes%}</strong> <button id="likes" data-prodid="{{product.id}}" class="btn btn-primary" type="button"> Like </button> <p id='test'></p> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script type="text/javascript"> $('#likes').click(function(){ var prodid; prodid = $(this).attr("data-prodid"); $('#test').html(prodid); $.get('/products/like/', {'product_id': prodid}, function(data){ $('#like_count').html(data); }); }) </script> My view function is simply this for the moment: def like_category(request): print('reached like_category') return HttpResponse('hello') Many thanks in advance for help with this. -
Django allauth disable new user creation
I am using Django allauth package I would like to implement the following functionality: If social user exists in my database, I do the usual logging in If there is not such social user, I would like to disallow user creation and return (in my response from view) just the data obtained from social network I understand how to disallow new users sign-up (through is_open_for_signup method), however I cannot figure out, how to return the data, obtained from the social network. Any help with that? -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/learn/learn-coming-soon/ Raised by: learn.views.CourseDetailView
i am trying to make a link on my home page to open another page. i created the template and i added the url path and view but i am still getting a page not found error. please help thanks. then name of the template is learn-coming-soon.html here is the code views.py class LearnComingSoonView(TemplateView): template_name = 'learn-coming-soon.html' urls.py path('learn-coming-soon/', views.LearnComingSoonView.as_view(), name='learn-coming-soon'), template {% extends 'base.html' %} {% load static %} {% block content %} <section id="default" class="hero-learn"> <div class="default"> <div class="hero-deets"> <h1>Coming Soon</h1> <!-- <h1>Learn anytime</h1> <p>become the best version of you today.</p> --> </div> </div> </section> {% endblock %}