Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset not JSON serializable
I am trying to pass a formset as JSON data but i am getting Object of type HabitFormFormSet is not JSON serializable. Why is that ? my view: def modal_view(request): HabitFormSet = modelformset_factory( Habit, extra=0, form=HabitModelForm) formset = HabitFormSet( request.POST, queryset=Habit.objects.filter(user=request.user), ) new_habit = HabitModelForm(request.POST) if formset.is_valid(): formset.save() data = {"formset": formset} return JsonResponse(data) return HttpResponseRedirect(reverse('home')) -
How to handle user authentication in django without relying on user models?
I'm working on an assignment. I'm using Django as the front end. The course is focused on databases and I cannot rely on Django's ORM features(including models). I have to write raw SQL queries for everything I do. I know that Django has a user model but I cannot rely on it for querying user info. The problem is that I still need to authenticate users. I could get away with storing user credentials on user models and add a field to store the SQL primary key for the info in there and use that for the queries but that is not a full solution. The rest of the framework seems to be coupled with the user model so I'm unsure as to whether it is even possible to do it without user models. -
Serving a django model containing objects
I have following django model: class Weather(models.Model): lat_lng = gis_models.PointField() raw_data = psql_fields.JSONField(null=True) I have following view: def weather(request): data = WeatherModel.objects.all() js_data = serializers.serialize('json', data) return HttpResponse(js_data, content_type='application/json') It throws error saying 'Point object is not json serializable.' I want this function to return json. Please help. -
How to integrate django with react and webpack to create a multipage webapp?
I have a django project, now I want to integrate react with it in such a way that routes or urls should be handled by django and other stuff inside the body should be handled by react and its components. For example: /profile/ is route which is served by django and after it has loaded everything all the crud operation could be done by react. One more thing I want all the static files should be generated by webpack, which will served by django -
Generate different checkboxes inside a loop html
Right now i'm working in my first python - django project's front end, and i'm having some trouble with the table i'm using to show data from my db. The thing is that i wanted to put a checkbox at the first column of the table at every row, but since i don't know how many registers will there be, i created a checkbox on the first column inside the loop that i'm using to show the registers. And every checkbox of the table that i click makes reference to the checkbox thats on the first register of the table. (If i click the 3rd's row checkbox, it would check the first row's one, and if i click the 5th's row table, it would uncheck the first row's one.) here is my code. HTML: {% for dominios in dominios %} <tr style="height: -2px;"> <td style="text-align:center;"> <div class name="checkboxWrapper"> <input type="checkbox" id="check" hidden="true" style="margin-top: 10px;"/> <label for="check" class="checkmark" ></label> </div> </td> <td style="color:#A9A9A9;">{{dominios.id_dom}}</td> <td style="color:#A9A9A9;">{{dominios.nombre_activo}}</td> <td style="color:#A9A9A9;">{{dominios.desc_act}}</td> <td style="color:#A9A9A9;">{{dominios.dat_cont_arch}}</td> <td style="color:#A9A9A9;">{{dominios.resp_dom}}</td> <td style="color:#A9A9A9;">{{dominios.estado}}</td> {% endfor %} So what i want to do is every checkbox unique, so i can select the register with the checkbox. I hope someone can help me … -
How do I read all the images with a specific prefix in django?
I am building a Face Recognition system. All the detected faces are stored in a directory. (Its stores both known and unknown) I want to create a log of all the unknown faces. The unknown faces are stored with a prefix unknown_2203.png My Question how do I fetch the unknown.pngs from that directory and show them on a django template? Any help would be great! -
How to replace python 2.7.16 to python 3?
MacBook-Pro:~ bsr$ pip install django DEPRECATION: Python 2.7 reached the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 is no longer maintained. A future version of pip will drop support for Python 2.7. More details about Python 2 support in pip, can be found at https://pip.pypa.io/en/latest/development/release-process/#python-2-support Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: django in ./Library/Python/2.7/lib/python/site-packages (1.11.29) Requirement already satisfied: pytz in /System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python (from django) (2013.7) Due this error unable to install the djengo. pip install django -
Django keeps on putting quotes around table name in mysql query and the query wont work
Table name in MySql is usercreds and the query that django generates works without the quotes around the table name. The model is created using inspectdb command from django, Im trying to django admin panel as a db manager. models.py: # This is an auto-generated Django model module. # You'll have to do the following manually to clean this up: # * Rearrange models' order # * Make sure each model has one field with primary_key=True # * Make sure each ForeignKey has `on_delete` set to the desired behavior. # * Remove `managed = False` lines if you wish to allow Django to create, modify, and delete the table # Feel free to rename the models, but don't rename db_table values or field names. from django.db import models class Usercreds(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=20, blank=True, null=True) password = models.CharField(max_length=20, blank=True, null=True) class Meta: managed = False db_table = 'usercreds' settings.py: """ Django settings for admindb project. Generated by 'django-admin startproject' using Django 2.2.11. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) … -
What is the correct solution for uploading images to s3 asynchronously using zappa? (aws serverless)
env django zappa boto3 (s3) The flow what i envisioned is as next User append images by website(input file html) and submit. zappa lambda receive the images and toss to s3 upload function asyncly. website waiting uploaded image and show image url. Two ways to upload images save image to local -> upload(saved_img) encode to byte -> stream as byte problem In the case of the Async function, the / tmp folder seems to point to a different physical location. Save is possible, but cannot be recalled. There is a limit to the number of characters in sns when streaming in bytes. Long files such as images cannot be put in arg. Is there any other good way to upload images to Async? -
how to create a main vue component to communicate with page related components with no npm (with django and django rest framework)
I have coded an IMDB clone website with django and vue via cdn. The vue ui is enhanced with vuetify and the json rest api created by django rest framework is get, put, post or delete by axios. There is no npm or webpack depency and configuration. The repo is installed as a usual django application. I have uploaded the repository with dummy data to github, the link is below. the requirements.txt file has all the django related versions. vue and vuetify versions are 2.x The reason of using vue is to enable inteactive ui. The ultimate aim is to create an alternative admin interface using vue like plain old jquery via cdn. For now, the project runs quite well. However, I have to write all vue component code to all pages. I copy & paste, then change some state related stuff (data) and add or remove some methods. Those components change according to model fields and relation with other models. The main skeleton is same. I have experienced zillions of trials and errors, but I couldn't achieve the way to interact many page related components communicate with one main component. All vue codes exist in templates folder and there … -
I AM GETTING CONFUSED WHEN TO USE ONE TO MANY AND FOREIGN KEY RELATIONSHIP IN DJANGO
Imagine i have a student who can have many academic details,so in this case which one should i use between foreign key and one to many relationship -
Pip shows web socket error and I cannot install any packages
I tried installing django but didn't work. Instead it gave me this error... WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError(': Failed to establish a new connection: [WinError 10013] An attempt was made to access a socket in a way forbidden by its access permissions')': /simple/django/ ERROR: Could not find a version that satisfies the requirement django (from versions: none) ERROR: No matching distribution found for django I tried to install other packages and modules but none of them could be installed. I reinstalled python and while doing that I lose all my previous packages. I had a project with PyQt5 which I could install successfully two weeks ago but after I reinstalled python my packages, modules, etc. where gone and now pip won't work I don't know why. I tried changing my network and tried using my phone's hotspot but it didnt solve the problem. I tried giving the version name of the packages but that didn't work either. My network doesn't have a proxy or is not connected to a vpn. I can download any other stuff but I just cannot download stuff with pip. Thanks in advance! -
Django--complex context or complex template?
I'm rather new to the Django world and am converting an existing Java/Javascript app to Django. The existing app has many complex queries and conditionals. I can solve most of those in the template, but it is starting to get ridiculous. Generally, is it better to put the database hits in the view and have a more complex context to pass to the template or simplify the context and burden the template? Or does it matter? Some quick figures--the database has 44 tables 16 of which are M2M join tables. There are four report templates--the only one I've tackled hits seven different tables. So far, I've found testing things in the template is quicker and more reliable than testing in the view class. But I'm inclined to push more of the logic back to the view and pass a more complex context to the template. Just wondering which way more experienced Django hands go.... -
Page not found (404) Request Method: GET
I keep getting this error: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/home Using the URLconf defined in personal_portfolio.urls, Django tried these URL patterns, in this order: admin/ home/ The current path, home, didn't match any of these. This is my urls.py for the overall project from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('home/', include('hello_world.urls')), ] this is my code for hello_world urls.py from django.urls import path from hello_world import views urlpatterns = [ path('home/', views.hello_world, name='hello_world'), ] this is my code for hello_world views.py from django.shortcuts import render def hello_world(request): return render(request, 'hello_world.html') -
Unable to install django, i get JWT error
When I try to install django (on Google cloud) I get this message: File "/root/lplatform/back/lplatform_api/urls.py", line 3, in <module> from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView ModuleNotFoundError: No module named 'rest_framework_simplejwt' this is my url.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('lplatform_api.urls')) ] and this is my setting.py: REST_FRAMEWORK = { "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", 'rest_framework.authentication.BasicAuthentication' , 'rest_framework.authentication.SessionAuthentication', ), } -
Django: non primary-key auto incremented field
is there a possible way to create a non primary-key auto incremented field like a AutoField/BigAutoField that is not prone to failure(duplicated ids, ...) ? -
Django : Difference between django-admin.py and django-admin
Okay here's the catch. When I create a django project with django-admin.py startproject myproject and starts server like python3 manage.py runserver, it all works fine. However, when I create project with django-admin startproject myproject and starts server like python3 manage.py runserver, it gives me tonnes of system check errors like : django.core.exceptions.ImproperlyConfigured: Passing a 3-tuple to include() is not supported. Pass a 2-tuple containing the list of patterns and app_name, and provide the namespace argument to include() instead. or django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E408) 'django.contrib.auth.middleware.AuthenticationMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E409) 'django.contrib.messages.middleware.MessageMiddleware' must be in MIDDLEWARE in order to use the admin application. ?: (admin.E410) 'django.contrib.sessions.middleware.SessionMiddleware' must be in MIDDLEWARE in order to use the admin application. -
How to create a elasticbeanstalk database with 'eb create'
I'm trying to create an ElasticBeanstalk environment using the 'eb create' command for the django-python application I'm developing. All the default necessary aws-infastructures are created. (e.g. cloudformation, loadbalancer, targetgroups, ec2-instance and so on). My application uses a postgresql database. I'm using the following DATABASE-definition in my productive-settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], }} Which uses the default environment-variables, provided by default if the elasticbeanstalk-enviroment creates a database. I tried to automate the creation of the database using the ebextensions as described here I tried the following steps to create the database automated when executing 'eb create': I added the following entries to my '01_container.config' in the '.ebextensions' directory, which by the way is definitely used (because I manipulate other values here and they are correctly changed in the elasticbeanstalk-container-configuration) option_settings: aws:rds:dbinstance: DBEngine: postgres DBEngineVersion: 9.6.16 DBUser: 'anyuser' DBPassword: 'anypassword' I also tried to set the same values using the 'Configuration files' and 'JSON document' described approaches here and none of these worked So what I need to do is to execute 'eb create', let it fail with the KeyError: 'RDS_DB_NAME'. Go to the elasticbeanstalk-environment, I just created and … -
How to get AWS static file urls from Javascript?
I'm trying to get the urls to a few static images from my AWS S3 bucket. I have a couple of javascript functions that change the image a user clicks on (clicking on a like button turns it green). I'm having trouble getting those images to work. The farthest I've gotten was getting a 403 error (Forbidden), and I'm not entirely sure why. Right now, I'm defining a few url variables in script tag and calling them in my JS function. Defining variables: <script> var is_bookmark_url = "{% static 'img/is-bookmark.svg' %}"; var bookmark_url = "{% static 'img/bookmark.svg' %}"; var like_button = "{% static 'img/like-button.svg' %}"; var liked_button = "{% static 'img/like-button-liked.svg' %}"; </script> Calling Variables in JS Function: function changeLike(id) { el = document.querySelector('#' + id) source = el.src if (source.substring(source.length - 26) == "/img/like-button-liked.svg" || source.substring(33, 59) == "/img/like-button-liked.svg") { el.src = like_button_url; } else { el.src = liked_button_url; } } (I know my function is the opposite of elegant, but I wasn't sure how else to get the image names from the urls -- but it works at least.) The point where I'm having trouble is I'm getting the error GET https://appname.s3.amazonaws.com/img/bookmark.svg? AWSAccessKeyId=XXXXXXXXXXXX&amp;Signature=XXXXXXXXXXXXX%3D&amp;Expires=1586147111 403 (Forbidden) So it's definitely … -
m2mchanged signal not working properly as expected
Here when adding an item in the cart and then increasing the quantity of that item. Works fine. The cart item increases the cart item total increases and the car total also gets the correct value. But when I a remove an item or decrease the quantity of that item the CartItem model works, but in Cart model the total don't change. It stays the same total when the items were added to the cart. def m2m_save_cart function is now working as expected. Every I item I add or remove or decrease the quantity. This function should save the changes. It runs as the number_of_items do change but the total doesn't cart models.py # Create your models here. class CartItem(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE) item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) def __str__(self): return f"{self.quantity} of {self.item.name}" def pre_save_cart_item(sender, instance, *args, **kwargs): instance.item_total = instance.quantity * instance.item.price pre_save.connect(pre_save_cart_item, sender=CartItem) class Cart(models.Model): owner = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE, related_name='cart') items = models.ManyToManyField(CartItem) number_of_items = models.PositiveIntegerField(default=0) total = models.DecimalField(default=0.00, max_digits=5, decimal_places=2) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) purchased = models.BooleanField(default=False) def __str__(self): return f"User: {self.owner}, items in cart {self.number_of_items}" def m2m_save_cart(sender, action, instance, *args, **kwargs): … -
Custom Model Attributes not being passed to template
I have a custom user model and have my settings.AUTH pointing to my custom model, 'Profile'. I am trying to display a page that will pick one of my Profile objects and randomly display them. Then, my user will be able to choose like or dislike. But I'm stuck at simply getting them to display. As I'm just getting a page that shows 'BIO' without the user's bio, nor the users photo. The logic in views.py is getting me to the template, but the info I need isn't showing up. And on top of that, every time I go to this link, the current logged in user is being changed to a different user! So not sure what's going on there either, but I believe something is wrong with my logic. template.html {% extends "dating_app/base.html" %} {% load bootstrap4 %} {% block content %} <div class="tindero"> {% if user %} <div class="container content is-child box column is-4 is-offset-4"> <img src="{{ profile.photo.url }}"> <p style="font-size: 25px">{{profile.username}}</p> <b>Bio:</b> <p>{{profile.description}}</p> </div> {% else %} <p>Wait for more people to join!</p> <p>Help us get more user. Share this link to your friends! <a href="http://localhost:8000/">http://localhost:8000/</a></p> {% endif %} {% endblock %} views.py def mingle(request): try: … -
Django create db view with multiply between cols, take average and group by time
I have a django model as below: class Source(models.Model): date = models.DateTimeField(primary_key=True, auto_now_add=True) curr_1 = models.DecimalField(decimal_places=2) volt_1 = models.DecimalField(decimal_places=2) curr_2 = models.DecimalField(decimal_places=2) volt_2 = models.DecimalField(decimal_places=2) curr_3 = models.DecimalField(decimal_places=2) volt_3 = models.DecimalField(decimal_places=2) class AvgPower(models.Model): ... Now I want to create a db view for above table group by day with cols as below: power_1 = avg(curr_1 * volt_1) power_2 = avg(curr_2 * volt_2) power_3 = avg(curr_3 * volt_3) Can any one tell me how to create view with "group by", multiply and average along time? -
Only the owner of a object can delete?
My project is a blog REST API where users can post an article. I customized the permissions to only the author owner can edit but whatever user can delete one post. views.py class ArticleViewSet(viewsets.ModelViewSet): serializer_class = ArticleSerializer queryset = Article.objects.all() def get_permissions(self): if self.action in ['update', 'partial_update', 'delete']: self.permission_classes = [IsOwnerOrReadOnly] return [permission() for permission in self.permission_classes] def get_serializer_class(self): if self.action == 'create': return CreateArticleSerializer return ArticleSerializer model.py class Article(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) slug = models.SlugField(db_index=True, unique=True, max_length=255) title = models.CharField(max_length=255) subtitle = models.CharField(blank=True, max_length=400) body = RichTextUploadingField() image = models.ImageField(upload_to='featured_image', blank=True) def __str__(self): return self.title permissions.py class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return obj.author == request.user -
chromedriver on different platforms
I am working on a Django project with my group from uni. One of my group mates implemented a scraper using a chromedriver.exe (apparently on Windows). I am working on the project from a Ubuntu. When I run the server (python3 manage.py runserver) I get the following error: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/selenium/webdriver/common/service.py", line 76, in start stdin=PIPE) File "/usr/lib/python3.6/subprocess.py", line 729, in __init__ restore_signals, start_new_session) File "/usr/lib/python3.6/subprocess.py", line 1364, in _execute_child raise child_exception_type(errno_num, err_msg, err_filename) FileNotFoundError: [Errno 2] No such file or directory: 'chromedriver': 'chromedriver' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/apps/registry.py", line 114, in populate app_config.import_models() File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/site-packages/django/apps/config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "/home/anton/Documents/Projects/Django/GroupProject/lib/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen … -
Django real time task automation
Let's say I have a model: class Person(models.Model): name = models.CharField(max_length=255) ... And another: class Group (models.Model): name = models.CharField(max_length=255) persons = models.ManyToManyField(Person) start_time = models.TimeField() end_time = models.TimeField() sunday = models.BooleanField() monday = models.BooleanField() ... All days in a week And finally: class Session(models.Model): group = models.ForeignKey(Group, on_delete=models.PROTECT) person = models.ForeignKey(Person, on_delete=models.PROTECT) STATUSES = ( ("P", "Pending"), ("C", "Completed"), ) status = models.CharField(max_length=1, choices=STATUSES, default="P") day = models.CharField(max_length=15, help_text="What day was this seesion? This is the on of days you chose in the Group") start_time = models.TimeField() end_time = models.TimeField() Okay, I know code doesn't make any sense but I would like to change that.l for you. Let's say I have a few Persons. I go on to create a Group with some Persons in that Group and select the days that these group sessions will take take place and when. a) After I create the Group, I want to automatically create seasions for this week for each person in the Group. This is very easily done by overriding the 'on_save()' function and creating Sessions for the this week. But then what do I do after this week is over? I don't want to go back and re-save this …