Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamic JsonForm with ImageField
I am creating a dynamic form (using JSON format) in Django, the form needs to save multiple images using Django Storage and save the reference to the file in the JSON field. This is what I have right now, it works but is really ugly, Django already do this, I can't figure out how to re-use same functionality. Class SomeModel(models.ModelForm): results = JSONField() class DynamicJsonForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # ... Add dynamic fields to the form self.extra = [] # Save the reference for the fields class Meta: model = SomeModel exclude = ("results",) def save(self, commit=True): results = {} for extra in self.extra: value = self.cleaned_data.get(extra) question = some_query.question if "photo" in extra and value: # value = photo filename, ext = value.name.split(".") filename = "media/the/path/to/photos/{}_{}.{}".format(filename, uuid4().hex, ext) uploaded_file = SimpleUploadedFile(filename, value.read(), value.content_type) image = Image.open(uploaded_file) if image.mode in ("RGBA", "P"): image = image.convert("RGB") image.save(fp=filename) results[question][extra] = filename else: results[question][extra] = value self.instance.results = results return super().save(commit) This actually works, it saves the data to the JSONField (results) and saves the image to local file system storage. How can this be improved to use Django Storage and make it simple? Using Django Model.save() seems a lot … -
Requested runtime (python 3.8) is not available for this stack (heroku-18)
I'm trying to deploy an app with Heroku, but it's not working... I have looked at a bunch of other posts on here with the same error, but I'm not finding what's wrong. I have Python 3.8.5 installed on my machine which is supported by Heroku-18, but for whatever reason when I do "git push heroku master" it sees python 3.8: -----> Python app detected ! Requested runtime (python 3.8) is not available for this stack (heroku-18). ! Aborting. More info: https://devcenter.heroku.com/articles/python-support ! Push rejected, failed to compile Python app. I have the runtime.txt file with python-3.8.5: python-3.8.5 I also checked the version on my PC specifically, and tried reinstalling to no success, either: $ python -V Python 3.8.5 And, again, it's supported as of July, 21st, 2020: https://devcenter.heroku.com/changelog-items/1833 I guess the question would be, how do I get Heroku to recognize that I have the correct version installed? I'm sure it's something small I'm overlooking, but I can't figure it out. -
Get / extract the date format currently used, from Django
Is there a function that gets / extracts the string literal "dd/mm/yyyy" or "mm/dd/yyyy" based on Django's localisation / internationalisation settings i.e. the default format that it is using, when displaying dates coming from a "models.DateField", in its template engine? -
Django can't create a new column
I've created a django project recently and it always starts to show problems. I've made some models let's say this is models.py: from django.db import models class MainModel(models.Model): text = models.CharField(max_length=1000, blank=False, null=False) other_text = models.CharField(max_length=1000, blank=False, null=False) def __str__(self): return f"Main obj: {self.id}" The first step before I write any code, is run python manage.py migrate so I can run the initial migrations. After that I write the model shown above and then execute python manage.py makemigrations and then python manage.py migrate. This worked and everything was fine. I tried to add a new column, let's say an integer field: models.py: from django.db import models class MainModel(models.Model): text = models.CharField(max_length=1000, blank=False, null=False) other_text = models.CharField(max_length=1000, blank=False, null=False) number = models.IntegerField(default=1) def __str__(self): return f"Main obj: {self.id}" Great! I run python manage.py makemigrations and everything breaks. I get 200 lines of errors and the output is django.db.utils.OperationalError: no such column: app_mainmodel.number This is fun and all but I couldn't find an answer to why was this happening. I tried changing folders. I created a new file in the same path. So the first project was located in C:/Users/user/Desktop/Site for example and the second one was in C:/Users/user/Desktop/Site2. I created the … -
Extract id field as key django rest framework serializer
Say I have a Blog model which has the following fields: id content title If I am to create a model serializer, It would serialize to this: [ {id: 1, content: "content1", title: "title1"}, {id: 2, content: "content2", title: "title2"}, ] But I want it to serialize to this: { '1': {content: "content1", title: "title1"}, '2': {content: "content2", title: "title2"}, } This way, I could access elements faster on the front end given their id instead of having to search for the id manually. How can I do that ? -
Django - Build queryset to get fields from extended User model
I have model Profile that extends User and I'd like to "join" User model to get some fields from it. I understand that it would not be joining because Profile is an extension of User, but I'm not sure how to make it work. Appreciate any help on this. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile') last_activity = models.DateTimeField(null=True, blank=True) def __str__(self): return self.user.username serializers.py class ProfileSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(read_only=True) # <- this part not correct, but not sure how to treat User model here class Meta: model = Profile fields = ('__all__') views.py class ProfileList(ListAPIView): queryset = Profile.objects.values('id', 'user__username', 'user__last_login', 'last_activity') # <- this isn't right, not sure what would be the correct way serializer_class = ProfileSerializer -
Django Is it correct to use uuid for a sales transaction
Is it correct to use a uuid as a sales order transaction? for example, in an ecommerce website when someones orders any product or products is it ok to use the uuid as a unique identifier for the order transaction? -
Django Shell exiting after running commands without error message
When using the Django shell to upload Raster data into a model, I run the following: In [1]: from django.contrib.gis.gdal import GDALRaster In [2]: from app.models import Mode In [3]: gdal_raster = GDALRaster('app/data/file.tif', write=True) In [4]: raster = Model(name='name', rast=gdal_raster) In [5]: raster.save() However, when I run this the shell exits and nothing is saved. My model is structured like so: class Ph(models.Model): name = models.CharField(max_length=500, null=True) rast = models.RasterField(srid=4326, null=True) When running through other operations in the shell (getting information about the raster)I encountered the same error. For example: In [10]: rst.width, rst.height Out[10]: (16000, 16000) In [11]: rst.srs.srid Out[11]: 4326 In [12]: rst_file = open('app/data/file.tif', 'rb') In [13]: rst_bytes = rst_file.read() In [14]: rst = GDALRaster(rst_bytes) In [17]: rst.driver.name Out[17]: 'GTiff' In [19]: rst.bands[0].data() The last command exitted the shell completely. I included the other data incase it may be helpful in uncovering the issue. For example, I was thinking it may be an issue with the size of the raster (being to large?) Any help is appreciated. My end goal is to successfully query the values of the raster at certain coordinates. -
read_only but still populated in create method on serializer
I have a custom create method on my serializer for adding tags where the consumer could solely send a payload with the tags key containing a list of tags' names. { "id": 1, "title": "Testing", ... "tags": ["Python", "Django", "Go"] } Serializer: class StreamSerializer(serializers.HyperlinkedModelSerializer): streamer = StreamerSerializer() tags = TagSerializer(many=True) class Meta: model = Stream fields = [ "id", "source", "stream_id", "started_at", "collected_at", "title", "thumbnail_url", "viewer_count", "video_type", "language", "streamer", "stream_data", "tags", "live_now", ] extra_kwargs = {"tags": {"validators": []}} def create(self, validated_data): # pop streamer and tags from the payload print(validated_data) streamer_data = validated_data.pop("streamer") tag_names = validated_data.pop("tags") # get_or_create the streamer for this stream streamer_user_id = streamer_data.pop("user_id") streamer, created = Streamer.objects.get_or_create( user_id=streamer_user_id, defaults=streamer_data ) # use get_or_create on the stream to prevent duplicates if stream # crashes or a node change and just update the existing stream # with new data instead. stream, created = Stream.objects.get_or_create( streamer=streamer, defaults=validated_data ) # add tags to the newly created stream for tag_name in tag_names: tag = Tag.objects.get(name=tag_name) stream.tags.add(tag.id) stream.save() return stream I would like for tags to have read_only=True, but by doing this I get a KeyError when posting to this endpoint since this is now excluded from any write methods. class StreamSerializer(serializers.HyperlinkedModelSerializer): streamer … -
Getting serialized grandparent from ManyToMany relation DRF
I'm struggling to serialize the grandparent(s) of a ManyToMany relation in my models. In the product serializer, i want to list the top level Category based on the SubCategory selected on the Product. My code is structured like this: models.py class Category(models.Model): ... name = models.CharField( _('category name'), max_length=255, unique=False ) ... class SubCategory(models.Model): parent = models.ForeignKey( Category, on_delete=models.CASCADE, related_name='children', ) name = models.CharField( _('category name'), max_length=255, unique=False ) ... class Product(models.Model): name = models.CharField( _('product name'), max_length=255, unique=True ) category = models.ManyToManyField( SubCategory, related_name='products' ) ... serializers.py class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ['name'] class ProductsSerializer(serializers.ModelSerializer): ... category = serializers.StringRelatedField(read_only=True, many=True) parent_category = CategorySerializer(read_only=True, source='category.parent', many=True) ... class Meta: model = Product fields = ( ... 'parent_category', 'category', ... ) Currently the field parent_category does not show up in the json-response. -
Django query for many to one relationship, how to retrive data many to one relationship
how to retrive data many to one relationship. class Ads(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=75) class Aimage(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) ads = models.ForeignKey(Ads, on_delete=models.CASCADE, related_name='ads_image') image = models.ImageField(blank=True) my view: qs = Ads.objects.all() template: {% for o in qs.aimage_set.all %} {{ o.title }} {{ o.image.url }} #does work {% endfor %} -
How to create in Django an object of a model while creating another of a different model?
It sounds pretty confusing but I will put my code here for a better understanding of my problem. I want to create a new object of Model Product every time I create an object of Model Client. I tried to overwrite the save method but it didn't work. class Product(models.Model): text = CharField( ... ) class Client(models.Model): name = CharField( ... ) ** method here to create a new Product object when a Client object is created ?** Edit: The main problem with overwriting the save method is that the Product object is created after editing the client object, not after creating. -
difficulty with psycopg2 on macOS Catalina 10.15.5
I have a finished simple django blog application that I am in the process of deploying to heroku. I have a live application now, but my static css files weren't included. I think that I've identified (part of) the problem in my settings.py file where django_heroku is unable to be imported. When i try to pip install django-heroku, I error out at the psycopg2: ld: library not found for -lssl clang: error: linker command failed with exit code 1 (use -v to see invocation) error: command 'gcc' failed with exit status 1 It seems that I have homebrew installed and have up-to-date versions of gcc, openssl, and xcode. Does anyone have any suggestions on what I could try next? -
Django - Why is this form not valid while it does have all fields?
In my Django project there's a form which has many fields, some of which are FileFields. The form.is_valid() method returns False, claiming the FileField fields are empty, but I do upload them, and I know they're being obtained, because when I print the results of both the request.POST.items() and request.FILES.items() I get this: POST > ('csrfmiddlewaretoken', 'GXS7HcM4MS87EwqsNn0bLyo3CFGLxAEJqGiJHyG0uHRoALzySdVTteXcYvhkojTG') POST > ('business_type', '0') POST > ('rfc', 'FOVL950527261') POST > ('full_name', 'Asdff Asdf Asdf') POST > ('email', 'asdf@asdf.com') POST > ('address', 'Sierra Madre Occidental #121 Colonia Lomas de San Francisco') POST > ('private_phone', '4921055833') POST > ('cellphone', '4921055833') POST > ('business_name', 'MUNICIPIO DE JEREZ ZACATECAS') POST > ('jobs_generated', '123') POST > ('expected_investment', '123') POST > ('gender', '0') POST > ('age', '123') POST > ('rfc_moral_person', 'FOV950527261') POST > ('economic_sector', '0') POST > ('address_street', 'Sierra Madre Occidental #121 Colonia Lom') POST > ('address_number', '123') POST > ('address_neighborhood', 'asfd') POST > ('address_locality', 'Zacatecas') POST > ('address_between_streets', '') POST > ('ammount_payed', '123') POST > ('rfc_copy', '') POST > ('constitutive_act_copy', '') FILES > ('official_id_copy', <InMemoryUploadedFile: sare_logo_qJg0oPx.png (image/png)>) FILES > ('business_address_voucher', <InMemoryUploadedFile: sare_logo_qJg0oPx.png (image/png)>) FILES > ('legal_posession_voucher_copy', <InMemoryUploadedFile: sare_logo_qJg0oPx.png (image/png)>) My form is only this: <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form|crispy }} <div class="border-top"> <div class="card-body"> {% … -
When deploying Django to Heroku: ModuleNotFoundError: No module named 'dotenv'
When deploying Django to Heroku, I get a ModuleNotFoundError: No module named 'dotenv' error. However, I do have python-dotenv listed in my requirements.txt. So I'm very confused about why Heroku is not happy about dotenv. Here is my requirements.txt: cffi==1.14.2 cryptography==3.1 dj-database-url==0.5.0 Django==3.1.1 django-cors-headers==3.5.0 django-heroku==0.3.1 django-rest-knox==4.1.0 django-simple-email-confirmation==0.70 djangorestframework==3.11.1 gunicorn==20.0.4 psycopg2==2.8.6 pycparser==2.20 python-dotenv==0.14.0 pytz==2020.1 six==1.15.0 sqlparse==0.3.1 whitenoise==5.2.0 -
Django admin filter – filter annotated relations
app.models class Courier(models.Model): pass class Order(models.Model): courier = models.ForeignKey(Courier, related_name='orders') class Delivery(models.Model): order = models.OneToOneField(Order) date = models.DateTimeField() # app.admin @admin.register(Courier) class CourierAdmin(admin.ModelAdmin) list_display = ('id', 'delivered_orders_count') list_filter = ('orders__delivery__date',) def get_queryset(self, request): return super().get_queryset(request).annotate( delivered_orders_count=Count( 'orders', filter=Q(orders__delivery__isnull=False) ) ) After filtering counted objects are the same. How can I filter orders to count against courier list? -
Django Rest Framework, how to get number of objects of foreignkey inside another foreignkey
I have three models Store, Product and Order class Store(models.Model): ...... class Product(models.Model): store = models.ForeignKey(Store, ...) class Order(models.Model): product = models.ForeignKey(Product ...) delivered = models.BooleanField() I want to create a @property for the Store model that calculates the number of orders that has its products and also has delivered=True how will i go about in doing that? -
Is it possible in Wagtail to use a proxy model with RoutablePageMixin?
My Wagtail site has certain items viewable in a gallery app, that the user can edit so that it would be also shown as an item in the shop app. It's strictly one-to-one, so I don't want them to be managing the items separately. I thought proxy models might be the best way to achieve this but I'm getting stuck and not finding very much documentation about using proxy models with Wagtail. Also possibly my regex is bad. In app 'gallery': class GalleryItem(Page): parent_page_types = ['InstallationPage'] description = models.CharField(blank=True, max_length=250) direct_sale = models.BooleanField("Direct Sale", default=False, help_text="Check this box to list this item for sale directly on your website.") direct_sale_price = models.DecimalField("Sale price, $", blank=True, null=True, max_digits=6, decimal_places=2, help_text="Add more info about this item for the store page only.") direct_sale_extra_description = models.CharField("Addtional sale description (optional)", blank=True, max_length=250, ) stock = models.IntegerField("Number in stock", blank=True, null=True,) In app 'shop': from gallery.models import GalleryImage class Shop(Page): def get_context(self, request): context = super().get_context(request) shop_items = ShopItem.objects.filter(Q(direct_sale=True) | Q(external_sale=True)) paginator = Paginator(shop_items, 24) page = request.GET.get('page') try: pagin = paginator.get_page(page) except PageNotAnInteger: pagin = paginator.get_page(1) context['shop_items'] = shop_items return context class ShopItem(GalleryItem, RoutablePageMixin): class Meta: proxy = True parent_page_types = ['Shop'] @route(r"^shop/(?P<item_slug>[-\w]*)/$", name="item_view") def item_view(self, … -
Get Options from Models post on Html Django
I'm having some issues trying to get the list out of the model and print it dynamically on my HTML view. Here's what I've done so far, and what I've got as view. models.py class Projeto(models.Model): acoes = ( ('', "---------"), ('Projeto', "Projeto"), ('Evento', "Evento"), ('Curso', "Curso"), ) areas = ( ('', "---------"), ('Comunicação', 'Comunicação'), ('Cultura', 'Cultura'), ('Direitos Humanos e Justiça','Direitos Humanos e Justiça'), ('Educação', 'Educação'), ('Meio Ambiente', 'Meio Ambiente'), ('Saúde', 'Saúde'), ('Tecnologia e Produção', 'Tecnologia e Produção'), ('Trabalho', 'Trabalho'), ) views.py def lista_projetos(request): projetos_unemat = Projeto.objects.order_by('id') page = request.GET.get('page', 1) paginator = Paginator(projetos_unemat, 10) try: users = paginator.page(page) except PageNotAnInteger: users = paginator.page(1) except EmptyPage: users = paginator.page(paginator.num_pages) lista_acoes = Projeto.acoes lista_areas = Projeto.areas context = { 'projetos': users, 'acoes': lista_acoes, 'areas': lista_areas } return render(request, 'lista_projetos.html', context) _filter.html <div class="container"> <div class="row justify-content-md-center"> <select class="form-control col-4" id="acoes"> {% for acao in acoes %} <option name="{{acao}}"> {{acao}} </option> {% endfor %} <div class="input-group-append"> <button class="btn btn-outline-secondary fas fa-search" type="submit"></button> </div> </div> And my page shows this: page view How do I get to show only the options? -
Best way to view data in django rest framework database?
I have tried to connect from PyCharm database tool to the mySQL django database and without success. By doing so - what is the best configuration for the tool? The image below shows my configuration with the apropriate error. What are the best practices to view data? Maybe ER-diagrams and stuff? -
Can't use FormData in UI material forms to fetch form field values
I am just trying to post data from my UI-material form into backend. I am using react hooks here. Below is code that i am trying to do using simple fetch. const [name, setName] = useState (''); const [email_id, setEmail] = useState (''); const [subject, setSubject] = useState (''); const onSubmit = (e) => { e.preventDefault(); const data = new FormData(e.target); console.log(data); fetch("http://127.0.0.1:8000/api/contact/", { method: "POST", body: data, }) .catch((error) => console.log("Request failed", error)); } This is the material UI form which i am using <form onSubmit={onSubmit}> <TextField autoComplete="new-password" id="outlined-basic" label="Full Name" variant="outlined" value={name} onChange={(e) => setName(e.target.value)} required /> <TextField id="outlined-basic" label="Email Address" variant="outlined" autoComplete="new-password" value={email_id} onChange={(e) => setEmail(e.target.value)} required /> <TextareaAutosize className="textbox" aria-label="minimum height" rowsMin={3} placeholder="Subject" value={subject} onChange={(e) => setSubject(e.target.value)} /> <button>Submit</button> </form> While using with material UI form it gives me error that says {"name":["This field is required."],"email_id":["This field is required."],"subject":["This field is required."]} When i use normal html form it works perfectly fine. But when i try to do the same with material-UI form it doesnt work. It will be really helpful if anyone can help. Thanks in advance. -
ImportError: cannot import name 'Blog' from 'blog.models'
Hi Can someone help me to sort out the below issue. Actually, I have created a Port_Folio project and 2 apps with the name of Blog and portfolio. When I import a blog in models it doesn't import and I am getting below error. ImportError: cannot import name 'Blog' from 'blog.models' Actual code is: Import Blog Error-PyCharm Terminal from django.contrib import admin from .models import Blog admin.site.register(Blog) Error: File "C:\Users\zeems\PycharmProjects\DjangoCourse\personal_portfolio-project\blog\admin.py", line 2, in <module> from .models import Blog ImportError: cannot import name 'Blog' from 'blog.models' (C:\Users\zeems\PycharmProjects\DjangoCourse\personal_portfolio-project\blog\models.py) -
Auto refering nesting with Django Rest Framework
I have this model in Django (based on a legacy database): class NationalTest(models.Model): unityId = models.IntegerField(primary_key=True) parentId = models.IntegerField(blank=True) grade = models.FloatField(blank=True) This model stores the grade that a "unity" (a school, a city, a region or a state in our country) received in a national test. unityId is the id of the unity, grade is its grade in the test, and parentId is the id of its upper parent (i.e.: if our unity is a school, parentId the id of the city where the school is located; if it's a city, parentId is the id of the state where the city is located, and so on). For front-end purposes, when I fetch some school's grade, I need also the grade of the city, the state, the region and the whole country (all 5 levels possible). When I fetch a city's grade I need state, region and country's grade too. When I fetch state's grade, just need the two levels above grade. I think that the best way I can solve it is to create a nested serializer based on parentId. I know how to do it when we have a foreign key from another model, but how can I … -
Ajax call not sending any data when added image data using django ajax
I'm trying to send data from a popup form through django template which includes an image also, when tried to access data in console. Data is properly visible. But when ajax function used, no data is received in 'request.POST' in django view. But when image file is removed from AJAX data data is recieved properly HTML code: <div class="form-popup-custom col-lg-12" id="myForm" data-method="POST"> <form enctype="multipart/form-data" action="/action_page.php" class="form-container" method="post"> <div class="header" id="myHeader"> <div class="col-lg-12"> <h5 style="font-size:22px;">Total Amount Selected :</h5> <h5 style="font-size:20px;" id="amount_text">0.0</h5> </div> </div> <input type="hidden" id="amount_text"> <label for="utr" style=" margin-bottom: 2vw; margin-left: 3vw; "><b>Enter UTR number</b></label> <input type="text" id="utr" maxlength="22" minlength="16" placeholder="Enter UTR number" name="UTR" required> <label for="utr"><b>Enter Amount</b></label> <input type="number" id="amt" placeholder="Enter UTR number" name="amt" required> <div class="header" id="myHeader" style=" margin-top: 2vw; "> <label for="enter-amount"><b>Upload UTR slip</b></label> <input type="file" id="slip" placeholder="select file" name="select_file" required> </div> <button type="button" class="btn cancel" onclick="closeForm()">Close</button> </form> </div> </center> <div class="col-lg-12 text-center" style=" text-align: center; "> <input type="submit" id="sbt_btn" onclick="submit()" value="Submit"> </div> Ajax call: function submit() { console.log("isme aa gyaa!!!!!!"); order_ids=Array(); $("input:checkbox[name=_selected_action]:checked").each(function(){ order_ids.push($(this).val()); }); var amount = document.getElementById('amount_text').innerHTML; var utr = document.getElementById("utr").value; var amt = document.getElementById('amt').value; var errorflag = false; files_=Array(); var files = document.getElementById("slip").files[0]; files_.push(files); {#var remark = document.getElementById('request_remark').value;#} if(order_ids.length <= 0){ alert("Please select orders."); … -
Where to define methods unrelated to models in Django project
Is there a convention related to where to define methods unrelated to models in Django? For example, I am developing a dictionary project in which I have a dictionary app as well as a tags app. From one of the views, I needed a method to collect all Tags from multiple Definitions. This method can not be implemented in any of my models.pys. Where should I define such a method? If I need to create a new file, what should I call it? Should it go in the project's folder, the dictionary app's folder, or in the tags app's folders?