Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-import-export does not work with 'delete' field
When importing with 'delete' field, it gives error: BaseBoqItem has no field named 'delete' I am also aware that this model doesn't have that field. That model should not have that field for sure, that is not a mistake. I need to add 'delete' field so that user can mark rows those he/she wants to delete, then when importing django-import-export deletes those rows. I followed documentation of django-import-export, and did exactly same. At the end all I get is this error. BaseBoqItem has no field named 'delete' What am I missing here? Here is my model: ``` class BaseBoqItem(models.Model): lot = models.ForeignKey(BaseLot, on_delete=models.PROTECT, related_name='boq_items') code = models.CharField(max_length=20, null=True) name_tm = models.CharField(max_length=255) name_ru = models.CharField(max_length=255, null=True) name_en = models.CharField(max_length=255, null=True) name_original = models.CharField(max_length=255, null=True) quantity = models.DecimalField(max_digits=12, decimal_places=2) unit = models.ForeignKey(BaseUnit, on_delete=models.PROTECT) material_unit_price = models.DecimalField(max_digits=12, decimal_places=2) labor_unit_price = models.DecimalField(max_digits=12, decimal_places=2) transport_unit_price = models.DecimalField(max_digits=12, decimal_places=2, null=True) def __str__(self) -> str: return f'{self.code} - {self.name_tm}' Here is my resource: class BaseBoqItemResource(resources.ModelResource): lot = fields.Field( column_name='lot', attribute='lot', widget=ForeignKeyWidget(BaseLot, field='code')) unit = fields.Field( column_name='unit', attribute='unit', widget=ForeignKeyWidget(BaseUnit, field='code_tm')) delete = fields.Field(readonly=True) def for_delete(self, row, instance): return self.fields['delete'].clean(row) class Meta: model = BaseBoqItem skip_unchanged = True use_bulk = True fields = ( 'id', 'lot', 'code', 'name_tm', 'name_ru', … -
Objects field is set with wrong default value in Django
I modified a default value in an objects' field but it has not been taken in account. I have deleted the database, migrations files and pycaches. In the current configuration shouldn't plateforme.name be set with 'Plateforme_Test_1' ? Because instead, I have the old default value 'default_plateforme'. I am talking about plateforme objects, not environnement objects. Thank you for your help. PS: Here is the snippet: class Plateforme(models.Model): name = models.CharField(max_length=50, default = 'Plateforme_Test_1') def __str__(self): return self.name class Environnement(models.Model): name = models.CharField(max_length=100, default = 'default_module') plateforme = models.ForeignKey('homepage.Plateforme', on_delete=models.CASCADE, related_name='Environnement', null = True) plateforme_name = models.CharField(max_length=100, default = 'default_plateforme') def save(self, *args, **kwargs): if self.name == 'M42048': self.name = 'Env' super().save(*args, **kwargs) def __str__(self): return self.name -
Google API Calendar mismatching_state
Google API Calendar mismatching state error: (mismatching_state) CSRF Warning! State not equal in request and response. erorr occcurs at flow.fetch_token(authorization_response=authorization_response): class GoogleCalendarInitView(View): """ Initiate the OAuth2 authorization flow. """ def get(self, request, *args, **kwargs): # Create a flow instance to manage the OAuth 2.0 Authorization Grant Flow steps. flow = InstalledAppFlow.from_client_secrets_file( 'client_secret.json', scopes=['https://www.googleapis.com/auth/calendar.events'] ) # The URI created here must exactly match one of the authorized redirect URIs # for the OAuth 2.0 client, which you configured in the API Console. If this # value doesn't match an authorized URI, you will get a 'redirect_uri_mismatch' # error. flow.redirect_uri = redirect_uri authorization_url, state = flow.authorization_url( # Enable offline access so that you can refresh an access token without # re-prompting the user for permission. Recommended for web server apps. access_type='offline', # Enable incremental authorization. Recommended as a best practice. include_granted_scopes='true', ) # Store the state so the callback can verify the auth server response. request.session['state'] = state print(f"Stored State in Session: {request.session.get('state')}") # Redirect the user to the authorization URL. return redirect(redirect_uri+"redirect/") class GoogleCalendarRedirectView(View): """ Callback view to handle the response from Google OAuth2 authorization server. This view is registered as the redirect_uri in the Google OAuth2 client configuration. The authorization … -
Reducing Database Queries per Row in Django Admin for Non-ForeignKey Fields
I'm working with Django Admin and facing a challenge related to database queries. In my ModelAdmin, I have multiple functions that fetch data from another model (App). However, this model is not directly related through a ForeignKey. Each function makes an individual query to the App model for each row in the admin list, which seems inefficient. Here's an example to illustrate my current setup: class MyModelAdmin(admin.ModelAdmin): list_display = ('data_from_app_a', 'data_from_app_b', ...) def data_from_app_a(self, obj): # Fetches and returns specific data from App model data_a = App.objects.get(app_no=obj.app_no).field_a return data_a def data_from_app_b(self, obj): # Fetches and returns different data from App model data_b = App.objects.get(app_no=obj.app_no).field_b return data_b In this example, data_from_app_a and data_from_app_b are functions that query the App model separately for each row. I'm looking to reduce the number of these per-row queries. Is there a way to aggregate or prefetch this data more efficiently in Django Admin when dealing with non-ForeignKey relationships? -
Django device tags
I am trying to have functionality on my edit_project page where, when the page loads the current device tag is pre selected from the options menu so that a user 1 knows what the current tag is for that device but also so that if the click save/update the tag will remain as whatever is was. at the moment when the page loads the initial state of the tag menu is "None" or blank if i remove the initial state from the forms function.enter image description here i am able to display the current tag on my dashboard page no problem,enter image description here here are my current files: Views.py from django.urls import reverse from django.contrib import messages from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.decorators import login_required from django.db import models, transaction from .models import DeviceInformation, Projects, ApiTokens from .forms import ProjectForm from django.db.models import Count, ExpressionWrapper, F, FloatField @login_required(login_url="/accounts/login") def dashboard(request): devices = get_devices_without_project() projects = get_queryset('Projects') tokens = get_queryset('ApiTokens') context = {'devices': devices, 'projects': projects, 'tokens': tokens} return render(request, 'dashboard/index.html', context) def get_devices_without_project(): return DeviceInformation.objects.filter(projects__isnull=True) def get_queryset(model): if model == 'Projects': return Projects.objects.all() elif model == 'ApiTokens': return ApiTokens.objects.all() @login_required(login_url="/accounts/login") def create_project(request): if request.method == 'POST': form … -
From Django 1.11 onwards, context passed in render method should be a dictionary rather than a Context object. Then how context.render_context works?
render() in django.shortcuts calls render_to_string method of loader module, which calls render method of Template class by creating a Template object. Till now, context is a dictionary. Inside render method in Template class, context.render_context.push_state(self): How does this works? Because render_context is an attribute of Context class which gets assigned a RenderContext object. So, how context being not an instance of Context class can access its attribute? -
Field expected a number but got <django.db.models.fields.IntegerField>
from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify class Quiz_Model(models.Model): quiz_name = models.CharField(max_length = 30) slug = models.SlugField(max_length = 30, default = '', blank = True) test_number = models.IntegerField(default = 0) max_test_number = models.IntegerField(default = 0) first_boundary = models.IntegerField(default = 0) last_boundary = models.IntegerField(default = 1) show_number = models.BooleanField(default = False) tests = models.TextField() user = models.ForeignKey(User, on_delete = models.CASCADE, default = '') def save(self, *args, **kwargs): if not self.last_boundary: self.last_boundary = self.max_test_number self.slug = slugify(self.quiz_name) super(Quiz_Model, self).save(*args, **kwargs) def __str__ (self): return self.quiz_name I keep gettings this error :TypeError: Field 'last_boundary' expected a number but got <django.db.models.fields.IntegerField>. -
Grouping data when you’ve unique together on foreign keys
Model student=models.FK(Student) grades=models.FK(Grades) unique together is true And i want to query data like [ …student, grades:[…gradeobjects] ] All grades objects related to student should come under the student details -
Mpeg Dash in Django
I was researching ways to stream videos served from the server when I came across MPEG-DASH. I also learned that both Netflix and YouTube use MPEG-DASH for video streaming. Since I'm using Django in the backend of my project, I searched for information on implementing MPEG-DASH in Django, but I couldn't find any relevant details. Could you please provide a comprehensive guide on how to use MPEG-DASH in Django? -
How do I display new posts in bootstrap cards?
I made this website and I wanted to use bootstrap cards in it to display the post I managed to put them in the position I wanted but the cards have same information I want each card to have the info of the new posts that the user update but when I delete one of the cards then the grid gets messed up how should I display new posts in each cards? if I need to post more codes please let me know Thanks in advance user_posts.html {% extends "online_shop/base.html" %} {% block content %} <div style="margin-top: 20px"></div> <h1 class="text-left" class="mb-3" style="font-family: Georgia, serif;">{{ view.kwargs.username }} ({{ page_obj.paginator.count }})</h1> <div style="margin-top: 20px"></div> {% for post in posts %} <div class="card-deck"> <div class="card" style="margin-top: 15px;"> <img class="card-img-top" src="{{ post.image.url }}" alt="Card image cap"> <div class="card-body"> <h5 class="card-title">{{ post.title }}</h5> <p class="card-text">{{ post.content|truncatewords_html:16 }}</p> <p class="text-muted" style="margin-top: 10px;">Price: <i class="fa fa-usd" aria-hidden="true"></i> {{ post.price }}</p> </div> <div style="margin-left: 10px; margin-top: -30px; padding: 10px;"> {% if user.is_authenticated %} {% if user == post.author%} <a href="{% url 'update' post.id %}" class="btn btn-outline-primary btn-small" >Edit</a> <a href="{% url 'delete' post.id %}" class="btn btn-outline-danger btn-small" >Delete <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" fill="currentColor" class="bi bi-trash" viewBox="0 0 16 … -
How to redirect next page after successfully login with flutter?
I create a simple login app with flutter. Backend is simple Jwt. After successfully login, Can not redirect to other page please help This is login page code //login buttom SizedBox( width: 360, child: Padding( padding: const EdgeInsets.only(top: 48.0), child: ElevatedButton( onPressed: () { authController.loginUser(); }, style: ElevatedButton.styleFrom( backgroundColor: const Color.fromARGB(255, 40, 41, 131), padding: const EdgeInsets.only( top: 16, bottom: 16, )), child: const Text( 'ログイン ', style: TextStyle( color: Colors.white, fontSize: 16, fontWeight: FontWeight.w700), ), ), ), ), //end login buttom const SizedBox( height: 60, ), ], ), ), ); } } This is auth controller code class AuthController { TextEditingController emailController = TextEditingController(); TextEditingController passwordController = TextEditingController(); Future loginUser() async { const url = 'http://127.0.0.1:8000/api/v1/login/'; var response = await http.post(Uri.parse(url), headers: { "content-type": "application/json", "accept": "application/json", "access": "Access-Control-Allow-Origin: *", "allow": "POST, OPTIONS", }, body: jsonEncode({ "email": emailController.text, "password": passwordController.text, })); if (response.statusCode == 200) { var loginArr = json.decode(response.body); print('Home'); // save this token in shared prefrences and make user logged in and navigate print(loginArr['token']); } else {} } } I try to fix this error please help me.how to navigate to other page after successfully login -
Django firebase phone auth
is there module for Django which working with Firebase and can use Firebase to send sms to phone, I use django-phone-auth , but its not working with Firebase. Thanks you. -
"This field cannot be blank" on bulk edit forms - cannot determine which field or why
I am working on a plugin for the Netbox project. In one of my forms, I get a "this field cannot be blank" validation error and I'm not sure why. It only occurs when the selected objects have a null 'vrf' property. Even if I remove the 'vrf' and 'destination_prefix' fields from my form, the validation error will still occur for objects which have a null 'vrf' property. I don't understand why this is happening. My suspicions and what I've been troubleshooting most are: My clean methods (I have removed these methods from both models and forms - same issue) The 'unique_together' property in the Meta class of the model (I have now removed the 'vrf' property - same issue; I have a lot of suspicion here because the Netbox project itself no longer uses the 'unique_together' property in its models, but other Netbox plugins do; it is simple and useful for my plugin too so I don't want to throw it out unnecessarily) The _str_ method (I haven't tried changing this - I want it to remain as is, but does it somehow make the fields in the form required?) I am a Django (and development in general) novice … -
Item in shopping cart dissapears once I navigate to a different page Django
I am creating a e-commerce website with Django and I stumbled onto a problem I cannot solve. If i click on add to cart button, the added product shows up in the shopping cart. However, if i navigate to lets say home page ( or any other page ) the newly added product is not displayed no more in the shopping cart. In JS file I have added some code for debugging. In views I have done the same, although with the current code I have parsed in here, most of the logging is already removed. Any suggestions how I can solve this? I have added logging to server side to debug. I have solved quite a bit there already. On the client side ( atleast, thats what i suspect where the rootcause may lie), the logging is still there. views: def add_to_cart(request): try: cart_product = { "product_name": request.GET["product_name"], "product_price": request.GET["product_price"], "product_quantity": int(request.GET["product_quantity"]), } product_id = str(request.GET["product_id"]) if "cart_data_obj" in request.session: cart_data = request.session["cart_data_obj"] if product_id in cart_data: # Product already exists in the cart, update the quantity cart_data[product_id]['product_quantity'] += int(cart_product['product_quantity']) else: # Product doesn't exist, add it to the cart cart_data[product_id] = cart_product request.session["cart_data_obj"] = cart_data else: # Cart … -
why the password of django admin page and new users that wnats to sign up are should be same?
i want to sign up to my website but it wants admin pages password for a new user which its username and emails are not same what should i do to solve this problem? I just confused plz help to solve this. admin.py from django.contrib import admin from .models import Room, Topic, Message, User admin.site.register(User) admin.site.register(Room) admin.site.register(Topic) admin.site.register(Message) def loginPage(request): page = 'login' if request.user.is_authenticated: return redirect('home') if request.method == 'POST': email = request.POST.get('email').lower() password = request.POST.get('password') try: user = User.objects.get(email=email) except: messages.error(request, 'User does not exist') user = authenticate(request, email=email, password=password) if user is not None: login(request, user) return redirect('home') else: messages.error(request, 'Username OR password does not exit') context = {'page': page} return render(request, 'base/login_register.html', context) def registerPage(request): form = MyUserCreationForm() if request.method == 'POST': form = MyUserCreationForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.username = user.username.lower() user.save() login(request, user) return redirect('home') else: messages.error(request, 'An error occurred during registration') return render(request, 'base/login_register.html', {'form': form}) -
A view in Django is returning a GET response instead POST
In my Django project, I'm trying to implement a logout method but the server throws the following error Method Not Allowed (GET): /logout/ Method Not Allowed: /logout/ [17/Jan/2024 21:01:58] "GET /logout/ HTTP/1.1" 405 0 Any idea why it sends a GET method where it's set to POST in my django form views.py from my main django_project app from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'), and logout.html {% extends "blog/base.html" %} {% block content%} <form method="POST" action="{% url 'logout' %}"> {% csrf_token %} <h2>You've been logged out!</h2> <div class="register_signin"> <a href="{% url 'login' %}"><b>Log In Again </b></a> </div> </form> {% endblock content %} I'm using Django 5.0.1 so I know it has to be a POST method I included the CSRF token There is no JS involved -
How to round 3 decimals instead of 2 with django currencies template tags?
{% change_currency video.price CURRENCY.code %} I have this template tag but it rounds the price to 2 decimal points when i change currency. I want to make it to round to 3 decimals points. Its from django-currencies library template tags I tried to add|floatformat:”3” but nothing -
how to upload photo to replicate API using Django?
i need to use i2vgen-xl model in Replicate website using Replicate API in Django and i need to pass an image (not url) but it gives me this error - input: prompt is required - input.image: Does not match format 'uri' view.py def X(request): form = ImageForm() if request.method == 'POST': form = ImageForm(request.POST,request.FILES) if form.is_valid(): form.save() image_name = str(form.cleaned_data['Image']) os.environ["REPLICATE_API_TOKEN"] = "X" image_path = rf"'media\images\\{image_name}" output = replicate.run( "ali-vilab/i2vgen-xl:5821a338d00033abaaba89080a17eb8783d9a17ed710a6b4246a18e0900ccad4", input={ "image": image_path } ) print(output) else: print("image is invalid") return render(request,"img2vid.html",{'form':form}) -
How to properly deploy a Django app while following 12FA?
I am deploying a Django app and I got stuck. I am trying to follow the 12 factor app principles. Specifically, they state that you should have all your configuration in environment variables. Also, I don't want to have multiple settings.py files, because that goes against the 12FA principles. So, I have simply a single settings.py file, which checks environment variables using os.environ['xxx'] for stuff like database login etc. On the local dev machine, these environment variables are pulled from a file called .env. On the server, I am planning to store all the environment variables inside a systemd unit using the Environment= syntax. Now, my problem occurs while deploying. I copy all the source Python files onto the server, and I need to call collectstatic and migrate. However, these actions both require the presence of a settings.py file which needs to have access to the database. However, collectstatic is called from my CI/CD pipeline and doesn't have all those environment variables; the only place where they're stored is the systemd unit file which has very limited permissions (only root can read and write to the file). My question is, what approach could I take in order to follow 12FA … -
Django ORM: how to cast geometry to geography in filter?
In my Django project, I have defined a geometry field on one of my model. Its SRID is 4326 (WGS 84). I would like to write with Django ORM a query that will translate to: select * from building where (ST_DWITHIN(shape::geography, ST_MakePoint(1.9217,47.8814)::geography,20)) In other words, I would like to filter the queryset using the ST_DWITHIN function, applied to a geometry field (shape) casted to a geography. The only way I could find is to use the extra() function, like so: Building.objects.extra( where=[ f"ST_DWITHIN(shape::geography, ST_MakePoint({lng}, {lat})::geography, {radius})" ]) But the extra function is supposed to be deprecated in future version of Django, according to the doc. Can I write this query without escaping from the ORM? Maybe using the Cast function ? -
Django REST framework issue : How to get action attribute in middleware
I want to check my action or some limitation in middleware, but i can't get the action in middleware, I always get None. I tried the following code. My middleware look like the following code. And when i create a new project. I need to get the action name, because i just need to limit the create method. Not the other @action method also POST method. class MyMiddleware: EXEMPT_URLS = ['some url'] # Add the URLs that should be exempted def __init__(self, get_response): self.get_response = get_response def get_record_count(self, viewset_name): # Define a mapping between viewset names and model classes model_mapping = { 'projects': Project, 'datas': Data, 'decisions': Decision } # Get the model class corresponding to the viewset name model_class = model_mapping.get(viewset_name) return model_class.objects.count() if model_class else 0 def __call__(self, request): # Call the next middleware in the stack response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): if request.path_info.lstrip('/') in self.EXEMPT_URLS: return None # Check if the request is a POST method if request.method != 'POST': return None resolver_match = request.resolver_match print(resolver_match) # this is ResolverMatch(func=aiwinops.apps.project.views.ProjectViewSet, args=(), kwargs={}, url_name=project-list, app_names=[], namespaces=[], route=api/v1/projects$) print(view_func.cls) # <class 'myproject.apps.project.views.ProjectViewSet'> if not resolver_match: return JsonResponse({'message': 'URL does not match any view'}, … -
Change generated model name without deleting model django
In django, by default, if you have a structure like this app ├── migrations └── models └ example The generated name of your model will be app_example when executing the command makemigrations. My problem is that I want to move my model from the directory app to the directory other_app which has the same structure. other_app ├── migrations └── models -> example will go here At the same time, I want the generated name of my model to be other_app_example once I migrate without having to delete my table, as to avoid losing the data in it. The thing is, when you create a migration in django after changing a model of place, django delete the model in the migration directory of app and recreate it in another migration in other_app. I know that I have to create a custom migration, but how can I achieve what I want to do ? All I found was RenameModel, but it doesn't change the name generated by django. -
Access the list of items send from view model to serialised
I have a dango app where I try to add all answer alternative to a question (from db) in the serializer. Which seems to work. **My Model** class MyModel(models.Model): Question = models.TextField(null=False, blank= False) Answer=models.CharField(max_length=200,null=False,blank= False) def __str__(self): return Question **My View Model** class get_english_q(APIView): serializer = English_Q_Serializer def get(self,request,**kwargs): language = self.kwargs.get('id') list1 = MyModel.objects.filter(.....) list2 = MyModel.objects.filter(.....) list3 = MyModel.objects.filter(.....) array1 = random.sample([x.id for x in list1], k=5) array2 = random.sample([x.id for x in list2], k=5) array3 = random.sample([x.id for x in list3], k=5) array1.extend(array2) array1.extend(array3) list = MyModel.objects.filter(id__in=array1) serializer = English_Q_Serializer(list, many=True) return Response(serializer.data) **My Serializer Model** class English_Q_Serializer(serializers.ModelSerializer): answers = serializers.SerializerMethodField('get_words') class Meta: model = english_technical fields = ( 'answers', 'id', 'question', ) def get_words(self, instance): list_all=MyModel.objects.all() answers=[instance.answer] array = random.sample([x.answer for x in list if x.answer != instance.answer],k=4) answers.extends(array) return answers Now when I define the list of questions to include I take 5 from one queryset, 5 from another and 5 from another. Now I want to make logic in serializer different depending on if they were in first set of 5, second set of 5 or third set of 5. Is there a way that I in the serializer can get the index … -
How do I render individual dynamic elements from a dictionary in a Django template?
This is my first question (sorry for any english mistakes), and I appreciate your help in advance! I'm working with a Django app (MVT). I have a view that returns a dictionary, and I would like to access individual elements of the dictionary in the template. However, in the template, I can render the complete dictionary without any issues, but I can't render individual elements. I'll show you the view that return the dict registros_por_dia. class GrillaView(View): template_name = 'grilla.html' def get(self, request): return render(request, self.template_name) def contar_registros(self, fecha): ... def post(self, request, fecha=None): if fecha: ... else: # Esta parte se ejecutará cuando se envíe el formulario del mes y año mes = int(request.POST.get('mes')) ano = int(request.POST.get('ano')) dias_en_mes = [dia for dia in range(1, monthrange(ano, mes)[1] + 1)] registros_por_dia = {} for dia in dias_en_mes: fecha = datetime(ano, mes, dia).strftime('%Y-%m-%d') contador = self.contar_registros(fecha) registros_por_dia[dia] = contador return render(request, self.template_name, {'dias_en_mes': dias_en_mes, 'registros_por_dia': registros_por_dia}) And now I'll show you the relevant part of the template. ... {% if dias_en_mes %} {% with fecha_format='%Y-%m-%d' %} <div style="display: flex; flex-wrap: wrap;"> {% for dia in dias_en_mes %} {% with fecha=dia|date:fecha_format %} <div style="width: 50px; height: 50px; border: 1px solid black; margin: 5px;"> … -
Configure PyCharm to run appropriate variant of manage.py that is built within Docker container but doesn't exist in source code?
We have our program all dockerized and I'm now trying to get my pycharm to connect to it to debug something. I've followed these steps but they are incomplete when it comes to how to define the Django application. At this point I'm getting an error saying "python script path must be set" I believe this is because it can't find the manage.py Django script, which it wouldn't find. Instead of having one manage.py script we have a dev, test, and prod script with different names. I should be able to set this in the Django configuration in the 'manage script' field in theory. Except our scripts are actually being built within the Docker environment, I don't have a dev.py script in my source code. I could easily tell it the location of the script on the Docker container, but it won't let me type an arbitrary path, it wants me to select a file within my source code and there is no file in my source code at this point. How can I point Django to a dev.py within my container?