Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django model form instance update / how to show only previously selected options and hide the rest
I need to completely hide just the "select" while creating new object and partialy show only previously selected while "update" without javascript if it is possible. thank you for any advice code in views.py ` def topic_create(request): form = TopicForm() if request.method == 'POST': new_tags = request.POST.get('new_tags').replace(',', " ").split() form = TopicForm(request.POST, request.FILES) if form.is_valid(): topic = form.save(commit=False) topic.save() for tag in new_tags: tag, created = Tag.objects.get_or_create(name=tag) topic.tags.add(tag) return redirect('topics') context = {'form': form} return render(request, 'blog_app/topic_form.html', context) def topic_update(request, pk): topic = Topic.objects.get(id=pk) form = TopicForm(instance=topic) if request.method == 'POST': new_tags = request.POST.get('new_tags').replace(',', " ").split() form = TopicForm(request.POST, request.FILES, instance=topic) if form.is_valid(): topic = form.save() for tag in new_tags: tag, created = Tag.objects.get_or_create(name=tag) topic.tags.add(tag) return redirect('topics') context = {'form': form} return render(request, 'blog_app/topic_form.html', context) ` this code in my form.py ` class TopicForm(ModelForm): class Meta: model = Topic fields = '__all__' widgets = { 'tags': forms.CheckboxSelectMultiple(), } ` and this is the template ` {% block content %} <main class="formPage my-xl"> <div class="content-box"> <div class="formWrapper"> <form class="form" method="POST" enctype="multipart/form-data"> {% csrf_token %} {% for field in form %} <div class="form__field"> <label for="formInput#text">{{field.label}}</label> {{field}} </div> {% endfor %} <div class="form__field"> <label>Add New</label> <textarea name="new_tags" placeholder="Separate with space or comma"></textarea> </div> … -
Export only the data registered by the user / Django import-export
Products can be exported in excel format from the Product table. But all the user's products are exported. How can I export only request.user's products? Here is view : def export_excel(request): dataset = ProductResource().export() response = HttpResponse(dataset.xlsx, content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") response["Content-Disposition"] = "attachment; filename=Products-" + str(datetime.datetime.now().date())+".xlsx" return response Here is resources.py : class ProductResource(resources.ModelResource): author = Field() brand_id = Field() class Meta: model = Product fields = ["id", "author", "brand_id", "name", "barcode", "unit"] export_order = ["id", "author", "brand_id", "name", "barcode", "unit"] def dehydrate_author(self, product: Product) -> str: return f"{product.author.username}" def dehydrate_brand_id(self, product: Product) -> str: return f"{product.brand_id.name}" -
User doesnt save to database Django
views.py def registerPage(request): form = UserCreateForm() if request.method=='POST': form=UserCreateForm(request.POST) if form.is_valid(): user=form.save(commit=False) user.save() return redirect('home') return render(request,'base/signup.html',{'form':form}) model.py class User(AbstractUser): name = models.CharField(max_length=200,null=True) email = models.EmailField(unique=True,null=True) bio=models.TextField(null=True) avatar = models.ImageField(upload_to='images/',null=True) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] forms.py class UserCreateForm(UserCreationForm): class Meta: model = User fields = ['name','email','password1','password2','bio','avatar'] when ever i try to sign up on html template it doesnt work but if i do it in admin panel it works how can i solve it ? -
Celery testing Django and how to properly raise an exception in a celery task and assert a retry
I have a Celery task in a Django project that sends an email utilising Django's EmailMultiAlternatives. I want to raise a ConnectionError to trigger a retry. The task works well in practice, with retries being attempted as expected when a ConnectionError exists, but I now want to test it. my_app.mailer.tasks.py from django.core.mail import EmailMultiAlternatives @app.task(bind=True, max_retries=4, base=BaseTaskEmail, ) def send_mail(self, *args, **kwargs): msg = EmailMultiAlternatives({some_data}) msg.attach_alternative({some_data}) try: msg.send(fail_silently=False) except ConnectionError as exc: self.retry(countdown=backoff(self.request.retries), exc=exc) I made the following attempt at testing, which results in an AssertionError: raise AssertionError(_error_message()) from cause AssertionError: expected call not found. Expected: send(exc=ConnectionError()) Actual: send(fail_silently=False) test.py class SendMailTest(TestCase): def setUp(self): self.message = {} @patch('my_app.mailer.tasks.EmailMultiAlternatives.send') @patch('my_app.mailer.tasks.send_mail.retry') def test_retry(self, mock_send, mock_retry): mock_send.side_effect = Retry() mock_retry.side_effect = error = ConnectionError() with raises(Retry): send_mail(kwargs=self.message) mock_retry.assert_called_with(exc=error) My question is, how I can correctly raise an exception in this task and assert that a retry has been called by the correct exception, in this case a ConnectionError. Additionally, if possible, assert that the correct number of retires have been attempted? -
How to merge queryset multiple dictionaries with common date value(not key) in django?
I have result queryset dictionaries like this. <QuerySet [ {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}, {'tags__name': 'Device', 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'tags_count': 5, 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')}, {'tags__name': 'Device', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')}, {'tags__name': 'Mobile', 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'tags_count': 3, 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')} ]> I want result like this {'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 11, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CDT-1 day, 19:00:00 DST>), 'price_avg': Decimal('120.400000'), 'price_sum': Decimal('602.00'), 'fee_sum': Decimal('17.01')} {'Mobile': 1,'Device': 1, 'month': datetime.datetime(2022, 12, 1, 0, 0, tzinfo=<DstTzInfo 'America/Chicago' CST-1 day, 18:00:00 STD>), 'price_avg': Decimal('311.000000'), 'price_sum': Decimal('933.00'), 'fee_sum': Decimal('27.99')} Any help will be appreciated. -
Django - Keep data filtered trough the duration of the session using django-filters
I have a view that lists all data from a model with a form that enables filtering using the django-filters library. The view also stores the filtered data in the session, inside the form_data variable. The view: def list_accsplan(request): accsplan = AccountsPlan.objects.all().order_by('code') accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan) request.session['form_data'] = accsplanfilter.data form_data = request.session.get('form_data') paginator = Paginator(accsplanfilter.qs, 30) page = request.GET.get('page') try: dataqs = paginator.page(page) except PageNotAnInteger: dataqs = paginator.page(1) except EmptyPage: dataqs = paginator.page(paginator.num_pages) return render(request, 'confi/pages/accounts_plan/list_accsplan.html', context={ 'accsplan': accsplan, 'accsplanfilter': accsplanfilter, 'dataqs': dataqs, }) The filter form is this: class AccountsPlanFilter(django_filters.FilterSet): accplantype = ChoiceFilter(choices=AccountsPlan.AccPlanType.choices, field_name='accplantype',) code = CharFilter(field_name='code', lookup_expr='icontains',) name = CharFilter(field_name='name', lookup_expr='icontains',) active = BooleanFilter(field_name='active', widget=CustomBooleanWidget,) class Meta: model = AccountsPlan fields = '__all__' What I want is to keep this list filtered as long as the session is active, even if the user changes pages and then get back to this one, but I'm stuck in how to do this. I tried to add an if statement in the view like this: if form_data: accsplan = AccountsPlan.objects.filter(**form_data) accsplanfilter = AccountsPlanFilter(request.GET, queryset=accsplan) But I receive this ValidationError in the list: ValidationError at /list_accsplan/ ["the value “['true']” must be True ou False."] I was thinking that this was because I … -
How to model many-to-many database with 3 tables
I'm working on a django backend and I'm trying to model a database and want to do it the best practice way. I need a "User" table, a "Portfolios" table and a "Stocks" table. A user can have multiple portfolios which consist of multiple stocks. This is my code so far: class User(models.Model): user_id = models.AutoField(primary_key=True) username = models.CharField(max_length=25) in_cash = models.DecimalField(max_digits=15, decimal_places=2) class Portfolios(models.Model): portfolio_id = models.AutoField(primary_key=True) user_id = models.ForeignKey("User", on_delete=models.CASCADE) stock_id = models.ForeignKey("Stocks", on_delete=models.CASCADE) buy_datetime = models.DateTimeField(default=datetime.now, blank=True) number_of_shares = models.IntegerField() class Stocks(models.Model): stock_id = models.AutoField(primary_key=True) stock_symbol = models.CharField(max_length=12) In my head I would have an entry in the "Portfolios" table for each stock of a portfolio. So "Portfolios" would look like portfolioid 1, userid: 1, stockid: 1, buydate: 12.01.2019, shares: 20 portfolioid 1, userid: 1, stockid: 2, buydate: 19.02.2020, shares: 41 So there is one portfolio, which contains two stocks. But overall that doesn't seem right. If used like in my example above I can't have the portfolioid as a primary key, how can I improve this? Thanks for your time -
can i use default argument on foreignkey?
i added a str default to foreign key but when i tried to create superuser i got error with this argument : ValueError: Field 'id' expected a number but got 'personal'. heres my code : class Genders(models.Model): get_gender = models.TextField() class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True,validators=[ MaxValueValidator(100),MinValueValidator(6)]) gender = models.ForeignKey(Genders,default='personal',on_delete=models.CASCADE) can you help with this problem ? im learning django cant debug yet but i thought maybe problem is that superuser doesnt have a gender value -
Django - register several template tags in one file
I'm just wondering whether it's possible to register more than one template tag in one file, like this: # (project root)/templatetags/my_inclusion_tags.py from django.template import Library register = Library() def func1(): ... return context def func2(): ... return context def func3(): ... return context register.inclusion_tag('templatetages/templates/template1.html', func=func1, name='tag1') register.inclusion_tag('templatetages/templates/template2.html', func=func2, name='tag2') register.inclusion_tag('templatetages/templates/template3.html', func=func3, name='tag3') I just think it makes for a much cleaner file tree. Since my functions for the inclusion tags are like 10 lines long I think it's more messy than useful to have it in separate files. I feel like this should be possible, although I'm not sure how to let settings.py know that these inclusion tags exist. I've tried it several different ways but haven't gotten anything to work, for example: # settings.py TEMPLATES = [ ... OPTIONS: { ... libraries: { 'tags': 'templatetags.my_templatetags' } } ] And then import them with something like this: {% load tags %} or {% load tags.tag1 %} But like i said, I haven't gotten anything to work and i haven't been able to find any information about this anywhere. -
why link is not working in html and how to solve it?
when i click a 'add to cart' button, it shows a blank page instead of cart page ` <a class="btn btn-secondary" href="{% url 'cart:add_cart' product.id %}">Add to Cart</a> this is the code from my product.html `` def add_cart(request, product_id): product = Product.objects.get(id=product_id) try: cart = Cart.objects.get(cart_id=_cart_id(request)) except Cart.DoesNotExist: cart = Cart.objects.create(cart_id=_cart_id(request)) cart.save() try: cart_item = CartItem.objects.get(product=product, cart=cart) if cart_item.quantity < cart_item.product.stock: cart_item.quantity += 1 cart_item.save() except CartItem.DoesNotExist: cart_item = CartItem.objects.create( product=product, quantity=1, cart=cart ) cart_item.save() return redirect('cart:cart_detail') and this is from cart.views` i hope someone can help me with this -
Django multi-country app with one database for all apps
I'm developing one template application which can be used in many countries and in each country I plan to show country-specific language set for users, also I want to use only ONE database for all those applications... So my question is: is it possible somehow to set LANGUAGES variable in settings.py for specific country? Because as I understood I have only one table with translations in my database where all translations are have column_lang model... so if i.e I had app for America with language list: en, es, fr and Poland application with language list: en, pl will I had some database conflicts if I had only one database and different languages? And if so maybe is there some way to avoid those conflicts? P.S use PostgreSQL database and Django 4.1.1; P.P.P.S I added column for country code to each table which should be country-specific; P.P.S in Database projecting and python I don't have so much experience so maybe dummy question =) Thanks for helping! -
How to create a section of cross infos from different tables in Django
I hope that the question below is well posed and it comfy to the rules of the community. Moreover, even if I tried to be more comprehensive as possible, if some more details are needed please feel free to ask for them. I am developing a web server on the footsteps of Local library from Mozilla Developers Among the pool of data, I have Odorants, Receptors and the interactions that they are able to make. Please find the models below: # Create your models here. class Odorant(models.Model): Pubchem_ID = models.IntegerField(primary_key = True) Name = models.CharField(max_length =50) IUPAC_Name = models.CharField('IUPAC Name', max_length = 250) Synonim = models.CharField(max_length = 50) SMILES = models.CharField(max_length = 100) #NOT NULL by default Molecular_Formula = models.CharField(max_length = 20) Molecular_Weight = models.DecimalField(max_digits = 8, decimal_places =4) Atom_Count = models.IntegerField() Rotatable_Bonds = models.IntegerField() Molecular_Refractivity = models.DecimalField(null = True, blank = True, max_digits = 5, decimal_places =3) Volume = models.DecimalField(max_digits = 6, decimal_places =2) SASA = models.DecimalField('SASA', max_digits = 6, decimal_places =2) H_Bond_Donor = models.IntegerField() H_Bond_Acceptor = models.IntegerField() Total_Charge = models.IntegerField() pKa = models.DecimalField('pKa', null = True, blank = True, max_digits = 5, decimal_places =2) AlogP = models.DecimalField('AlogP', null = True, blank = True, max_digits = 5, decimal_places =2) … -
How do i solve field error for querying my model?
Cannot resolve keyword 'username_contains' into field. Choices are: bio, id, username @api_view(['GET']) def endpoints_list(request): query=request.GET.get('query') if query == None: query='' print(query) adv_data=Advocate.objects.filter(username_contains=query) serializer=AdvocateSerializer(adv_data,many=True) return Response(serializer.data) I tried querying model but it says it cannot convert it into field -
Djoser reset password email with Celery
I want to send reset password email using Celery. I try to override the reset_password method of the class djoser.views.UserViewSet: class CustomUserViewSet(UserViewSet): @action(["post"], detail=False) def reset_password(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.get_user() if user: send_reset_password_email.delay( self.request, {'user': user}, [get_user_email(user)] ) return Response(status=status.HTTP_200_OK) But I get an error: Traceback (most recent call last): File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 39, in _reraise_errors yield File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\serialization.py", line 210, in dumps payload = encoder(data) File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 68, in dumps return _dumps(s, cls=cls or _default_encoder, File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\__init__.py", line 238, in dumps **kw).encode(obj) File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Dev\rich-peach\venv\lib\site-packages\kombu\utils\json.py", line 58, in default return super().default(o) File "C:\Users\lev_k\AppData\Local\Programs\Python\Python310\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type Request is not JSON serializable During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Dev\rich-peach\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Dev\rich-peach\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\viewsets.py", line 125, in view return self.dispatch(request, *args, **kwargs) File "C:\Dev\rich-peach\venv\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) … -
Django can't catch all the values throwing an exception
I am trying to import excel data to a django model. So to test it, I used an excel file with more than 4000 rows. One of the fields in the model requires the entry to be unique, so I tried to catch all the entries that aren't. I have a try-catch block around the code that tries to add the values of each row to the model. integrity_catches = {} integrity_counts = 0 # loop start try: new_student = Student( student_school = school, student_class = selected_class, student_stream = selected_stream, admission_number = admission_number_cell, student_name = student_name_cell, parent_phone = parent_phone_cell, kcpe_marks = kcpe_marks_cell ) new_student.save() except IntegrityError as e: integrity_catches[admission_number_cell] = student_name_cell integrity_counts = integrity_counts + 1 continue # loop end The code runs well, but only imports 250 students, so I expect it to add the rest to the integrity_catches dictionary. The problem is, the dictionary contains 202 entries, while the integrity_counts is showing 4035. This means that more than 4000 entries raised an exception but didn't get stored in the dictionary. I am trying to make sure that when someone imports the data from an excel sheet, they can see all the entries that failed to be added to … -
I want to send notification from django app to flutter
I want to send a notification from django to flutter everytime i add something in my database. I retrieve the fcmtoken in flutter and send it in my django app then i save it for my device because i want to send the notification to a specific user. When i add something in my database get my device token from FCMDevice model. DEVICE_TOKEN = device.registration_id notification = { "title": task_model.headline, "body": task_model.deadline, } device = FCMDevice.objects.get(registration_id=DEVICE_TOKEN,user_id = task_model.user_id, active=1) print("id user e ") print(device.user_id) device.send_message(data=notification) I don't know how to send it to my flutter app and push the notification on the mobile because i tried something and it didn't work. -
nginx doesn't acess folders inside static folder (django app)
I searched and didn't find this exact problem. I deployed an application in django on GCP, using gunicorn + nginx It's working normally, except for the static files I ran django's collectstatic and got the files folder and statics like this: lnmat@sistema-ag:~/app_repo$ ls apps gunicorn-error-log requirements.txt static venv base_static manage.py sistema_vendas_ag templates lnmat@sistema-ag:~/app_repo$ cd static lnmat@sistema-ag:~/app_repo/static$ ls admin global lnmat@sistema-ag:~/app_repo/static$ ls admin css fonts img js lnmat@sistema-ag:~/app_repo/static$ ls global css js vendor In the nginx error log: 2022/12/13 20:36:00 [error] 8136#8136: *1 open() "/home/lnmat/app_repo/static/js/sb-admin-2.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/js/sb-admin-2.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/login/?next=/" 2022/12/13 20:36:09 [error] 8136#8136: *7 open() "/home/lnmat/app_repo/static/css/sb-admin-2.min.css" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/css/sb-admin-2.min.css HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/" 2022/12/13 20:36:09 [error] 8136#8136: *12 open() "/home/lnmat/app_repo/static/vendor/jquery/jquery.min.js" failed (2: No such file or directory), client: x.x.x.x, server: -, request: "GET /static/vendor/jquery/jquery.min.js HTTP/1.1", host: "x.x.x.x", referrer: "http://x.x.x.x/" Apparently nginx is trying to access the static files directly in the main folder without accessing the subfolders global/ and admin/ which is where the files are. My nginx server block: server { listen 80; server_name x.x.x.x; location = /favicon.ico { access_log off; log_not_found off; … -
Comparing two lists with each other and color the difference with django
I have a django application. And I try to mark the difference values in the lists red in the template. So I have some methods with lists inside. Because in the real situation. You can upload a pdf and excel file. But this is just for testing. So that I can use it in the real situation. But the idea is the same. So this are the metods: class FilterText: def total_cost_fruit(self): return [3588.20, 5018.75, 3488.16] def show_extracted_data_from_file(self): regexes = [self.total_cost_fruit()] matches = [(regex) for regex in regexes] columns = ["kosten fruit"] return mark_safe( tabulate( zip_longest(*matches), # type: ignore headers=columns, tablefmt="html", stralign="center", ) ) and second class: class ExtractingTextFromExcel: def init(self): pass def extract_data_excel_combined(self): new_fruit_list = [[i] for i in self.total_fruit_cost()] columns = ["totaal", "kosten", "fruit"] return mark_safe(tabulate(new_fruit_list, headers=columns, tablefmt="html", stralign="center")) def total_fruit_cost(self): dict_fruit = {"Watermeloen": 3588.10, "Appel": 5018.40, "Sinaasappel": 3488.16} fruit_list = list(dict_fruit.values()) #[[i] for i in dict_fruit.values()] print(fruit_list) return fruit_list and the views.py: def test(request): filter_excel = ExtractingTextFromExcel() filter_text = FilterText() compare_data = CompareData() total_fruit_cost_pdf = filter_text.total_cost_fruit() total_fruit_cost_excel = filter_excel.total_fruit_cost() diff_set = compare_data.diff(total_fruit_cost_pdf, total_fruit_cost_excel) print(diff_set) content_excel = "" content_pdf = "" content_pdf = filter_text.show_extracted_data_from_file() content_excel = filter_excel.extract_data_excel_combined() context = { "content_pdf": content_pdf, "content_excel": content_excel, "diff_set": diff_set, } return … -
Extend social pipeline and prevent a specific function to run during tests
I'm using Python Django Social Auth and extended the pipeline with the following three steps One before the user is created (partial pipeline) requesting some data. One for the user creation (overrides the social.pipeline.user.create_user method). One after the user is created. In order to test it, I'm following similar logic to the one used here. This is what I have @mock.patch("social_core.backends.base.BaseAuth.request") def test_complete(self, mock_request): url = reverse("social:complete", kwargs={"backend": "facebook"}) url += "?code=2&state=1" mock_request.return_value.json.return_value = {"access_token": "123"} with mock.patch( "django.contrib.sessions.backends.base.SessionBase" ".set_expiry", side_effect=[OverflowError, None], ): response_1 = self.client.get(url) self.assertEqual(response_1.status_code, 302) self.assertEqual(response_1.url, "/before-user-is-created/") response_2 = self.client.post("/before-user-is-created/", {"some_keys": "some_values"}) self.assertEqual(response_2.status_code, 302) self.assertEqual(response_2.url, "/social-auth/complete/facebook/") response_3 = self.client.post("/social-auth/complete/facebook/") return response_3 For step 1, I have a url (/before-user-is-created/) and a specific view. So, when running response_1 = self.client.get(url) I get it that view and I'm able to act on it. The problem is with step 3. That is essentially a function (after_user_creation()) that calls another one (function_called()) def after_user_creation(user, *args, **kwargs): ... function_called(something_from_user) How to prevent function_called(something_from_user) to run during tests? -
'list' object has no attribute 'get'
I would like to return number in views.py but always get the attribute error. I am not want to get something, I just want to return a variable, but it always shows " object has no attribute 'get'". I had tried to change return the number to string and list, but all got this error Traceback (most recent call last): File "C:\Users\Asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\handlers\exception.py", line 55, in inner response = get_response(request) File "C:\Users\Asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\deprecation.py", line 136, in __call__ response = self.process_response(request, response) File "C:\Users\Asus\AppData\Local\Programs\Python\Python310\lib\site-packages\django\middleware\clickjacking.py", line 27, in process_response if response.get("X-Frame-Options") is not None: Exception Type: AttributeError at /scan-port/ Exception Value: 'int' object has no attribute 'get' This is my code in views.py function number = 3 return number Can anyone help me to solve this. I had searched online but no solution found! -
How to know if a user is logged in via Oauth
I added authorization through social networks to my site. How can I find out that the user used exactly this authorization? In the process of authorizing a user through a social network, I need to change the verified value in the database table, as well as add his photo to this table. Note: I didn't rewrite the default user model, but extended it by creating a ForeignKey in the Profile table. This table stores information about the user (phone number, gender, etc.) Note2: I'm using social-auth-app-django It seems to me that I should implement a separate View for authorization on social networks in order to catch all the data I need. But what should it look like? I am new to this matter. -
multi file-upload fields in one model
I need something like this: In one form there will be several file upload fields with multi uploads. I would make it as single field, but I need then to filter it. E.g: I will need to display on frontend all the file1, not file1 - file2 - file3 combined. So, I Need model like this (but that works only for a single file upload) class TestModel(models.Model): #info 1 exp_date = models.DateField(default=None, blank=True, null=True) file1 = models.FileField(upload_to="1/", blank=True, null=True)#multi files #info 2 member_number = models.CharField(max_length=50, default=None) file2 = models.FileField(upload_to="1/", blank=True, null=True)#multi files #info 3 member_exp_date = models.CharField(max_length=50, default=None) file3 = models.FileField(upload_to="1/", blank=True, null=True)#multi files But it has to have multi file uploads in each "file upload" field, therefore I have to create another model like this for every file field class FilesOne(models.Model): file = models.FileField(upload_to="%Y-%m-%d/", blank=True, null=True) files_key = models.ForeignKey('TestModel', on_delete=models.CASCADE, default=None, null=True) class FilesTwo(models.Model): file = models.FileField(upload_to="%Y-%m-%d/", blank=True, null=True) files_key = models.ForeignKey('TestModel', on_delete=models.CASCADE, default=None, null=True) ... and in views make for loop and run "create-objects" 'file-number' Times for every field like this: add_files = request.FILES.getlist("file") for i in add_files : FilesOne.objects.create(files_key=user.driver, file=i) So, is there any good solution to make it happen? -
How to filter records that doesn't have a record in a related table?
Consider the two models below: from django.db import models class Author(models.Model): name = models.CharField(max_length=255) class Book(models.Model): author = models.ForeignKey(Author, models.CASCADE, related_name="books") how to get only authors that does not have books? -
Why doesn't my css effect my django html template?
So I am trying to create navigation bar to my django template but I can't make any css adjustments. Django doesn't throw any error messages... {% load static %} <head> <link rel='stylesheet' type='varaustiedot/styles.css' href="{% static 'style.css' %}"/> <title>Varaus</title> <! Varaus = Reserve> </head> <body> <div class="topnav"> <!> <!a class="active" href="home"><!/a> <a href="register">Varaa</a> <a href="#">Yhteystiedot</a> <a href="#">Tietoa meistä</a> </div> </body> Here is my css file html, body{ font-size: 15px; background-color: #1f2029; } .osoite{ margin: auto; width: 50%; text-align: center; } .centered-form { text-align: center; } .topnav{ text-align: right; margin-top: 20px; margin-bottom: 40px; padding: 20px; background-color: black; } I tried to google the answer and I even asked chatbotGPT. So far I haven't found any issues. I have changed class names and all the names I could think of. I had ?{% now "U" %} when i did that link at first. But it didn't seem to do anything and every time I refreshed the site and had done some changes to css code (I checked with control + u) it had been updated... I am not sure if there is some sort of typo or something like that but usual ?{% now "U" %} fix didn't seem to work for me. … -
Uncaught TypeError in javascript
I have created chatbot using pytorch and integrating it into flask project. But getting some erros please help me with it. Thanks! // app.js app.js file used while creating chatbot class Chatbox { constructor() { this.args = { openButton : document.querySelector('.chatbox__button'), closeButton : document.querySelector('.chatbox__support'), sendButton : document.querySelector('.send__button') } this.state = false; this.messages = []; } display() { const {openButton, chatBox, sendButton} = this.args; openButton.addEventListener('click', () => this.toggleState(chatBox)) sendButton.addEventListener('click', ()=> this.onSendButton(chatBox)) const node = chatBox.querySelector('input'); node.addEventListener("keyup", ({key}) => { if (key === "Enter"){ this.onSendButton(chatBox) } }) } toggleState(chatBox){ this.state = !this.state; if(this.state){ chatBox.classList.add('chatbox--active') }else{ chatBox.classList.remove('chatbox--active') } } onSendButton(chatbox){ var textField = Chatbox.querySelector('input'); let text1 = textField.value if (text1 === ""){ return; } let msg1 = {name : "User", message:text1} this.messages.push(msg1); fetch($SCRIPT_ROOT + '/predict', { method: 'POST', body : JSON.stringify({message:text1}), mode : 'cors', headers : { 'Content-Type' : 'application/json' }, }) .then(r => r.json()) .then(r => { let msg2 = {name: 'Sam', message: r.answer}; this.messages.push(msg2); this.updateChatText(chatbox) textField.value = '' }).catch((error) => { console.error('Error:', error); this.updateChatText(chatbox) textField.value = '' }); } updateChatText(chatbox){ var html = ''; this.messages.slice().reverse().forEach(function(item,){ if (item.name === 'Sam'){ html += '<div class="messages__item messages__item--visitor'> + item.message + '<div>' } else{ html += 'div class="messages-__item messages__item--operator' + item.message + '<div>' } }); …