Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Media file not being found in production Django-Heroku: returns 404 error
I have some default images in my media folder in Djang. However, on my website, I cannot see the images being displayed and I get a 404 error. Now my project folder tree is(project name is register): register -- live-static ---- static-root ---- media-root ------ defaults and my media and static files settings are: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] STATIC_ROOT = os.path.join(BASE_DIR, 'live-static', 'static-root') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'live-static', 'media-root') STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' And inside my urls.py in the same folder as wsgi.py I have: urlpatterns = [ """ My other urls """ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) My static files are loaded and the server can retrieve them, however, the images that I added to my folders in media-root are returning a 404 error by the server. Why is this happening as I have already also set STATICFILES_STORAGE as well? -
I am getting src(unknown) when calling an ImageField (pic) on a ForeignKey (handheld) DJANGO
I hope someone can help me out (newbie). I am getting src(unknown) when calling an ImageField (pic) on a ForeignKey (handheld) I see that I am able retrieve all the other values but not the models.ImageField via "cpu.handheld.pic.url", no errors in the python log. If I user for example "cpu.handheld.reg"_date works as you can see below: HTML/JINJA: <!-- Listing 1 --> <div class="col-md-6 col-lg-4 mb-4"> <div class="card listing-preview"> <img class="card-img-top" src="{{ cpu.handheld.reg_date }}" alt=""> <div class="card-img-overlay"> <h2> python log: [12/Sep/2020 21:51:35] "GET /static/css/style.css HTTP/1.1" 200 61 Not Found: /cpus/Sept. 12, 2020, 8:25 p.m. **[12/Sep/2020 21:51:35] "GET /cpus/Sept.%2012,%202020,%208:25%20p.m. HTTP/1.1" 404 3474** When using "cpu.handheld.pic.url" Starting development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. [12/Sep/2020 21:57:02] "GET /cpus/ HTTP/1.1" 200 8329 [12/Sep/2020 21:57:02] "GET /static/css/style.css HTTP/1.1" 200 61 enter image description here These are the two models: =======CPU from django.db import models from datetime import datetime from django.db import models from batt_serials.models import Battery from serials.models import Serial from sites.models import Site from status.models import Status class Cpu(models.Model): cpu = models.CharField(max_length=100) **handheld = models.ForeignKey(Serial, on_delete=models.DO_NOTHING)** battery = models.ForeignKey(Battery, on_delete=models.DO_NOTHING) site = models.ForeignKey(Site, on_delete=models.DO_NOTHING) status = models.ForeignKey(Status, on_delete=models.DO_NOTHING) reg_date = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.cpu ===================Device from django.db import models from … -
Python server 500 error when dealing with whitenoise
So i parked up a python website project for a month and now want to start back into it. Only problem is that I forgot the fine details of the project after a month. I had uploaded the python website online using: -Heroku -Gunicorn -Github -whitenoise -pipenv No coming back to the project i want to run it locally just to test a few things out. so I cd'd into the project folder an did python3 manage.py runserver. This threw a server error (500) song with a warning in my terminal saying warnings.warn(u"No directory at: {}".format(root)). I played around to try and fix it and found that if I removed the reference to whitenoise in my settings.py the website rendered with the same warning, but was visible. however my static files weren't being used (css). STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join('static'),) STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' I removed STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'. how can i fix my problem of the site not loading properly locally? -
Add count next to each aggregated value
I currently aggregate a query to get a unique list of strings used in my endpoint. As of now, the fetched data looks like this: { "data": [ "Beige", "Grey", ... ] } However, I'm attempting to do something like this: { "data": [ { name: "Beige", count: 7 }, { name: "Grey", count: 3 }, ... ] } Where count is the amount of times the value occurs in the datbase. Currently, my viewset is structured like this: class ProductFiltersByCategory(APIView): """ This viewset takes the category parameter from the url and returns related product filters """ def get(self, request, *args, **kwargs): """ Gets parameter in urls and aggregated filtered result """ category = self.kwargs['category'] aggregated_result = Product.objects.filter( category__parent__name__iexact=category, status='available' ).distinct().aggregate(data=ArrayAgg('colors__name', distinct=True)) return Response(aggregated_result) How do i go about making the key-value pair structure i want, as well as do the count for each "color"? -
"The submitted data was not a file. Check the encoding type on the form." validation error, despite uploading correct file (django rest framework)
I'm trying to create endpoint for uploading images, in my api, which i'm building with django rest framework. When I try to test the endpoint with postman, i'm getting response "image": [ "The submitted data was not a file. Check the encoding type on the form." ] with status code 400. When I try to print variable with image to console I get [<TemporaryUploadedFile: test.jpg (image/jpeg)>] I've checked out some tutorials and I think i'm sending the file correctly. That is my post man configuration that's the view class ImageView(APIView): parser_classes = (MultiPartParser, ) permission_classes = (IsAuthenticated, IsRestaurant) def post(self, request, *args, **kwargs): data = { 'image': request.data.pop('image'), 'info': request.user.info.pk } file_serializer = RestaurantImageSerializer(data=data) if file_serializer.is_valid(): file_serializer.save() return Response(status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) the serializer class RestaurantImageSerializer(serializers.ModelSerializer): class Meta: model = RestaurantImage fields = '__all__' and model class RestaurantImage(models.Model): info = models.ForeignKey(RestaurantInfo, related_name='images', on_delete=models.CASCADE) image = models.ImageField() def __str__(self): return self.image.name -
raise NodeNotFoundError
Please help me , I when deploy project on herokou server migrating I encountered this error While in my system there was no such error and the project was working properly Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, i n execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 395, i n execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 328, in ru n_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 369, in ex ecute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/base.py", line 83, in wra pped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/commands/migrate.py", lin e 86, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in _ _init__ self.loader = MigrationLoader(self.connection) File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __i nit__ self.build_graph() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 274, in bu ild_graph raise exc File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/loader.py", line 248, in bu ild_graph self.graph.validate_consistency() File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 195, in val idate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 195, in <li stcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "/app/.heroku/python/lib/python3.7/site-packages/django/db/migrations/graph.py", line 58, in rais e_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration account.0001_initial dependencies reference nonexistent parent node ('auth', '0013_auto_20200828_2241') Where is the error problem? -
How to make DRF GenericViewSet async
I know one shouldn't do long lasting tasks in the main thread, nevertheless I did it... ;-) Now since Django 3.1 there is the possibility to make functions async. I was wondering if this is a way to improve my bad code. IF it is how can I make this DRF View async? class ExportViewSet(mixins.RetrieveModelMixin, viewsets.GenericViewSet): permission_classes = (IsAdminUser,) queryset = myObjects.objects.all() def list(self, request): # this takes very long return response -
display category title in django
I am trying to display the title for the category if it has a title that I want to display, but what happens is that it displays all the titles for the categories #models class category(models.Model): name = models.CharField(max_length=255) head_titel = models.CharField(max_length=255) titel = models.TextField(max_length=1000) def __str__(self): return self.name def get_absolute_url (self): return reverse('store') class Product(models.Model): name = models.CharField(max_length=200) price = models.DecimalField(max_digits=7,decimal_places=2) category = models.CharField(choices=choice_list,max_length=255) def __str__(self): return self.name @property def imageURL(self): try: url = self.image.url except: url = '' return url #view def CategoryView(request,cats): data= cartData(request) cartItems = data['cartItems'] cat_menu = category.objects.all() Category_Post = Product.objects.filter(category__iexact=cats.replace('-' ,' ')) cate = Product.objects.all() return render (request,'store/catogrise.html',{'cats':cats.title().replace('-',' ') , 'Category_Post':Category_Post,'cat_menu':cat_menu,'cat_menu':cat_menu,'cartItems':cartItems,'cate':cate}) #template {% for cate in cat_menu %} <div class="cartEmpty"> <h4>{{cate.head_titel}}</h4> <div class="CartEmpaty"> <small class="a-size-Cart"> <p>{{cate.titel}}</p></small> </div> </div> {% endfor %} -
Dynamically move an item from one list to another in Django
I'm trying to create a simple interface for a recipe app where there is a list of ingredients and when an ingredient is clicked, it moves from the "Ingredient" column to the "Meal Ingredients" column. I'm trying to do this in a simple way of just clicking a button, the ingredient, and moving it to a different column. I'm new to JavaScript, JQuery, and AJAX, so I'm not quite sure how to piece it together, but this is what I have so far in a template: {% block title %}Home{% endblock title %} {% block content %} <div class="container"> <div class="text-center"> <h1>Create a Meal</h1> </div> <div class="row"> <div class="col"> <div class="text-center"> <h3>Ingredients</h3> <div class="text-left"> <ul> {% for ingredient in ingredients %} <div class="row"> <button id="btnName" class="btn my-1">{{ ingredient.name }}</button> </div> {% endfor %} </ul> </div> </div> </div> <div class="col-8"> <div class="text-center"> <h3>Current Meal</h3> </div> <div class="row"> <div class="col"> <div class="text-center"> <h4>Meal Ingredients</h4> <div class="text-left"> <ul class="justList"> </ul> </div> </div> </div> <div class="col"> <div class="text-center"> <h4>Amount(g)</h4> </div> </div> </div> </div> </div> </div> <script> $('#btnName').click(function(){ var text = 'test'; if(text.length){ $('<li />', {html: text}).appendTo('ul.justList') } }); </script> {% endblock content %} I'm able to add the "test" string to the new list, … -
migrating django3.1 project in pythonanywhere error
enter image description here Hi, im trying to migrate a django3.1 project on python anywhere. it does not seem to work. thanks for the help in advance -
Django - Min/Max values not displaying on Index
I'm calculating the min and max values so I can display the spread of RRPs for a car model. Here I just have the min value, which is being calculated correctly but it will not display to the index file using the guidance I got from various examples/sites. Greatly appreciatte any help. Models.py class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True, default=False) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' class MotorModelsV2(models.Model): MotorMakeName = models.CharField(max_length=50, default=False,) MotorModelName = models.CharField(max_length=50, default=False,) Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False) Mlid = models.IntegerField(default=False, unique=True) MotorImage = models.ImageField(upload_to='Car_Pics', default=False,blank=True) def __str__(self): return self.MotorModelName or '' def __unicode__(self): return u'%s' % (self.MotorModelName) or '' class Meta: ordering = ('MotorMakeName',) class MotorDetail(models.Model): MotorMakeName = models.CharField(max_length=50, default=False,) MotorModelName = models.CharField(max_length=50, default=False,) title = models.CharField(max_length=100, default=False,) fuel = models.CharField(max_length=25, default=False,) body = models.CharField(max_length=25, default=False,) engine = models.CharField(max_length=5, default=False,) #Mkid = models.CharField(max_length=5, default=False,) #Mlid = models.CharField(max_length=5, default=False,) Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False, null=True) Mlid = models.ForeignKey(MotorModelsV2,on_delete=models.CASCADE, default=False, null=True) RRP = models.DecimalField(max_digits=10, decimal_places=2, default ='0' ) MotorImage = models.ImageField(upload_to='Car_Pics', default=False,blank=True) def __str__(self): #return self.title or '' return '%s %s %s' % (self.MotorMakeName,self.MotorModelName, self.title,) or '' def __unicode__(self): return u'%s' % (self.title) or '' class Meta: ordering = ('MotorMakeName',) View.py def … -
importing moviepy package errors in django view file
I'm working on Django rest API. On one of the endpoints, the user uploads a video and I want to resize it after that. According How To Resize a Video Clip in Python I want to use moviepy package. I've installed moviepy package with pip but I get an error on import moviepy.editor as mp which I added on top of view.py file. Error message is: ModuleNotFoundError: No module named 'moviepy'. The weird thing is when I open python console and I type the exact same line I don't get any errors. what should I do? -
TypeError: argument of type 'WindowsPath' is not iterable when i try to use a module in django
I was working on this other Django project and i was facing this error saying TypeError: argument of type 'WindowsPath' is not iterable when i try to use a module in django when I''m trying to use modules such as requests and BeautifulSoup So i found it helpuful to post it on this community maybe someone can face the same exception in the future and i fixed it by going to the settings and change instead of using the os module i used the pathlib and i modified my setting.py and looks as follows: settings.py from pathlib import Path BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "newsapp1" ] MIDDLEWARE = [ ... ] ROOT_URLCONF = 'newsapp.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [Path.joinpath(BASE_DIR, 'templates')], #i made the changes here!!! 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'newsapp.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] ..... Thanks guys hope this will … -
Unit testing in Django & Django Rest Framework to get 100% code coverage on SonarQube
It is the first time I'm writing unit test cases I'm not much aware what all I need to test because we're using SonarQube application for code quality and etc and in SonarQube for our Django & DRF project it's showing most of the lines are not covered by unit test cases (for ex settings.py, serializers.py and etc) I was going through Django & DRF testing docs and I found that it was all about testing views (kind of integration testing). I have already written a lot of code and now I want to unit test whatever code I've written (like serializers, APIViews, URLs, models and etc) Also I read one post about testing serializers on Stack Overflow, that we don't need to write any unit test for serializers and all. Because django already does it for us. If that is the case could anyone please advise/suggest me what and all I need to test in order to get 100% code coverage on SonarQube. Kindly excuse if the question is repeated or it is an off topic question. -
Static files not found when Docker container is running in Django React app
I am trying to run my Docker image to see it on my browser yet all that appears is an empty screen, upon inspection I see the following errors: [2020-09-12 17:31:42 +0000] [12] [INFO] Starting gunicorn 20.0.4 [2020-09-12 17:31:42 +0000] [12] [INFO] Listening at: http://0.0.0.0:8000 (12) [2020-09-12 17:31:42 +0000] [12] [INFO] Using worker: sync [2020-09-12 17:31:42 +0000] [14] [INFO] Booting worker with pid: 14 Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js Not Found: /static/css/2.7253a256.chunk.css Not Found: /static/css/main.a85cbe2c.chunk.css Not Found: /static/js/2.8ba00362.chunk.js Not Found: /static/js/main.8eee128b.chunk.js The commands I have run are: docker build . -t projecthub and docker run -d -p 8000:8000 --name theprojecthub projecthub:latest I am very unsure why these static files are even being looked for, I cannot seem to find any reference to them in my code. Does anybody know what I should do? -
Using get_absolute_url in a QuerySet
I'm trying to create a serialized JSON response with names array field and the absolute url of my Host model. I tried adding absolute_url to the values method in views.py but Django gave me an error because it is not a field name. How do I get the value returned by get_absolute_url into my serialized JSON response? Current JSON response { "hosts":[ { "names":[ "a.example.com" ] }, { "names":[ "b.example.com" ] } ] } Desired JSON response { "hosts":[ { "names":[ "a.example.com" ], "url": "/explore/example.com/e7ad4069-7fe5-447d-895d-633ce59d5f49" }, { "names":[ "b.example.com" ], "url": "/explore/example.com/a79b677d-ab26-46ea-83a5-ca54a3f2566e" } ] } views.py class TestApiView(View): def get(self, request, domain_name): data = list(Host.objects.filter(domain__name__exact=domain_name).values('names')) return JsonResponse({'hosts': data}) models.py class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) names = ArrayField(models.CharField(unique=True, max_length=settings.MAX_CHAR_COUNT), default=list, null=False) domain = models.ForeignKey(Domain, on_delete=models.CASCADE) class Meta: ordering = ['names'] def __str__(self): return "[Host object: id = {}, names = {}, domain = {}]".format(self.id, self.names, self.domain) def __repr__(self): return "[Host object: id = {}, names = {}, domain = {}]".format(self.id, self.names, self.domain) def __eq__(self, other): if isinstance(other, Host): return sorted(self.names) == sorted(other.names) return False def __hash__(self) -> int: return hash(tuple(sorted(self.names))) def __lt__(self, other): return self.names[0] < other.names[0] def get_absolute_url(self): return '/explore/{}/{}'.format(self.domain.name, self.id) -
Pass data form from database to modal Django
My teacher gave me schoolwork on how to pass data table to modal class in Django. I just want to display the profile click in table to modal. Any help can make me grateful thanks.I'm just a newbie here and since it was almost 2 weeks I've been starting learning django Below is my currently code and it's not working. Before | modal after accounts.html <table style="width: 100%;" id="example" class="table table-hover table-striped table-bordered"> <thead> <tr> <th>Action</th> <th>Firstname</th> <th>Lastname</th> <th>Email</th> <th>Username</th> <th>Date joined</th> </tr> </thead> <tbody> {% for user_information in user_information %} <tr> <td><a class="btn btn-info" class="open-modal" href="{{ user_information.id }}">Edit</a></td> <td>{{user_information.first_name}}</td> <td>{{user_information.last_name}}</td> <td>{{user_information.email}}</td> <td>{{user_information.username}}</td> <td>{{user_information.date_joined}}</td> </tr> {% endfor %} </tbody> </table> <div id="modal-div"></div views.py def edit(request,id): user = auth.authenticate(id=id) return render(request, 'accounts.html',{'user_information':user,'successful_submit': True}) js <script > var modalDiv = $("#modal-div"); $(".open-modal").on("click", function() { $.ajax({ url: $(this).attr("data-url"), success: function(data) { modalDiv.html(data); $("#exampleModal").modal(); } }); }); </script> -
Drop down selection on non-model form on form error
I've created a non-model form. with a modelchoicefield class BookingFormSetupForm(forms.Form): paymentmethod = forms.ModelChoiceField(queryset=PaymentMethod.objects.none(),required=False) I'm running into a problem whereby when a user selects a value on the modelchoicefield and then interacts with the rest of the form, but doesn't enter something correctly on one of the other form fields, an error on the form is thrown on save (which is good), but when the form reloads with the error message being displayed, the value that the user had selected on the modelchoicefield is no longer selected (this is bad). What is selected is the value that was last saved to this field. Is there a way to have the users previous selection be selected on the reload of the page when an error is displayed? Thanks! -
Django: How do you get user id on model.py page and set dynamically a default value
I have 2 models(Model Projects and Model Variables) in two apps (Projects app and Variables app). The models are not related in any ways. I want to set the default value in Projects with value in Variables Model Projects: class Projects(models.Model): completion_time = models.FloatField(default='0') Model Variables: class Variables(models.Model): user_var_id = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) internal_completion_time = models.FloatField(default='0') I want users to set a value in the variables and when they create a new project they would have that value from the variables be set as a default value for a new project by default. eg how could i do something like this variable = Variables.Objects.Get(user_var_id=current_user_id-that i dont know how to get) class Projects(models.Model): completion_time = models.FloatField(default=variable.internal_completion_time ) I thought it could be done by adding dynamically the default value, querying the variables filtering for the user and adding the value to the model but i dont know how to get the current user id on the model.py page. How can i do this maybe with another method. -
How to show icon in Django?
I gave the script of the font awesome to my head of the HTML but it is showing the squares instead of the icons. Code is : <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <link rel="stylesheet" href="{% static "all.css" %}"> <link rel="stylesheet" href="{% static "bootstrap.css" %}"> <link rel="stylesheet" href="{%static "style.css" %}"> <link href="https://fonts.googleapis.com/css2?family=Candal&family=Lora&display=swap" rel="stylesheet"> <title>Online yuridik xizmatlar</title> <script src="//code.jivosite.com/widget/pvNOxCEa74" async></script> <!--Font Awesome --> <script src="https://use.fontawesome.com/6cd0e4d425.js"></script> <style> #loader{ position: fixed; width: 100%; height: 100vh; background: #000000 url('../static/contact/images/Infinity-1s-200px.gif') no-repeat center; z-index: 99999; } </style> </head> -
Firebase or Django for a social network app
Good Morning. I have an idea about a social network and I have some knowledge of web application development. The fact is that I have serious doubts about how to design the app; the application would be for Android and would connect to the server. I was thinking and looking for information about firebase hosting, but I have no experience with that. Instead, I have experience with Django. What do you recommend for me to develop the backend, develop it in Django and run it on a server or use firebase services? I have to say that I'm in college and I don't mind using something I haven't used before; precisely, my goal is to learn. Perhaps I am very wrong in everything, I would like to read other alternatives. The volume of users would not be excessively large, and the volume of data to be stored would be basic data and a few photos per profile created. -
How to Get Data Out of a Django Model and in to the HTML Template
I have an AttendanceReport model where staff register information such as the feedback and the number of hours worked "nbr_heures" My model: class AttendanceReport(models.Model): id=models.AutoField(primary_key=True) consultant_id=models.ForeignKey(Consultant,on_delete=models.DO_NOTHING) mission_id=models.ForeignKey(Mission,on_delete=models.CASCADE,null=True) session_year_id=models.ForeignKey(SessionYearModel,on_delete=models.CASCADE, null=True) nbr_heures = models.IntegerField(blank=False) feedback = models.TextField(max_length=255,null=True, default="") created_at=models.DateTimeField(auto_now_add=True) updated_at=models.DateTimeField(auto_now_add=True) objects=models.Manager() I'm trying to the sum the values of 'nbr_heures' How can i properly do that ? I tried this but its not working.. hours_count=AttendanceReport.objects.annotate(nbr_heur=Sum('nbr_heures')) Thank you in advance. -
Search bar using Django to search in a JSON file?
I am trying to create a search bar that searches in a JSON file that has previously been added to a table using Django views and HTML. The JSON file is directly added from the user. This is part of the Django views: if url_parameter: music = context["music"].filter(name__icontains=url_parameter) else: music = context["music"] if request.is_ajax(): html = render_to_string( template_name="music_table.html", context=context ) data_dict = {"html_from_view": html} return JsonResponse(data=data_dict, safe=False) return render(request, "index.html", context=context) The Django view has to be the same for the upload and the search. The search is live so that it automatically changes what displayed in the html table. -
Django localhost redirected you too many times "ERR_TOO_MANY_REDIRECTS" when trying to signin
in my project i had two views in two separate templates for some reason i needed those two views in a single template that already has a view after i added them i started facing this issue when i removed them it stopped note that those two views were working properly when it was in two separate templates in my views.py here is the view that has those two views that were separate i'll be pointing to them with comments from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout as django_logout from django.urls import reverse from .models import * from .forms import * def home(request): user = request.user # it had only this creating a post part form = TextForm() if request.method == "POST": form = TextForm(request.POST) if form.is_valid(): obj = form.save(commit=False) author = User.objects.filter(email=user.email).first() obj.author = author form.save() form = TextForm() texts = Text.objects.all().order_by('-id') # here is the other view that i added it's for signing in if user.is_authenticated: return redirect("home") if request.POST: signin_form = SigninForm(request.POST) if signin_form.is_valid(): email = request.POST['email'] password = request.POST['password'] user = authenticate(email=email, password=password) if user: login(request, user) return redirect("home") else: signin_form = SigninForm() # and here is the other one,it's for signing … -
How to properly design a database for rating system with multiple rating criterias
I am doing rating system on my current django project and I need to implement database for rating. Database would be simple, if I didn't have multiple rating criteries, now I have to ask: How would you design a database with these objects: User RatedObject Rating there will ofcourse be multiple users and objects to be rated AND multiple rating criterias. Now my current idea would be to go for few separate tables with each of the objects such as: USER(pk=id, fk= rating.id) RATED_OBJECT(pk=id, fk= rating.id, overall_attribute_1, overall_attribute_2, overall_rating) RATING(pk=user.id, pk=rated_object.id, fk=rated_attribute1, fk=rated_attribute2) RATED_ATRIBUTE(pk=id, fk=type, value) TYPE(pk=id, name) - 2 types since we have 2 attributes to be rated (now overal_rating will be average of all overall attributes and each overal attribute will be average of all attributes of one type from ratings, where the id of rated object will be same) I have a bad feeling about doing this 'multiple-FK-to-one-PK' operation. Would it make more sence to make table for each rated attribute? Or maybe say **** it and have values in the RATING itself and screw RATED_ATTRIBUTE and TYPE table? What do you guys think?