Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying a python app to heroku, struggling with gunicorn configuration
I've inherited a python django app and am trying to breathe new life in it. It's currently using python 2.7 and many old packages that I will eventually need to upgrade. But the first thing before upgrading is I want to have it running successfully on heroku. So far I have it running fine locally, but I'm running into issues with heroku and gunicorn. Here is the error I'm getting: 2020-09-10T03:48:27.212247+00:00 heroku[web.1]: Starting process with command `gunicorn spotlit_due_diligence.spotlit_due_diligence.wsgi:application` 2020-09-10T03:48:29.477479+00:00 heroku[web.1]: State changed from starting to up 2020-09-10T03:48:29.206728+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Starting gunicorn 19.10.0 2020-09-10T03:48:29.207159+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Listening at: http://0.0.0.0:45741 (4) 2020-09-10T03:48:29.207253+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [4] [INFO] Using worker: sync 2020-09-10T03:48:29.211268+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [11] [INFO] Booting worker with pid: 11 2020-09-10T03:48:29.250434+00:00 app[web.1]: [2020-09-10 03:48:29 +0000] [13] [INFO] Booting worker with pid: 13 2020-09-10T03:48:29.000000+00:00 app[api]: Build succeeded 2020-09-10T03:48:30.075238+00:00 app[web.1]: [2020-09-10 03:48:30 +0000] [11] [ERROR] Exception in worker process 2020-09-10T03:48:30.075250+00:00 app[web.1]: Traceback (most recent call last): 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/arbiter.py", line 586, in spawn_worker 2020-09-10T03:48:30.075251+00:00 app[web.1]: worker.init_process() 2020-09-10T03:48:30.075251+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 135, in init_process 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.load_wsgi() 2020-09-10T03:48:30.075252+00:00 app[web.1]: File "/app/.heroku/python/lib/python2.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-09-10T03:48:30.075252+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-09-10T03:48:30.075253+00:00 app[web.1]: … -
Testing Graphene returns error JSONDecodeError: Expecting value: line 2 column 1 (char 1)
I am new to Unit Test on Graphene and DJango. I am trying to test my graphql query by graphene https://docs.graphene-python.org/projects/django/en/latest/testing/ But I have no idear why I am getting this error. Please help me. import json from graphene_django.utils.testing import GraphQLTestCase # Create your tests here. class CryptoBankQueryTestCase(GraphQLTestCase): def test_cryptobank_query(self): response = self.query( ''' query cryptoBank($id: Int!){ cryptoBank(cryptoBankId: $id) { id, name, phoneNumber, address } } ''', op_name="cryptoBank", variables={"cryptoBankId": 1} ) content = json.loads(response.content) # This validates the status code and if you get errors self.assertResponseNoErrors(response) # Add some more asserts if you like Error: ERROR: test_cryptobank_query (cryptobank.tests.test_cryptobank_query.CryptoBankQueryTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/cafafanscoders/Desktop/python/CryptoBankGraphQL/src/cryptobank/tests/test_cryptobank_query.py", line 22, in test_cryptobank_query content = json.loads(response.content) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/__init__.py", line 348, in loads return _default_decoder.decode(s) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 337, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/local/Cellar/python/3.7.5/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/decoder.py", line 355, in raw_decode raise JSONDecodeError("Expecting value", s, err.value) from None json.decoder.JSONDecodeError: Expecting value: line 2 column 1 (char 1) -
Django Oscar Dashboard link not accessible
I have developed oscar /django applications before but I am completely stumped by this issue: I can see the dashboard url in the supported urls list but I am not able to access it. 404 Page I have forked a few apps from oscar like voucher, shipping, checkout, reviews and customized them in various ways(None of these are dashboard related) . This is my INSTALLED_APPS: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages', 'oscar.config.Shop', 'oscar.apps.analytics.apps.AnalyticsConfig', 'iirns.checkout.apps.CheckoutConfig', 'oscar.apps.address.apps.AddressConfig', 'iirns.shipping.apps.ShippingConfig', 'oscar.apps.catalogue.apps.CatalogueConfig', 'iirns.catalogue.reviews.apps.CatalogueReviewsConfig', 'oscar.apps.communication.apps.CommunicationConfig', 'oscar.apps.partner.apps.PartnerConfig', 'oscar.apps.basket.apps.BasketConfig', 'iirns.payment.apps.PaymentConfig', 'oscar.apps.offer.apps.OfferConfig', 'oscar.apps.order.apps.OrderConfig', 'oscar.apps.customer.apps.CustomerConfig', 'oscar.apps.search.apps.SearchConfig', 'iirns.voucher.apps.VoucherConfig', 'oscar.apps.wishlists.apps.WishlistsConfig', 'oscar.apps.dashboard.apps.DashboardConfig', 'oscar.apps.dashboard.reports.apps.ReportsDashboardConfig', 'oscar.apps.dashboard.users.apps.UsersDashboardConfig', 'oscar.apps.dashboard.orders.apps.OrdersDashboardConfig', 'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'oscar.apps.dashboard.offers.apps.OffersDashboardConfig', 'oscar.apps.dashboard.partners.apps.PartnersDashboardConfig', 'oscar.apps.dashboard.pages.apps.PagesDashboardConfig', 'oscar.apps.dashboard.ranges.apps.RangesDashboardConfig', 'oscar.apps.dashboard.reviews.apps.ReviewsDashboardConfig', 'oscar.apps.dashboard.vouchers.apps.VouchersDashboardConfig', 'oscar.apps.dashboard.communications.apps.CommunicationsDashboardConfig', 'oscar.apps.dashboard.shipping.apps.ShippingDashboardConfig', # 3rd-party apps that oscar depends on 'widget_tweaks', 'haystack', 'treebeard', 'sorl.thumbnail', 'django_tables2', 'mailer', 'extra', ] and this is my root url file: from django.conf.urls import url from django.contrib import admin from django.apps import apps from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('extra.urls')), path('', include(apps.get_app_config('oscar').urls[0])), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
How to create a separeate log file for each user logged in using Django?
Am new to DJango, how to create a new logger or log file on each user logon? how to access this logger to log user specific actions? And also, Need to close the logger on the user logout. Please share any ideas or examples if any? -
django-pytest with user-agent cant find request.user-agent
thanks for your time. i've got a app thats getting tested with pytest-django. although i've been facing some issues for the request function o views.py. at my views i've got some statements based on the request.user_agent(app installed django-user-agents) to select if will be displayed a mobile or desktop template. And those are getting me errors on pytest-django. views.py: def curriculo_view(request): context = {} if request.user_agent.is_mobile: return render(request, 'amp/Curriculo-mobile.html', context) elif request.user_agent.is_pc: return render (request, 'admin/Curriculo.html', context) else: return render (request, 'admin/Curriculo.html', context) test_views.py: def test_curriculo_view(self): path = reverse('curriculo') request = RequestFactory().get(path) response = views.curriculo_view(request) assert response.status_code == 200 error: def curriculo_view(request): context = {} > if request.user_agent.is_mobile: E AttributeError: 'WSGIRequest' object has no attribute 'user_agent' accounts\views.py:98: AttributeError i've tried to set like when i want to set a user (ex:request.user = User.objects.get()), tried to set to the key of request.META['USER_AGENT'] and none is getting me trough this. -
Cannot assign "'value'": "model.attr" must be a "model" instance
I am new en django, I have the next models in models.py class Persona(models.Model): cedula_p= models.CharField(primary_key=True, max_length=10) Nombre_p= models.CharField(User, max_length=100) fecha_nacimiento_p= models.DateField() #11111, User1, 01/01/1991 #22222, User2, 02/02/1992 #Others 13998 items def __str__(self): return "{0},{1}".format(self.cedula_p, self.Nombre_p) class Producto(models.Model): Nombre_prod = models.CharField(max_length=100) precio = models.PositiveIntegerField() def __str__(self): return "{0}".format(self.Nombre_prod) class compra(models.Model): cedula_prod= models.ForeignKey(Persona, max_length=10, on_delete=models.CASCADE) producto = models.ForeignKey(Producto, on_delete=models.CASCADE) The forms.py is: class formulario_compra(forms.ModelForm): cedula_prod = forms.CharField() #I have 14.000 elements, for that reason i don't use select o choicefield class Meta: model = compra fields = '__all__' #input test cedula_prod: 11111 or 22222 and the views.py class crear_persona(CreateView): model = Persona form_class = formulario_persona template_name = 'web1.html' success_url = reverse_lazy('EjemploVista1') class crear_compra(CreateView): model = compra form_class = formulario_compra template_name = 'Web2.html' success_url = reverse_lazy('EjemploVista2') in the forms, in formulario_compra i don't use the default form for cedula_prod because would be a list with some values (14000), so, I use a charField. I need to verify that the input exists in the model Persona.cedula_p. At the moment to try to save appear: Cannot assign "11111": "compra.cedula_prod" must be a "Persona" instance. I try different things, but I can't solve this situation. -
How to check email is already in database or not in django?
I want to add a functionality in registration form that if email is already in database than display massage ie this email is already register. i am trying this with the following code but this is not working accounts/forms.py from django.contrib.auth import get_user_model from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserCreateForm(UserCreationForm): # email = forms.EmailField() class Meta: fields = ["username","email","password1","password2"] model = get_user_model() def clean_email(self): email = self.cleaned_data.get('email') if email in User.objects.all(): raise forms.ValidationError("Only .edu email addresses allowed") return email def __init__(self,*args, **kwargs): super().__init__(*args, **kwargs) self.fields['username'].label = 'Display Name' # self.fields['email'].label = 'Email Address' -
How to get ManytoManyField's data from another model in Django?
I am here asking for guides on how to get ManyToManyField's data from another model. Let's say I have 3 models, Student, Course, and Attendance. Course model has a many to many relationship with Student. In CourseForm I set the widget of student to CheckBoxSelectMultiple so that user can check which student can get into that course in form. In another model called Attendance I also have a field which also has many to many relationship with Student. Now in my AttendanceForm on student field I want to display only the students who were selected when the Course was created. I think maybe we can do the queryset inside the AttendanceForm because right now the default queryset for student inside AttendanceForm is Student.objects.all() but I don't know how to do the queryset to get only the students who were selected when the Course was created. Can anyone help me please? models.py class Student(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) class Course(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) random_code = ShortUUIDField(default=code, editable=False) class Attendance(models.Model): teacher = models.ForeignKey(CustomUser, on_delete=models.CASCADE) student = models.ManyToManyField(Student) course = models.ForeignKey(Course, on_delete=models.CASCADE) forms.py class CourseForm(forms.ModelForm): class Meta: model = Course fields = ['student', 'random_code', ..] widgets = {'student': … -
Integrating Google Calendar into existing Django app
I'm currently trying to integrate Google calendar to a Django project I'm working on for my job (not a programming job originally but is going in that direction thanks to corona). I started learning programming very recently and we haven't had a very structured course for learning, so I'm pretty close to a beginner. I found plenty of resources on how to get started using the Google Calendar API but nothing on how to actually use it in the Django app, so I'm pretty much just winging it. For now I just need to have the site add an event to our calendar when a booking is made, I have a file with some copy-pasted code (the only changes I made were to get the event date and time from a booking in the database instead of inputting it manually), which will add the event when I run the file on its own. I've run into some problems trying to integrate it with the existing files. Below is that code (again, I'm still struggling to learn things so be kind) from __future__ import print_function from datetime import datetime, timedelta import pickle import os.path from googleapiclient.discovery import build from google_auth_oauthlib.flow import … -
Django-rules setup issue: has_perm always False for custom user model
I am new to Django. I have been trying to set up django-rules with a custom user model but keep getting a 404 when trying to access the page. Here is how the setup looks: Custom user model class User(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name = _('user') verbose_name_plural = _('users') id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) is_active = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def __str__(self): return self.email settings.py AUTHENTICATION_BACKENDS = ( 'rules.permissions.ObjectPermissionBackend', 'django.contrib.auth.backends.ModelBackend', ) installed apps INSTALLED_APPS = [ # ... 'rules.apps.AutodiscoverRulesConfig', ] rules.py @rules.predicate def is_organisation_member(user, organisation): """Check if user is an active organisation member""" m = get_if_exists( OrganisationMember, user=user, organisation=organisation, organisation__state=Organisation.LifecycleState.ACTIVE ) if not m: return False if not m.is_active: return False return True rules.add_perm('organisations.member', (is_authenticated & is_active & is_organisation_member)) views.py def get_organisation_by_slug(request, *args, **kwargs): return get_object_or_404(Organisation, workspace_name=kwargs['workspace']) @permission_required('organisations.member', fn=get_organisation_by_slug) def OrganisationView(request, workspace): # ... According to the debug, is_organisation_member returns True, but the user still gets a 404 error when trying to view the page (without django-rules permission_required decorator the page works). Any ideas why am I getting a 404 response? -
Django query: Item in model who is not in other model
Noob Django ORM question here: I have a model similar to this: class Company(models.Model): id = models.PositiveIntegerField(null=False, blank=False, primary_key=True) name = models.CharField(max_length=255, null=True, blank=True, default="") class Audited(models.Model): company = models.ForeignKey( Company, null=False, blank=False, on_delete=models.CASCADE, related_name="logs" ) city = models.CharField(null=False, blank=False, max_length=255) I have been scratching my head with this problem and I can not figure out how to solve it. Given a city, I need the company that do not have been audited on that city, so basically the Company who does not have a record on Audited with that city. So for example, if the city is New York, and there is no record in Audited with a company like Oracle and city as New York, I receive Oracle. It is very confusing to me because the ORM appears to have been designed for positive relations, like "the item from table A who has a record on Table B", and this is precisely the opposite. Any clue of how can I do this? -
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"> {% …