Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to create file txt and download using html in django
i have encrypt text and i want to create file txt which contains encrypt text and can be download the file via html. the encrypt file was in the function variable, how to get the result encrypt? and i don't know how to create file txt from another variable function. please help me with it. here's my encrypt code: def encrypt(key, pt): plaintext = read_file(pt) if isinstance(plaintext, str): pt= plaintext.encode("utf-8") print(pt) if len(key) <= key_bytes: for x in range(len(key),key_bytes): key = key + "0" print(key) assert len(key) == key_bytes # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(pt) print(ciphertext) return (iv, ciphertext) #what i want to keep in new file is ciphertext and here's how i called that func: def homepage(request): form = AudioForm() if request.method == "POST": form = AudioForm(request.POST, request.FILES) if form.is_valid(): form.save() last_audio = Audio_store.objects.all().last() plaintext = Audio_store.objects.all().values_list('password').last() key = Audio_store.objects.all().values_list('key').last() pt = plaintext[0] ky = key[0] print(pt) print(ky) context={'form':form, … -
Django redirect another view from another app form
contact/views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms import ContactForm def contactView(request): if request.method == 'GET': form = ContactForm() else: form = ContactForm(request.POST) if form.is_valid(): subject = form.cleaned_data['subject'] from_email = form.cleaned_data['from_email'] message = form.cleaned_data['message'] try: send_mail(subject, message, from_email, ['admin@example.com']) except BadHeaderError: return HttpResponse('Invalid header found.') # return redirect('success') return redirect('PostList') #another view from another app return render(request, "contact.html", {'form': form}) # def successView(request): # return HttpResponse('Success! Thank you for your message.') contact/urls.py from django.contrib import admin from django.urls import path from .views import contactView urlpatterns = [ path('contact/', contactView, name='contact'), # path('success/', successView, name='success'), ] blog/views.py from django.views import generic from .models import Post, PostImage # Create your views here. class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' class PostDetail(generic.DetailView): model = Post template_name = 'post_detail.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super().get_context_data(**kwargs) # Add in a QuerySet of all the books # context['image_list'] = PostImage.objects.all() # context['image_list'] = self.get_object().postimage_set.all() context['image_list'] = PostImage.objects.filter(post__slug=self.kwargs.get('slug')) return context blog/urls.py from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] I need the following in the SIMPLEST … -
How to filter liked posts by User? (Django)
I'm trying to list all posts that are liked by userself. This is what i'm trying to code (likeapp/models.py) class LikeRecord(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='like_record') article = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='like_record') class Meta: unique_together = ('user', 'article') (likeapp/views.py) @transaction.atomic def db_transaction(user, article): article.like += 1 article.save() # like_count = LikeRecord.objects.filter(article=article).count() if LikeRecord.objects.filter(user=user, article=article).exists(): raise ValidationError('Like already exists') else: LikeRecord(user=user, article=article).save() @method_decorator(login_required, 'get') class LikeArticleView(RedirectView): def get_redirect_url(self, *args, **kwargs): return reverse('articleapp:detail', kwargs={'pk': kwargs['pk']}) def get(self, *args, **kwargs): user = self.request.user article = get_object_or_404(Article, pk=kwargs['pk']) try: db_transaction(user, article) messages.add_message(self.request, messages.SUCCESS, '좋아요가 반영되었습니다') except ValidationError: messages.add_message(self.request, messages.ERROR, '좋아요는 한번만 가능합니다.') return HttpResponseRedirect(reverse('articleapp:detail', kwargs={'pk': kwargs['pk']})) return super(LikeArticleView, self).get(self.request, *args, **kwargs) (articleapp/models.py) class Article(models.Model): writer = models.ForeignKey(User, on_delete = models.SET_NULL, related_name = 'article', null = True) project = models.ForeignKey(Project, on_delete = models.SET_NULL, related_name = 'article', null = True) title = models.CharField(max_length=200, null=True) image = models.ImageField(upload_to='article/', null=False) content = models.TextField(null=True) price = models.IntegerField(default=0) amount = models.CharField(max_length=200, null=True) created_at = models.DateField(auto_now_add=True, null=True) like = models.IntegerField(default=0) (articleapp/views.py) class ArticleLikeListView(ListView): model = Article context_object_name = 'article_like_list' template_name = 'articleapp/likelist.html' def get_queryset(self): user = self.request.user queryset = LikeRecord.objects.filter() return queryset I'm trying to use filter() function to distinct liked posts by userself. How can I fix this code? Thank You! -
Get informations for each x seconds
I would like to know if there is a way to check every x seconds a value in a database table in django, and if it is the desired value, the user is redirected to another page. what i tried: I tried to use a form and it posts every 3 seconds and as soon as it makes the post it would check the table (model), but the page doesn't even load, because of sleep (it's worth mentioning that I tried SetTimeout and SetInterval) def wait(request, slug): form = MatchForm() if request.method == 'POST': roomName = Match.objects.get(roomname = slug) if (int(roomName.num_players) > 1): return redirect(f'../play/{slug}') return render (request, 'chess/waiting_room.html', {'slug':slug, 'form':form}) waiting_room.html - javascript function sleep(milliseconds) { const date = Date.now(); let currentDate = null; do { currentDate = Date.now(); } while (currentDate - date < milliseconds); } subm_form() function subm_form(){ var form = $("#form") form.submit(); sleep(3000) subm_form() }; -
Use django formset for only a few specific fields
I am relatively new to django (about 3 months using it) and ran into the following problem at work. I have a model with several fields, and they asked me that of those fields, 4 specifically should be able to dynamically add another register, that is, if i register something in one of those fields, there should be the option to do it again indefinitely. I understand that this can be achieved using formset but all the examples I find are using all the fields of the model and not just a few. Any ideas on what I can do? this is the model class Mercancia(SafeDeleteModel): _safedelete_policy = SOFT_DELETE_CASCADE id = models.AutoField(primary_key=True) factura = models.ForeignKey("Factura", on_delete=models.CASCADE) desc_mercancia = models.CharField(max_length=256, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'La descripción de la mercancia no acepta caracteres especiales.')]) comercio = models.ForeignKey("ClaveComercio", on_delete=models.CASCADE) tipo_moneda = models.ForeignKey("Moneda", on_delete=models.CASCADE) cantidad_comerc = models.DecimalField(max_digits=30, decimal_places=0) valor_unitario = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total = models.DecimalField(max_digits=22, decimal_places=6, validators=[MinValueValidator(0)]) valor_total_dolares = models.DecimalField(max_digits=20, decimal_places=4, validators=[MinValueValidator(0)]) marca = models.CharField(blank = True, max_length=35, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) modelo = models.CharField(blank = True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El modelo solo permite valores alfanuméricos.')]) submodelo = models.CharField(blank=True, max_length=50, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', 'El submodelo solo permite valores alfanuméricos.')]) numero_serie = models.CharField(blank = True, max_length=25, validators=[RegexValidator(r'^[0-9a-zA-Z\s]*$', … -
ModuleNotFoundError: No module named 'django' after adding specific path into the global .bashrc file
I am getting this weird messages: it says Couldn't import Django when I type this on command line: python3 manage.py startapp engine I have found out that the Django is located in: /home/h/hswong00/miniconda3/lib/python3.9/site-packages But the way I found out where it is located is by loading python, not python 3. But I need python3, not python for my work. So when I typed: in linux terminal: python after loading python in terminal: import sys : sys.path that's how I found out where Django is installed. So I googled for some solution here, and I found that I could tried edit the bashrc file by adding: export PYTHONPATH="${PYTHONPATH}:/home/h/hswong00/miniconda3/lib/python3.9/site-packages" to the .bashrc file. But still when I type: python3 manage.py startapp engine it still produces the same error message. And indeed after loading python3 and typing sys.path, I also don't see the path: /home/h/hswong00/miniconda3/lib/python3.9/site-packages I am just wondering did I not edit the .bashrc file correctly so that python3 will search for that directory (python3.9/site-packages)? if I have done it correctly, how come that path doesn't show up when sys.path after loading python3? could someone points out where my error is? I have searched for many of the previous posts regarding this … -
How to access MTM field with through setting to template
price = models.ManyToManyField("price.Price", verbose_name='Ціни', through='services_count', through_fields=('service','price'), blank=True) and through model class services_count(models.Model): quantity = models.IntegerField(verbose_name='Кількість цієї послуги у сервісі', null=True) service = models.ForeignKey("medservices.Medservices", verbose_name='Послуга або акція', on_delete=models.CASCADE,default=None) price = models.ForeignKey("price.Price", verbose_name='Ціна яка', on_delete=models.CASCADE, default=None) views.py def service_page(request, post_slug): post_content = Medservices.price.through.objects.all() post = get_object_or_404(Medservices, slug=post_slug) post_dict = {'post_rows':post , 'post_alt':post_content,} return render(request, 'medservices/service.html', context=post_dict) So i want to have oportunity to access service_count model through model with MTM field -
Dificuldade em salvar Mater/Detail com Django REST framework
Estou tentando salvar os dados em uma API Django REST framework, mas mesmo depois de muitas mudanças no código sempre retorna a mensagem de que o objeto pai não existe quando tenta adcionar os objetos filho. Não tenho muita experiencia com Django Rest e consegui chegar até esse ponto com alguns posts aqui mesmo do stackoverflow: Toda ajuda é bem vinda e desde ja agradeço. JSON enviado pelo app: { "unity": "PL20220831T143756903", "pallet": 2, "employee": 1, "quantity": 3, "variety": 2, "maturation": 1, "box": 2, "producer": 1, "processed": false, "packers": [ { "unity": "PL20220831T143756903", "packer": "E0001B0000000001F", "packing_date": "2022-08-31T14:38:23.017756-03:00" } { "unity": "PL20220831T143756903", "packer": "E0001B0000000002F", "packing_date": "2022-09-01T13:00:23.016766-03:00" } ] } Serializer que recebe os dados: class PendingPalletDetailSerializer(serializers.ModelSerializer): """ API Pallets Pendentes Detalhes """ class Meta: model = PendingPalletDetail fields = ( 'unity', 'packer', 'packing_date', ) class PendingPalletTotSerializer(serializers.ModelSerializer): """ API Pallets Pendentes """ packers = PendingPalletDetailSerializer(many=True) class Meta: model = PendingPallet fields = ( 'unity', 'pallet', 'employee', 'quantity', 'variety', 'maturation', 'box', 'producer', 'person', 'date_in_cold_chamber', 'date_out_cold_chamber', 'processed', 'packers', ) def create(self, validated_data): details_data = validated_data.pop('packers') # grab the data on details pendingpallet = PendingPallet.objects.create(**validated_data) # create the master reservation object for reservation_detail in details_data: # create a details_reservation referencing the master reservation PendingPalletDetail.objects.create(**reservation_detail) return … -
django add pdf to a request value
in the following request I receive a total of 10 pdfs which I must combine in one document once this is done I have to upload it to the client model which stores the files in aws s3, once I pass the file with all the pdfs together it gives me the following error { "error": true, "message": { "documents": [ "The submitted data was not a file. Check the encoding type on the form." ] } } this is mi code merger = PdfFileMerger() for x in request.FILES: print(request.FILES[x]) merger.append(request.FILES[x]) merger.write(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf')) merger.close() pdf = open(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'media/' + str(getUser.id) + '.pdf'), 'rb') # set the client Data clientData = { 'type_client': request.data['type_client'], 'type_identity': request.data['type_identity'], 'document_number': request.data['document_number'], 'first_name': request.data['first_name'] if 'first_name' in request.data else None, 'last_name': request.data['last_name'] if 'last_name' in request.data else None, 'social_reason': request.data['social_reason'] if 'social_reason' in request.data else None, 'address': request.data['address'], 'city': request.data['city'], 'email': request.data['email'], 'phone_number': request.data['phone_number'], 'ciiu': request.data['ciiu'], 'broker': request.data['broker'], 'user': getUser.id, 'documents': pdf, 'status': 0, 'income': request.data['income'], 'entered_by': request.user.id } # Create a new client client = ClientSerializer(data=clientData) this is my model from django.db import models # Relations from apps.misc.models import City, TypeIdentity, TypeCLient, CIIU from apps.clients.api.models.broker.index import Broker from apps.authentication.api.models.user.index import … -
Where Can I Find the The Setting.py File For PostgreSQL?
I am trying to install PostgreSQL to work with Django. I searched my hard drive for the PostgreSQL settings.py file but could not find what I was looking for. I found one under the PgAdmin folder (C:/Program Files/PostgreSQL/14/pgAdmin 4/python/Lib/site-packages/azure/core/settings.py), but it does not appear to be what I'm looking for. All of the documentation that I find says that I have to have the following in my settings.py file for PostgreSQL to work with Django: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'db_name', 'USER': 'db_user', 'PASSWORD': 'db_user_password', 'HOST': '', 'PORT': 'db_port_number', } } I cannot find the file to place the setting in it. Where should I be able to find it, or where should I create it? What else should be in the file? -
I want to get the top 8 latest products of each category in django
This is my product_views.py This is serializers.py While printing products in terminal everything looks good, but after serializing product attributes becomes null -
Django test to check for pending migrations
Django has a --check argument that let's you check if migrations need to be created for your project. This is relatively easy to add in CI, but that won't perform the check on developer computers. I want to add this check as a unit test in my Django project, so that it is covered when developers run our test suite. What is a good way to accomplish that? -
problem after moving from sqllite3 to postgresql database in django
enter image description hereI have changed an existing database for a Django project from SQLite3 to PostgreSQL. As presently i am in development environment, and was carrying some dummy data in my SQlite3 so do not need that data. After changing the database from sqlite3 to PostgreSQL, I run the makemigrations, and migrate commands, and then created a super user. Now when i try to access the admin panel, by http://127.0.0.1:8000/admin/ django is showing me the following error. I have search a lot for the solution, but failed. I would be grateful, if you could please help me in this. errorerror2 -
django put save button
I would like to change the data that is in this column from a form but I can't display the data and save them and also add a delete button. anyone have a solution. models.py class Employe(models.Model): Matricule = models.CharField(max_length=10, null=False) Prenom = models.CharField(max_length=40, null=True) Nom = models.CharField(max_length=40, null=True) Tel = models.CharField(max_length=20, null=True) Adresse = models.CharField(max_length=100, null=True) Courriel = models.CharField(max_length=100, null=True) Horaire = models.CharField(max_length=50, null=True) Date_embauche = models.CharField(max_length=100, null=True) UtilisateurOSP = models.CharField(max_length=100, null=True) MotdepasseOSP = models.CharField(max_length=50, null=True) Anciennete = models.CharField(max_length=10, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) class Disciplinaire(models.Model): employe = models.ForeignKey(Employe, null=True, on_delete=models.SET_NULL) Avis_verbal = models.CharField(max_length=300, null=True) Avis_ecrit = models.CharField(max_length=300, null=True) Avis_ecrit2 = models.CharField(max_length=300, null=True) Suspension = models.CharField(max_length=300, null=True) Fin_emploie = models.CharField(max_length=300, null=True) data_created = models.DateTimeField(auto_now_add=True, null=True) forms.py class disciplinaireForm(ModelForm): class Meta: model = Disciplinaire fields = '__all__' views.py def updateDisciplinaire(request, id): emp = Disciplinaire.filter() forms = disciplinaireForm(instance=emp) if request.method == 'POST': forms = disciplinaireForm(request.POST, instance=emp) if forms.is_valid(): forms.save() return redirect('/') context = {'forms':forms} return render(request, 'accounts/updateDisciplinaire.html', context) page.html <th scope="col">Avis Verbal</th> <th scope="col">1er Avis Écrit</th> <th scope="col">2e Avis Écrit</th> <th scope="col">Suspension</th> <th scope="col">Fin d'emploi</th> <th scope="col">Action</th> </tr> {% for j in disci %} <tr> <td>{{j.Avis_verbal}}</td> <td>{{j.Avis_ecrit}}</td> <td>{{j.Avis_ecrit2}}</td> <td>{{j.Suspension}}</td> <td>{{j.Fin_emploie}}</td> <td><a class="btn btn-outline-info" href="{% url 'updateDisciplinaire' j.id %}">Modifier</a> </tr> {% endfor … -
Best way to integrate existing Python tools with Django?
I have number of Python tools that I run, mostly for scraping websites or pulling data from various web APIs. Currently they are all run from bash with the parameters passed as command line arguments e.g. $ python my_tool.py -arg1 -arg2 --output foobar.json I want to move away from using the command line and instead run the tools via a web interface. My aim is to have a setup where a user can authenticate to the website, enter the arguments via a web form, click to run the tools, and have the returned json data to a database for later analysis. I've chosen Django as a framework for the web interface and db since I already have experience with Python. However I'm seeking advice as to best practice for integrating the Python tools I already have with Django. Am I best to integrate the tools directly as Django apps, or keep them separate but with a means to communicate with Django? I'd be grateful for the advice and experience of others on this one. -
Django - Object of type FloatField is not JSON serializable
I have a service in django, and I am trying to get the list of all vital signs, but when I run it, it throws me the following error. This is the model "SignoVital". from django.db import models from .paciente import Paciente class SignoVital(models.Model): oximetria = models.FloatField() frecuenciaRespiratoria = models.FloatField() frecuenciaCardiaca = models.FloatField() temperatura = models.FloatField() presionArterial = models.FloatField() glicemia = models.FloatField(), paciente = models.ForeignKey( Paciente, on_delete=models.CASCADE, unique=False, blank=True, null=True ) This is serializer "SignoVitalSerializer". from rest_framework import serializers from hospiApp.models.signoVital import SignoVital class SignoVitalSerializer(serializers.ModelSerializer): class Meta: model = SignoVital fields = ['oximetria', 'frecuenciaRespiratoria', 'frecuenciaCardiaca', 'temperatura', 'presionArterial', 'glicemia', 'paciente'] This is View "SignoVitalTodosView". from rest_framework import generics,status, views from rest_framework.response import Response from rest_framework.views import APIView from hospiApp.models.signoVital import SignoVital from hospiApp.serializers.signoVitalSerializer import SignoVitalSerializer class SignoVitalTodosView(generics.ListCreateAPIView): queryset = SignoVital.objects.all() serializer_class = SignoVitalSerializer def get(self, request, *args, **kwargs): return super().get(request, *args, **kwargs) This is urls.py from django.contrib import admin from django.urls import path from hospiApp import views urlpatterns = [ path('admin/', admin.site.urls), path('signoVitalTodos/', views.SignoVitalTodosView.as_view()), ] -
Django only returns last row of dict in template
I am trying to return the values from a Dict in Django. My views.py prints the the correct data in the terminal when doing a GET-request to my page, however, in my template I only get the last line of the dictionary. I have tried looping the dict in my template and all sorts of combinations but I can't seem to make it work. Am I missing something? For instance, in the template below I print the entire dict. But it still only prints the last row somehow. views.py fruits = [ 'Apple', 'Banana', 'Orange'] for fruit in fruits: price_change = historical_prices['price_change'][::-1] low_price = 0 for day in price_change: if day < -0.1: low_price += 1 else: break if low_price >= 0: ls_dict = {'fruit': fruit, 'low_price': low_price} print(ls_dict) return render(request, "prices/index.html", { "ls_dict": ls_dict, }) Template <p>{{ ls_dict }}</p> Template output {'fruit': 'Orange', 'low_price': 1} Correct print which views.py produces {'fruit': 'Apple', 'low_price': 1} {'fruit': 'Banana', 'low_price': 3} {'fruit': 'Orange', 'low_price': 1} -
def __str__(self): return str(self.name) in model
Here is my models.py. def str(self):return str(self.name) still won't change Product object (1) to the product name. from cgi import print_exception from django.db import models from django.contrib.auth.models import User # Create your models here. class Product(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) name = models.CharField(max_length=200, null=True, blank=True) # image = category = models.CharField(max_length=200, null=True, blank=True) description = models.TextField(null=True, blank=True) rating = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) numReviews = models.IntegerField(null=True, blank=True, default=0) price = models.DecimalField( max_digits=7, decimal_places=2, null=True, blank=True) countInStock = models.IntegerField(null=True, blank=True, default=0) createdAt = models.DateTimeField(auto_now_add=True) _id = models.AutoField(primary_key=True, editable=False) def __str__(self): return str(self.name) -
fastapi python throw Exception in ASGI application
i have script that on my linux server working with fastapi it worked but after while of testing its throwing back this error and i am lost with finding why. this is my code that worked @app.get("/") async def root(request: Request): client_host = request.client.host client_port = request.client.port return(f'{client_host}:{client_port}- NEW') @app.get("/Search") async def read_item(request: Request,query:str, gl: str|None): client_host = request.client.host if str(client_host) not in WHITELIST: return(f'What Are you doing here: {client_host}') return await Google(query=query,gl=gl,use_proxy=True) this is the throwback that came from nowhere :/ [2022-09-02 17:08:42 +0000] [864] [ERROR] Exception in ASGI application Traceback (most recent call last): File "/home/fastapi/venv/lib/python3.10/site-packages/uvicorn/protocols/http/h11_impl.py", line 404, in run_asgi result = await app( # type: ignore[func-returns-value] File "/home/fastapi/venv/lib/python3.10/site-packages/uvicorn/middleware/proxy_headers.py", line 78, in __call__ return await self.app(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/applications.py", line 269, in __call__ await super().__call__(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/applications.py", line 124, in __call__ await self.middleware_stack(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 184, in __call__ raise exc File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/middleware/errors.py", line 162, in __call__ await self.app(scope, receive, _send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/exceptions.py", line 93, in __call__ raise exc File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/exceptions.py", line 82, in __call__ await self.app(scope, receive, sender) File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 21, in __call__ raise e File "/home/fastapi/venv/lib/python3.10/site-packages/fastapi/middleware/asyncexitstack.py", line 18, in __call__ await self.app(scope, receive, send) File "/home/fastapi/venv/lib/python3.10/site-packages/starlette/routing.py", line 670, in __call__ … -
django admin - when adding a model, restrict foreignkey that belong to current user
I have two models in my app. Each model has a foreignkey to the user and the two models are also related through a foreignkey. I want to use the django admin to add new objects for a model. The add_view page gives me a drop down to pick the foreignkey field, but I want to restrict these choices to the current user. models.py class Notebook(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) name = models.CharField(max_length=20) class Post(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) entry = models.CharField(max_length=500) notebook = models.ForeignKey(Notebook, on_delete=models.CASCADE) So when I am in the admin and click to add a new post, I want to choose from notebooks that only belong to me. I see all the notebooks in the dropdown (I am logged in as admin with superuser permissions). -
django assign User to a model
I want to assign a User to a Model in django, I created a custom User model and sign-up/sign-in Forms but now I want to Assign a User model to another model named Customer whenever a new user is Created Here he the Customer model class Customer(models.Model): id = models.AutoField(primary_key=True) User = models.OneToOneField( Account, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, default='0', null=True, blank=True) address = models.CharField( max_length=200, default=' ', null=True, blank=True) city = models.CharField(max_length=200, default=' ', null=True, blank=True) def __str__(self): if self.name == None: return "ERROR-CUSTOMER NAME IS NULL" return self.name Note: I can assign the User manually in the Database and It lists All the Users but I want it to do it itself when a new user is created -
Django manipulate / modify date in template
Is it possible to make an input that changes the date.today for the whole template ? my template {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} {% endfor %} the filter then would show those <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> instead of the first ones when the date is modified, I tried to use javascript but I guess it dont work bc of python objects -
Invalid object name 'table'
I have a few bases in my project. Hence I need to redefine methods which get some information from base. Everything had worked fine until I decided to authorize via active directory. Finally I get this: authorization works (default database), requests to database that is not default fails. Authorization info is stored in PostgreSQL database. Data is stored in MSSQL database. Django-ajax-datatable is response for render data from MSSQL database. Environment: Request Method: GET Request URL: http://localhost:8000/admin/app/table/ Django Version: 3.2.14 Python Version: 3.10.5 Installed Applications: ['app.apps.CrmConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'django_filters', 'bootstrap3', 'ajax_datatable'] Installed Middleware: ['debug_toolbar.middleware.Debu gToolbarMiddleware', 'django.middleware.security.Se curityMiddleware', 'django.contrib.sessions.middl eware.SessionMiddleware', 'django.middleware.common.Comm onMiddleware', 'django.middleware.csrf.CsrfVi ewMiddleware', 'django.contrib.auth.middlewar e.AuthenticationMiddleware', 'django.contrib.messages.middl eware.MessageMiddleware', 'django.middleware.clickjackin g.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.10/site-packages/mssql/base.py", line 598, in execute return self.cursor.execute(sql, params) The above exception (('42S02', "[42S02] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid object name 'table'. (208) (SQLExecDirectW)")) was the direct cause of the following exception: File "/usr/local/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/usr/local/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib/python3.10/site-packages/django/contrib/admin/options.py", line 616, in wrapper return self.admin_site.admin_view(vie w)(*args, **kwargs) File "/usr/local/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = … -
Django - Retrieve a session value to a form
I have a Django aplication and need to get a value from the session and put it in a HiddenInput. I have this code in my view: @login_required(redirect_field_name='login') def obra_open_view(request, obra_id): obra = get_object_or_404(Obra, pk=obra_id) if obra: request.session['obra_aberta_id'] = obra.id request.session['obra_aberta_name'] = obra.nome return redirect('obra_detail_url') else: request.session['obra_aberta_id'] = 0 request.session['obra_aberta_name'] = "" return redirect('obra_lista_url') When I have some value on 'obra_aberta_id' I need to put this value on a HiddenInput: class FormCarga(ModelForm): class Meta: model = Carga fields = ('__all__') widgets = { 'tag': forms.TextInput(attrs={'class': 'form-control'}), 'nome': forms.TextInput(attrs={'class': 'form-control'}), 'descricao': forms.Textarea(attrs={'class': 'form-control'}), 'potencia': forms.TextInput(attrs={'class': 'form-control'}), 'unidade_medida_potencia': forms.Select(attrs={'class': 'form-control'}), 'area': forms.Select(attrs={'class': 'form-control'}), 'tensao': forms.Select(attrs={'class': 'form-control'}), 'fonte': forms.Select(attrs={'class': 'form-control'}), 'atividade': forms.Select(attrs={'class': 'form-control'}), 'fator_potencia': forms.Select(attrs={'class': 'form-control'}), 'condutores_carregados': forms.Select(attrs={'class': 'form-control'}), 'obra': forms.HiddenInput(attrs={'class': 'form-control','initial' : request.session['obra_aberta_id']}), } But I'm getting an error on 'request': name 'request' is not defined How can I get a value from the session e set os this HiddenInput? I don't know if the models will help, but there it is anyway: class Carga(models.Model): tag = models.CharField(max_length=10) nome = models.CharField(max_length=100) descricao = models.TextField(blank=True, verbose_name='Descrição') potencia = models.CharField(blank=True, max_length=10, verbose_name='Potência') unidade_medida_potencia = models.ForeignKey(UnidadeMedidaPotencia, on_delete=models.DO_NOTHING, null=True, blank=True, verbose_name='Unidade de Medida') area = models.ForeignKey(Area, on_delete=models.DO_NOTHING, null=True, verbose_name='Área') tensao = models.ForeignKey(Tensao, on_delete=models.DO_NOTHING, null=True, verbose_name='Tensão') fonte … -
Django 3.2 Admin FK Inline with edit
I am pretty new to Django. I have two models: Service, and ServiceBlock. I want to be able to have many ServiceBlock objects on the edit page for a Service in the Django Admin. Models.py from django.db import models class ServiceBlock(models.Model): title = models.CharField(max_length=200) subtitle = models.CharField(max_length=200) content = models.CharField(max_length=500) image = models.ImageField(upload_to='serviceBlocks', blank=True, null=True) class Service(models.Model): title = models.CharField(max_length=200) subtitle = models.CharField(max_length=200) image = models.ImageField(upload_to='service', blank=True, null=True) serviceBlocks = models.ManyToManyField(ServiceBlock, related_name="serviceserviceblocks") admin.py from django.contrib import admin from .models import * class ServicesServiceBlocksInline(admin.TabularInline): model = Service.serviceBlocks.through class ServicesAdmin(admin.ModelAdmin): inlines = [ ServicesServiceBlocksInline, ] admin.site.register(Service, ServicesAdmin) I understand why I am seeing what I am seeing in the screenshot below. What I want is to have many ServiceBlock objects but with the ability to edit/create new ServiceBlocks inline. What am I doing wrong?