Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_po
I had finished deploying my django app on heroku. But, when I went there to see it, I saw this error: ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_po... If you want to see the full error message, go here: https://fathomless-lowlands-24834.herokuapp.com/blog/ I could not include the entire message as it was really long, and exceeded the limit of words I was allowed to have in my question. I can't even understand where the error is. I tried searching for this online, but did not find any response that helped me. -
How to set such an object to Django memcached
How can I set such object: {'request': <rest_framework.request.Request object at 0x7fd5df07c6a0>, 'format': None, 'view': <jobs.api.views.JobDetailAPIView object at 0x7fd5df065790>, 'coordinates': None} to Django Memcached? I get a pickle error when I try: cache.set(key, context, time..) context variable is the dictionary: {'request': <rest_framework.request.Request object at 0x7fd5df07c6a0>, 'format': None, 'view': <jobs.api.views.JobDetailAPIView object at 0x7fd5df065790>, 'coordinates': None} -
group base on dates and create arrays of dates in django
hello I have a problem in achieving this I have Model class TimeLine(models.Model): lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='lead') user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='user',null=True) created_at = models.DateTimeField(auto_now_add=True) action = models.CharField(max_length=60) action_type = models.CharField(max_length=60) action_id = models.IntegerField() **Note: created_at is time stamp so it will be "2020-10-31 14:15:21.474851+05:30" ** Problem: I want to group by base on creation date (date only not time) of creatde_at field and order by those group in descending of that date with every data inside each group will be also ordered by created_at descending Ex: [ 2020-11-02 : { {name:'abc', created_at: '2020-11-02 14:17:05.638698+05:30'}, {name:'xyz', created_at: '2020-11-02 14:16:50.703442+05:30'}, }, 2020-11-01: { {name:'sss', created_at: '2020-11-01 12:16:28.262846+05:30'}, {name:'aaa', created_at: '2020-11-01 13:18:09.262846+05:30'}, {name:'rrr', created_at: '2020-11-01 16:16:27.262846+05:30'}, } ] Summary: I want every record of database bundle in dates then order by those bundle in descending and every row in the bundle should be in descending order of there created_at field. Thanks in advance by <3. -
Django forms.ModelChoiceField does not dynamically update html select options on page refresh
Django 2.2.16. I have a django form with an owner field. End-users of my django app need to select an owner between logged-in users. Django renders this field with a <select><option>...</option></select> html tag. I want the options contained in the tag to be updated on page refresh (when end-user hits F5). Since the owner field must contain a list of logged-in users, the option list has to be reasonably up-to-date. As far as I understood, forms.ModelChoiceField should have this behavior, since "(the queryset passed to forms.ModelChoiceField) is evaluated when the form is rendered", cfr. https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield My assumption here is that the form gets re-rendered upon page refresh, but this is not happening. The queryset passed to forms.ModelChoiceField works fine, i.e. when users log-in/out from my django app, a call to _get_logged_in_users() returns a queryset containing the correct list of logged-in users. Finally, I noticed the option list of logged-in users gets correctly updated only upon django restart. forms.py from django import forms from django.contrib.auth.models import User from django.contrib.sessions.models import Session from django.utils import timezone from .models import Event def _get_logged_in_users(): # private helper to return a queryset of logged-in users, by querying # all non-expired sessions sessions = Session.objects.filter(expire_date__gte=timezone.now()) uid_list … -
Django view definition with subfolder not rendering correctly in second time
I have a Django app accounts and in my Login link, when I click for the first time, it loads correctly: When I click for the second time it loads incorrectly. It basically trying to add the account/login at the end of the previous URL. I want to load http://127.0.0.1:8000/accounts/login when I click on the Login link, no matter I many times I have clicked on it. I am a newbie on Django and Python. I have tried to redirect, render, if-else statement and still no luck. Here are the details, I have an app name accounts in my project. The project urls.py: urlpatterns = [path("accounts/", include("accounts.urls")) ]. The account app urls.py urlpatterns=[ path("register", views.register, name="register"), path("login", views.login, name="login"), ]. The accounts app has two view function register and login: def register(request): return render(request, "register.html") def login(request): return render(request, "login.html") I am using two links, <li><a href="accounts/login">Login</a><i></i></li> <li><a href="accounts/register">Register</a></li> -
How can i add to a list in python without creating it
I have the following django view @login_required def statistics(request, slug=False): qn = get_object_or_404(Questionnaire, slug=slug) questions = Question.objects.filter(questionnaire=qn).count() qs = Question.objects.filter(questionnaire=qn) responses = Response.objects.filter(question__in=qs, user=request.user).count() if questions == 0 or responses == 0 or not questions <= responses: return render(request, "questionnaire/stats.html") out = {} for q in qs: response = Response.objects.filter(question=q, user=request.user).order_by("session_datetime").first() out[q.category] = {} time = response.session_datetime time_string = time.strftime("%d/%m/%Y") out[q.category][time_string] = [] responses_in_time = Response.objects.filter(question=q, user=request.user, session_datetime__gte=time, session_datetime__lt=time + datetime.timedelta(hours=24)) for res in responses_in_time: out[q.category][time_string] += [res.value] print(out) for category in out.keys(): print("outcat"+ str(out[category])) for time in out[category].keys(): out[category][time] = sum(out[category][time])/len(out[category][time]) print(out) return render(request, "questionnaire/stats.html", context={"questionnaire": qn, "stats_json": json.dumps(out)}) and i am wondering if there is a way to put together the dictionary with a time from the model/record in the loop without reseting it each time, if i try += without creating it first it complains but i do not know the initial time inside the loop. -
TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role'
I get this error when trying to create superuser: TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role' Is this the proper way to create it? I want to create superusers without username, just with email, and user can login only with their email addresses, and now when I create superuser it wants email, how I wanted, but gives me the error too. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_employee = True user.is_headofdepartment = True user.is_reception = True user.is_patient = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractUser): ADMIN = 1 RECEPTION = 2 HEADOFDEPARTMENT = 3 EMPLOYEE = 4 PATIENT = 5 NOTACTIVE = 6 ROLE_CHOICES = ( (ADMIN, 'Admin'), (RECEPTION, 'Reception'), (HEADOFDEPARTMENT, 'HeadOfDepartment'), (EMPLOYEE, 'Employee'), (PATIENT, 'Patient'), (NOTACTIVE, 'NotActive'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_headofdepartment = models.BooleanField(default=False) is_reception = models.BooleanField(default=False) is_patient … -
Time Data Format Non Accepting On PostgreSQL
I have a script that goes into my outlook calendar to change a date on a event that is already posted. Basically what happens is it does a query on the date you enter and searches for the name of the event. If it exists, it will delete the old event and post new. My current code im posting works on my dev server that is a SQL-Lite backend, my production server is on Heroku with PostgreSQL. It fails on my production. Here is my code. print('Authenticated W/ O365') # Checkes if event exists in K8 Calendar calendar = schedule.get_calendar(calendar_name ="K-8") calendar.name = 'K-8' print('Checking if Event Exits in K8 Calendar') print("Event Name:", obj.event_name) print("Event Start:", obj.start_date) print("Event End:", obj.end_date) q = calendar.new_query('start').equals(datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z')) <-- These are the lines that fail q.chain('and').on_attribute('end').equals(datetime.strptime(str(obj.end_date) ,'%Y-%m-%d %H:%M:%S%z')) <-- These are the lines that fail k8 = calendar.get_events(query=q, include_recurring = True) Traceback ValueError at /eventscalendar/event_request_non_approval_view/49 time data '2020-10-31 14:00:18-04:00' does not match format '%Y-%m-%d %H:%M:%S%z' -
Converting serialized data to dictionary in django
I tried to serialize user data in Django but then I wanted to print it in the console as a dictionary, it was giving me an empty dictionary, how would I go about this. serializer.py from rest_framework import routers, serializers, viewsets from accounts.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'username', 'email', 'first_name', 'last_name', 'date_joined' views.py from django.shortcuts import render from rest_framework.generics import ListAPIView from rest_framework.response import Response from .serialize import UserSerializer import json class userApi(ListAPIView): def get(self, request): queryset = User.objects.all() serializer_class = UserSerializer(queryset, many=True) return Response(serializer_class.data) apiuser=userApi() point = json.dumps(apiuser.__dict__) print(point) console Watching for file changes with StatReloader [2020-11-02 15:45:50,086] autoreload: INFO - Watching for file changes with StatReloader Performing system checks... **{}**#This is what it is printing Any help guys -
host django project on windows laptop can be access through internet [duplicate]
I want to host my Django project on a local machine with docker. I have configured the docker and create an image of it. i configured in dockerfile: EXPOSE 8000 cmd python manage.py runserver 0.0.0.0:8000 but I can only access only on local machines and machines which are connected in LAN. I want to access through any other device which is out of my LAN. I don't want any external software for hosting. in short, I want to host my website with IP address and run on my machine with docker. and can be accessed through internet. -
Axios interceptor returns 400 as 200
I'm using interceptors in a react native app and it works well except for a single request. This is my axios instance import axios, { AxiosResponse, AxiosError } from 'axios'; import JwtDecode from 'jwt-decode'; import { baseURL } from './utils/variables'; import { store } from './redux/store'; import { navigate } from './services/navigation/NavigationService'; import { ActionType, RootState } from './redux/types'; const _axios = axios.create({ baseURL, headers: { Accept: 'application/json' } }); _axios.interceptors.response.use( (response) => { if (__DEV__) { console.log(response.config.url); const axiosResponse = response; console.log({ axiosResponse }); } return response; }, async (error) => { console.log('[INSIDE ERROR]'); if (__DEV__) { if (error.config) { console.log(error.config.url); console.log(error.response?.status); console.log(error.response); const axiosError = error; console.log({ axiosError }); } } const originalRequest = error.config; console.log('[BEFORE RESPONSE CHECK]'); if (!error.response) return Promise.reject(error); console.log('[BEFORE 401 CHECK AND FALSE RETRY]'); if (error.response.status === 401 && !originalRequest._retry) { console.log('[IS 401!!]'); originalRequest._retry = true; if (originalRequest.url === '/login/') return Promise.reject(error); if (error.response.status === 401 && originalRequest.url == '/token/refresh/') return Promise.reject(error); return _axios .post('/token/refresh/', { refresh: (store.getState() as RootState).auth.authenticationRefreshToken, }) .then((res) => { store.dispatch({ type: ActionType.AUTHENTICATE, payload: { authenticationToken: res.data.access, }, }); store.dispatch({ type: ActionType.LOAD_TOKEN_INFO, payload: JwtDecode(res.data.access), }); originalRequest.headers.Authorization = `Bearer ${res.data.access}`; console.log('[BEFORE REQUEST RETRY]'); return _axios(originalRequest); }) .catch((err) => { if (err.response) … -
I am using django right now and i don't know how i could parse the data direct from the admin panel to the homepage template
I did this in my views.py file from django.shortcuts import render from . import models def home(request): context = { 'name': models.alldets, } return render(request, 'sites/home.html', context=context) on my home.html i did this <h1> {{ name }}</h1 and this is now my models.py from django.db import models class alldets(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name all files are in the same directory. I want to parse the data in my models.py to my homepage through the admin panel -
How to use GroupConcat on subquery in Django
I've got an app storing played music on different musicstations. My models looks like these: class PlaylistItem(models.Model): played_at = models.DateTimeField(_('played at')) station = models.ForeignKey(Station, on_delete=models.CASCADE) log_track = models.ForeignKey('LogTrack', on_delete=models.CASCADE) class LogTrack(UpdateInfo): track = models.ForeignKey(Track, on_delete=models.CASCADE, blank=True, null=True) class Track(UpdateInfo): artist = models.CharField(_('artist'), max_length=150) tracktitle = models.CharField(_('tracktitle'), max_length=150) The Track model is a model consisting standardised names of LogTrack songs. What I want is an overview of overlapping songs between different stations (matching a master station) in a period of time. And I want to know how many times this song has been played at the different stations. The idea is: I'm thinking of an output like this: Master Station | Station B | Station C ----------------------------------------- Track 1 (5 plays) | 8 plays | 3 plays Track 2 (2 plays) | No | 5 plays Track 3 (2 plays) | 2 plays | No In MySQL I've got this (maybe overcomplicated) query: select playlist_logtrack.track_id, count(playlist_logtrack.track_id) as playcount, json_group_played_per_station from playlist_playlistitem p1 left join playlist_logtrack on p1.log_track_id = playlist_logtrack.id left join ( select track_id, group_concat(json_played_per_station) as json_group_played_per_station, count(json_played_per_station) as station_count from (select track_id, concat('{"id":"', track_id, '", "station":"', station_id, '", "play_count":"', count(log_track_id), '"}') as json_played_per_station from playlist_playlistitem left join playlist_logtrack on playlist_playlistitem.log_track_id … -
How to create dropdown in django and pass the selected value to a method in django?
I am trying to create a combo box which should also allow me type the text using choicefield in django. This is Model. CATEGORY_CHOICES = Choices( ('KtCoffee', 'Karnataka Coffee'), ('Atea', 'Assam tea'), ('WBRice', 'West Bengal Rice'), ('GujCotton', 'Gujarat Cotton'), ('KerCocoa', 'Kerala Cocoa'), ) class maincategory(models.Model): category = models.CharField(choices=CATEGORY_CHOICES,max_length=25) def __str__(self): return self.category VIEW def update(request): if request.method == "GET": context = { 'choices': maincategory._meta.get_field('category').choices } return render(request, 'update.html', context) HTML <div> <input list="category-input"> <datalist id="category-input" style="width:100px"> {% for des,text in choices %} <option value={{text}}>text</option> {% endfor %} </datalist> </div> I am able to get dropdown list but only first word is shown in dropdownlist like for 'Karnataka Coffee' only 'Karnataka' comes in dropdown. -
Take the aggregate of an aggregate
I am trying to perform a number of calculations on a database table that requires me to aggregate (perform groupby's) at different levels. Let's say I have an existing queryset qs which looks something like <QuerySet [{'foo': foo_value, 'bar': bar_value, 'quantity': '10'}, {'foo': foo_value, 'bar': ... ]> where the vales in foo and bar are not unique. I can then groupby on fields foo and bar using qs = qs.values("foo", "bar").annotate(foobar_quantity=Sum("quantity")) to obtain the total quantity for each unique foo-bar combination. Then, a problem arises when I try to obtain the total for foo from the current query set. That is, if I try qs = qs.values("foo").annotate(foo_quantity=Sum("foobar_quantity")) I get the error django.core.exceptions.FieldError: Cannot compute Sum('foobar_quantity'): 'foobar_quantity' is an aggregate How would I go about aggregating on a field that itself is an aggregate? Keeping in mind that I need to groupby on certain fields and that I need to do some calculations in between the two groupby's. Is there some way around this or is this simply not possible in the Django ORM? -
Hello coders i have a problem with showing the image in django and i don't know how to fix it and i'm just a begginer
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/profile_pics/686319f4c9b83342a478a1a41561efbf.jpg Using the URLconf defined in basic_project.urls, Django tried these URL patterns, in this order: [name='index'] admin/ basic_app/ The current path, media/profile_pics/686319f4c9b83342a478a1a41561efbf.jpg, didn't match any of these. -
Django ValueError: Cannot query "user": Must be "Profile" instance
I am trying to add simple user to user messaging functionality to my blog app in Django. I have a view that allows a user to send a message but I am having difficulty in displaying the messages after. Here is my Message model: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages') sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages_from') message = models.TextField(blank=True) timestamp = models.DateTimeField(default=timezone.now, editable=False) unread = models.BooleanField(default=True) Here is my MessagesView attempt: class MessagesView(ListView): model = Profile template_name = 'users/messages.html' context_object_name = 'msg' def get_queryset(self): return Profile.objects.filter(messages_from__isnull=False, messages__user_id=self.request.user) And here is the url: path('messages/<int:pk>/', MessagesView.as_view(), name='messages'), Upon trying to load this page I receive the error Cannot query "user": Must be "Profile" instance where "user" is the name of the logged in user who's messages I am attempting to load. I have spent a long time googling a solution to this but have found nothing that relates to my case. Please help -
add dynamic field to serializer class
In my serializer class, i have defined two properties, and third property could be derived from those two properties. Please see the code below class ItemNameSerializer(NestedCreateUpdateMixin, ModelSerializer): nested_child_field_name = 'attribute_names' nested_child_serializer = AttributeNameSerializer attribute_names = AttributeNameSerializer(many=True) class Meta: model = ItemName fields = '__all__' from the above code we can see that attribute_names = AttributeNameSerializer(many=True) can be derived by [nested_child_field_name] = nested_child_serializer(many=true) So my question is can i add add dynamic field which will derived from other fields (to avoid writing redundant code) ? if yes then how ? the possible solutions can be of two types A. overriding some ModelSerializer method. B. generalised solution for any python class. please try to provide both type of solutions (if possible)(and may be of some another type ?) -
Django Styling a UserCreationForm with css
I a trying to add some style to the UserCreationForm, I cannot user Bootstrap for this project so need to modify its html and css directly. I have not been able to find anything in its documentation the allows me to do this. I added a email field to my UserCreationForm field by adding this snippet of code to models.py class CreateUserForm(UserCreationForm): class Meta: model = User fields = ['username', 'email', 'password1', 'password2'] and I pass the form as context to my template in views.py def register(request): if request.method == 'GET': if request.user.is_authenticated: return redirect('news') else: form = CreateUserForm() context = {'form': form} return render(request, 'base1.html', context) if request.method =='POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('login') return render(request, 'registration.html', context) this is how I have manage to display it inside my HTML5 template <form action="" method="post"> {% csrf_token %} <h1 class="t34"> Register </h1> <div class="t34">{{form.username.label}}</div> {{form.username}} {{form.email.label}}{{form.email}} {{form.password1.label}}{{form.password1}} {{form.password2.label}}{{form.password2}} <input type="submit" name="Create User"> </form> More over I have looked at several tutorials and did not find what I was looking for as well as an Stackoverflow where this answers seem to help but since they are years … -
Django 'django-admin' command not found. django version : 2.2
I'm trying to use the django-admin but sadly its not working correctly and I must use python -m django how can i fix it the commandline exception that it gives: django-admin : The term 'django-admin' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + django-admin version + ~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (django-admin:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException -
When calling a specific url, do not give full media url in django rest framework
After changing image to url, I am giving it to API. However, even though serialization has been carried out through the same serializer, when a request is sent to a particular url, it is transferred in the form of media/image_name instead of 127.0.0.1:8000/media/image_name. I can't find the cause of this. Can you help me find the cause by looking at my code? feed\serializers.py class PostSerializer (serializers.ModelSerializer) : owner = userProfileSerializer(read_only=True) like_count = serializers.ReadOnlyField() comment_count = serializers.ReadOnlyField() images = ImageSerializer(read_only=True, many=True) liked_people = LikeSerializer(many=True, read_only=True) tag = serializers.ListField(child=serializers.CharField(), allow_null=True, required=False) comments = CommentSerializer(many=True, read_only=True) class Meta : model = Post fields = ('id', 'owner', 'title', 'content', 'view_count', 'images', 'like_count', 'comment_count', 'liked_people', 'tag', 'created_at', 'comments') def create (self, validated_data) : images_data = self.context['request'].FILES post = Post.objects.create(**validated_data, created_at=str(datetime.now().astimezone().replace(microsecond=0).isoformat())) for i in range(1, 6) : image_data = images_data.get(F'image{i}') if image_data is None : break Image.objects.create(post=post, image=image_data) return post def to_representation (self, instance) : data = super().to_representation(instance) images = data.pop('images') liked_people = data.pop('liked_people') comments = data.pop('comments') images_array = [image.get('image') for image in images] liked_people_array = [liked_person.get('liked_people') for liked_person in liked_people] comments_array = [comment for comment in comments] if comments_array != [] : if len(comments_array) == 1 or len(comments_array) == 2: data.update({'image_urls': images_array, 'liked_people': liked_people_array, 'comment_preview': … -
django: [WinError 2] The system cannot find the file specified
I am working on a Django project where the user enters a file in pdf, doc, pptx or text (any document) that processed further and show some results as a plagiarism report. But I am getting error and unable to resolve it. I am a newbie to Django. someone, please help me out. this is full traceback. Environment: Request Method: POST Request URL: http://127.0.0.1:8000/index-trial/ Django Version: 3.1.2 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main'] Installed 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'] Traceback (most recent call last): File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\site- packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\Farhana Noureen\plagtrap\main\views.py", line 302, in post results = process_homepage_trial(request) File "C:\Users\Farhana Noureen\plagtrap\main\services.py", line 435, in process_homepage_trial queries = pdf.get_queries(filename) File "C:\Users\Farhana Noureen\plagtrap\util\getqueriespertype\pdf.py", line 17, in get_queries pdf_to_text_output = subprocess.check_output([settings.PDF_TO_TEXT, "-layout", absolute_file_path, "- "]) File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 395, in check_output **kwargs).stdout File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 472, in run with Popen(*popenargs, **kwargs) as process: File "C:\Users\Farhana Noureen\AppData\Local\Programs\Python\Python37\lib\subprocess.py", line 775, … -
Saving bound result to the database instead of actuall value
This is my first time working on Django, Python and MSSQL. I am creating a simple webpage where I take a name of an application and store it to the database using forms. Here is the classes: models.py from django.db import models from django.forms import forms, ModelForm # Create your models here. class Application(models.Model): name = models.CharField(max_length=100) forms.py from django import forms from .models import Application # define the class of a form class ApplicationForm(forms.ModelForm): class Meta: # write the name of models for which the form is made model = Application # Custom fields fields = ['name'] views.py from django.shortcuts import render from .forms import ApplicationForm def add_application_view(request): form = ApplicationForm(request.POST or None) if form.is_valid(): print('Form = ', form) # it shows the html code for debugging purpose print('cleaned = ', form.cleaned_data['name']) # it shows <bound method Field.clean of <django.forms.fields.CharField object at 0x7fcdd56c3910>> print(form['name'].value()) # it shows the correct value I entered print(form.data['name']) # it shows the correct value I entered form.save() form = ApplicationForm() context = { 'form': form } return render(request, 'application/add_application.html', context) whenever I test the page and enter any value as the name of the application, it stores the below value in the database as … -
a syntax error is showing in the code i don't know but its happen while building a web app with pyton and django
error wihile developing a web app with python and django PLS HELp -
Django - Unable to remove objects in the database through Full Calendar
I've been trying to implement Full Calendar in Django and I'am following this question FullCalendar in Django. I have successfully rendered the data in my database in Full Calendar but failed to implement a "remove/delete" function because of an error. The error generated None Internal Server Error: /scheduler/remove/ Traceback (most recent call last): File "C:\Users\Emman\Anaconda3\envs\elxr\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Emman\Anaconda3\envs\elxr\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Emman\Anaconda3\envs\elxr\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Emman\Desktop\elxr\elxr\scheduler\views.py", line 42, in remove event = Appointment.objects.get(id=id) File "C:\Users\Emman\Anaconda3\envs\elxr\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Emman\Anaconda3\envs\elxr\lib\site-packages\django\db\models\query.py", line 417, in get self.model._meta.object_name scheduler.models.Appointment.DoesNotExist: Appointment matching query does not exist. [02/Nov/2020 18:15:52] "GET /scheduler/remove/ HTTP/1.1" 500 80403 This is my models.py class Appointment(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='scheduler_appointments') id = models.AutoField(primary_key=True) client_name = models.CharField(max_length=50,null=True,blank=True) start_date = models.DateTimeField(null=True,blank=True) end_date = models.DateTimeField(null=True,blank=True) appointment_type = models.CharField(max_length=250,null=True,blank=True) client_sessions = models.IntegerField(null=True, blank=True) objects = models.Manager() def __str__(self): return 'ID : {0} Client Name : {1}'.format(self.id, self.client_name) my views.py excluding the calendar function because I think the problem is in this function def remove(request): id = request.GET.get("id", None) print(id) # prints None event = Appointment.objects.get(id=id) event.delete() data = {} return …