Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unsupported operand type(s) for *: 'QuerySet' and 'IntegerField'
Im trying to multiply the result from subquery with 1000 but instead i got the error "unsupported operand type(s) for *: 'QuerySet' and 'IntegerField'" this is my code : last_lrpa = LRPA_File.objects.order_by('-file_export_date').first() last_mou = FileMouPengalihan.objects.order_by('file_export_date').first() sq_1 = MacroData.objects.filter(macro_file=skai_1.macro.macro_file_1, prk=OuterRef('prk')) sq_2 = MacroData.objects.filter(macro_file=skai_2.macro.macro_file_1, prk=OuterRef('prk')) sq_3 = MacroData.objects.filter(macro_file=skai_3.macro.macro_file_1, prk=OuterRef('prk')) sq_mou = MouPengalihanData.objects.filter(file=last_mou, prk=OuterRef('prk')) lrpa = LRPA_Monitoring.objects.select_related('prk').filter(file=last_lrpa). \ annotate(ai_1 = Round(sq_1.values('ai_this_year')*1000), aki_1 = sq_1.values('aki_this_year'), status_1 = sq_1.values('ang_status'), ai_2 = Round(sq_2.values('ai_this_year')*1000), aki_2 = sq_2.values('aki_this_year'), status_2 = sq_2.values('ang_status'), ai_3 = Round(sq_3.values('ai_this_year')*1000), aki_3 = sq_3.values('aki_this_year'), status_3 = sq_3.values('ang_status'), mou_jan = sq_mou.values('jan'),mou_feb = sq_mou.values('feb'),mou_mar = sq_mou.values('mar'),mou_apr = sq_mou.values('apr'), mou_mei = sq_mou.values('mei'),mou_jun = sq_mou.values('jun'),mou_jul = sq_mou.values('jul'),mou_aug = sq_mou.values('aug'), mou_sep = sq_mou.values('sep'),mou_okt = sq_mou.values('okt'),mou_nov = sq_mou.values('nov'),mou_des = sq_mou.values('des'), sd_1 = sq_1.values('sumber_dana'), sd_2 = sq_2.values('sumber_dana'), sd_3 = sq_3.values('sumber_dana'), ) context["lrpa"] = lrpa -
Exporting Django models to Excel (different sheets) using Django-tables2
I've checked django-tables2 documentation, however I haven't find an easy way to export models to different sheets in Excel. To make it simple, let's suppose I have two different models: Sales and Products. I would like to export an excel document with two different sheets: Sales and Products. I can export the first model with the code shown below, but I'm not sure if there's a way to export the Products model to another sheet. Any help would be appreciated. export_format = request.GET.get('_export', None) if TableExport.is_valid_format(export_format): table = [[Sales Table Object]] exporter = TableExport(export_format, table) return exporter.response('File_Name.{}'.format(export_format)) ``` -
Django multitenant using middleware - can you persist connections
I'm using django with django-tenants for a SaaS app and it is using the user's subdomain to set the db schema in postgresql. So a call to user1.app.com will use the 'user1' schema. Each call to a view creates a new database connection by default. If the view call ajax, a new connect/disconnect happens. Using this method works as each call gets it's postgresql search path set to the correct schema using the django-tenants middleware. My question is if I set CONN_MAX_AGE to persist connections for a period of time to reduce the heavy connect/disconnect load on the server, will django pool connections from multiple users potentially using different schemas? I am concerned, because: All users are using the 'default' DATABASE. (just the search path changes) I don't see any logic that binds a connection to a unique user session. The built in development server ignores the CONN_MAX_AGE setting so I can't test locally. I have looked into the connection_created signal, but I would be duplicating logic with django-tenants and I'm not sure of any unintended consequences. Using django 4.0.7 and posgresql 12 Any insight or suggestions are appreciated. -
How to set another instance as foreign key on delete in django?
so if I have a "company" model and a "person" model, and the "company" model has an owner ( a "person" model instance), and a co-owner( a "person" model instance too), I want to make it so that when the owner is deleted the co-owner becomes the owner and the co-owner becomes empty, is that possible in Django? -
How I can use Nested serializer in Django Rest Framework
Hi I'm creating a serializer where I wanna show user profile details and all his products from the product model but it's not working serializer.py class UserSerializer(serializers.ModelSerializer): related_products = ProductSerializer( source="user.product_set.all", read_only=True, many=True ) class Meta: model = User fields = [ "first_name", "last_name", "bio", "phone", "agency", "related_products", ] views.py class ProfileView(generics.RetrieveAPIView): serializer_class = UserSerializer permission_classes = [permissions.IsAuthenticated, onlyuser] def retrieve(self, request, *args, **kwargs): serializer = self.serializer_class(request.user) return Response(serializer.data, status=status.HTTP_200_OK) -
Why i have already installed modules in my virtualenv?
I have globally installed modules in my pc, but when i create a virtualenv some of the modules are already preinstalled in it, but when i execute 'pip freeze' in my virtualenv there are no installed modules. commands like 'django-admin' , 'cookiecutter' already work in my virtualenv though i have never installed them in it. But other commands like 'numpy' or 'pandas' do not work , though i have installed them in my machine globally like django or cookiecutter. How do i fix this? I am using python version 3.9.6. -
Django DM model constraint: uniqueConstraint or checkConstraint?
I am trying to define a unique constraint for my DB model. I have 3 constraints and have no trouble with 2. But the 3rd one is doing my head a little. So the model class is fairly simply; its a social media connection request model (between user accounts). These are the constraints I am trying to enforce: User1 should have only one connection request to User2: UniqueConstraint works fine. User1 should not be able to send a connection request to User1 (ie self): CheckConstraint works fine. If User1 sends a connection request to User2, then User2 should not be able to send a connection request back to User1: this is the one I am struggling with. How can I enforce the 3rd constraint here? I initially thought the 1st one enforces the reverse constraint actually (where the uniqueness of the 2 entries in the table are enforced regardless of the order) but it doesnt seem it like (and makes sense too). class ConnectionRequest(models.Model): senderAccount = models.ForeignKey( Account, related_name='sender_Account', on_delete=models.CASCADE) recipientAccount = models.ForeignKey( Account, related_name='recipient_Account', on_delete=models.CASCADE) requested = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.senderAccount.id) + ' to ' + str(self.recipientAccount.id) class Meta: constraints = [ # duplicate connection request constraint models.UniqueConstraint(name='duplicate_connreq_constraint', … -
TemplateDoesNotExist at / chat_app/dashboard.html
I am makeing a chat app, and I have run into some issues. I think I hace had this problom befor but I can not figure out how to fix it. Django is sitting the error is where I have the bootstrap import in y base HTML. I have checked I have included the template DIRs. any help would be appreciated. base.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous"> <!-- Optional theme --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap-theme.min.css" integrity="sha384-6pzBo3FDv/PJ8r2KRkGHifhEocL+1X2rVCTTkUfGk7/0pbek5mMa1upzvWbrUbOZ" crossorigin="anonymous"> <!-- Latest compiled and minified JavaScript --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script> <meta charset="utf-8"> <title>Chatter</title> <link rel="stylesheet" href={% static "css/master.css" %}> </head> <body> {% block content %} {% endblock %} </body> </html> setting.py """ Django settings for chatapp project. Generated by 'django-admin startproject' using Django 3.1.7. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATE_DIR = Path(BASE_DIR) / "templates" MEDIA_ROOT = Path(BASE_DIR) / "media" STATIC_DIR = Path(BASE_DIR) / 'static' MEDIA_URL = "/media/" # Quick-start development settings - unsuitable … -
Django updating username results in unusable password. How to prevent this?
I am using code to update the user details and whilst the values are updating I have noticed that when I update the username, which is an email address, the password is set to an unusable password, as if set_unusable_password() were used. If I don't update the username but change the first_name and last_name everything is fine. Why? And how can I stop this behaviour? User.objects.filter(username=username).update( first_name=first_name, last_name=last_name, username=username/new_user_name, ) FYI, this is base User model in django. -
Django Rest Framework when doing a POST getting TypeError at Function.objects.create()
I have the following model class Funcion(models.Model): idPelicula = models.ForeignKey(Pelicula, on_delete=models.PROTECT) idSala = models.ForeignKey(Sala, on_delete=models.PROTECT) horaEntrada = models.TimeField(auto_now=False, auto_now_add=False) horaSalida = models.TimeField(auto_now=False, auto_now_add=False) fecha = models.DateField(auto_now=False) And the next serializer class FuncionSerializer(serializers.ModelSerializer): pelicula = PeliculaSerializer(read_only=True) idPelicula = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Pelicula.objects.all(), source='pelicula') sala = SalaSerializer(read_only=True) idSala = serializers.PrimaryKeyRelatedField(write_only=True, queryset=Sala.objects.all(), source='sala') class Meta: model = Funcion fields = '__all__' When I try to post a new Funcion with the Django api root I get the following error: TypeError at /funcion/ Got a `TypeError` when calling `Funcion.objects.create()`. This may be because you have a writable field on the serializer class that is not a valid argument to `Funcion.objects.create()`. You may need to make the field read-only, or override the FuncionSerializer.create() method to handle this correctly. I have used this method before for other project practices and it worked correctly. If i delete the source='pelicula' argument for the PrimaryKeyRelatedField() it post the new funcion but when I do a get to bring al the data it doesn't show the Pelicula or Sala field just the rest I tried deleting those arguments because the error at the end shows this message TypeError: Funcion() got unexpected keyword arguments: 'pelicula', 'sala' -
Filters for CBV ListView using GET from Previous and Current Page
I am trying to add search functionality to a ListView in two places in my Django application. From the homepage, I want users to be able to filter by zip code, and on the ListView template, I also want users to have the ability to filter by another attribute in the model. My issue is that the self.request.GET.get('q') returns None when filtering from the ListView page, and I want it to retain the zip code filter that I used in the previous page. For search functionality, I am using Q. How can I retain the zip code filter from the initial request so that I can query on both zip code and category? views.py class ListingsView(ListView): model = Listing template_name = 'listings/list.html' context_object_name = 'listing_list' def get_queryset(self): query_zip = self.request.GET.get('q_zip_code') query_category = self.request.GET.get('q_category') if query_category == None: queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip)) else: queryset = Listing.objects.filter(Q(zip_code__icontains = query_zip) & Q(category__icontains = query_category)) return queryset home.html <p> <form class="form-homepage-search" action="{% url 'rental_listings_list' %}" method="get"> <input name="q_zip_code" class="form-zip" type="text" placeholder="Zip Code" aria-label="Zip Code"> <button class="button" type="submit">SEARCH</button> </form> </p> list.html <form class="form-listing-search" action="{% url 'rental_listings_list' %}" method="get"> <input name="q_category" class="form-category" type="text" placeholder="Category" aria-label="Category"> <button class="button" type="submit">UPDATE</button> </form> -
Persisting external classes in Django
I am working on a Django application that uses the SimpleGmail package to fetch mails from a Gmail inbox and I need to persist them. Normally I'd have written a model for the class, but given it's an external class, I can't figure out how to cleanly persist it. I have come across solutions such as making it an attribute of a new model that is persisted or multiple inheritance of the desired class, but none of these seem correct to me. How do I properly register an external class as a model for Django's persistence? -
How to use timezone.now() in django with activate timezone?
I am using Django 3.2 and changed my setting.py as TIME_ZONE = 'Asia/Calcutta' USE_I18N = True USE_L10N = True USE_TZ = True and try to use timezone.now() It gives me the UTC time when I print it from my view.py It worked well for DateTimeField in models when I store some data into it. I also activate the timezone from django.utils.timezone import activate activate(settings.TIME_ZONE) I don't know why it works for models but not for view. Can anybody explain how to use timezone in django. datetime.datetime.now() # 2022-08-29 02:03:44.941847 timezone.localtime(timezone.now()) # 2022-08-29 02:03:44.941847+05:30 timezone.now() # 2022-08-28 20:33:44.941847+00:00 timezone.get_current_timezone() # Asia/Kolkata -
How to add Formset in this methodology?
I'm trying to make a inline formset where the people who are trying to register can also add his pincodes that he can work. I'm not sure how to make the forms, views and html template for it. The reason being it because I've already made a function in the def so I'm not sure how to add this inline formset also. So Thanks in advance models.py class User(AbstractUser): ADDCHKS_ID=models.CharField(max_length=16, blank=True, null=True) is_active=models.BooleanField(default=False,blank=True, null=True) is_excutive=models.BooleanField(default=False,blank=True, null=True) class ExcutiveRegistration(models.Model): User = models.ForeignKey(User, on_delete=models.CASCADE,null=True) '''Personal Details''' First_name = models.CharField(max_length=100,null=True ,blank=True) Last_name = models.CharField(max_length=100,null=True ,blank=True) DOB = models.DateField(max_length=100,null=True ,blank=True) Fathers_name = models.CharField(max_length=100,null=True ,blank=True) Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) Alt_Contact_number = models.IntegerField(max_length=10,null=True ,blank=True) # Profile_picture=models.ImageField(upload_to='images/', null=True, verbose_name="") '''Current Addresss''' Pin_code_c = models.IntegerField(max_length=6,null=True ,blank=True) State_c = models.CharField(max_length=50,null=True ,blank=True) District_c = models.CharField(max_length=50,null=True ,blank=True) Taluk_c = models.CharField(max_length=50,null=True ,blank=True) Location_c = models.CharField(max_length=100,null=True ,blank=True) House_no_c = models.IntegerField(max_length=4,null=True ,blank=True) Street_c = models.CharField(max_length=100,null=True ,blank=True) class ExcutiveRegistrationPincode(models.Model): ExcutiveRegistration=models.ForeignKey(ExcutiveRegistration, on_delete=models.CASCADE) Covering_Pincode=models.IntegerField(max_length=6) forms.py class ExcutiveRegistrationform(forms.Form): First_name = forms.CharField( label='First_name', widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'First_name', 'rows':1 }) ) views.py def test2(request): form = ExcutiveRegistrationform() if request.method == 'POST': form = ExcutiveRegistrationform(request.POST, request.FILES) if form.is_valid(): user21 = User.objects.create_user( username=form.data['First_name'], password=str(random.random()), ) ExcutiveRegistrationform_data = ExcutiveRegistration.objects.create( User=user21, First_name=form.data['First_name'], ) return redirect('/Accounts/Physcial_checks') context = {'form': form} return render(request, 'accounts\Registration_Pages\Excutive_Registration.html', context) -
Imported file has a wrong encoding: 'charmap' codec can't decode byte 0x8d in position 4510: character maps to in django import-export
I am trying to import data from a csv. Here is the csv's screenshot as you can see I've imported another csv it was completely ok but. For this csv it's not working. I am getting the error all the time. I am using encoding "utf8" Here is my code: import json import requests from bs4 import BeautifulSoup import pandas as pd from csv import writer url = "https://prowrestling.fandom.com/wiki/New_Japan_Pro_Wrestling/Roster" page = requests.get(url) soup = BeautifulSoup(page.content, 'html.parser') # links = [ # "https://prowrestling.fandom.com/" + a["href"] for a in soup.select("classname a") # ] links = [ "https://prowrestling.fandom.com/" + a["href"] for a in soup.select("td a") ] with open("real/njpw.csv", 'a', encoding="utf8", newline="") as f: print(f) wrt = writer(f) header = ["ring_name", "height", "weight", "born", "birth_place", "trainer", "debut", "resides"] wrt.writerow(header) for link in links: soup = BeautifulSoup(requests.get(link).content, "html.parser") ring_name = soup.h2.text.strip() height = soup.select_one('.pi-data-label:-soup-contains("Height") + div') if height is not None: height = height.text.strip() else: height = "" weight = soup.select_one('.pi-data-label:-soup-contains("Weight") + div') if weight is not None: weight = weight.text.strip() else: weight = "" born = soup.select_one('.pi-data-label:-soup-contains("Born") + div') if born is not None: born = born.text.strip() else: born = "" birth_place = soup.select_one('.pi-data-label:-soup-contains("Birth Place") + div') if birth_place is not None: birth_place = … -
NoReverseMatch problem with UpdateView class in Django
I am trying to create an update view in django, inheriting UpdateView. My view looks like this: class UpdateStudentView(UpdateView): model = Student form_class = StudentForm template_name = "students/students_update.html" success_url = reverse_lazy("students:students") This view takes Student`s primary key as an argument from url path("update/<uuid:pk>/", UpdateStudentView.as_view(), name="update_student"), And here is the template, which should take this primary_key from url and pass it to view. {% block content %} <form action="{% url "students:update_student" pk %}" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock content %} However, it doesn`t work and throws a NoReverseMatch: NoReverseMatch at /students/update/primary_key_here/ Reverse for 'update_student' with arguments '('',)' not found. 1 pattern(s) tried: ['students/update/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/\\Z'] Could you please explain me why does this happen and how can I avoid this error? Please don`t tell me about using pk_url_kwarg = 'pk', as it is 'pk' by default Thanks in advance! -
Exception Value: Profile matching query does not exist
I have automatically created a profile with signals when a user is created. In this profile you can add followers in the ManyToMany field called followers. But when I try to use the AddFollower or RemoveFollower method I get this error. This only happens with profiles created automatically with signals, those created with the django admin work fine. I'd appreciate your help! My views.py class AddFollower(ListView): def post(self, request, pk , *args, **kwargs ): profile = Profile.objects.get(pk=pk) profile.followers.add(self.request.user) return redirect('profile', username = profile.user.username) class RemoveFollower(ListView): def post(self, request, pk , *args, **kwargs ): profile = Profile.objects.get(pk=pk) profile.followers.remove(self.request.user) return redirect('profile', username = profile.user.username) Urls.py: urlpatterns = [ path('profile', profile,name='profile'), path('profile/<str:username>/', profile,name='profile'), path('add_follower/<int:pk>/', AddFollower.as_view(),name='add_follower'), path('remove_follower/<int:pk>/', RemoveFollower.as_view(),name='remove_follower'), path('all_followers/<int:pk>/', AllFollowers.as_view(), name='all_followers'), path('feed', Feed.as_view(),name='feed'), path('register', register, name='register'), path('login', LoginView.as_view(template_name='network_app/login.html'), name='login'), path('logout', LogoutView.as_view(template_name= 'network_app/logout.html'), name='logout'), path('create_post', CreatePost.as_view(), name='create_post' ), path('following_posts', FollowingPosts.as_view(), name= 'following_posts') ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) html: {% if user.is_authenticated and user != current_user %} {% if is_following %} <h1>{{ is_following }}</h1> <form method="POST" action="{% url 'remove_follower' user.pk %}" > {% csrf_token %} <button type="submit">Unfollow</button> </form> {% else %} <h1>{{ is_following }}</h1> <form method="POST" action="{% url 'add_follower' user.pk %}" > {% csrf_token %} <button type="submit">Follow</button> </form> {% endif %} {% endif %} Profile function: def profile … -
How to download a visiting card with dynamic content?
I am creating a django app, where i wanted to provide our clients a downloadable visiting card inside their account. For that i have a user models as follows: class Country(models.Model): name = models.CharField(max_length=100, unique=True) class CustomUser(models.Model): email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) contact_number = models.CharField(max_length=30) country = models.ForeignKey(Country, on_delete=models.SET_NULL) profile_pic = models.ImageField() def full_name(self): return f'{self.first_name} {self.last_name}' my url is as follows: from django.urls import path from . import views urlpatterns = [ path('visiting-card/<int:vid>', views.visitingCard, name='visiting-card'), ] and i have created a view to get all the content from respective users: def visitingCard(request, mid): user = get_object_or_404(CustomUser, id=vid) context = { 'user': user, } return render(request, 'visitng-card.html', context) and the below code is my visting card landing page html file {% extends 'base.html' %} {% load static %} {% block content %} <div class="container-fluid"> <div class="main-content-body"> <div class="row row-sm"> <div class="col-lg-4"> <div class="card crypto crypt-primary overflow-hidden"> <div class="card-body"> <div style="position: relative;" > <img src="{% static 'dashboard/img/visiting-card-bg.jpg' %}" /> </div> <div style="position: absolute; top: 90px; left: 85px;" > <img src="{{user.profile_pic.url}}" alt="{{user.full_name}}" style="max-width:130px;" class="rounded"> </div> <div style="position: absolute; top: 100px; left: 230px;"> <p> <strong>Name: {{user.full_name}}</strong><br> <strong>Country: {{user.country.name}}</strong><br> <strong>Email: {{user.email}}</strong><br> <strong>Contact: {{user.contact_number}}</strong><br> </p> </div> <div class="pt-3"> <a href="#" … -
Django Celery cannot get access to redis running on another raspberry pi
I'm currently following this tutorial on how to set up celery. I want to use my Raspbery Pi for the redis server, thus I have installed redis on it, and it works. Now, in the Django project I have defined #settings.py CELERY_BROKER_URL = "redis://192.168.0.21:6379" CELERY_RESULT_BACKEND = "redis://192.168.0.21:6379" (where the IP-address is the IP of my Raspberry running the redis server) but my local computer cannot access the redis server; the command python -m celery -A django_celery worker throws the error ERROR/MainProcess] consumer: Cannot connect to redis://192.168.0.21:6379//: DENIED Redis is running in protected mode because protected mode is enabled, no bind address was specified, no authentication password is requested to clients. In this mode connections are only accepted from the loopback interface. If you want to connect from external computers to Redis you may adopt one of the following solutions: 1) Just disable protected mode sending the command 'CONFIG SET protected-mode no' from the loopback interface by connecting to Redis from the same host the server is running, however MAKE SURE Redis is not publicly accessible from internet if you do so. Use CONFIG REWRITE to make this change permanent. 2) Alternatively you can just disable the protected mode by editing … -
relation "django_plotly_dash_statelessapp" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "django_plotly_dash_statel
I am trying to deploy my Django app on render. But there is an error which I don't understand what type of error is this.Please help to solve this error: ProgrammingError at /nickelpure/[relation "django_plotly_dash_statelessapp" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "django_plotly_dash_statel... ^ Error screenshot -
for loop for password add letters in django
so i want to check if my password less from key_bytes (which is 16) then the password will be add "0" until it's have len 16. i was using django. for example password = katakataka. it's only 10. then it will became "katakataka000000" i don't know how to make loop for, so please help me. here's my code key_bytes = 16 if len(key) <= key_bytes: for x in key_bytes: key = key + "0" print(key) -
irregular arbitrarily Cross-Origin request blocked error in Django on Ionos hosting
I am currently making a project for school where I made a quiz. The quiz is supposed to evaluate in the front-end, which works perfectly fine, and after that it should send the information to the backend. The Backend should save the details to the database and after that it should send the information back to the front end. The front end should show a message with some details about how you passed compared to all the others, the information are the one from the database. So, the weird thing about all that is, that it works sometimes and sometimes not... If I test it at the local host, the code works perfectly fine, the error only occurs on the Ionos server (I got a hosting contract so I do not have access to the console...). Here is btw. the Link to my website: https://tor-netzwerk-seminarfach2024.com/ .If you click in the upper left corner and then on the quiz buttonm, you will get to the quiz. If I look at the console and network analytics and I got the "luck" that the error occurs the following message shows up: Cross-Origin request blocked: The same source rule prohibits reading the external resource … -
Django Rest Framework SimpleJWT, custom use case
In DRF SimpleJWT, we need to set a value for when the Refresh Token and the access token would expire. So, the user must log in again after the refresh token expires. But when using Firebase Auth, the user does not need to log in repeatedly. Is there a way to emulate a similar behavior in Django Rest Framework, like in Firebase Authentication. -
Django form and formset are not valid
I'm trying to make a view containing one form and one formset but something does not work. both form and formset after checking if .is_valid returns false. I do not really undersand why it is like that def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") #print(request.POST) returns csrfmiddlewaretoken ... #print(request.FILES) returns file : inmemoryuploadedfile ... #print(list(request.POST.items())) context['form'] = form formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): created_images = formset.save() print("Successfully created new imagest: {}".format(created_images)) else: print("formset is not valid") context['formset'] = formset return render(request, "Ecommerce/create_product_test.html", context) my template - create_product_test.html {% extends 'base.html' %} {% block content %} <div id="alert-box"> </div> <div id="image-box" class="mb-3"> </div> <div id="image-box"></div> <div class="form-container"> <button class="btn btn-primary mt-3 not-visible" id="confirm-btn">confirm</button> <form method="POST" enctype="multipart/form-data" action="" id="image-form"> {% csrf_token %} <div> {{form}} {{formset.management_form}} {{formset.as_p}} </div> </form> </div> {% endblock content %} forms.py file ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, ) where is the problem ? -
Two exactly same repositories but different result
Sorry for this weird question but my mind went blank. I can install a script from its original Github repo (project1) in an Ubuntu server: I clone the original repo and start installation in the server, no problem at all. However if I create a repo (project2) in my GitHub account, then copy all the files (except .git) from the original repo (project1) to my new repo (project2), then clone my repo and start installation in the server, installation gives me an error. ango.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'dictionary.MetaFlatPage'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/3.2/topics/migrations/#dependencies for more Those two repositories are the exactly same. I didn't change any file, any line. Do you know what possibly causes this issue? Script is a Django script.