Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django, query filter not applying to prefetched data
I have a table that contains the details of cards, and another table that holds the inventory data for those cards for the users. I am trying to get the card's data and include the inventory quantities for the cards returned. I do this by adding a prefetch for the query. However when I try to filter the prefetched data by the user id, it is still returning data for the users other than the one that is logged in. Code: sql_int = "CAST((REGEXP_MATCH(number, '\d+'))[1] as INTEGER)" cards = magic_set_cards.objects.all().exclude(side='b').extra(select={'int': sql_int}) \ .prefetch_related(Prefetch('inventoryCards', queryset=inventory_cards.objects.filter(user_id=request.user.id))) \ .values('id', 'set_id__code', 'set_id__name', 'set_id__isOnlineOnly', 'number', 'name', 'imageUri', 'hasNonFoil', 'hasFoil', 'inventoryCards__user_id', 'inventoryCards__nonfoil', 'inventoryCards__foil') \ .order_by('-set_id__releaseDate', 'set_id__name', 'int', 'number') Data returned: { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 3, 'inventoryCards__nonfoil': 2, 'inventoryCards__foil': 0 }, { 'id': UUID('a7ef0985-345d-4d0d-bd71-069870ce4fd6'), 'set_id__code': 'MID', 'set_id__name': 'Innistrad: Midnight Hunt', 'set_id__isOnlineOnly': False, 'number': '46', 'name': 'Curse of Surveillance', 'imageUri': 'https://c1.scryfall.com/file/scryfall-cards/normal/front/d/6/d6a5b3b2-4f27-4c97-9d87-d7bdcc06d36a.jpg?1634348722', 'hasNonFoil': True, 'hasFoil': True, 'inventoryCards__user_id': 1, 'inventoryCards__nonfoil': 0, 'inventoryCards__foil': 1 } ... As you can see from the data above, they are the same cards but it is returning the inventory data for two different users. Please … -
How to serialize a list of objects into list of numbers
With django-rest-framework, how can I serialize the many elements of a one-to-many relationship into a list of integers with their ids? For example in class Album(models.Model): album_name = models.CharField(max_length=100) artist = models.CharField(max_length=100) class Track(models.Model): album = models.ForeignKey(Album, related_name='tracks') order = models.IntegerField() title = models.CharField(max_length=100) duration = models.IntegerField() I would like to get something like { 'album_name': 'Things We Lost In The Fire', 'artist': 'Low', 'tracks': [15, 16, 17, 23] } -
urlpatterns in django for unicode names
I was working on categories in my website and after adding category with id like 11 or more it had a error . Reverse for 'category' with arguments '('more-cat', 14)' not found. 1 pattern(s) tried: ['category/(?P[\w-]+)/(?P[0-9])/'] its the urls.py re_path(r'^category/(?P<slug>[\w-]+)/(?P<id>[0-9])/' , views.listofproducts , name="category"), and its models.py class category(models.Model): sub_category = models.ForeignKey('self' , on_delete=models.CASCADE , null=True , blank=True , related_name='sub') sub_cat = models.BooleanField(default=False) name = models.CharField(max_length=200 , blank=True , null=True) create = models.DateTimeField(auto_now_add=True ,blank=True , null=True) update = models.DateTimeField(auto_now=True ,blank=True , null=True) slug = models.SlugField(allow_unicode=True , unique=True , null=True , blank=True) image = models.ImageField(upload_to = 'category' , blank=True , null=True) def __str__(self): return self.name def get_absolute_url(self): return reverse("home:category" , args=[self.slug , self.id]) please help me with this problem.! -
File "/usr/local/lib/python3.6/site-packages/seacucumber/tasks.py", except SESAddressBlacklistedError, exc:
I working on transferring old version Django Project(1.8) to new version. I use python 3.9, Django 3.2.7, docker with celery, Redis, flower on a board. Right now such containers as db(postgres), web(python 3.6), Redis are working well, but celery(worker) and flower do not indicate sights of been live with the error above. celery.py from __future__ import absolute_import, unicode_literals import celery import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings') from django.conf import settings # noqa app = Celery('core') app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) cwd = os.path.dirname(os.path.realpath(__file__)) environment_name = os.getenv('ENVIRONMENT_NAME', 'dev').lower() environment_path = os.path.join(cwd, '', os.getenv('DJANGO_ENVDIR', 'envs/%s' % environment_name)) if os.path.isdir(environment_path): import envdir envdir.open(environment_path) class Celery(celery.Celery): def on_configure(self): if settings.ENABLE_SENTRY: import raven from raven.contrib.celery import register_signal, register_logger_signal client = raven.Client(settings.RAVEN_DSN) # register a custom filter to filter out duplicate logs register_logger_signal(client) # hook into the Celery error handler register_signal(client) Docker-compose.yaml version: '3.8' services: redis: image: redis networks: - default ports: - 6379:6379 worker: build: context: . dockerfile: Dockerfile image: madefire/chordtest command: celery worker -A core --loglevel=info networks: - default depends_on: - redis env_file: - ./.env.dev db: container_name: db hostname: db image: postgres:13.0-alpine networks: - default ports: - 5432:5432 volumes: - ./postgres_data:/var/lib/postgresql/data/ env_file: - … -
Why don't I see options from models.py in the template?
a doubt, do you know how to pass the options of a select from forms.py? It turns out that I made a model in the client app, then I passed it to the client app form, I inherited it in another form of an app called estimates, and when presenting it in the template, you only see the empty field without the options models.py (app clientes) class Clientes(models.Model): TITLE=( ('Mrs.','Mrs.'), ('Miss','Miss'), ('Mr.','Mr.'), ) titulo=models.CharField(max_length=200, null=True,choices=TITLE) nombre =models.CharField(max_length=80) def __str__(self): return f'{self.id}:{self.titulo}{self.nombre}' forms.py (app clientes) class ClientesForm(forms.ModelForm): class Meta: model=Clientes fields=['titulo','nombre'] forms.py (from the budget app inheriting from forms.py from the customer app) class PresupuestosClientesForm(forms.ModelForm): class Meta: model = Clientes fields = '__all__' widgets = { 'titulo': forms.TextInput( attrs={ 'class': 'form-select' } ), 'nombre': forms.TextInput( attrs={ 'class': 'form-control' } ), } in the presupuestos-form.html template where the options reflected are not seen <label for="titulo" id="titulo">Título</label> {{presupuestosclientesform.titulo}} <select class="form-select"> <option>Elige</option> <option>Mrs.</option> <option>Miss</option> <option>Mr.</option> </select> views.py (app clientes) def create_Clientes(request): form=ClientesForm(request.POST or None) if form.is_valid(): form.save() return redirect('clientes:index') return render(request,'clientes/clientes-form.html',{'form':form}) views.py (app presupuestos) def create_Presupuestos(request): presupuestosclientesform=PresupuestosClientesForm(request.POST or None) presupuestosvehiculosform=PresupuestosVehiculosForm(request.POST or None) presupuestosparteform=PresupuestosParteForm(request.POST or None) presupuestosmanoobraform=PresupuestosManoObraForm(request.POST or None) presupuestospagosform=PresupuestosPagosForm(request.POST or None) if presupuestosclientesform.is_valid(): presupuestosclientesform.save() return redirect('presupuestos:index') return render(request,'Presupuestos/presupuestos-forms.html',{'presupuestosclientesform':presupuestosclientesform,'presupuestosvehiculosform':presupuestosvehiculosform, 'presupuestosparteform':presupuestosparteform, 'presupuestosmanoobraform':presupuestosmanoobraform,'presupuestospagosform':presupuestospagosform}) -
django heroku template password_reset_confirm.html does not work
I'm using this build feature of Django. On my local machine everything works just fine. But on heroku the is no actually form on this template. Code of template: <div class="container p-5"> <h2 class="font-weight-bold mt-3">Password Reset Confirm</h2> <hr> <p>Please enter your new password.</p> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-primary" type="submit">Reset password</button> </form> </div> code one developers panel: <div class="container p-5"> <h2 class="font-weight-bold mt-3">Password Reset Confirm</h2> <hr> <p>Please enter your new password.</p> <form method="POST"> <input type="hidden" name="csrfmiddlewaretoken" value="0Vpkz9Uhbp5RjG3op8FnAU77abxRwdf8OtA7r9buOAWnweVueKSRkbbRY6vHh2B6"> <button class="btn btn-primary" type="submit">Reset password</button> </form> </div> -
How to grab data from a rendered Jinja file in a custom filter?
In a website I'm making people can use a custom filter to get the currency that they have set in their account settings. The custom filter would re-render their price with the appropriate currency symbol. <span>{{ product.price | money }}</span> The problem is, I need their store ID to be able to fetch their chosen currency from the DB. Instead of having them pass in their store ID with every filter I wanted to do it all on the backend. I came up with a solution (maybe?) to add JS to the template that would supply that info in an object <script> const shopData = { id: 123123' } </script> My question is can I grab that JS to use in the Django backend without the user supplying a second filter value? -
websocket receiving incomplette data
receiving data from websocket i have notice that fields are missing from the models please help you can see the resualt in postman wil connecting to the django channels consumer.py # Receive message from room group async def chat_message(self, event): method = event['method'] model = event['model'] data = event['data'] description = event['description'] receiver = event['receiver'] sender = event['sender'] created = event['created'] seen = event['seen'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'method': method, 'model': model, 'data': data, 'description': description, 'receiver': receiver, 'sender': sender, 'created': created, 'seen': seen, })) views.py async_to_sync(layer.group_send)(("chat_" + str(channel_name)), { 'type': 'chat_message', 'method': 'POST', 'model': 'social', 'data': json.dumps(serializers.data), 'description': 'new post', 'sender': json.dumps(LikeSerializer(request.user, many=False).data), 'receiver': json.dumps(sorted(my_profile.profile_followers.all().values_list('id', flat=True))), 'created': json.dumps(str(timezone.now())), 'seen': None }) resualt 1 -
ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead
I'm doing my first question on StackOverFlow about something ig going me crazy. My project is an Auction site, and is based on django and Web3 to interact with a smart contract deployed on my Ganache. Now i have got this error on my view : ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead. The problem is: If i register a customer and an address, then i try to receive tokens from the Faucet, If i put customer address i don't receive anything. But if i select another address, i receive token in the first address. I really don't understand why... Thank you very much for your help my Model: class Customer(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) address = models.CharField(max_length=256, blank=False, null=False, unique=True, error_messages={'unique': 'This address is already registered'}) tokenBalance = models.FloatField(default=0) dollarBalance = models.FloatField(default=0) my Registration to the site def registrationForm(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): username = form.cleaned_data['username'] password = form.cleaned_data['password'] address = form.cleaned_data['address'] user = User.objects.create_user( username=username, password=password, ) newCustomer = Customer( user=user, dollarBalance=random.randrange(500, 1500), address=address, tokenBalance=0 ) user.save() newCustomer.save() user = authenticate(username=username, password=password) login(request, user) messages.success(request, f'''Welcome in DNote {request.user}''') return redirect('homepage') else: form = RegistrationForm() … -
Shop in an iframe
My company has an online shop that is used by third party merchants to sell their goods. Each merchant has their own page, with a list of all their products. Many have asked for a way to embed their page into their own website through an iframe, so I managed to create an embeddable version of their page, and all the code on the server is executed correctly: a new order is created, it's filled with a list of all the purchased products, and then the buyer is sent to our site's basket page. This process is advantageous to us, because in this way we generate traffic towards our shop, and customers can look at other merchants' wares as well, increasing our potential revenue. It also lets me rewrite a lot less code, since I don't have to recreate an embeddable version of every page from purchase to payout. As I said, the order is registered correctly, but when the user lands on the basket page, the basket is always empty. To explain the process a bit more in detail: our shop lets unregistered users put articles in their baskets, but at most during the checkout process they have to … -
Django Rest Framework endpoint is missing 'Access-Control-Allow-Origin' response header
I have a flutter app that makes a call to two different endpoint, one of them responds as expected but the other is blocked by CORS because "No 'Access-Control-Allow-Origin' header is present on the requested resource." Acording to the django rest framework docs i can pass headers as dictionary of HTTP headers to use in the response like this: @api_view(['GET']) @permission_classes((AllowAny,)) def get_new_blog_posts(request): blog_posts = BlogPost.objects.all().order_by('-id')[:5] serializer = BlogPostPreviewSerializer(blog_posts, many=True) return Response(serializer.data, headers={'Access-Control-Allow-Origin':'http://localhost:51626'}) Which should let the front end make the call and get the information, but somehow the response is ignoring the headers. The view that works looks like this: class ApiJobPostsContentView(generics.ListAPIView): queryset = JobPost.objects.all() serializer_class = JobPostCardSerializer authentication_classes = [] permission_classes = [permissions.BasePermission] filter_backends = [SearchFilter, OrderingFilter, DjangoFilterBackend] I have tried making the failing view a generic ListAPIView but it does not matter, the header is still missing. django-cors-headers is installed in the app and my settings.py file haswhat it needs to allow the other views to work the way they should. My setting.py: MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( 'http://localhost:51626', ) CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_HEADERS = [ 'accept', … -
Django Real Time actions
How Can I create real time actions in python / django? for more info: Some user add some thing to database also other user add same one too (not same as they are but they have similar property) at same time (and all times) program should being check if they are objects with similar property {if they are not same check both of them in other time with all other objects that may be added/edited on database} these actions should be in real time or at last by few minuts appart. -
Django bootstrap form and button is displaying on browser output extra large
this is my link: <a href="#" class="btn btn-danger">link</a> in the browser it looks too big with djnago but when this link I aplly without django then it's size works well what should i do -
Django not loading static css files
In the process of conntec to a space on digital ocean, I ran python manage.py collectstatic For {% static 'image/image_name.jpg %} works, my images show up, bu for <link rel="stylesheet" type="text/css" href="{% static 'css/fontawesome/css/all.css' %}"> my font awesome isn't showing up. I've checked the location of this link, and I am getting back the correct location, but I don't know what is causing the issue. settings.py STATIC_URL = '/static/' STATICFILES_DIRS = os.path.join(BASE_DIR, 'static'), # https://unlock-optimal-performance.nyc3.digitaloceanspaces.com STATIC_ROOT = os.path.join(BASE_DIR,"staticfiles-cdn") # in production we want cdn MEDIA_ROOT = os.path.join(BASE_DIR, 'staticfiles-cdn', 'uploads') from .cdn.conf import AWS_ACCESS_KEY_ID,AWS_SECRET_ACCESS_KEY,AWS_STORAGE_BUCKET_NAME,AWS_S3_ENDPOINT_URL,AWS_S3_OBJECT_PARAMETERS,AWS_LOCATION,DEFAULT_FILE_STORAGE,STATICFILES_STORAGE urls.py urlpatterns += staticfiles_urlpatterns() Any reason why my images are showing up but not my css ? -
AttributeError at 'WSGIRequest' object has no attribute 'Post'
When i click vote button I got this error AttributeError at /polls/2/vote/ 'WSGIRequest' object has no attribute 'Post'. When i tried to vote for any poll. This is my results.html file I am using django==3.2 and python 3.8 <form action="{% url 'polls:vote' question.id %}" method="post"> {% csrf_token %} <fieldset> <legend><h1>{{ question.question_text }}</h1></legend> {% if error_message %} <p><strong>{{ error_message }}</strong></p> {% endif %} {% for choice in question.choice_set.all %} <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}"> <label for="choice{{ forloop.counter }}">{{ choice.choice_text }}</label> <br> {% endfor %} </fieldset> <input type="submit" value="Vote" > </form> -
Django - importing from subordinary folder
I'm making django blog app. And i have problem with import .py file from subordinate directory. Does anyone has any advice maybe what is wrong here? enter image description here -
Redirect back to original post after updateview
I have an update view that is working as expected. The only issue is that I cant figure out how to redirect back to the post that was being updated. I believe I am on the right track with get_success_url but I cant get it working view class UpdateBuildLog(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = BuildLog form_class = BuildLogupdateForm template = 'blog/buildlog_update.html' def get_object(self): return BuildLog.objects.get(pk=self.kwargs["pkz"]) def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def get_success_url(self): pk = self.kwargs["pkz"] return reverse("build-log-view", kwargs={"pkz": pk}) def test_func(self): post = self.get_object() if self.request.user.id == post.author_id: return True return False urls: path('post/<int:pk>/build-log/<int:pkz>/', views.BuildLogDisplay, name='build-log-view'), path('post/<int:pk>/build-log/<int:pkz>/delete/', views.BuildLogDelete, name='build-log-delete'), path('post/<int:pk>/build-log/<int:pkz>/update/', UpdateBuildLog.as_view(), name='build-log-update'), -
Django model generates hundreds of files in a saving loop
I'm using Django 3.8.2 on Ubuntu 18.04, I'm generating a PDF file upon saving a django model but files are generated in a loop endlessly. I have this django model: class Fattura(models.Model): ordine = models.ForeignKey(Ordine, on_delete=models.CASCADE, related_name="fatture", null=False) pdf = models.FileField(upload_to='archivio/fatture/%Y/%m') the pdf field is generated when an instance is saved, based on the information contained in the related "ordine" field which is a ForeignKey to this other model: class Ordine(models.Model): utente = models.ForeignKey(User, on_delete=models.CASCADE, related_name="ordini", null=False) data = models.DateField(auto_now_add=True) abbonamento = models.ForeignKey(Abbonamento, on_delete=models.PROTECT, null=False) importo = models.DecimalField(max_digits = 5, decimal_places = 2, null=False) I declared every instructions for the generation of the PDF inside the save() method of my Fattura model. I'm using the library that is recommended by Django's documentation: reportlab. Here is the custom save method: def save(self, *args, **kwargs): self.count_save += 1 # I defined this attribute which I increment to understand what is actually looping print("COUNT SAVE: " + str(self.count_save)) # it always grows, that's the save method being re-called if self.pdf._file == None: try: buffer = io.BytesIO() p = canvas.Canvas(buffer) p.drawString(100,100, str(self.ordine)) p.showPage() p.save() buffer.seek(0) utente = self.ordine.utente num_questa_fattura = utente.ordini.count() nome_file = "{}_{}-{}.pdf".format( self.ordine.utente.first_name.lower(), self.ordine.utente.last_name.lower(), num_questa_fattura) percorso = '{}/upload/archivio/fatture/{}/{}/{}'.format( BASE_DIR, # from settings.py … -
Django Python Creating Object inside Model delete function returns 500 Error
I am trying to create a new Entry of CloudProfileTransaction before deleting a record. When saving a new record the exact same code works fine ( with: super().save(*args, **kwargs)). If I remove the CloudProfileTransaction code the deletion works. the following code throws a Response 500 Error. what am I missing? def delete(self, *args, **kwargs): CloudProfileTransaction.objects.create( cloud_giver = self.follower, cloud_receiver = self.followee, cloud_model = CloudModel.objects.get(investment='Follow'), add = False ) Followers.objects.filter(user=self.follower).update(followers=F('followers')-1) Followees.objects.filter(user=self.followee).update(followees=F('followees')-1) super().delete(*args, **kwargs) Error Message: E/Volley: [28490] NetworkUtility.shouldRetryException: Unexpected response code 500 -
How to display all fields, including related ones, in a Django Serializer using abbreviated syntax?
I know I can use this syntax for all fields: class EventSerializer(serializers.ModelSerializer): class Meta: model = models.Event fields = '__all__' class GuestList(LogicalDeleteModel): events = models.ManyToManyField(Event, through='EventGuestList', through_fields=('guest_list', 'event'), related_name='guest_list') But this does NOT include any of the related fields. In this example, I want guest_list to also be a part of the serializer. I know that I can simply declare all the fields explicitly, including the related ones, but I was wondering if there's any chance I could avoid it. -
How to count number of student in a school in Django?
class School(models.Model): name = models.CharField() city = models.CharField() street = models.CharField() class Student(models.Model): school_id = models.ForeignKey(School, on_delete=models.CASCADE) first_name = models.CharField() last_name = models.CharField() I want to join two classes School and Student and get the number of students in these school, So I wrote this code in my serializers. but I got no resulte of number of students, only the two classes joined. Can someone help me? serializers.py from django.db.models import Count class SchoolSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = School fields = ['name'] class StudentSerializer(serializers.HyperlinkedModelSerializer): school = SchoolSerializer() school.objects.annotate(num_of_students=Count('student')) class Meta: model = Student fields = ['first_name', 'last_name', 'school'] views.py In my views I wrote the following code: class StudentViewSet(viewsets.ModelViewSet): serializer_class = StudentSerializer queryset = Student.objects.all() -
django.db.utils.OperationalError: no such table: MainApp_user when i try to create superuser
I make some web application, and almost in the end of development process i decided to customize user model to make profile page with many other info. Recently i have found a video where example from django docs is explained, and i made the same code as there was, but at first i delete my file db.sqlite3 and now when i try to create a superuser i do always catch the next error: django.db.utils.OperationalError: no such table: MainApp_user Here is my models.py: class MyUserManager(BaseUserManager): def create_user(self, username, password): if not username: raise ValueError("Mailname field is empty") if not password: raise ValueError("You have to set password") user = self.model( username=username, ) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser): username = models.CharField(max_length=30, unique=True) password = models.CharField(max_length=64) name = models.CharField(max_length=30, blank=True) surname = models.CharField(max_length=30, blank=True) avatar = models.ImageField(width_field=512, height_field=512) email_link = models.CharField(max_length=64, blank=True, null=True) bio = models.CharField(max_length=512, blank=True, null=True) registered = models.DateField(auto_now_add=True) USERNAME_FIELD = "username" REQUIRED_FIELDS = ['password'] objects = MyUserManager() def __str__(self): return self.username Also i've added the next variable in settings.py: AUTH_USER_MODEL = "MainApp.User" Why this error happens and how to solve it, help please. ***Ofc, i did made migrations to database -
How to use an outside script within a Django Project?
Sorry for the wording on the question if it isn't clear. I am rather new to Django but not too new to Python. I have a Model in my Django Project, which keeps track of trailer locations. I then need to use another script to update this data. However, when running this script, the Dict that is suppose to be returned is not getting returned properly. class TrailerLocation(models.Model): trailer = models.OneToOneField(Trailer, on_delete=models.CASCADE) locationCity = models.CharField(max_length=70, null=True, blank=True) locationState = models.CharField(max_length=30, null=True, blank=True) locationCountry = models.CharField(max_length=50, null=True, blank=True) locationStatus = models.CharField(max_length=200, null=True, blank=True) latitude = models.CharField(max_length=200, null=True, blank=True) longitude = models.CharField(max_length=200, null=True, blank=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) # def __str__(self): # return self.trailer def createLocation(self, trailer): trailerLocation = TrailerLocation(trailer=trailer) trailerLocation.save() def getLocations(self): locDataDict = trailerLocations.run() print(locDataDict) for key in locDataDict.keys(): datalist = locDataDict[key] self.updateLocation(key, datalist) -
Django - How to populate choices in a modelchoicefield with a field from another model filtered by logged in user
I'm trying to made a modelform with a modelchoicewidget which inherits its choices from another model than the model the modelform is connected to, and this selection is to be filtered by the current logged in user. The example below illustrates my intentions - let's say I have two different models where one model allows the user to register meal types (breakfast, dinner etc), and the other model allows the user to create specific meals based on those meal types, with the connecting variable being the title of the meal type. models.py: class Mealtypes(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200, default='') description = models.TextField(default='') class Specificmeals(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) meal_name = models.CharField(max_length=200, default='') mealtype = models.CharField(max_length=200, default='') fruit = models.BooleanField(default=False) meat = models.BooleanField(default=False) dairy = models.BooleanField(default=False) forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Mealtypes, Specificmeals class MealAdder(ModelForm): class Meta: model = Specificmeals fields = [ 'meal_name', 'mealtype', 'fruit', 'meat', 'dairy', ] widgets = { 'text': forms.Textarea(attrs={"style": "height:10em;" "width:60em;"}), 'mealtype': forms.ModelChoiceField(queryset=Mealtypes.title.filter(author='author')), 'fruit': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'meat': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), 'dairy': forms.CheckboxInput(attrs={"style": "margin-left:350px;"}), } I'm trying to play around with the ModelChoiceField to make it query the mealtypes from the Mealtypes model filtered … -
Read from file output to html template in django
How would the solution linked below be written in views.py to read from multiple files and output those various fields? I can make this work for one but if I try copy pasting f = open('path/text.txt', 'r') file_content = f.read() f.close() context = {'file_content': file_content} and changing the letters slightly to have unique versions it seems to break it...I am passing in unique variations not reusing "f" ex: h = open(BASE_DIR, 'path/tofile') file_content = h.read() h.close() context = {'file_contenth': file_contenth} I then pass in to the return return render(request, pathtohtml, {'file_content': file_content}, {'file_contenth': file_contenth} and that "breaks" it. I've tried a few variations of passing those variables in to no avail I used the solution found here Django: Display contents of txt file on the website