Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-Deploy AWS ElasticBeanstalk - Health Red
Hello trying to deploy my django app in EB Note: my app has literally nothing, i just created a new one to check my eb status keeps helth = red Note: in my local env when i type python --version it shows 3.9.12 but when i created the eb init i did eb init -p python-3.8 store-django i don't know if there's much problem Full log of eb create store-django: eb create store-django Creating application version archive "app-220422_041439243455". Uploading: [-------------------------------------Uploading: [#######------------------------------Uploading: [##############-----------------------Uploading: [#####################----------------Uploading: [#############################--------Uploading: [####################################-Uploading: [#####################################Uploading: [##################################################] 100% Done... Environment details for: store-django Application name: store-django Region: us-west-2 Deployed Version: app-220422_041439243455 Environment ID: e-kpknmry6cd Platform: arn:aws:elasticbeanstalk:us-west-2::platform/Python 3.8 running on 64bit Amazon Linux 2/3.3.12 Tier: WebServer-Standard-1.0 CNAME: UNKNOWN Updated: 2022-04-22 07:16:53.279000+00:00 Printing Status: 2022-04-22 07:16:52 INFO createEnvironment is starting. 2022-04-22 07:16:53 INFO Using elasticbeanstalk-us-west-2-106867183434 as Amazon S3 storage bucket for environment data. 2022-04-22 07:17:14 INFO Created security group named: sg-01633b0706407c8aa 2022-04-22 07:17:29 INFO Created load balancer named: awseb-e-k-AWSEBLoa-1CUR121EIGENQ 2022-04-22 07:17:29 INFO Created security group named: awseb-e-kpknmry6cd-stack-AWSEBSecurityGroup-15U6VRTD05NMK 2022-04-22 07:17:29 INFO Created Auto Scaling launch configuration named: awseb-e-kpknmry6cd-stack-AWSEBAutoScalingLaunchConfiguration-G27zecBdyLEc 2022-04-22 07:18:33 INFO Created Auto Scaling group named: awseb-e-kpknmry6cd-stack-AWSEBAutoScalingGroup-L2RKI6CKUCOF 2022-04-22 07:18:33 INFO Waiting for EC2 instances to launch. This may take a few minutes. 2022-04-22 … -
Django CreateView object.id in get_succes_url pk(id) is NONE and then after redirecting to another URL it prints out created entry ID
I have a problem that I just can't figure out. After creating a work order I want to redirect to the detail page of that work order. Here is my models.py class Radni_nalozi(models.Model): Klijent = models.ForeignKey(Klijenti, on_delete=models.CASCADE) Pacijent = models.CharField(max_length=100) Rok_isporuke = models.DateField() Cijena = models.FloatField(default=0) Napomene = models.CharField(max_length=400,blank=True) Zaduzenja = models.CharField(max_length=400,blank=True) Status = models.CharField(max_length=50, choices=STATUS_CHOICES, default = "OTVOREN") Aktivan = models.BooleanField(default=True) def __str__(self): return f"{self.id} - {self.Klijent}, {self.Pacijent}" And here is my model form: class RadniModelForm(BSModalModelForm): class Meta: model = Radni_nalozi fields = ["Klijent","Pacijent","Rok_isporuke","Napomene","Zaduzenja"] labels = {"Klijent":"Klijent: ", "Pacijent":"Pacijent: ", "Rok_isporuke":"Rok isporuke: ", "Napomene":"Napomene: ","Zaduzenja":"Zaduženja: "} widgets = {'Rok_isporuke': DatePickerInput(options={ "locale":"en-gb", })} I want to create a new work order and I'm using django BSModalCreateView. Here is my views.py: class RadniCreateView(LoginRequiredMixin,BSModalCreateView): template_name = 'app/radni_nalozi/dodaj_rn.html' form_class = RadniModelForm def get_form(self): form = super(RadniCreateView,self).get_form() #instantiate using parent form.fields['Klijent'].queryset = Klijenti.objects.filter(Aktivan=1) return form def get_context_data(self, **kwargs): context = super(BSModalCreateView, self).get_context_data(**kwargs) context['title'] = 'NOVI RADNI NALOG' context['gumb'] = 'KREIRAJ' return context def get_success_url(self): print(self.object.pk) return reverse_lazy('detalji_rn', kwargs={'pk': self.object.pk}) The command print(self.object.pk) returns NONE although the object is created. If I put some other hardcoded value in reverse_lazy function (for example number 13) then my view executes, it redirects to the hardcoded value and … -
Django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0001_initial
I was trying to build logins with Google. I added django.contrib.sites in INSTALLED_APPS image. When I run python manage.py migrate on my Django project, I get the following error: django.db.migrations.exceptions.InconsistentMigrationHistory: Migration socialaccount.0001_initial is applied before its dependency sites.0001_initial on database 'default'. How can I solve this problem? -
Django error - ModuleNotFoundError: No module named 'polls.ulrs'
I just write the code the create app in django , its named "polls", configure like below: my project\urls.py from django.contrib import admin from django.urls import include, re_path urlpatterns = [ re_path('admin/', admin.site.urls), re_path(r'^$', include("polls.ulrs")), # path("", include("polls.ulrs")), ] my project\settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls' ] polls\ulrs.py from django.urls import re_path from . import views urlpatterns = [ re_path(r'^$', views.index, name='index'), ] polls\views from django.shortcuts import render # Create your views here. from django.http import HttpResponse def index(request): response = render() response.write("<h1>Welcome</h1>") response.write("This is the polls app") return response The issue i got as below, could you please help look this? File "C:\ProgramData\Anaconda3\lib\site-packages\django\urls\conf.py", line 38, in include urlconf_module = import_module(urlconf_module) File "C:\ProgramData\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'polls.ulrs' -
Why isn't django recognizing my token after i'm redirecting from browser?
In my frontend i'm logging into an app's api from the browser, I'm then redirected back to a View in my backend which gets a code from the app's api, sends it back in a post request then receives an access token and stores it in a model associated with the current user. I'm using token auth. View: class APICallback(APIView): authentication_class = [authentication.TokenAuthentication] permission_class = [permissions.IsAuthenticated] def api_callback(request, format=None): code = request.GET.get('code') if not code: return Response({'Error': 'Code not found in request'}, status=status.HTTP_400_BAD_REQUEST) response = post('https://accounts.api.com/api/token', data={ 'code': code, }).json() print(response) user = request.user access_token = response.get('access_token') token = APIToken(user=user, access_token=access_token) token.save() return redirect('frontend') I have other Views that make requests and it has been able to get the token to know who the user is, but when this View is called I get a 401 Unauthorized error. How do I let Django know the token I'm receiving from the other app's api belongs to the current user? also... when I take off permissions and authentication class from the View it returns the user as Anonymous User -
ModuleNotFoundError: No module named 'model' in Torch.load in Django project
I have trained my model and working well with just script. It load my model with torch as expected. However, when i connect it to the request, i got following error: File "/Users/feqanrasulov/Desktop/sdp/ner/testing/test.py", line 23, in main model = torch.load("/Users/feqanrasulov/Desktop/sdp/ner/testing/model.pth", map_location=lambda storage, loc: storage) File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 712, in load return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args) File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 1046, in _load result = unpickler.load() File "/Users/feqanrasulov/Desktop/sdp/venv/lib/python3.8/site-packages/torch/serialization.py", line 1039, in find_class return super().find_class(mod_name, name) ModuleNotFoundError: No module named 'model' [22/Apr/2022 07:08:20] "POST /ner HTTP/1.1" 500 123282 -
How to use custom authentication class inside ListAPIView
I am using react components and to test my code I wrote a quick custom authentication class and defined in the settings for the rest_framework as follow: DEFAULT_AUTHENTICATION_CLASSES += ['restaurant.rest_api.dev.DevAuthentication'] This works great and uses the user I tell it to class DevAuthentication(authentication.BaseAuthentication): def authenticate(self, request): user = User.objects.get(id=6) return (user,None) However, I am now trying to use ListAPIView from generics and the user that prints out is an anonymous user which means that it is not using my authentication class. I found that classes can be explicitly defined inside the function and so I did class SearchUsersAPIView(generics.ListAPIView): search_fields = ['email', 'first_name', 'last_name', 'phone_number'] filter_backends = (filters.SearchFilter,) queryset = CustomUser.objects.all() authentication_classes = [restaurant.rest_api.dev.DevAuthentication] serializer_class = userSerializer @permission_classes([IsAuthenticated]) def dispatch(self,request, *args, **kwargs): self.request = request print(self.request.user) if request.user.is_anonymous or request.user.is_user_superuser()==False: response = Response({"message":"Action Denied"}, status = status.HTTP_400_BAD_REQUEST) response.accepted_renderer = JSONRenderer() response.accepted_media_type = "application/json" response.renderer_context = {} return response return super().dispatch(request,*args, **kwargs) I must add that if I write a simple function view with the api_view decorator the user authenticated is the one that I have specified. I wonder why this is not working only for this class and uses its defaults which are basic and session authentication. Is there a way … -
Vercel error deploying Django project, python version error
1 When running the vercel command in Ubuntu terminal: Error! Command failed: python3.6 /tmp/2de7da56/get-pip.py --user ERROR: This script does not work on Python 3.6 The minimum supported Python version is 3.7. Please > use https://bootstrap.pypa.io/pip/3.6/get-pip.py instead. python --version returns 3.8.10. pip --version returns 22.0.4. vercel --version returns 24.0.1 requirements.txt just has Django == 4.0.3 What I tried: Ran the script linked in the error message and added its installation directory to PATH. Updated pip in default directory to 22.0.4. Even aliased python3.6 to python at one point. Tried on both Windows and Ubuntu. -
Failed to get value from html page in Django
I have a problem with trying to get a response from my HTML page using Django (admin). I have a pretty simple div = contenteditable and need to pass data from this div back after the submit button was clicked. Everything, including choosing selection and opening the intermediate page works fine. But when I tapped submit button, the condition if "apply" in request.POST failed to work. Please, tell me, what I'm doing wrong? This is my Django admin: class QuestionAdmin(AnnotatesDisplayAdminMixin, admin.ModelAdmin): def matched_skills(self, question): return ', '.join(s.name for s in question.skills.all()) def update_skills(self, request, queryset): if 'apply' in request.POST: print("something") skills = [] for question in queryset: skills.append(self.matched_skills(question)) return render(request, 'admin/order_intermediate.html', context={'skills': skills}) update_skills.short_description = "Update skills" This is my order_intermediate.html page: {% extends "admin/base_site.html" %} {% block content %} <form method="post"> {% csrf_token %} <h1>Adjust skills. </h1> {% for skill in skills %} <div> <div id="title" style="margin-left: 5px" contenteditable="true" > {{ skill }} </div> </div> {% endfor %} <input type="hidden" name="action" value="update_status" /> <input type="submit" name="apply" value="Update skills"/> </form> {% endblock %} -
Django Rest Framework and JWT authentication [closed]
I need to write Rest Api using JWT authentication My api should have endpoints like log in and sign up And also I need to extend User model with “last_request” attribute. What is the best way to extend the model? Can you help me with how to do sign up and log in with JWT more correct? I need some links and helpful videos about how to do it -
BeautifulSoup cannot scrap all images and image in bad quality
I have script for scrapping google image: import requests, base64 from bs4 import BeautifulSoup baseurl = "https://www.google.com/search?q=dog&sa=X&biw=1920&bih=880&tbm=shop&sxsrf=APq-WBthh6vre95oa-9ef0cSMsChCA6SAw:1649941428917&tbs=p_ord:p&ei=tBtYYv-gN52h4t4P47yHSA&ved=0ahUKEwj_ypTmzpP3AhWdkNgFHWPeAQkQuw0IkQcoAg" headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0"} r_images = requests.get(url=baseurl) soup_for_image = BeautifulSoup(r_images.text, 'html.parser') productimages = [] for item in soup_for_image.find_all('img'): print(item.attrs['src']) There are about 60 images that should be scrapped, but i just always get for about 20 images with really bad quality(low resolution). the result are about like this: data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNHB4IiBoZWlnaHQ9IjI0cHgiIHZpZXdCb3g9IjAgMCAyNCAyNCIgZmlsbD0iI2ZmZiI+PHBhdGggZD0iTTE5IDYuNDFMMTcuNTkgNSAxMiAxMC41OSA2LjQxIDUgNSA2LjQxIDEwLjU5IDEyIDUgMTcuNTkgNi40MSAxOSAxMiAxMy40MSAxNy41OSAxOSAxOSAxNy41OSAxMy40MSAxMnoiLz48cGF0aCBkPSJNMCAwaDI0djI0SDB6IiBmaWxsPSJub25lIi8+PC9zdmc+Cg== https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcQNk__f8LZateEE2C7-_H4TGXHnPNRgnlMfqB8-_bjWNgQuM84cDuLN0cXfWuBstyfm_DYLMA&usqp=CAE https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcQjC1vEyODtstOt2Yb9yUmTZxQRrbpNjjJ2qiX8yh0mS0e7OWopwU19OAat72F3tgRJ7dvS&usqp=CAE https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcTjs2ceUBAlGnGR1_ce-8J1KdjSZuIY5DoR-OVUuY3C-beE2zllqWANKCY&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcTbPaCI8R4rzD2URuN0XE1VMCldU0cMj0jCxj24UC67NAkfgLH6I1NctQel&usqp=CAE https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcSsPx9P3HWTAMTHXX4rTSOJD-iUAvTFMn9Q-eKTSGZ9dUwwhoLKsaxk5VQ&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcQKyuJL3PSso9FJCP5BQICvvH3sDfDDUfHOsa51VCzCqNHzTr_oHDnlgQWz&usqp=CAE https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcTO8tenhDQdGv3kDbrApVLAiGgr8WqOKTd1SJEFoXCDXd7xSFArnxBzQsoicNYOvR9X_sO5Ww&usqp=CAE https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcRV393tLnTZmEqu4Zm7Glc_TpOFPNX-ZY4V3uGnHAOsh6OC4BpmWMCKui2CW1A6XDDTqk2H&usqp=CAE https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcRZt6agJ0e3c1ySALArRxhSqi88tnerelb0u_WxGEApafo_JTvyxSdiRtMCNkwDencqGJrI&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcRFKj8o87bI17Vg0nVZFVplSIAiV_PmxekpeOIaUt3_d5lLzb957hMPyis&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcThzTxMcWvPcb7Q053Xw04qmYCuPHHHcW5xsg3fpa3eMFpAxOZYH-jccyBs&usqp=CAE https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcT0rZc0zInQV1a6OcSjT8YS6zi80y2-v8z5QObZKF7QY98HBiR27fkk7lShxiUV3NTzhv_z&usqp=CAE https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcQBUSEjeNdtSgD7Sjb5nd4S5b43YUsvoYG1U4YkVGc5G41KnxjiYAlAOAAdGK68T9EaIuxECg&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcRLv2e6MOeCb_kb5_u6wY9xLHAa4WfxzDwqE7s1eIH-wGqsOUFOe9AgF1I11wvL-ywUh8U2&usqp=CAE https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcSbWXF7yvud0aIiiYZ9B8-QlwosvGOm3kYscETZCfgQOUiWHaNmEmE3SAHVeqG500XC92Q9&usqp=CAE https://encrypted-tbn0.gstatic.com/shopping?q=tbn:ANd9GcT9qwFNC7w6sEdezOvmcP5fvGmlWiBr0lVErJs0FHen8RIm9IAbFZYqXAFMct7KZADe5Ney&usqp=CAE https://encrypted-tbn1.gstatic.com/shopping?q=tbn:ANd9GcT6pZTAAARwtnxxahwm9_2KNOPt-iIRwL_pV9EyPycJb3GclFthXIfOnSI&usqp=CAE https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcRGjhKHX1EY5XqLszVTKqId2CF-h8P1bpGtxOM5F_6cns7hzais_FWcb8w&usqp=CAE https://encrypted-tbn3.gstatic.com/shopping?q=tbn:ANd9GcTvDPtD-1qF8mQ_0_J_9RqgH6VEy-0K33o8lsrqbtbNc9L7GlNIy2R2-A8tMax8AoUCd9OnTw&usqp=CAE https://encrypted-tbn2.gstatic.com/shopping?q=tbn:ANd9GcRzMe9UCIv_hTSGUcz6jEGEskGQjYMDeScGWUS1CoCeO1_MHW5b0c2iAt8&usqp=CAE is there any way to get all the images(60 images) with the good resolution. -
How to create dropdown box in forms?
I am getting difficulty here to create dropdown box in forms. Please tell what to do here. I want to create dropdown box in forms for only section name and status. In admin site dropdown box is showing there but I don't know, how to create in forms. This will be great for me. I am new here. please help. forms.py: from django import forms from . import models class SpecificationForm(forms.ModelForm): class Meta: model=models.Specification fields=['section_name','operation_name','specification','hole_count','instrument_name','status'] widgets = { 'section_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'specification': forms.TextInput(attrs={ 'class': 'form-control' }), 'hole_count': forms.TextInput(attrs={'class':'form-control'}), 'instrument_name':forms.TextInput(attrs={'class':'form-control'}), 'status':forms.TextInput(attrs={'class':'form-control'}) } models.py: from django.db import models # Create your models here. class Specification(models.Model): sec=(('s3','s3'),('s327','s327'),) section_name = models.CharField(max_length=100,null=False,choices=sec) operation_name = models.CharField(max_length=100,null=False) specification = models.CharField(max_length=100,null=False) hole_count = models.PositiveIntegerField(null=False) instrument_name = models.CharField(max_length=100,null=False) stat=(('Active','Active'),('Inactive','Inactive'),) status = models.CharField(max_length=100,null=False,choices=stat) class Meta: db_table = "specification" index.html: <form method="post" class="post-form" action="/Master/specification_addnew"> {% csrf_token %} <div class="container"> <br> <div class="form-group row"> <label class="col-sm-1 col-form-label"></label> <div class="col-sm-4"> <h3>Specification Details</h3> </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Section Name:</label> <div class="col-sm-4"> {{ form.section_name }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Operation Name:</label> <div class="col-sm-4"> {{ form.operation_name }} </div> </div> <div class="form-group row"> <label class="col-sm-2 col-form-label">Specification:</label> <div class="col-sm-4"> {{ form.specification }} </div> </div> <div … -
API Encryption and Decryption in Django
How to encrypt and decrypt api response and request in django. The response data should be encrypted and send. -
Putting if else conditions in Django Rest Framework API View while searching
I was writing API with DRF and what I want is to change queryset, if the search will return no results. from rest_framework.generics import ListAPIView from rest_framework import filters from .models import Item from .serializer import ItemSerializer from .pagination import ItemPagination class SearchItemApi(ListAPIView): queryset = Item.objects.all() serializer_class = ItemSerializer filter_backends = [filters.SearchFilter] search_fields = ['name',] pagination_class = ItemPagination Here is the serializer: class ItemSerializer(serializers.ModelSerializer): class Meta: model = Item fields = ('id', 'name',) And this APIView will show these results on the page: { "count": 2, "next": null, "previous": null, "results": [ { "id": 1, "name": "Blue Jeans", }, { "id": 2, "name": "Red Jeans", } ] } How can I add a condition to return other queryset, if the search will bring zero results? -
when I send the cookies from the front-end (nextjs-reactjs), at the back-end (django-rest-framework) I get an empty dictionary with request.COOKIES
in the nextjs getServerSideProps i send request to api with this code : const groups = await api.getGroups() and the getGroups is : const getGroups = async ()=>{ const { data } = await api.get("http://localhost:8000/group", {withCredentials: true}) return data } in the back-end i print the request.COOKIES but it retruns an empty dictionary I'm using JWT authentication in the dj-rest-auth -
How To Update Specific Model Field From Django View Before Saving A Form
So, How can I update some Model Fields automatic, without the user having to input the values? In Models: class Url(models.Model): long_url = models.CharField("Long Url",max_length=600) short_url = models.CharField("Short Url",max_length=7) visits = models.IntegerField("Site Visits",null=True) creator = models.ForeignKey(CurtItUser,on_delete=models.CASCADE,null=True) def __str__(self): return self.short_url In Views: def home(request): """Main Page, Random Code Gen, Appendage Of New Data To The DB""" global res,final_url if request.method == 'POST': form = UrlForm(request.POST) if form.is_valid(): res = "".join(random.choices(string.ascii_uppercase,k=7)) final_url = f"127.0.0.1:8000/link/{res}" form.save() redirect(...) else: form = UrlForm return render(...) Sow how can for exapmle set from my view the value of short_url to final_url ??? -
Will I need to create separate HTTP methods(POST, PUT, DELETE) for ManyToManyField Operations - Django
I am having two tables group and action. class Group(models.Model): name = models.CharField() action = models.ManyToManyField(Action) class Action(models.Model): name = models.CharField() I have pre-defined data inserted into Group and Action table. My requirement is that, When I want to map Group table into Action table (Say for example "Mapping group to action(inserting to many to many table)","removing existing group to action mapping" ) I need to create Separate HTTP request for these Operation (POST, PUT, DELETE) or For single HTTP request(PUT) I can do these operations. Kindly help me on that. -
Can I create a Django Rest Framework API with Geojson format without having a model
I have a Django app that requests data from an external API and my goal is to convert that data which is returned as list/dictionary format into a new REST API with a Geojson format. I came across django-rest-framework-gis but I don't know if I could use it without having a Model. But if so, how? -
How to fix errors for Django's Auth/CustomUser after resetting the migrations and db?
After experimenting with setting up CustomUser and many-to-many relationships, I decided to make some (what turned out to be major) changes to the models. I had read that CustomUser/Auth needs to be set up first, or else it'll be a mess. But since I'm just learning and there was barely any data involved, I just went for it--not to mess up the CustomUser model intentionally, but I changed a model name--and (maybe this is the critical error) I updated the names everywhere it appeared. Now I'd deleted and reset the database, VENV folder, all the migration (along with __pycache__) files, and recreated test data so many times that I thought I could download the GitHub repo and set up a fresh new app easily again. But the app refuses to run and keeps asking for a missing table. Re-creating the app isn't my main concern-I'd like to understand what happened-what is this missing table (see the snippet of the error code)? AND: Why is a perfectly intact repo having the same issue with the missing table? Exception in thread django-main-thread: Traceback (most recent call last): File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Volumes/Volume2/dev/lms6-v2/venv/lib/python3.9/site-packages/django/db/backends/sqlite3/base.py", line 477, in execute … -
How to get multiple ajax functions to work correctly
I have a django template with two forms in it. When the first form is submitted, an ajax function is triggered and the second form is displayed on the page. When the second form is submitted, the ajax function linked to that form does not seem to work. For testing purposes, I tried to submit the second form before submitting the first form, and the ajax function works as expected. How do I make multiple ajax functions work correctly one after the other? This is my template <div class="form_container"> <div class="form"> <form action="{% url 'process_url' %}" method="post" id="youtube_link_form"> {% csrf_token %} <div class="input-group mb-3"> <input type="text" class="form-control youtube_link_input" placeholder="Put the youtube link or video id" aria-label="youtube_submit_input" aria-describedby="youtube_submit_button" name="youtube_submit_input"> <button class="btn youtube_submit_button" type="submit" id="youtube_submit_button">Submit</button> </div> </form> </div> </div> <div class="user_target_select"> <div class="target_buttons d-flex justify-content-between"> <form method="get" action="{% url 'user_select_positive' %}" id="positive_user_select_form"> <input type="hidden" id="positive_user_select_input" name="positive_user_select_input"> <button class="target_button btn btn-outline-success" id="user_select_positive" type="submit" data-bs-toggle="modal" data-bs-target="#thank_model">Positive</button> </form> </div> </div> Here, user_target_select div is hidden by default. When the first form is submitted, the div is displayed. This is my js file function youtube_link_form_submit(event) { event.preventDefault(); var data = new FormData($('#youtube_link_form').get(0)); $.ajax({ url: $(this).attr('action'), type: $(this).attr('method'), data: data, cache: false, processData: false, contentType: false, success: … -
How to get the sum of inlines in Django Admin
I want to show in admin the total money used in a computer by adding inline parts. models.py class Material(models.Model): name = models.CharField(max_length=30, null=False, blank=False) class Computer(models.Model): name = models.CharField(max_length=90) class UsedMaterial(models.Model): computer = models.ForeignKey(Computer, on_delete=models.SET_NULL, null=True) material = models.ForeignKey(Material, on_delete=models.SET_NULL, null=True) cost = models.DecimalField(max_digits=11, decimal_places=2, null=False, blank=False, default=0) quantity = models.IntegerField(null=False, blank=False, default=0) admin.py class UsedMaterialAdmin(admin.TabularInline): model = UsedMaterial def total(self, obj): return obj.cost * obj.quantity readonly_fields = ("total",) fields = ("material", "cost", "quantity", "total" ) @admin.register(Computer) class ComputerAdmin(admin.ModelAdmin): inlines = [UsedMaterialInline] fields = ("name",) I have found the way to show the total per article in the inline as you can see show Screen shot But how do I get the total of all the materials in the inline? -
How can I refresh another page in Django?
Is there any way to refresh another page by clicking a button on current page? (Any way for server to send a packet that makes every broswer on a certain url page refresh itself) example: 127.0.0.1:8000/main -> a page that has the button 127.0.0.1:8000/list -> a page I want to refresh My desktop web browser is currently on '/main' and my laptop web browser is currently on '/list'. How can I refresh my labtop web browser(to a newer version of '/list'page) by clicking a button in '/main' page on my desktop? Is using websocket(like django-channels) only way to do this work? -
How can I connect to the IPFS network using web3.storage API in Django?
Web3.Storage site can be used to upload files, but it's also quick and easy to create and run a simple upload script — making it especially convenient to add large numbers of files. The script contains logic to upload a file to Web3.Storage and get a content identifier (CID) in return which would basically be the address to access files. However, in the documentation, the in-built functions are given using Node.js. How can this be done using Django or any other Python based framework? -
Separating files based on file extension?
I want to separate the files in my models based on extension type. Right now I am able to print all the files but now i want to separate them based on extension and apply separate funtions based on the extensions. The code in my models.py class File(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=100) doc = models.FileField(upload_to='files/docs/', validators=[FileExtensionValidator(allowed_extensions=['pdf','docx'])]) and my code in view.py def file_p(): for file in File.objects.all(): print(file.doc) I am getting an output something like this. files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_1s00TUA.docx files/docs/12.6.1-packet-tracer---troubleshooting-challenge---document-the-network_z9b2tyh.pdf How can i separate them based on extension so that i can apply further functions based on the file type. -
Custom Decorator for Django admin.ModelAdmin to Append Actions
I'm trying to create an "export model to csv in admin panel" function and append it to actions in admin.ModelAdmin. By selecting a few rows in a table in the admin panel, the goal is to export the selected rows to csv. However, my current code in decorators.py::exportable_model didn't achieve my goal. Versions: Python: 3.10 Django: 4.0.4 mixins.py import csv import codecs from django.http import HttpResponse class ExportCsvMixin: # ref: https://books.agiliq.com/projects/django-admin-cookbook/en/latest/export.html def export_as_csv(self, request, queryset): meta = self.model._meta field_names = [field.name for field in meta.fields] response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename={}.csv'.format(meta) # To export CN characters. Ref: https://stackoverflow.com/a/63242835/16450509 response.write(codecs.BOM_UTF8) writer = csv.writer(response) writer.writerow(field_names) for obj in queryset: row = writer.writerow([getattr(obj, field) for field in field_names]) return response export_as_csv.short_description = "Export Selected (.csv)" admin.py @exportable_model(export_format="csv") @admin.register(ParticipantType) class ParticipantTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in ParticipantType._meta.get_fields()] @exportable_model(export_format="csv") @admin.register(PropsEventType) class PropsEventTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in PropsEventType._meta.get_fields()] @exportable_model(export_format="csv") @admin.register(LimitedTimeEventType) class LimitedTimeEventTypeAdmin(admin.ModelAdmin, ExportCsvMixin): list_display = [field.name for field in LimitedTimeEventType._meta.get_fields()] Tentative decorators.py, which references the coding style in register function in @admin.register (from django.contrib import admin): def exportable_model(export_format: str): from django.contrib.admin import ModelAdmin from .mixins import ExportCsvMixin def _decorator(admin_class): if not issubclass(admin_class, ModelAdmin): raise ValueError("Wrapped class must subclass ModelAdmin.") actions …