Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why i can't save data in mutiple query?
I read several posts here on this subject, I tried to apply them but I still have this lack of backup in my database and i don't know why. my code : models.py class Noms (models.Model) : n_soza = models.CharField(max_length=20) nom = models.CharField(max_length=100) particule = models.CharField(max_length=20, null=True, blank=True) prenom = models.CharField(max_length=100) .... def __str__ (self): return self.n_soza class Conjoint (models.Model) : c_soza = models.ForeignKey(Noms, on_delete=models.CASCADE, null=True, blank=True) conjoint1 = models.CharField(max_length=100, null=True, blank=True) conjoint2 = models.CharField(max_length=100, null=True, blank=True) conjoint3 = models.CharField(max_length=100, null=True, blank=True) def __str__ (self): return str(self.c_soza) import_xls.py noms = Noms( n_soza=nom_list[0], nom=nom_list[2], particule= nom_list[3], prenom=nom_list[4], .... ) noms.save() conjoint = Conjoint( c_soza = Noms.objects.get(n_soza=nom_list[0]), conjoint1 = nom_list[8], conjoint2 = nom_list[9], conjoint3 = nom_list[10], ) conjoint.save() I have an excel that I acquire as a list and part of the list fields go to a specific location in my database. when I run my code, "Noms" fills up correctly but the "Conjoint" remains completely empty. I tried : conjoint = Conjoint.objects.create( conjoint1=nom_list[8], conjoint2=nom_list[9], conjoint3=nom_list[10] ) conjoint.c_soza = Noms.objects.get(n_soza=nom_list[0]) conjoint.save() but without "conjoint.save()" instancies are create but not for field "c_soza" (it's normal) and with "conjoint.save()" my queryset "Conjoint" is empty I don't know why one works (Noms) and not the … -
ModuleNotFoundError: No module named 'Django-Banking-App.settings' when migrating my Django app to Heroku
I have been trying for two days to deploy my django app to heroku but stuck with the modulenotfound error. Think it might have something to do with my static files but I am not sure. I would forever appreciate someone helping me out with this Here is the error: $ heroku run python manage.py migrate Running python manage.py migrate on ⬢ bb-bank... up, run.4227 (Free) Traceback (most recent call last): File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 330, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 371, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/base.py", line 82, in wrapped saved_locale = translation.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 254, in get_language return _trans.get_language() File "/app/.heroku/python/lib/python3.8/site-packages/django/utils/translation/__init__.py", line 57, in __getattr__ if settings.USE_I18N: File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.8/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'Django-Banking-App.settings' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, … -
Django: add row to formset within template
I have a template that renders a formset where the user can add rows. I added a "add" button for the user to add row. However, I am not very familiar with javascript but clicking the button does not render anything. here is what the javascript code look like: function updateElementIndex(el, prefix, ndx) { var id_regex = new RegExp('(' + prefix + '-\\d+)'); var replacement = prefix + '-' + ndx; if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement)); if (el.id) el.id = el.id.replace(id_regex, replacement); if (el.Id) el.Id = el.Id.replace(id_regex, replacement); if (el.Date) el.Date = el.Date.replace(id_regex, replacement); if (el.Quantity) el.Quantity = el.Quantity.replace(id_regex, replacement); if (el.NetAmount) el.NetAmount = el.NetAmount.replace(id_regex, replacement); } function cloneMore(selector, prefix) { var newElement = $(selector).clone(true); var total = $('#id_' + prefix + '-TOTAL_FORMS').val(); newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() { var Id= $(this).attr('Id').replace('-' + (total-1) + '-', '-' + total + '-'); var Date= $(this).attr('Date').replace('-' + (total-1) + '-', '-' + total + '-'); var Quantity= $(this).attr('Quantity').replace('-' + (total-1) + '-', '-' + total + '-'); var NetAmount= $(this).attr('NetAmount').replace('-' + (total-1) + '-', '-' + total + '-'); var id = 'id_' + Id; $(this).attr({'Id': Id, 'id': id, 'Date': Date, 'Quantity': Quantity, 'NetAmount': NetAmount}).val('').removeAttr('checked'); }); newElement.find('label').each(function() { var forValue = $(this).attr('for'); if (forValue) { forValue … -
how to see attributes of User model when creating a model that has one to one relation?
I have a model for example Doctor model that has one to one relation to User model. When creating an instance of Doctor model, django says choose between existing users or create new user by clicking on plus button and create a new one. How to create user and a doctor at one time. I mean how can I show User form and Doctor form in a single page. (in the django administration panel) -
How do I get my handle function to run with the right arguments, (Django, bootstrap script)
Here is my code: class Command(BaseCommand): def handle(self, *args, **options): main_api_header = "https://pokeapi.co/api/v2/" specific_pokemon = f"{main_api_header}pokemon/" for name in pokemon_names: pokemon_stats = f"{specific_pokemon}{name}" response = requests.get(pokemon_stats).json() Pokemon.objects.create( [ Pokemon(name=f"{pokemon_stats}{['name']}"), Pokemon( front_normal_image=f"{pokemon_stats}{['sprites']}{['front_default']}"), Pokemon( front_shiny_image=f"{pokemon_stats}{['sprites']}{['front_shiny']}"), Pokemon( hp=f"{pokemon_stats}{['stats']}{[0]}{['base_stat']}"), Pokemon( attack=f"{pokemon_stats}{['stats']}{[1]}{['base_stat']}"), Pokemon( defense=f"{pokemon_stats}{['stats']}{[2]}{['base_stat']}"), Pokemon( speed=f"{pokemon_stats}{['stats']}{[5]}{['base_stat']}"), Pokemon( ability_One=f"{pokemon_stats}{['abilities']}{[0]}{['ability']}{['name']}"), Pokemon( ability_Two=f"{pokemon_stats}{['abilities']}{[1]}{['ability']}{['name']}"), Pokemon( type_One=f"{pokemon_stats}{['types']}{[0]}{['type']}{['name']}"), Pokemon( base_experience=f"{pokemon_stats}{['base_experience']}") ] ) With the above, I am getting the data I need, but if I run it like this, it says: TypeError: create() takes 1 positional argument but 2 were given (self, *args) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' (self) gives me: TypeError: handle() got an unexpected keyword argument 'verbosity' I think you get the idea, but I've been trying different arguments, and none of them work. Is it my syntax? Or is this not the way I can make this happen? -
Django: Best Practice for Storing Images (URLField vs ImageField)
There are cases in a project where I'd like to store images on a model. For example: Company Logos Profile Pictures Programming Languages Etc. Recently I've been using AWS S3 for file storage (primarily hosting on Heroku) via ImageField uploads. I feel like there's a better way to store files than what I've been doing. For some things (like for the examples above) I think it would make sense to actually just get an image url from a more publically available url than take up space in my own database. For the experts in the Django community who have built and deployed really professional projects, do you typically store files directly into the Django media folder via ImageField? or do you normally use a URLField and then pull a url from an API or an image link from the web (e.g., go on any Google image, right click and copy then paste image URL)? Hope this makes sense. Thanks in advance! -
Instead of form.save() update entry if already exists
So I'm building an auction site where users can bid on active listings. The lister can then choose to close the listing and all the bids that have been placed will appear and they can choose a winner. After a lot of tweaking, I've managed to get my placebid view set up and I'm quite happy with how it is working. The problem is if a user has already placed a bid, rather than a new bid is placed I want that existing bid to be located and then updated. What is currently happening is when I click to close the bid I am seeing several bids placed all by the same user which isn't very helpful. My functioning views.py looks like this: def placebid(request, id): listing_bid = get_object_or_404(Listing, id=id) highest_bid = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] or Decimal('0') currentHighest = Bid.objects.filter(bid_item_id=id).aggregate(Max('bid_input'))['bid_input__max'] listing = Listing.objects.get(pk=id) if request.method == "POST": bidform = BidForm(request.POST) if bidform.is_valid() and highest_bid == 0: bid_placed = bidform.cleaned_data['bid_input'] if bid_placed <= listing.start_price: messages.error(request, 'Make sure your bid is greater than the start price') return HttpResponseRedirect(reverse("listing", args=(id,))) else: newbid = bidform.save(commit=False) newbid.bidder = request.user newbid.bid_input = bidform.cleaned_data['bid_input'] newbid.bid_item = listing_bid newbid.time = timezone.now() newbid.save() messages.success(request, 'Bid placed succesfully') return HttpResponseRedirect(reverse("listing", args=(id,))) if … -
How can I change the name(s) of folders in my Django project without destroying its ability to find its own parts?
I'm reading through Two Scoops of Django and the authors note that best practices involve having a config folder and an apps folder. I've been building a Django project for the last few months here & there and want to get in the habit of complying with these practices, but when I change the name of my <project_name> folder (with the wsgi, settings, etc.), Django can't seem to find the contents of the folder anymore. How do I change this folder name and put the project apps into an app folder without breaking the connections they have? -
Do it exist a helper function how data_get (Laravel) in Django?
The data_get function retrieves a value from a nested array or object using "dot" notation: $data = ['products' => ['desk' => ['price' => 100]]]; $price = data_get($data, 'products.desk.price'); // 100 More detail in Laravel Doc -
Django How can I log client ip address?
I save the logs to the file with this configuration. But I could not log the client ip address. I also want to keep logs for 1 day. Is there a simple method for this? Does anyone have an idea about this? django-requestlogging I tried this library but failed. I do not know if it is up to date. Thanks LOGGING ={ 'version':1, 'loggers':{ 'django':{ 'handlers':['file','file2'], 'level':'DEBUG' } }, 'handlers':{ 'file':{ 'level':'INFO', 'class': 'logging.FileHandler', 'filename':'./logs/info.log', 'formatter':'simpleRe', }, 'file2':{ 'level':'DEBUG', 'class': 'logging.FileHandler', 'filename':'./logs/debug6.log', 'formatter':'simpleRe', } }, 'formatters':{ 'simpleRe': { 'format': ' {asctime} {levelname} {message} ', 'style': '{', } } } -
Django restframework nested serializing
A Django beginner here. My problem simplified: I have models Vocabulary and Transaltion and I want endpoint .../api/vocabulary/pk to return something like: { "name": "some vocabulary", ...other fields "translations": [ {"word": "some word", "tarnslation": "the word in other language"} {"word": "some word2", "tarnslation": "the word2 in other language"} ... ] } My current code: View: @api_view(["GET"]) def vocabulary(request, pk): vocab = Vocabulary.objects.get(id=pk) serializer = VocabularySerializer(vocab, many=False) return Response(serializer.data) Serializers: class TranlationSerializer(serializers.ModelSerializer): class Meta: model = Translation fields = "__all__" class VocabularySerializer(serializers.ModelSerializer): translations = TranslationSerializer(many=True) class Meta: model = Vocabulary fields = ("name", ...other fields, "translations") -
Django failed to load resuorcese of static file (net::ERR_ABORTED 404 (Not Found))
I have changed settings of the base directory(telusko) of my Django framework and also added {%load static%} in index.html but then also the console of chrome shows GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) code snippet of setting.py sitetravello contains all the HTML, CSS, js files and I have created assets for all the static file through cmd python manage.py collectstatic # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' STATICFILILE_DIRS = [ os.path.join(BASE_DIR, 'sitetravello') ] STATIC_ROOT = os.path.join(BASE_DIR,'assets') the main index.html file code is {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>Travello</title> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content="Travello template project"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="{% static 'styles/bootstrap4/bootstrap.min.css' %}"> <link href="{% static 'plugins/font-awesome-4.7.0/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css"> ERROR IN CHROME Failed to load resource: the server response with the status of 404(not found) ERROR IN CHROME CONSOLE GET http://127.0.0.1:8000/static/plugins/OwlCarousel2-2.2.1/owl.carousel.css net::ERR_ABORTED 404 (Not Found) -
Custom Drop-down into the Wagtail editor
How can i add the custom drop-down options, on click of which wagtail editor adds the option to the editor text ? -
Access Pgadmin4 in Production within dockerized django application
I'm not sure how much sense it would make, but I was learning docker to deploy Django app with Gunicorn + Nginx + AWS. So far, it works fine, where I have unit tested it in production. My question is how can I access pgAdmin4 now? docker-compose.staging.yml version: '3.8' # networks: # public_network: # name: public_network # driver: bridge services: web: build: context: . dockerfile: Dockerfile.prod # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:web command: gunicorn djangotango.wsgi:application --bind 0.0.0.0:8000 volumes: # - .:/home/app/web/ - static_volume:/home/app/web/static - media_volume:/home/app/web/media expose: - 8000 env_file: - ./.env.staging networks: service_network: db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.staging.db networks: service_network: # depends_on: # - web pgadmin: image: dpage/pgadmin4 env_file: - ./.env.staging.db ports: - "8080:80" volumes: - pgadmin-data:/var/lib/pgadmin depends_on: - db links: - "db:pgsql-server" environment: - PGADMIN_DEFAULT_EMAIL=pgadmin4@pgadmin.org - PGADMIN_DEFAULT_PASSWORD=root - PGADMIN_LISTEN_PORT=80 networks: service_network: nginx-proxy: build: nginx # image: <aws-account-id>.dkr.ecr.<aws-region>.amazonaws.com/django-ec2:nginx-proxy restart: always ports: - 443:443 - 80:80 networks: service_network: volumes: - static_volume:/home/app/web/static - media_volume:/home/app/web/media - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro labels: - "com.github.jrcs.letsencrypt_nginx_proxy_companion.nginx_proxy" depends_on: - web nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.staging.proxy-companion networks: service_network: volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d depends_on: - nginx-proxy networks: service_network: volumes: postgres_data: pgadmin-data: static_volume: media_volume: certs: html: vhost: I can access … -
Django Serializer getting attribute from another model
I am working just for my experience and I stacked with the following problem. There are three models: Book, Chapter, and Publisher. Each model is related to one another with the foreign key. class Book(models.Model): name = models.CharField(max_length=64) publisher = models.ForeignKey('Publisher', on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return self.name class Chapter(models.Model): name = models.CharField(max_length=128) book = models.ForeignKey(Book, related_name='books', on_delete=models.CASCADE) class Publisher(models.Model): title = models.CharField(max_length=128) description = models.TextField() def __str__(self): return self.title class Meta: ordering = ['title'] I want to serialize the data in PublisherDetailSerializer which should show their books and all chapters related to their books. Here are my serializers: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'name', 'publisher') def to_representation(self, instance): ret = super().to_representation(instance) return ret class ChapterSerializer(serializers.ModelSerializer): id = serializers.IntegerField() name = serializers.CharField(required=False) location = serializers.SerializerMethodField() class Meta: model = Chapter fields = ('id', 'name', 'location') def get_location(self, instance): serializer = BookSerializer(instance.author, context=self.context) return serializer.data class PublisherSerializer(serializers.HyperlinkedModelSerializer): books = BookSerializer(many=True, read_only=True) class Meta: model = Publisher fields = ('id', 'title', 'description', 'books') class PublisherDetailSerializer(PublisherSerializer): chapters = serializers.SerializerMethodField() class Meta: model = Publisher fields = ('id', 'title', 'description', 'books', 'chapters') def get_chapters(self, instance): serializer = ChapterSerializer(Chapter.objects.filter(location=instance.books.name), many=True, context=self.context) return serializer.data def to_representation(self, instance): ret = super().to_representation(instance) return … -
Error code: Unhandled Exception - pythonanywhere
the error log was to logn so I put it on pastebin I am not sure how to fix this at all any help is appriecated! heres the error log https://pastebin.com/raw/eZFSUXnX -
Is there any way I can access Django template variables and URL tags in a JS file so that the user can not inspect the data and links?
I want to excess Django template variables and URL tags from my javascript file. currently, I'm doing it like follows- <script> const addcommentlink = "{% url 'post:add_comment'%}"; const postid = '{{post.id}}'; const deletecommentlink = "{% url 'post:delete_comment' %}"; const editlikelink = "{% url 'post:edit_like' %}"; const profilelink = "{% url 'instagram:profile' 'name' %}"; </script> <script src="{% static 'post/js/post_details.js' %}"></script> but I want to access it directly from the post_details.js file. Is there any way to do that? -
Call function that uses newly created model object (instance) when save model object in DJANGO
class Experience(models.Model): teacher = models.ForeignKey(User, on_delete=models.CASCADE) classroom = models.ForeignKey(Classes, on_delete=models.DO_NOTHING, verbose_name ="Clase") project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, related_name="project_exp", verbose_name ="Experiencia") project_phases = ChainedManyToManyField( ProjectPhases, horizontal=True, verbose_name ="Fases de la experiencia", chained_field="project", chained_model_field="project") created_at = models.DateTimeField(auto_now_add=True, verbose_name = "Creado en") updated_at = models.DateTimeField(auto_now=True, verbose_name = "Actualizado en") class Meta: verbose_name = "Experiencia" verbose_name_plural = "Experiencias" default_related_name = 'experience' ordering = ['id'] def __str__(self): return f'Experiencia {self.id} - {self.project}' def save(self, *args, **kwargs): super(Experience, self).save(*args, **kwargs) ## Call a function with the newly created object @receiver(post_save, sender=Experience) def create_evaluations(sender, instance, **kwargs): if instance: create_experience_evaluation(instance) -
Package not found at IN heroku web application
I have a DJANGO web application which was deployed via heroku, it runs a particular process on media files. Whenever a user submits a form containing a file, the application saves the file in the database hence giving it a particular URL e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx. Once the file is saved, the application uses celery to perform some tasks on the saved file which will then be saved in my database. I was able to get celery working by including worker: celery -A myprojectName worker -l info in my Procfile, then heroku ps:scale worker=1 after git push heroku master as stated in the heroku docs. Everything seems to work fine, celery receives tasks from the redis server but it keeps logging the same type of error e.g (Package not found at '/app/media/documents/2020-10-08/test1.docx') and the web application doesn't perform the process.I am able download the file from the server by accessing the url e.g https://my-special-app-name.herokuapp.com/media/documents/2020-10-08/test1.docx, unfortunately I have no idea why celery is receiving the app url with (/app/) preceding everything and not performing the desired process.It worked fine in development with an example url of http://127.0.0.1:8000//media/documents/2020-10-08/test1.docx. I don't know how to fix the error and I will really appreciate your help. enter … -
Display fields from one model in another in Django Admin connected with a Foreignkey
I have two models, one for uploaded files and one for comments. I now want to display the comments in the Admin view of each uploaded file. So for example, if I upload a file TestFile1, once I click on it in the Uploaded view in Django admin, I want to have all of the comments associated with that file. Is this possible? class Uploaded(models.Model): objects: models.Manager() user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users") file = models.FileField(upload_to=user_directory_path) def __str__(self): return f"{self.description} {self.file}" class Comment(models.Model): objects: models.Manager() file = models.ForeignKey('Uploaded', on_delete=models.CASCADE, related_name='comments') text = models.TextField() def __str__(self): return self.text -
nginx as a proxy to react and django backend
Hello guys Im very new to nginx, recently I have been attempting to connect nginx to my django backend and react frontend but have been facing some issues. What im trying to achieve is that a user will be able to access my nginx proxy at port 8080 or the default port, and be served with my built react application. There after any api calls will then be routed to my django backend that is listening at port 8000. Here is my nginx config file : upstream api { server backend:8000; } server { listen 8080; location /test/ { proxy_pass http://api$request_uri; } location /api/ { proxy_pass http://api$request_uri; include /etc/nginx/uwsgi_params; } location /static/rest_framework/ { proxy_pass http://api$request_uri; } # ignore cache frontend location ~* (service-worker\.js)$ { add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'; expires off; proxy_no_cache 1; } location / { root /var/www/frontend; try_files $uri /index.html; } } and here is my docker-compose file for production: version: "3.7" services: postgres: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=user - POSTGRES_DB=user backend: build: ./backend volumes: - static_data:/vol/web env_file: - ./.env.dev depends_on: - postgres frontend: tty: true build: ./frontend command: ["yarn","build"] volumes: - ./frontend:/usr/src/frontend redis: restart: always image: redis:latest ports: - "6379:6379" … -
How to filter on a Sum() containing F()s?
Suppose I have those two models: class Category(models.Model): name = models.CharField(max_length=32) class Item(models.Model): category = models.ForeignKey('Category', related_name='items', on_delete=models.CASCADE) quantity = models.SmallIntegerField() price = models.DecimalField(max_digits=10, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) Then I'd like to query all categories to find out how each is performing with its items: (Category.objects.all() .annotate( sales_yesterday=Sum('items__quantity', filter=Q(items__created_at__date=yesterday)), revenue_yesterday=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()), sales_today=Sum('items__quantity', filter=Q(items__created_at__date=today)), revenue_today=Sum(F('items__price') * F('items__quantity'), output_field=DecimalField()) ) ) But revenue_yesterdayand revenue_today don't filter for yesterday and today respectively, unlike sales_yesterday and sales_today which do. Meaning the revenue_* annotations do their aggregations over the entire table and that's not what I want. The challenge I'm facing is how to apply those needed filters on my revenue_* annotations and one of the approaches I've tried is something similar to what I've done with my sales_* annotations: ( revenue_today=Sum(F('items__price') * F('items__quantity'), filter=Q(items__created_at__date=today), output_field=DecimalField()) ) Which only throws up an error: FieldError: Expression contains mixed types. You must set output_field. And I'm not sure what I should do since I already set output_field, and it's not clear to me if I'm putting that filter in the right place or in the right way inside Sum(). How do I solve this? -
Django one-to-one relationships and initial values
I´m learning to code and I´m trying to make a small app using Django. I have two models, Groups and Lists. The idea is that a user creates a Group, and then a List of students (which uses a formset). class Groups(models.Model): name = models.CharField(max_length=50) students_number = models.IntegerField() def __str__(self): return self.name class List(models.Model): name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) second_last_name = models.CharField(max_length=50) group = models.OnetoOneField(Groups, max_length=50, on_delete=models.CASCADE, default="Grupo") def __str__(self): return self.name All the students on that list should be assigned to the group you just created. I already set the one-to-one relationship, but in this way, the user has to choose the group for every student (it is supposed that ALL of these students belong to this group, so I think doing this repeatedly is unnecessary). This is the view: def addList(request): AddListFormSet = modelformset_factory(List, fields=("name", "last_name", "second_last_name", "group"), extra=2,) if request.method == "POST": form = AddListFormSet(request.POST) form.save() return redirect("/grupos") form = AddListFormSet(queryset=List.objects.none()) return render(request, "new_list.html", {"form": form}) How can I pre-assign the group that I just created for all the students that I capture in the next step? -
aggregate method in Django
I am new to Django and when i use Aggregate method , it returns something like {'max__age' : 35} but I need to display just the number (35 in this example). How can I solve it? Thanks all. -
No 'Access-Control-Allow-Origin' header is present on the requested resource React Django error
Access to fetch at 'http://localhost:8000/api/product/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.