Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to define a field of a model to have a choice from another field of another model of another app?
I have two models defined in two different apps. I want to have a choice option for a particular field in a model, which is deriving those attributes from another field of a model in another app. eg: I have a model "Inventory" that has a field 'title'. class Inventory(models.Model): title = models.CharField('Title', max_length=120, default='') .... I also have another model 'Invoice' that has a field 'line_one'. Both these models are located in different apps. class Invoice(models.Model): line_one = models.CharField('Line 1', max_length=120) .... I created a Django form for adding the Invoice details. I want a choice option for line_one that has all the values stored in the Inventory.title field so that the user can only select those values from a dropdown menu. How can I implement this? Thanks. -
Venda matching query does not exist
ês I don't know how to fix this little problem, I tried to change and change the form, but I still don't understand why it is not reading froms=sales , and when I looked for the error in depth it gave: order_forms Error in formatting: TypeError: unsupported format string passed to NoneType.format> ** MY models ** numero_ven = models.AutoField('Número sequencial da venda',primary_key=True) data_ven = models.DateTimeField('Data e hora da venda',auto_now_add=True,auto_now=False) nf_ven = models.IntegerField('NF',null=True,blank=True) cliente_ven = models.ForeignKey('core.Customer',db_column='cliente_ven',related_name='customer_sale',on_delete=models.CASCADE) formapag_ven = models.ForeignKey(CondPag,db_column='formapag_ven',related_name='forma_pag',on_delete=models.CASCADE) usuario_ven = models.ForeignKey('users.User',db_column='usuario_ven',related_name='usuario_sale',on_delete=models.CASCADE) desconto_ven = models.DecimalField('Desconto',max_digits=7,decimal_places=2,null=True,blank=True) condicao_ven = models.IntegerField('Condição',null=True,blank=True) obs_ven = models.TextField('Observações',blank=True,null=True) frete = models.DecimalField('Frete',max_digits=7,decimal_places=2,null=True,blank=True) seguro = models.DecimalField('Seguro',max_digits=7,decimal_places=2,null=True,blank=True) despesas_acess = models.DecimalField('Despesas acessórias',max_digits=7,decimal_places=2,null=True,blank=True) codigo_transport = models.IntegerField('Código Transporte',null=True,blank=True) placa_veic = models.CharField('Placa veículo',max_length=10,null=True,blank=True) uf_veic = models.CharField('UF veículo',max_length=2,null=True,blank=True) frete_por_conta = models.CharField('Frete por conta',max_length=1,null=True,blank=True) marca = models.CharField('Marca',max_length=10,null=True,blank=True) especie = models.CharField('Espécie',max_length=10,null=True,blank=True) numeracao = models.CharField('Numeração',max_length=10,null=True,blank=True) prev_entrega = models.DateTimeField('Data e hora da previsão de entrega',auto_now_add=True,auto_now=False) setor_ven = models.IntegerField('Setor',null=True,blank=True) precosetor_ven = models.IntegerField('Preço setor',null=True,blank=True) datanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) horanfsai_ven = models.DateTimeField('Data e hora da Nota Fiscal',auto_now_add=True,auto_now=False) imprime_romaneio_ven = models.CharField('Imprime romaneio',max_length=1,null=True,blank=True) cupom_impresso_ven = models.CharField('Cumpom Impresso',max_length=1,null=True,blank=True) prestador_serv_ven = models.IntegerField('Prestador serviço',null=True,blank=True) usuario_atu_ven = models.IntegerField('Usuário atual',null=True,blank=True) data_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) hora_atu_ven = models.DateTimeField('Data e hora da atualização da venda',auto_now_add=True,auto_now=False) cupom_ven = models.IntegerField('Cupom',null=True,blank=True) qtd_vol_ven = models.IntegerField('Quantidade volume',null=True,blank=True) num_venda_antecip_ven … -
Error with form.non_field_errors are not displayed
I try show errors without fieldname identifier. For this i run in template {{ form.non_field_errors }}. But error not displayed. If i run with form.errors the erros are displayed, but with fieldname too, it's not what i want. I use AbstractBaseUser like: models.py class User(AbstractBaseUser): username = models.CharField( verbose_name = u'Nome', max_length=33 ) #identifier email = models.EmailField( verbose_name = u'Email', max_length=255, unique=True, ) phone = models.CharField( verbose_name = u'telefone', max_length=12 ) #... forms.py class SignupForm(UserCreationForm): username = forms.CharField( label=False, max_length=100, required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Nome', 'autocomplete':'off', } )) email = forms.EmailField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Email'} )) email_confirmation = forms.EmailField( required=True, widget=forms.TextInput( attrs={ 'placeholder': 'Confirme o email', 'id': 'email_confirmation', 'class': 'input cemail-cad' } )) phone = forms.CharField( label=False, required=True, widget=forms.TextInput( attrs={'placeholder': 'Telefone'} )) password1 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Senha'} )) password2 = forms.CharField( label=False, max_length=50, required=True, widget=forms.PasswordInput( attrs={'placeholder': 'Confirme sua senha'} )) class Meta: model = User fields = ['username', 'email', 'phone', 'password1', 'password2'] def clean_username(self): # mínimo 2 caracteres máximo 150 caracteres if not re.compile(r'^\S*[\w\.\-\_\d]{3,150}').match(str(self)): raise ValidationError("Nome inválido: Mínimo 3 caracteres, somente letras, números e '.', '-' ou '_' especiais") def clean_email(self): cleaned_data = super(SignupForm, self).clean() email = cleaned_data.get('email') email_confirmation = cleaned_data.get('email_confirmation') if email != email_confirmation: … -
run initial commands in a docker-compose service
I followed this tutorial to run my django web-app locally, apart for the web-app the only service is a postgres db. I wrote a simple script entrypoint.sh to automate the initial operations needed by a django app, like migrate, makemigrations, collectstatic, createsuperuser; Everything works fine, except that entrypoint.sh runs everytime I use docker-compose up, performing initial operations that should only run once. How can I set up my Dockerfile or docker-compose.yml so that entrypoint.sh is run just the first time and not everytime I docker-compose down and then docker-compose up again? Dockerfile # importing base image FROM python:3.9 # updating docker host or host machine RUN apt-get update \ && apt-get install -y --no-install-recommends \ && rm -rf /var/lib/apt/lists/* # changing current working directory to /usr/src/app WORKDIR /usr/src/app # copying requirement.txt file to present working directory COPY requirements.txt ./ # installing dependency in container RUN pip install -r requirements.txt # copying all the files to present working directory COPY . . # informing Docker that the container listens on the # specified network ports at runtime i.e 8000. EXPOSE 8000 ENTRYPOINT ["./entrypoint.sh"] docker-compose.yml version: '3.7' services: db: image: postgres volumes: - ./data/db:/var/lib/postgresql/data environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres app: … -
OrgChart in Django and JQuery
I have an app that I created in Django and OrgChart jQuery that displays an organizational workchart. I have UserProfile model that I create every time when user is created so it updates automatically. Right now, I am working on a script that would allow me to add 2 people to the same position and level of hierarchy. For instance, I want to add 2 CEO's on the top of the hierarchy but the function is giving me an error that: MultipleObjectsReturned at /organizational-chart/ get() returned more than one UserProfile -- it returned 2! views.py def work_organizational_chart(request): def recursion(data, profile_id): new_child_list = [] ro = data.filter(supervisor=profile_id) for j in ro: temp = {'profile_id': j.profile_id, 'user_full_name': j.user.get_full_name(), 'email': j.user.email, 'team': j.team.title, 'job_position': j.job_position, 'phone': j.phone_number, 'photo': j.photo.url } temp['children'] = recursion(data, temp['profile_id']) if len(temp['children']) == 0: del temp['children'] new_child_list.append(temp) return new_child_list data_list = UserProfile.objects.filter(profile_id__gte=1) categories = Category.objects.exclude(title="optimazon") final_json = {} cs = data_list.get(team=5) final_json['profile_id'] = cs.profile_id final_json['user_full_name'] = cs.user.get_full_name() final_json['email'] = cs.user.email final_json['team'] = cs.team.title final_json['job_position'] = cs.job_position final_json['phone'] = cs.phone_number final_json['photo'] = cs.photo.url final_json['children'] = recursion(data_list, final_json['profile_id']) return render(request, 'organizational_chart/org_chart.html', {'a_staff': final_json, 'categories': categories}) models.py class UserProfile(models.Model): profile_id = models.IntegerField(primary_key=True) user = models.OneToOneField(User, unique=True, on_delete=models.CASCADE, null=True) body = models.TextField(verbose_name='Job description', … -
How to create Reactive Dropdowns using django to Rank Criteria
I have 4 different Criteria which I need to rank using django forms. something like this Priority 1 : Dropdown (Criteria 1/2/3/4 as different options) Priority 2 : Dropdown (criteria 1/2/3)[basically removes the criteria that they have selected in prority 1) same for priority 3 and 4. I am using django.. Any help -
Getting ImportError: cannot import name 'total_budget_left' from 'walletapp.views' in Django
I am working on one Django web application. And getting the ImportError: cannot import name 'total_budget_left' from 'walletapp.views'. I want to import total_budget_left this variable from one function of walletapp's views.py to another app's views.py 's function. My walletapp.views.py def budgetView(request): preference = UserPreferences.objects.get_or_create(user=request.user) if preference: prefered_currency = UserPreferences.objects.get(user=request.user) budgets = Budget.objects.filter(owner=request.user) total_budget = sum(budgets.values_list('amount', flat=True)) if budgets: for bud in budgets: cdate = bud.created_date edate = bud.end_date expenses = Expense.objects.filter(owner=request.user, date__gte=cdate, date__lte=edate) total_expense = sum(expenses.values_list('amount', flat=True)) total_budget_left = total_budget - total_expense I want to import the variable total_budget_left into another app function myapp.views.py My myapp.views.py from walletapp.views import total_budget_left def index(request): print(total_budget_left) Even after trying multiple ways, I am not able to proceed, please help me with this. Thanks in advance. -
How I do convert an md file to HTML
Here is my code: def title(request, title): try: html = markdown.markdown(util.get_entry(title)) return render(request, "encyclopedia/title.html", { "html": html }) except: return render(request, "encyclopedia/error.html") The issue: The above function convert the content of md file to html and save it into a variable called 'html' and it works. The problem comes when I use this variable in my html file: when I open the html file it displays for example: <h1>Hello World</h1> instead of heading that says Hello World. Thank You -
returning more than one variable in render of django
I define home request in views.py, db=client.inventory_data def home(request): collection_data_1 = db['orders'] mydata = list(collection_data.find()) return render(request,'home.html',{'mydata': mydata}) The above function works fine but when I try to return one more list, it does not work. def home(request): collection_data_1 = db['orders'] collection_data_2 = db['product'] mydata = list(collection_data_1.find()) product_data = list(collection_data_2.find()) return render(request,'home.html',{'mydata': mydata},{'product_data':product_data}) I want to return both the list, how can we achieve this? looking for kind help. -
Axios error when using catch for error processing
I'm using React + Django. Simple backend with one button on frontend handling POST requests: function handleSubmit(e){ e.preventDefault(); axios.post(API_URL, { forklift, battery }).then((response) => { console.log(response) }).catch((error) => { console.log(error.response) }); } The problem is when I try to submit the form while including .catch it always throws an 404 error on first request and then my development server on django crashes on second request (stops). When I delete catching error it works perfectly. function handleSubmit(e){ e.preventDefault(); axios.post(API_URL, { forklift, battery }).then((response) => { console.log(response) }); } My Django API_VIEW @api_view(['POST']) def start_charging(request): if request.method == 'POST': print('test') forklift_ean = request.data['forklift'] battery_ean = request.data['battery'] try: forklift = Forklift.objects.get(for_ean=forklift_ean) battery = Battery.objects.get(bat_ean=battery_ean) except Forklift.DoesNotExist or Battery.DoesNotExist: return Response({'error_message': "No object error"}, status=status.HTTP_404_NOT_FOUND) return Response({"message": "OK"}) Main url.py file urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('my_app.urls')) ] App url.py file urlpatterns = [ path('charging/', views.start_charging, name='start_charging'), ] Error on first request: xhr.js:220 POST http://127.0.0.1:8000/api/charging/ 404 (Not Found) Error on seconds request (server crashes): xhr.js:220 POST http://127.0.0.1:8000/api/charging/ net::ERR_CONNECTION_REFUSED Any idea why might be the reason for .catch to act that way? -
{'sub_categories_name': [ErrorDetail(string='This field may not Internal Server Error: /sub_categories/insert_sub_categories/
Hi I am new to DJango nad html,I am making a CRUD on models products ,categories,subcategories,SIze,colors. below is my views function of showing the data of subcategories def show_sub_categories(request): showsubcategories = SUBCategories.objects.filter(isactive=True) print(showsubcategories) serializer = SUBCategoriesSerializer(showsubcategories,many=True) print(serializer.data) return render(request,'polls/show_sub_categories.html',{"data":serializer.data}) insert function def insert_sub_categories(request): category = ['9-6wear', 'Bridal-Wear', 'desi_swag', 'fusion_wear'] context = {'context': category} if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') print(form.errors) return render(request,'polls/insert_sub_categories.html',context) else: print(form.errors) return render(request,'polls/insert_sub_categories.html',context) else: return render(request,'polls/insert_sub_categories.html',context) yet when I submit the data which I want to add there is nothing in the show webpage what could be the problem?it isnt visible even in the database -
add cookies in django
I want to set cookies in order to save to refresh token. I've triyed using set_cookies() function with a HttpResponse object but there's no cookies get in Postman. I've triyed also with a Response object but I've get an "AttributeError: 'Response' object has no attribute 'set_cookie' " enter image description here Response in Postman Code -
Error when working with qs, does not take a field in the query
I have a queryset with data. I want to add an annotate for it with data from another qs. To do this, I filter by pk and by FK field, I take in_stock values in this field, but I get error: Related Field got invalid lookup: in_stock. This way the query will work if you pass product, without its fields, but I specifically need to refer to __. How can I add a query to make it work? qs.annotate(test=Subquery(OrderList.objects.filter(order=OuterRef('pk'), product__in_stock=True).values('pk')) -
Error Matching query does not exist Django
I wanted to consult about a question I have, in my system I want this view to give me the products selected by their primary key that would be id, this is done with the form that is in a toggle window enter image description here views.py def add(request): cart = get_or_create_cart(request) productos = Producto.objects.get(pk=request.POST.get('producto_id')) cart.productos.add(productos) return render(request, 'carts/add.html', { 'productos': productos }) Models.py class Cart(models.Model): cart_id = models.CharField(max_length=100, null=False, blank=False, unique=True) user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) productos = models.ManyToManyField(Producto) subtotal = models.DecimalField(default=0.0, max_digits=8, decimal_places=2) total = models.DecimalField(default=0.0, max_digits=8, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.cart_id HTML {% csrf_token %} <form action="{% url 'Carts:add' %}" method="post"> <input type="hidden" name="producto_id" value="{{ producto.id }}"> <button type="submit" class="btn btn-warning">Agregar al carrito</button> </form> -
Django Admin: How to use the button to move to the selected URL?
I am very new to Django and trying to make my first project. I find it difficult to use the buttons I created to move to the selected URL. Let's say my app is called TestForms and my models are: Patients, General, PST and ERBT. I would like to create two buttons - 'Previous' and 'Next' - which will be used to go to previous/next forms respectively. I try to do so using admin templates in django. NOTE: I know changing built-in templates are not a very good idea, I will create new html file to extend this templates before doing changes on the server. For now I am doing it locally on my computer. In submit_line.html I created two new buttons and they are like so: {% if show_save_and_go_to_next_form %}<input type="submit" value="{% translate 'Next' %}" class="default" name="_gotonextform">{% endif %} {% if show_save_and_go_to_previous_form %}<input type="submit" value="{% translate 'Previous' %}" class="default" name="_gotopreviousform">{% endif %} This gives me two good-looking buttons on the site. But these are just saving the results (working like 'Save' button), but not redirecting me to the next form as I would like to. When I am adding a new patient (admin/TestForms/patient/add/), after clicking on 'Next' I would … -
Scraper does not support field
I have built a scraper to webscrape info from the web and then upload this to my django database. However, I am getting the following error: raise KeyError(f"{self.class.name} does not support field: {key}") KeyError: 'ScraperItem does not support field: title' Here's my items.py from scrapy_djangoitem import DjangoItem from cruise_control.models import Cruises, Destination class ScraperItem(DjangoItem): django_cruises = Cruises django_destination = Destination My scraper import scrapy from scrapy.http import JsonRequest from scraper.items import ScraperItem from scrapy.spiders import CrawlSpider headers = { 'authority': 'www.tripadvisor.co.uk', 'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="98", "Google Chrome";v="98"', 'sec-ch-ua-mobile': '?0', 'x-requested-by': 'TNI1625!AG1YRRpHOjQMgbfsrg1FWY4Ai8UH+StE3D7tD1/oCg3qzWRAYM2ff14YfUM2JUbFAl0x6vTP5McIcIHK3vGsWp/OUNzOT5pIGiZKb0BGLlQkrHttvrrkMiEX1B08Oy4WjTHFseLIh9VcHJi4Gh0/+LjAQFKarv7VPh3A6Lba2SV/', 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36', 'sec-ch-ua-platform': '"macOS"', 'accept': '*/*', 'origin': 'https://www.tripadvisor.co.uk', 'sec-fetch-site': 'same-origin', 'sec-fetch-mode': 'cors', 'sec-fetch-dest': 'empty', #'referer': 'https://www.tripadvisor.co.uk/Cruises-g4-Europe-Cruises', 'accept-language': 'en-GB,en-US;q=0.9,en;q=0.8', #'cookie': 'TADCID=wxS4TbuLpUspXUnWABQCFdpBzzOuRA-9xvCxaMyI12uHBUXU8sLyLHDaoIuwxzQKyBrTFlgsk84ZsL_itZEhwu8hHz-VItOKi2w; TAUnique=%1%enc%3A8kwUAflygK31tlwOhg%2Fo76dh9wxu05Ut4MznwnYlPlg2jHwltRJPGQ%3D%3D; TASSK=enc%3AAPiLXN0t%2B8Q%2Fy9%2FxR%2BD5555CPTdegwxcaa1ok4l9U33f3IyY6Qg8GN25OIJ4ccUZntma4TTL9a%2Bl%2BoIz%2FTAucOZ2TqYV6tkQbMAYMyq1l5ArmPX7CjgQq2QO%2B9HE%2BLVGaw%3D%3D; ServerPool=X; PMC=V2*MS.18*MD.20220214*LD.20220214; TART=%1%enc%3A9bZcDoYP6O8GE%2BreSp1djAImFcYdHhqBzveZGrQkjMRhW3dIKV4FZ%2FdZWju6gRL2CeyaC1LeImE%3D; TATravelInfo=V2*A.2*MG.-1*HP.2*FL.3*RS.1; TASID=A32BBADDF2344464B10CA8620CFBF2AF; TAReturnTo=%1%%2FCruises-g4-Europe-Cruises; ak_bmsc=D33D58B4C6C12D1D96C6D50E4A8267F6~000000000000000000000000000000~YAAQ3Jl6XLHYnul+AQAAegxz9w6zDYaRpZULIXbmwExafFXbLk88He8U5RsFRJJHYrPKRs60IK77pXrkBd1Bl7bvDGDEhZqKkbtOP/6nqDF1R4eUq2ZuIfReBoo+S9nxAuR2rla11JjDVD65qUN1aH0uichlgPClLxslcNh3JclKJzPv3kg7aDgrvT2CaDQ5f5zz2UPkb+EOkAEyOPwhg8exOgHhsbD2BhGqL7PAOPfZPVuocBXutZBOcDBrsy1rZlHC79MQQdX5szmK9zwQnZUVDvmln+DUVXXyN835bImRRSbTNz12EDee2RgtZwmuQNv+eSXnS3gJHBkTErdp7jEdbbCytqTdI2Ix8OR8QzmJnUAXL0dOvpqmUmkGFnWxUz68QxHkf7hC91Pqt3CJ2A==; OptanonAlertBoxClosed=2022-02-14T08:57:03.130Z; eupubconsent-v2=CPUZP2aPUZP23AcABBENCCCsAP_AAH_AACiQIltf_X__b3_j-_5_f_t0eY1P9_7_v-0zjhfdt-8N3f_X_L8X42M7vF36pq4KuR4Eu3LBIQdlHOHcTUmw6okVrzPsbk2cr7NKJ7PEmnMbO2dYGH9_n93TuZKY7______z_v-v_v____f_7-3_3__5_3---_e_V_99zLv9____39nP___9v-_9_____4IhgEmGpeQBdmWODJtGlUKIEYVhIdAKACigGFoisIHVwU7K4CfUELABCagJwIgQYgowYBAAIJAEhEQEgB4IBEARAIAAQAqQEIACNgEFgBYGAQACgGhYgRQBCBIQZHBUcpgQFSLRQT2ViCUHexphCGWeBFAo_oqEBGs0QLAyEhYOY4AkBLxZIHmKF8gAAAAA.f_gAD_gAAAAA; OTAdditionalConsentString=1~39.43.46.55.61.66.70.83.89.93.108.117.122.124.131.135.136.143.144.147.149.159.162.167.171.192.196.202.211.218.228.230.239.241.259.266.272.286.291.311.317.322.323.326.327.338.367.371.385.389.394.397.407.413.415.424.430.436.440.445.449.453.482.486.491.494.495.501.503.505.522.523.540.550.559.560.568.574.576.584.587.591.733.737.745.780.787.802.803.817.820.821.829.839.864.867.874.899.904.922.931.938.979.981.985.1003.1024.1027.1031.1033.1034.1040.1046.1051.1053.1067.1085.1092.1095.1097.1099.1107.1127.1135.1143.1149.1152.1162.1166.1186.1188.1201.1205.1211.1215.1226.1227.1230.1252.1268.1270.1276.1284.1286.1290.1301.1307.1312.1345.1356.1364.1365.1375.1403.1415.1416.1419.1440.1442.1449.1455.1456.1465.1495.1512.1516.1525.1540.1548.1555.1558.1564.1570.1577.1579.1583.1584.1591.1603.1616.1638.1651.1653.1665.1667.1677.1678.1682.1697.1699.1703.1712.1716.1721.1722.1725.1732.1745.1750.1765.1769.1782.1786.1800.1808.1810.1825.1827.1832.1837.1838.1840.1842.1843.1845.1859.1866.1870.1878.1880.1889.1899.1917.1929.1942.1944.1962.1963.1964.1967.1968.1969.1978.2003.2007.2008.2027.2035.2039.2044.2046.2047.2052.2056.2064.2068.2070.2072.2074.2088.2090.2103.2107.2109.2115.2124.2130.2133.2137.2140.2145.2147.2150.2156.2166.2177.2183.2186.2202.2205.2216.2219.2220.2222.2225.2234.2253.2264.2279.2282.2292.2299.2305.2309.2312.2316.2322.2325.2328.2331.2334.2335.2336.2337.2343.2354.2357.2358.2359.2366.2370.2376.2377.2387.2392.2394.2400.2403.2405.2407.2411.2414.2416.2418.2425.2427.2440.2447.2459.2461.2462.2465.2468.2472.2477.2481.2484.2486.2488.2492.2493.2496.2497.2498.2499.2501.2510.2511.2517.2526.2527.2532.2534.2535.2542.2544.2552.2563.2564.2567.2568.2569.2571.2572.2575.2577.2583.2584.2589.2595.2596.2601.2604.2605.2608.2609.2610.2612.2614.2621.2628.2629.2633.2634.2636.2642.2643.2645.2646.2647.2650.2651.2652.2656.2657.2658.2660.2661.2669.2670.2677.2681.2684.2686.2687.2690.2695.2698.2707.2713.2714.2729.2739.2767.2768.2770.2772.2784.2787.2791.2792.2798.2801.2805.2812.2813.2816.2817.2818.2821.2822.2827.2830.2831.2834.2836.2838.2839.2840.2844.2846.2847.2849.2850.2851.2852.2854.2856.2860.2862.2863.2865.2867.2869.2873.2874.2875.2876.2878.2879.2880.2881.2882.2883.2884.2886.2887.2888.2889.2891.2893.2894.2895.2897.2898.2900.2901.2908.2909.2911.2912.2913.2914.2916.2917.2918.2919.2920.2922.2923.2924.2927.2929.2930.2931.2939.2940.2941.2942.2947.2949.2950.2956.2961.2962.2963.2964.2965.2966.2968.2970.2973.2974.2975.2979.2980.2981.2983.2985.2986.2987.2991.2993.2994.2995.2997.2999.3000.3002.3003.3005.3008.3009.3010.3012.3016.3017.3018.3019.3024.3025.3028.3034.3037.3038.3043.3044.3045.3048.3052.3053.3055.3058.3059.3063.3065.3066.3068.3070.3072.3073.3074.3075.3076.3077.3078.3089.3090.3093.3094.3095.3097.3099.3100.3104.3106.3109.3111.3112.3116.3117.3118.3119.3120.3124.3126.3127.3128.3130.3135.3136.3145.3149.3150.3151.3154.3155.3162.3163.3167.3172.3173.3180.3182.3183.3184.3185.3187.3188.3189.3190.3194.3196.3197.3209.3210.3211.3214.3215.3217.3219.3222.3223.3225.3226.3227.3228.3230.3231.3232.3234.3235.3236.3237.3238.3240.3241.3244.3245.3250.3251.3253.3257.3260.3268.3270.3272.3281.3288.3290.3292.3293.3295.3296; TATrkConsent=eyJvdXQiOiIiLCJpbiI6IkFMTCJ9; PAC=AJukZreSlVt2otjGKRNkBz00tWSjLZs1tpXwS8IQ0s9vLyuOrKUvS1c6om5r-WD0fR_Iq3GAZVuS7Hnkp36pQwhrEE0TfQD_2HKg4iY1nBIuQhuDqCWdbnFs1YNDeC2DHqRS5g91y4fgvYu2t67DsbY-k350iSZC1V5Q8MOom6ii; roybatty=TNI1625!APC1CnSJ7d3OhZC8OZmN5URwrla0tLHPbhlztWxjhZhT6aUqZSiQblRTSzow7ftctB099qedPBwThnzphE8mD%2BhqV6BvNYPIhvySRzEFTVzRp06wXxRc8ZRTjzdR%2B6TMtg6r4C0frqplHn1ukZ4jm5nriuS8VgJVY1P1ep6OFaNM%2C1; __vt=wzYY-5Il_FhNE1AIABQCIf6-ytF7QiW7ovfhqc-AvRtk3_lgKJDj5Zq9Ugk-YcW1aWXqbclfQV6lVC3XwLDW4R4P6wRyFZBracNMyGIQ5t0P83yLijLokcFANA9-zVQ698yGW3svmERyK7AnfVnyS4CdjUA; OptanonConsent=isGpcEnabled=0&datestamp=Mon+Feb+14+2022+09%3A54%3A26+GMT%2B0000+(Greenwich+Mean+Time)&version=6.30.0&isIABGlobal=false&hosts=&consentId=bd1952f6-01ff-41b6-861f-a54916a04f3b&interactionCount=1&landingPath=NotLandingPage&groups=C0001%3A1%2CC0002%3A1%2CC0003%3A1%2CC0004%3A1%2CSTACK42%3A1&geolocation=GB%3BENG&AwaitingReconsent=false; SRT=%1%enc%3A9bZcDoYP6O8GE%2BreSp1djAImFcYdHhqBzveZGrQkjMRhW3dIKV4FZ%2FdZWju6gRL2CeyaC1LeImE%3D; TASession=V2ID.A32BBADDF2344464B10CA8620CFBF2AF*SQ.11*LS.PageMoniker*GR.86*TCPAR.46*TBR.15*EXEX.62*ABTR.9*PHTB.8*FS.28*CPU.39*HS.recommended*ES.popularity*DS.5*SAS.popularity*FPS.oldFirst*FA.1*DF.0*TRA.true*LD.4*EAU._; TAUD=LA-1644829020144-1*RDD-1-2022_02_14*LG-3446857-2.1.F.*LD-3446858-.....; bm_sv=2A36E698463670EE6568739F8CDB1175~3+hcdvQLIRwah/ob3yiC6FDLIUMklns+OmkkhCI+VXdPQ9Cu0Tgp1gj42eltojUxM4qnZc+AQhSLEPtZgkZVPf7jtaIT9dgLdeJFsXrByFiSKAtnDYW8m7bd+9XZCOjX0Vs6okcP/XE3YBv7UlJP6aVMfxFgMK5VPFHA9GoE1IA=', } class CruisesSpider(CrawlSpider): name = 'test' start_urls = ['https://www.tripadvisor.co.uk/data/graphql/ids'] # custom_settings = { # 'DOWNLOAD_DELAY':1 # } def start_requests(self): for urls in self.start_urls: for i in range(1, 600): yield JsonRequest( url = urls, method = 'POST',callback = self.parse, headers = headers, data = [ { 'query': '013d760a68c9a4f77e9a9a903e241eb8', 'variables': { 'page': i, 'limit': 20, 'minPrice': None, … -
SECURITY WARNING: don't run with debug turned on in production even it's already change to false
I host in Niagahoster using VPS My directory is like this root |- cyberpanel |———cyberpanel |—————-settings.py |- manage.py I already change debug status to false which is located only in that folder. I tried to list all files. I already waited around 2 hours but still no change. This is the warning, it still gave me a security warning -
" TypeError: list indices must be integers or slices, not str. " I'm web-scraping for data and I'm having trouble with this error at the moment
I'm trying to scrape a website. I want to be able to retrieve a URL link from this webpage and use it to get to another page wherein I can access this information that I need. import requests from bs4 import BeautifulSoup headers = {'User-agent': 'Mozilla/5.0 (Windows 10; Win64; x64; rv:101.0.1) Gecko/20100101 Firefox/101.0.1'} baseUrl = 'https://elitejobstoday.com/' url = "https://elitejobstoday.com/" r = requests.get(url, headers = headers) c = r.content soup = BeautifulSoup(c, "lxml") table = soup.find_all("a", attrs = {"class": "job-details-link"}) This part works fine however the next part is where I get stuck. def jobScan(link): the_job = {} jobUrl = '{}{}'.format(baseUrl, link['href']) the_job['urlLink'] = jobUrl job = requests.get(jobUrl, headers = headers ) jobC = job.content jobSoup = BeautifulSoup(jobC, "lxml") name = jobSoup.find("h3", attrs={"class": "loop-item-title"}) title = name.a.text the_job['title'] = title company = jobSoup.find_all("span", {"class": "job-company"})[0] company = company.text the_job['company'] = company print(the_job) return the_job jobScan(table) I'm getting this error "File "C:\Users\MUHUMUZA IVAN\Desktop\JobPortal\absa.py", line 41, in jobScan jobUrl = '{}{}'.format(baseUrl, link['href']) TypeError: list indices must be integers or slices, not str " I'm clearly doing something wrong but i can't see it. I need your help. thanks. -
How to combine opencart and django database (catalog)
I have catalog on django and I need to connect it to catalog on opencart. In other words, when I add product in django it needed to appear on opencart Is any ideas how I can to this? If it doesn't work with opencart, the prestashop also fits. -
403 forbidden You don't have permission to access this resource after deploying django web app using apache server
When I tried to deploy my django app to the server using apache I am experiencing some error messages when trying to access my website.After deploying and When I tried to visit the website browser returns 403 Forbidden You don't have permission to access this resource. -
Connecting Redis server with django
I have no error message, because Django automatically uses LocMem as cache instead of Redis. This is my settings.py file. I have followed the django-redis tutorial https://github.com/jazzband/django-redis, but was unable to connect the server correctly. I am using Redis Cloud, is this probably the cause of the problem? CACHE = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', 'LOCATION': 'redis://default@localhost:6379/0', 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', 'PASSWORD': env('REDIS_PASSWORD'), } }} -
Django model Q object combining operations with an exclude
I am using Django 3.2 I have a model like this: class MyModel(models.Model): status = models.PositiveSmallInteger(default=0) last_field = models.TextField() I am writing a custom QuerySet to return all records of MyModel that meet the criteria: status == 1 OR last_field is NOT empty or null This is what I have: class MyModelQuerySet(models.QuerySet): def what_i_want(self): Q1 = Q(status=1) Q2 = (Q(last_field__isnull=True) | Q(last_field__exact='')) return self.filter() # <- ?? -
Trying to implement django dropdown using for loops and foreign keys
Hi I am new to django html,I am making a CRUD with models Products,Categories,SUBCategories,Size,Colors. I am trying to make a django reliant dropdown for the property 'Category' below is the model polls.models class Products(models.Model): Categories = models.ForeignKey(Categories,on_delete=models.CASCADE,default=None) sub_categories = models.ForeignKey(SUBCategories,on_delete=models.CASCADE, default=None) Colors = models.ForeignKey(Colors,on_delete=models.CASCADE) Size = models.ForeignKey(Size,on_delete=models.CASCADE) image = models.ImageField(upload_to = 'media/',width_field=None,height_field=None,null=True) title = models.CharField(max_length=50) price = models.CharField(max_length=10) sku_number = models.CharField(max_length=10) prod_details = models.CharField(max_length=300) quantity = models.IntegerField(default=0) isactive = models.BooleanField(default=True) sub_categories.models class SUBCategories(models.Model): category_name = models.ForeignKey(Categories,on_delete=models.CASCADE,default=None) sub_categories_name = models.CharField(max_length=20) sub_categories_description = models.CharField(max_length=20) isactive = models.BooleanField(default=True) below is the insert function of the insert_sub_categories def insert_sub_categories(request): context = {'9-6 wear':'9-6wear','bridalwear':'Bridal-Wear','desi_swag':'DesiSwag','fusion_wear':'FusionWear'} if request.method == "POST": insertsubcategories = {} insertsubcategories['sub_categories_name']=request.POST.get('sub_categories_name') insertsubcategories['sub_categories_description']=request.POST.get('sub_categories_description') form = SUBCategoriesSerializer(data=insertsubcategories) if form.is_valid(): form.save() print("hkjk",form.data) messages.success(request,'Record Updated Successfully...!:)') # return redirect('sub_categories:show_sub_categories') return render(request,'polls/show_sub_categories',context) else: print(form.errors) else: return render(request,'polls/insert_sub_categories.html',context) below is the insert_sub_categories.html <td>category name</td> <td> <select name="category_name" id=""> {% for c in context %} <option value="{{c.category_name}}"></option> {% endfor %} </select> </td> despite all that the dropdown isnt showing the contents of the 'context' dictionary what going wrong? -
Method Not Allowed (POST) in ajax request with django
I am trying to pass the values of form data through ajax .And getting method not allowed error. I am trying to add comment in a blog post. This is my form which is inside blog_detail page <form id="commentform" class="commentform" method="post"> {% csrf_token %} {%with allcomments.count as total_comments%} <p> {{total_comments}} comment{{total_comments|pluralize}} </p> {%endwith%} <select name="blog" class="d-none" id="id_blog"> <option value="{{blog.id}}" selected="{{blog.id}}"></option> </select> <label class="small font-weight-bold">{{comment_form.parent.label}}</label> {{comment_form.parent}} <div class="d-flex"> <img class="avatar_comment align-self-center" src="{% for data in avatar%}{{data.avatar.url}}{%endfor%}" alt=""> {{comment_form.content}} </div> <div class="d-flex flex-row-reverse"> <button value="commentform" id="newcomment" type="submit" class="newcomment btn btn-primary">Submit</button> </div> </form> And when I click the button it should call the ajax $(document).on('click','#newcomment',function(e){ e.preventDefault(); var button =$(this).attr("value"); var placement = "commentform" if (button=="newcommentform"){ var placement = "newcommentform" } $.ajax({ type: 'POST', url: '{% url "website:addcomment" %}', data: $("#" + button).serialize(), cache: false, sucess: function(json){ console.log(json) $('<div id="" class="my-2 p-2" style="border: 1px solid grey"> \ <div class="d-flex justify-content-between">By ' + json['user'] + '<div></div>Posted: Just now!</div> \ <div>' + json['result'] + '</div> \ <hr> \ </div>').insertBefore('#' + placement); }, error: function(xhr,errmsg,err){ } }); }) This is my urls.py path('blog/<int:blog_id>', BlogDetails.as_view(), name="blog_detail"), path('addcomment/',addcomment, name="addcomment"), and my views.py is: class BlogDetails(View): def get(self, request, blog_id): query = request.GET.get('query') if query: return redirect(reverse('website:search') + '?query=' + … -
Bootstrap 5 Table Column Spacing
Need help with formatting a Bootstrap table column spacing. The data shown is populated dynamically. The Add New on the header is a clickable link. The Departments table has only one field but each row should have to clickable link buttons namely Edit and Delete as shown. My challenge is getting the spacing between all three columns (Department Name, Edit and Delete) to look more or less like the Process table. Kindly help correct the below code for the Departments table to render like the Process table <div class="container"> <div class="panel panel-primary"> <div class="panel-heading"> <div class="row"> <div class="col-xs-4 text-left">Departments</div> <div class="col-xs-8 text-right"> <a class="link-dark text-light" href="{% url 'add_department' %}">Add New </a> </div> </div> </div> <table class="table"> <thead> <tr> <th scope="col">Department Name</th> <th scope="col" colspan="2">Action</th> </tr> </thead> <tbody> {% for department in all_departments %} <tr> <td>{{department.department_name}}</td> <td> <a class="link-primary" href="{% url 'update_department' department.id %}">Edit</a> </td> <td class="w-10"> <a class="link-danger" href="{% url 'delete_department' department.id %}">Delete</a> </td> </tr> {% endfor %} </tbody> </table> </div>