Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
views.py not working and member is not removed, interest not removed too
Ok in my project, every blogpost has their own group of members. You are only a member if your interest status is 'Accepted', and you get auto added to the member list. Every user can "submit interest" to any blogpost. In case you are confused, the members is a field of BlogPost model, and the status is a field in the InterestInvite model :) I am trying to make it such that when I press the 'remove member' button, they get removed from the member list, and also the initial interest that they have submitted would be removed. Which means members that are removed can submit interest again. There are 2 views, the first view is the functionality for the blog post author to be able to remove ANY member from the members list, the second view is the functionality for any of the members to be able to remove THEMSELVES from the members list. Can any kind soul help to see why my views aren't working models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) members = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name="members") … -
How do I host a Django project (including media files) on AWS? ( Can I get a step by step guide? ) [closed]
I want to host a Django application on AWS ( paid tier ) with media files ( I assume we have to set up a S3 bucket for that ). This is the first time I am hosting my Django app on AWS, so can anyone give me a step by step guide? -
Data from session delete after logging out. How to fix that?
I have a simple event app. Each user can join other users' events and they show up in "My events" of this user. When i log out and log in again on this user, those events dissapear. How to fix that? Joining events works properly, but leaving does not. How to fix that? @login_required(login_url='login') def join_event(request, pk): event = Event.objects.get(id=pk) if request.method == "POST": event.current_members += 1 if request.session.get("joined_event"): request.session["joined_event"].append(pk) else: request.session["joined_event"] = [pk] request.session.modified = True if event.current_members <= event.total_members: event.save() return redirect('/') else: messages.error(request, 'Event is full!') context = {'event': event} return render(request, 'events/join_event.html', context) @login_required(login_url='login') def leave_event(request, pk): event = Event.objects.get(id=pk) if request.method == "POST": event.current_members -= 1 if request.session.get("joined_event"): request.session["joined_event"].remove(pk) else: request.session.modified = True request.session["joined_event"] = [pk] if event.current_members >= 0: event.save() return redirect('/') context = {'event': event} return render(request, 'events/leave_event.html', context) @login_required(login_url='login') def my_events(request): request.session.modified = True joined_event = Event.objects.filter(id__in=request.session.get("joined_event", [])) events = request.user.event_set.all() context = {'events': events, 'joined_event': joined_event} return render(request, 'events/my_events.html', context) -
How to query the blogpost wihtout slug as my function argument?
Sorry I am quite new to Django. Ok in my project, every blogpost has their own group of members. You are only a member if your interest status is 'Accepted', and you get auto added to the member list. Every user can "submit interest" to any blogpost. So now on the account page of the user, i want to query the blog posts that the user is a member to (aka interest status = "accepted" I also want to query the blog posts that the user has submitted interest to and that they are waiting to be accepted. to (aka interest status = "pending" and not a member yet) In case you are confused, the members is a field of BlogPost model, and the status is a field in the InterestInvite model :) so in my template i want to have the title of all those blogpost that I am a member to and those blogpost where my interest is still pending status to be displayed. And when I click on the title, I will be directed to that particular blog post. Can anyone share how this querying can be done? Problem i am facing is that i cannot use … -
Django object.raw('query') doesnot return updated queryset
class view_name(viewsets.ModelViewSet): queryset = model_name.objects.raw('call stored_procedure();') serializer_class = model_name_Serializers permission_classes = [IsAuthenticated] So, when I execute the above the rest framework view set. It works fine. But when I update any value which will effect the queryset of the stored procedure. It still return the previous queryset not the updated one. I have then checked by running the call procedure sql statement in my database(mysql) where it returns the updated queryset. But this raw function continues to show the queryset with the previous values. It only returns the updated queryset after restarting the localhost server. -
Django Changing Date Input Format
I have a simple booking form which is having a date input in a line like: reservation.html <textarea name="booking" class="form-control" id="reservation" value="{{placement.date|date:'d/m/Y'}}"></textarea> models.py class Lib(models.Model): booking = models.DateField(null=True, blank=True) My database postgresql based and also store date as in "date" format. I would love to change date-input like dd/mm/yyyy I also tried to use placement.date|date type format in double quotes like: <textarea name="booking" class="form-control" id="reservation" value="{{placement.date|date:"d/m/Y"}}"></textarea> But its still accept as mm/dd/YY. Is there any problem about my placement? My forms.py kinda simple like: from django.forms import ModelForm from .models import Lib from django.utils import formats class LibForm(ModelForm): class Meta: model = Lib fields = ['title','name','email','booking'] I searched on google and on stackoverflow and found something on Django - Setting date as date input value and django how to format date to DD/MM/YYYY but i couldn't find anything that could help me. I have to seek help here as a last resort. Thanks in advance. -
Post json data as plain text with new line in Django REST API
I have a python service(web) in which i want to input plain texts with new lines using Django REST API. For example, Input: 3 January February June I want to input this constrains with new line in the below django API content form. See below picture, I will get the output by some calculation after retrieving the post input values in APIView. The Response will be the output as an JSON. For example, [ "01", "02", "03" ] My problem is when i try to post that input (texts with new lines). It gives error as below, How can i input (plain text with new line) through this python Django REST API and the output will be as a response be an ordered json array. Thanks in advance for your guidelines -
Getting Django model name of uploaded file
I have a django model and I want to access its name. I am using objects.get with id set to 1 because I know that there is only one file that has currently been uploaded to excel_upload class. below is how i go that path for the file. However I a looking to try and access the name of the file. by name i mean the the string associated with the file. I know i can go into the admin panel and just click on excel_upload -> my_excel_file and then see the name. but I am looking for a way to access it in code. the_uploaded_excel_file = excel_upload.objects.get(id=1) excel_file_path_from_db = the_uploaded_excel_file.my_excel_file.path print(excel_file_path_from_db) -
Django cookiecutter with postgresql setup on Ubuntu 20.4 can't migrate
I installed django cookiecutter in Ubuntu 20.4 with postgresql when I try to make migrate to the database I get this error: python manage.py migrate Traceback (most recent call last): File "manage.py", line 10, in execute_from_command_line(sys.argv) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 361, in execute self.check() File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/base.py", line 387, in check all_issues = self._run_checks( File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 64, in _run_checks issues = run_checks(tags=[Tags.database]) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/core/checks/database.py", line 9, in check_database_backends for conn in connections.all(): File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 216, in all return [self[alias] for alias in self] File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 213, in iter return iter(self.databases) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/utils/functional.py", line 80, in get res = instance.dict[self.name] = self.func(instance) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/db/utils.py", line 147, in databases self._databases = settings.DATABASES File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 79, in getattr self._setup(name) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 66, in _setup self._wrapped = Settings(settings_module) File "/home/mais/PycharmProjects/django_cookiecutter_task/venv/lib/python3.8/site-packages/django/conf/init.py", line 176, in init raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.") django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty. I did the whole instructions in cookiecutter docs and createdb what is the wrong? -
django queryset values not merging
based on this answer i have this model class PortfolioExchangeTransaction(models.Model): creator = models.ForeignKey('accounts.Account', on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Creator')) create_time = models.DateTimeField(default=timezone.now, verbose_name=_('Create Time')) portfolio = models.ForeignKey(Portfolio, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Portfolio'), related_name='exchange_transaction') type = models.CharField(max_length=40, choices=Transaction_TYPE, blank=True, null=True, verbose_name=_('Type')) exchange = models.ForeignKey(BorseExchange, on_delete=models.SET_NULL, null=True, blank=True, verbose_name=_('Exchange')) count = models.IntegerField(default=0, verbose_name=_('Count')) i want to sum count of all PortfolioExchangeTransaction per exchange so i want sum similar records queryset per exchange as below code: PortfolioExchangeTransaction.objects.all().values('exchange') and i was hopping get something like this: <QuerySet [{'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 940}]> but with values i got like this: <QuerySet [{'exchageid': 591}, {'exchageid': 591}, {'exchageid': 512}, {'exchageid': 248}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 591}, {'exchageid': 940}, {'exchageid': 591}, {'exchageid': 248}, {'exchageid': 248}]> how fix this? -
Azure MySQL transaction.atomic() in Django gives a server error
I use an Azure VM, mysqlclient==1.4.6, Django==2.1.5 My code in admin.py: from django.db import transaction ... try: with transaction.atomic(): ... settings.py: 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': DB_HOST, 'PORT': '3306', 'NAME': 'db', 'USER': ..., 'PASSWORD': ..., 'AUTOCOMMIT': True, 'OPTIONS': { 'ssl': {'ssl-ca': '...'} # i modified it } I get: The page cannot be displayed because an internal server error has occurred. any help is appreciated -
Django ORM queryset equivalent to group by year-month?
I have an Django app and need some datavisualization and I am blocked with ORM. I have a models Orders with a field created_at and I want to present data with a diagram bar (number / year-month) in a dashboard template. So I need to aggregate/annotate data from my model but did find a complete solution. I find partial answer with TruncMonth and read about serializers but wonder if there is a simpliest solution with Django ORM possibilities... In Postgresql it would be: SELECT date_trunc('month',created_at), count(order_id) FROM "Orders" GROUP BY date_trunc('month',created_at) ORDER BY date_trunc('month',created_at); "2021-01-01 00:00:00+01" "2" "2021-02-01 00:00:00+01" "3" "2021-03-01 00:00:00+01" "3" ... example 1 "2021-01-04 07:42:03+01" 2 "2021-01-24 13:59:44+01" 3 "2021-02-06 03:29:11+01" 4 "2021-02-06 08:21:15+01" 5 "2021-02-13 10:38:36+01" 6 "2021-03-01 12:52:22+01" 7 "2021-03-06 08:04:28+01" 8 "2021-03-11 16:58:56+01" 9 "2022-03-25 21:40:10+01" 10 "2022-04-04 02:12:29+02" 11 "2022-04-13 08:24:23+02" 12 "2022-05-08 06:48:25+02" 13 "2022-05-19 15:40:12+02" 14 "2022-06-01 11:29:36+02" 15 "2022-06-05 02:15:05+02" 16 "2022-06-05 03:08:22+02" expected result [ { "year-month": "2021-01", "number" : 2 }, { "year-month": "2021-03", "number" : 3 }, { "year-month": "2021-03", "number" : 3 }, { "year-month": "2021-03", "number" : 1 }, { "year-month": "2021-04", "number" : 2 }, { "year-month": "2021-05", "number" : 3 }, { "year-month": … -
500 internal server error when editing files on ubuntu server(No Module named Django)
I had my website running normally not until I made a few changes in the views.py and one of the templates file. Then I had this Werid error, "500 Internal Server Error", and when I changed the error logs. I saw the error. Error Logs (venv) root@vps-e47d7ac6:/home/ubuntu/app# sudo tail /var/log/apache2/error.log [Tue Jan 26 07:40:03.581363 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] Traceback (most recent call last): [Tue Jan 26 07:40:03.581405 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] File "/var/www/app/station/asgi.py", line 12, in <module> [Tue Jan 26 07:40:03.581414 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] from django.core.asgi import get_asgi_application [Tue Jan 26 07:40:03.581446 2021] [wsgi:error] [pid 18182:tid 140673103349504] [remote 197.210.227.43:50689] ImportError: No module named 'django' [Tue Jan 26 07:40:04.348655 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] mod_wsgi (pid=18182): Target WSGI script '/var/www/app/station/asgi.py' cannot be loaded as Python module. [Tue Jan 26 07:40:04.348789 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] mod_wsgi (pid=18182): Exception occurred processing WSGI script '/var/www/app/station/asgi.py'. [Tue Jan 26 07:40:04.348939 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] Traceback (most recent call last): [Tue Jan 26 07:40:04.348978 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] File "/var/www/app/station/asgi.py", line 12, in <module> [Tue Jan 26 07:40:04.348987 2021] [wsgi:error] [pid 18182:tid 140673220962048] [remote 197.210.54.234:55809] … -
xhtml2pdf on heroku deployment gets (404)
deployed my little django app to heroku. locally everything with xhtml2pdf is working fine. on heroku i get: Page not found (404) Request Method: GET Request URL: https://ers-heatscreen-app.herokuapp.com/1/pdf/ Raised by: angebot.views.generate_pdf_view do i have to install/configure something extra on heroku? requirements.txt arabic-reshaper==2.1.1 asgiref==3.3.1 dj-database-url==0.5.0 Django==3.1.5 django-crispy-forms==1.10.0 django-heroku==0.3.1 future==0.18.2 gunicorn==20.0.4 html5lib==1.1 Pillow==8.1.0 psycopg2==2.8.6 PyPDF2==1.26.0 python-bidi==0.4.2 python-form==0.2.3 pytz==2020.5 reportlab==3.5.59 six==1.15.0 sqlparse==0.4.1 webencodings==0.5.1 whitenoise==5.2.0 xhtml2pdf==0.2.5 -
Django can you give the same user 2 usernames(with "profiles")?
I'm working on a system where the same user might have 2 profiles (ex one as an employee and one as his personal profile) and I want him to access diff parts of the app based on his profile, can he get 2 usernames and get diff permissions based on the username he signed in with? Thought of making a profile model which has a user type and a foreign key to user and then make user type and user unique together so that the user could have multiple profiles but not of the same time. and then make the username on the profile and then keep the profile in the request instead of the user, but that is making a lot of issues, one is that Django doesn't allow having no username field on the user model, so does anyone know any workaround? Or the only way is giving him multiple users??? Please I need a fast answer.... -
How should I implement delayed topic architecture in python Kafka
I am. building a project which uses Kafka . I have to implement retry strategies, if a msg process failed in the main topic it will be published to retry_topic. Here I want to try /retry to send/consume a message after every 15 minutes. Can anyone suggest a solution for this? Kafka consumer should process the message after 15 minutes corresponding to the timestamp in the msg data. I am using python Kafka client. -
Django post single form to 1 model and another model twice
I have a customer form containing name, email, email2 and email3 inputs. I would like to save the form using a class based view and post name and email to Customer model and iterate thru email2 and email3 and post to AdditionalEmail model, which has a foreign key to the customer model. I got it to work using a function based view, but the code seems a bit...hacky to me and I wanted to see if someone had a better way to do this, preferably using a CBV instead of FBV. Here is what I have: models.py class Customer(models.Model): name = models.CharField(max_length=100, unique=True) email = models.EmailField(max_length=64, null=True, blank=True) def __str__(self): return f"{self.name}" def get_absolute_url(self): return reverse('customer_list') class Meta(object): ordering = ['name'] class AdditionalEmail(models.Model): name = models.ForeignKey(Customer, on_delete=models.CASCADE) email = models.EmailField(max_length=64, null=True, blank=True) def __str__(self): return f"{self.email}" class Meta(object): ordering = ['name'] forms.py class CustomerForm(forms.ModelForm): class Meta: model = Customer fields = '__all__' widgets = { 'name': forms.TextInput(attrs={'autofocus': 'true', 'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), } class AdditionalEmailForm(forms.ModelForm): class Meta: model = AdditionalEmail fields = ['email'] widgets = { 'email': forms.EmailInput(attrs={'class': 'form-control'}), } views.py def CustomerCreateView(request): if request.method == 'POST': customer_form = CustomerForm(request.POST) email_form2 = AdditionalEmailForm(request.POST, prefix='email2') email_form3 = AdditionalEmailForm(request.POST, prefix='email3') if … -
How to create a line chart with Json in Django?
I created a system with Django. I want to display a line chart. I decided to use chart.js library. I have an API address and I take values from there. I can get values correctly, but I can not figure out how to display this values in a line chart. I try create some for loop but I had so many charts with only one value. It is wrong. Please, can you help me? views.py def Trend(request): response = requests.get('https://api.f-...gelir') data = response.json() return render(request, 'trend.html', {'data': data}) trend.html <div class="col-md-6"> <div class="card"> <div class="card-header"> <div class="card-title">Line Chart</div> </div> <div class="card-body"> <div class="chart-container"> <canvas id="lineChart"></canvas> </div> </div> </div> </div> <script> var lineChart = document.getElementById('lineChart').getContext('2d') var myLineChart = new Chart(lineChart, { type: 'line', data: { labels: [{{ data.text }}], datasets: [{ label: "Trend", borderColor: "#1d7af3", pointBorderColor: "#FFF", pointBackgroundColor: "#1d7af3", pointBorderWidth: 2, pointHoverRadius: 4, pointHoverBorderWidth: 1, pointRadius: 4, backgroundColor: 'transparent', fill: true, borderWidth: 2, data: [{{ data.value }}] }] }, options : { responsive: true, maintainAspectRatio: false, legend: { position: 'bottom', labels : { padding: 10, fontColor: '#1d7af3', } }, tooltips: { bodySpacing: 4, mode:"nearest", intersect: 0, position:"nearest", xPadding:10, yPadding:10, caretPadding:10 }, layout:{ padding:{left:15,right:15,top:15,bottom:15} } } }); </script> API [{"text":"Satış Gelirleri","value":0.04148631496798572},{"text":"TİCARİ FAALİYETLERDEN … -
Django filter does not filter
I'm trying to filter my API results through url parameters, but it's not working as expected. what am I missing in my code? even on DateRangeFilter, it's not filtering. Thanks! class RainfallFilter(filters.FilterSet): start_date = DateFilter(field_name='date', lookup_expr=('gt')) end_date = DateFilter(field_name='date', lookup_expr=('lt')) date_range = DateRangeFilter(field_name='timestamp') class Meta: model = Rainfall fields = ('level', 'amount', 'timestamp') class RainfallView(generics.ListCreateAPIView): serializer_class = RainfallSerializer queryset = Rainfall.objects.all() filterset_class = RainfallFilter def get(self, request, *args, **kwargs): queryset = self.get_queryset() serializer = RainfallSerializer(queryset, many=True) return Response(serializer.data) -
'NotificationQuerySet' object has no attribute 'mark_as_read'
I am implementing the django-notifications package in my code. Everything is simple and easily adoptable except I don't know how to use a method of AbtractionNotification class. The model in package is as bellow: # -*- coding: utf-8 -*- # pylint: disable=too-many-lines from distutils.version import \ StrictVersion # pylint: disable=no-name-in-module,import-error from django import get_version from django.conf import settings from django.contrib.auth.models import Group from django.contrib.contenttypes.models import ContentType from django.core.exceptions import ImproperlyConfigured from django.db import models from django.db.models.query import QuerySet from django.utils import timezone from jsonfield.fields import JSONField from model_utils import Choices from notifications import settings as notifications_settings from notifications.signals import notify from notifications.utils import id2slug from swapper import load_model if StrictVersion(get_version()) >= StrictVersion('1.8.0'): from django.contrib.contenttypes.fields import GenericForeignKey # noqa else: from django.contrib.contenttypes.generic import GenericForeignKey # noqa EXTRA_DATA = notifications_settings.get_config()['USE_JSONFIELD'] def is_soft_delete(): return notifications_settings.get_config()['SOFT_DELETE'] def assert_soft_delete(): if not is_soft_delete(): # msg = """To use 'deleted' field, please set 'SOFT_DELETE'=True in settings. # Otherwise NotificationQuerySet.unread and NotificationQuerySet.read do NOT filter by 'deleted' field. # """ msg = 'REVERTME' raise ImproperlyConfigured(msg) class NotificationQuerySet(models.query.QuerySet): ''' Notification QuerySet ''' def unsent(self): return self.filter(emailed=False) def sent(self): return self.filter(emailed=True) def unread(self, include_deleted=False): """Return only unread items in the current queryset""" if is_soft_delete() and not include_deleted: return self.filter(unread=True, deleted=False) … -
Django app crashes when I try to submit a photo to a form
So I have a django app in which I have created a form. When I get to submitting an image on the form I click the image icon and the app automatically crashes and i get this in the terminal: django.utils.datastructures.MultiValueDictKeyError: 'photo' ''' {% extends "auctions/layout.html" %} {% block body %} <h2>Create New Listing</h2> <form action="{% url 'newListing' %}" method="post"> {% csrf_token %} <div class="form-group"> <input autofocus class="form-control" type="text" name="title" placeholder="Title"> </div> <div class="form-group"> <input class="form-control" type="text" name="description" placeholder="Description"> </div> <div class="form-group"> <input class="form-control" type="number" name="bid" placeholder="Price"> </div> <div class="form-group"> <input class="form-control" type="image" name="photo" placeholder="Image"> </div> <input class="btn btn-primary" type="submit" value="Post"> </form> {% endblock %} ''' views.py ''' from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import User def index(request): return render(request, "auctions/index.html") def login_view(request): if request.method == "POST": # Attempt to sign user in username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "auctions/login.html", { "message": "Invalid username and/or password." }) else: #if user didnt just fill form they … -
How to GET API data USING AJAX BY ID in FULLCALENDAR
events: { // your event source url: 'http://127.0.0.1:8000/api/blocks-view/', // use the url property textColor: 'white', // an option! extraParams: { procedure: 'procedure', scheduler: 'scheduler' }, failure: function() { alert('there was an error while fetching events!'); } }, eventClick: function(info) { var event = info.event; $.ajax({ url:'http://127.0.0.1:8000/api/blocks-view/', type: 'GET', dataType: 'json', data: 'id=' + event.id, success: function(data) { var id = event.id; console.log(event.id); $('#spanBlockname').html(data.title); $('#spanStart').html(data.start); $('#spanEnd').html(data.end); $('#spanProcedure').html(data.procedure); $('#spanSchedulername').html(data.scheduler) $('#fullCalModal').modal('toggle'); }, -
No Reverse Match error for python crash course learning logs project
I am following the book Python Crash Course and am trying to do the Learning Logs app for Django. Everything was going well except when I tried to add entry forms for users on chapter 19. I am encountering the error "Reverse for 'new_entry' with arguments '('',)' not found. 1 pattern(s) tried: ['new_entry/(?P<topic_id>[0-9]+)/$']" My models.py look like this: from django.db import models # Create your models here. class Topic(models.Model): """A topic the user is learning about""" text = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return a string representation of the model.""" return self.text class Entry(models.Model): """Something specific learned about a topic""" topic = models.ForeignKey(Topic, on_delete=models.CASCADE) text = models.TextField() date_added = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'entries' def __str__(self): """Return a string representation of the model.""" return self.text[:50] + "..." My urls.py: """Defines url patterns for learning_logs""" from django.urls import path from . import views urlpatterns = [ # Homepage path('', views.index, name='index'), path('topics/', views.topics, name='topics'), #Detail page for single topic path('topics/<int:topic_id>/', views.topic, name='topic'), #page for adding a new topic path('new_topic', views.new_topic, name='new_topic'), #page for adding a new entry path('new_entry/<int:topic_id>/', views.new_entry, name='new_entry'), ] my views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from django.urls import reverse from .models import Topic … -
axios shows CORS error, with django rest framework
Thanks for reading. I am working with vuejs SPA with flask and django backends. Yes there are 2 backends. The application is in transition. I am switching the back end from Flask to Django Rest Framework. Some parts are still with Flask. Problem axios POST request does not hit django server. The error in console shows as a CORS error. Same calls worked with flask-restful and flask-CORS. GET request works fine with Django Relevant code BACKEND settings.py ... INSTALLED_APPS = [ ... 'rest_framework', 'corsheaders' ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ] CORS_ALLOW_ALL_ORIGINS=True ... views.py ... class SnippetView(ListCreateView): queryset = Snippet.objects.all() serializer_class = SnippetSerializer urls.py ... path('snippets/', SnippetListView.as_view(), name='snippet-list') ... FRONTEND Vuejs component <template> <v-form ref="form" v-model="valid" > <v-text-field v-model="code" label="Code" ></v-text-field> <v-text-field v-model="text" label="text" ></v-text-field> </v-form> </template> axios ... let snippet = { code: 'abc', text: ''} // comes from vuetifyjs form axios.post('http://localhost:8000/data/snippets', snippet) .then(res => console.log(res.data) // not working ... Adding json data works normally in django-admin dashboard, django_rest_framework API interface and in httpie command line client So it appears the issue is with axios. I have tried headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin' : '*', 'Content-Type': 'application/x-www-form-urlencoded' } Above have been tried separately I have also … -
I need to open a modal if a condition is satisfied and get the post value. Is this possible in django?
In my app there are several if conditions. In one of the if condition a modal with two buttons will be shown. if the user clicks one button it should go execute a statement. If user clicks another one it should execute another statement. Is it possible in django. In my views.py def something(request): if statement: (modal should pop up in window) and from the post value from the modal another process should be done.