Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Timed Based Graph Plotting Python Django Using Firebase
I am using Django to make a dashboard to show sensor data. I am using chart.js for that I am retrieving sensor data of two days or less only. The problem is that how can I divide my graph for it.I think it might be possible using python time library or Django or something like that if so kindly suggest me some way to do it. I think that if java script can help us that will be great too. I just want data parsing based on time to plot and view it nicely. -
how to use django class model self in views.py
I want to create a filtering function and output the result value to the table. [A - models.py] class School(models.Model): .... def proceeding(self, request): from_date = request.GET.get('from_date') to_date = request.GET.get('to_date') student= Student.objects.filter(school_id=self.id) return Feedback.objects.filter( entry_date__range=[from_date, to_date], student_id__in=student).values('entry_date').distinct().count() [B- models.py] class Student(models.Model): ... school = models.ForeignKey(School, on_delete=models.CASCADE) class Confirm(models.Model): .... school = models.ForeignKey(Student, on_delete=models.CASCADE) I know why the results are not displayed. I know that the request written next to self in models.py doesn't work. However, the reason you must use it in models.py rather than views.py is that you must use self. Please answer to the seniors who know how to make a request in models.py!! -
django-environ with gunicorn
Just followed the guide https://django-environ.readthedocs.io/en/latest/ added my .env file to project and settings, this runs fine with manage.py runserver, but goes to error with gunicorn: source project/settings/.env # export my local var echo $DEBUG #check if they exist on # this is the correct value from bash pipenv run gunicorn project.asgi:application -w 2 -k uvicorn.workers.UvicornWorker --log-file - #starting the server [2021-04-13 14:37:05 +0200] [80721] [INFO] Starting gunicorn 20.1.0 [2021-04-13 14:37:05 +0200] [80721] [INFO] Listening at: http://127.0.0.1:8000 (80721) [2021-04-13 14:37:05 +0200] [80721] [INFO] Using worker: uvicorn.workers.UvicornWorker [2021-04-13 14:37:05 +0200] [80737] [INFO] Booting worker with pid: 80737 [2021-04-13 14:37:05 +0200] [80738] [INFO] Booting worker with pid: 80738 [2021-04-13 14:37:05 +0200] [80737] [ERROR] Exception in worker process Traceback (most recent call last): File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/arbiter.py", line 589, in spawn_worker worker.init_process() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/uvicorn/workers.py", line 63, in init_process super(UvicornWorker, self).init_process() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/workers/base.py", line 134, in init_process self.load_wsgi() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/workers/base.py", line 146, in load_wsgi self.wsgi = self.app.wsgi() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 58, in load return self.load_wsgiapp() File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 48, in load_wsgiapp return util.import_app(self.app_uri) File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/site-packages/gunicorn/util.py", line 359, in import_app mod = importlib.import_module(module) File "/home/gigi/.local/share/virtualenvs/gigi--Sphh5X0/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in … -
Assign a model to another model using ModelChoiceField
I am new to Django and would like to create a platform where teachers can create student profiles and assign reports to the specific student. Therefore, I have made two models (Student & Report) and two CreateViews. When creating a report, the teacher has the option to select a student from a choice field. This I have done using ModelChoiceField. However, when submitting the report model, the students name is not saved to that model. How can I accomplish this? Ultimately I would like to have a profile to each student showing their info and reports attached to their model. models.py class Student(models.Model): author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) name = models.CharField(max_length=30, default="") age = models.CharField(max_length=2, default="", blank=True) class Report(models.Model): date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=30) forms.py class StudentForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(StudentForm, self).__init__(*args, **kwargs) class Meta: model = Student fields = ['name','age',] class ReportForm(forms.ModelForm): student = forms.ModelChoiceField(queryset=Student.name, initial=0) class Meta: model = Report fields = ['title','file','player',] views.py class StudentCreate(LoginRequiredMixin, CreateView): model = Student template_name = 'student_create.html' form_class = forms.StudentForm def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class ReportCreate(LoginRequiredMixin, CreateView): model = Report template_name = 'report_create.html' form_class = forms.ReportForm def form_valid(self, form): form.instance.author = … -
Dynamic filter in django template
I would like to provide users possibility of filtering orders by any value, for example date, id etc. Is there any way how to do it using django feautures? I know, that i could create API and sort the values using js, but for the time being i would like to avoid it. Model: class Order(models.Model): is_printed = models.BooleanField(default=False) id = models.IntegerField(primary_key=True) done = models.BooleanField(default=False) ...other fields View: class OrdersView(View): def get(self, request, *args, **kwargs): orders = Order.objects.all().order_by('-id') return render(request, "orders.html", {"orders": orders} HTML Template: {% for o in order %} {{o}} {% endfor %} -
Iframe stops working after upgrading to Django 3.2 LTS
I was using Django 2.2 up till now and I recently tried upgrading to Django 3.2 We use a website live chat plugin called tawk.to which works by embedding an iframe to our page with the chat option in there. However, after upgrading to Django 3.2, even though the plugin's JS code is loading, the iframe is missing from the website altogether. I am not sure what is causing the issue. Is the iframe blocked in Django 3.2 or do I have to enable any setting for it? -
Django - reading MultiPolygons from postgres database does not return valid geometries
I'am creating web app to display some data in forms of charts, maps etc. I am using Bokeh for plotting. For maps I need to load shapefile with MultiPolygons containing regional borders. I have it loaded in my PostgreSQL database and I can display geometries from pgAdmin. I have a model for this table registered, here's the code class Polska(models.Model): gid = mdls.AutoField(primary_key=True) region = mdls.CharField(max_length=80, blank=True, null=True) geom = mdls.MultiPolygonField(srid=0, blank=True, null=True) When I'm trying to load these shapes and pack them into GeoDataFrame from geopandas I get a massive wall of text with an error (its just a snippet, basically it prints me the entire geometry) Input must be valid geometry objects: MULTIPOLYGON (((494179.5260320738 358814.2954531405, 494173.5314778397 358816.6456283908, 494178.0633204972 358822.8603784787, 494231.7738932786 358896.5675205989, 494321.7782545781 359023.6103092115, 494341.6988730072 359051.7332468079.....))) Code from loading in my views:geodf = gpd.GeoDataFrame(pd.DataFrame(Polska.objects.values("region","geom")),geometry="geom") So there is a geometry object, but for some reason it doesnt read as one. Interestingly when I try to check the type of this Multipolygon object it tells me "MULTIPOLYGON EMPTY". Can someone help me out and suggest where the problem can be? If some info is missing than let me know, I'll update asap. -
Argparse arguments in Flask application (production)
I'm trying to refactor a command line Python 3 application to an API with Flask. The application has a computer vision use case and I'm receiving an image for analysis. I'm currently using OpenCV, Python 3.8.7 I am not sure on how to refactor the arguments passes into the command line. What is the best way to bring these arguments into a production environment? Maybe move away from them? These are the Arguments: ap = argparse.ArgumentParser() ap.add_argument("-i", "--image", required=True, help="path to image") ap.add_argument("-y", "--yolo", required=True, help="path to YOLO Directory") ap.add_argument("-c", "--confidence", type=float, default=0.8, help="minimum confidence") ap.add_argument("-t", "--thereshold", type=float, default=0.3, help="thereshold") args = vars(ap.parse_args()) Thank you! -
Is my approach for creating a custom user model for my Ecommerce website correct?
I am creating a Custom User Model for my Ecommerce website . There are three types types of users in my website : Buyer Seller Company employee (Note : Company employee are further classified into the following types) 3.a) Sales support 3.b) Moderation team 3.c) Analytics team 3.d) Ticket manager 3.e) Super admin So basically there are 7 different types of users in our ecommerce seller , buyer and 5 types of company users . Now , In order to achieve this , I first created a new app called "Users" in my freshly made blank Django project . Inside the Users/models.py , I created the Custom user model as follows : #Users/models.py from django.contrib.auth.models import AbstractUser from django.db import models user_type_choices = ( (1, 'buyer'), (2, 'seller'), (3, 'Sales-Support'), (4, 'Moderator-Team'), (5, 'Analytics-Team'), (6, 'Ticket-Manager'), (7, 'Super-Admin') ) class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) user_type = models.PositiveIntegerField(choices=user_type_choices) phone = models.PositiveBigIntegerField() After this model was created , I did the required changes to the settings.py file in the main app of the project by adding the "Users" app to the list of installed apps and adding the following line : AUTH_USER_MODEL = 'Users.CustomUser' Is my approach for creating custom user … -
Django channels doesn't work properly with production environment
i have a really big problem with channels. when I try to run asgi server in production the problems come up but there is no problem when running in terminal. first let me show you a little code class LogConsumer(AsyncConsumer): async def websocket_connect(self, event): print('befor') await self.send({ "type": "websocket.accept", "text": "hellow" }) print('after') async def websocket_disconnect(self, event): print(event) there are more but i commented them too see problem is solving or not and guess what ... application = ProtocolTypeRouter({ 'websocket': AllowedHostsOriginValidator( AuthMiddlewareStack( URLRouter( [ url(r"^ws/monitoring/$", LogConsumer), ] ) ), ) }) ASGI_APPLICATION = "fradmin_mainserver.routing.application" CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], }, }, } ASGI_THREADS = 1000 supervisor config [fcgi-program:asgi] socket=tcp://localhost:8008 environment=PYTHONPATH=/home/datis/.pyenv/versions/cv/bin/python User=datis environment=HOME="/home/datis",USER="datis" # Directory where your site's project files are located directory=/home/datis/PycharmProjects/fradmin_mainserver/ # Each process needs to have a separate socket file, so we use process_num # Make sure to update "django_chanels.asgi" to match your project name command=/home/datis/.pyenv/versions/cv/bin/daphne -u /run/uwsgi/daphne%(process_num)d.sock --fd 0 --access-log - --proxy-headers fradmin_mainserver.asgi:application # Number of processes to startup, roughly the number of CPUs you have numprocs=1 # Give each process a unique name so they can be told apart process_name=asgi%(process_num)d # Automatically start and recover processes autostart=true autorestart=true # … -
How can I access my graphql endpoint with authentication implemented using graphene_django_crud?
I want my api to be accessible by only authenticated user, So, I used **views.py** class PrivateGraphQLView(LoginRequiredMixin, GraphQLView): pass **urls.py** from users.views import PrivateGraphQLView from users.views import activate_account,password_reset from graphene_django.views import GraphQLView urlpatterns = [ path('admin/', admin.site.urls), path('api/',PrivateGraphQLView.as_view(graphiql=True)), But now I am not able to login , which seems reasonable since I put my endpoints in the LoginRequiredMixin. What I thought to make two endpoints but which is also not possible. What should I do, so that it won't be accessible to unauthenticated user and also able to do the login. I also tried schema.py from graphene_django_crud.types import DjangoGrapheneCRUD from graphene_permissions.mixins import AuthNode class ItemType(AuthNode,DjangoGrapheneCRUD): permission_classes = (AllowAuthenticated,) class Meta: model = Item max_limit = 10 but then I am able to access Item query being unauthorized user -
ModelViewSet multiple databases put get post serializer.is_valid
I use multiple databases. Branch.objects.using (db_name) .update (** validated_data) also updates this way, but I have to do "serializer.is_valid(raise_exception=True)". It constantly returns valid errors from the default database. How do I mount ModelViewSet put get and post "using(db)". Can you help me? I'm sorry for my bad english. class BranchViewSet(viewsets.ModelViewSet): queryset = Branch.objects.all() serializer_class = BranchSerializer def get_queryset(self): company_db = self.request.GET.get('company-db', False) db_name = self.request.GET.get('db-name', False) if db_name and company_db : queryset = Branch.objects.using(db_name).filter(company_db=company_db) else: queryset = Branch.objects.none() return queryset def update(self, request, *args, **kwargs): request.data._mutable = True instance = self.get_object() serializer = self.get_serializer(instance, data=request.data) serializer.is_valid(raise_exception=True) # is_valid().using("self.request.GET.get('db-name')") < does it check from the second database here? self.perform_update(serializer) return Response(serializer.data) -
Django - return each model value without field
The Priority model has three values, for each of them values I'm returning an inlineform which allows the user to set a score for each priority & then save with the Project. This is what it currently looks like: Current view My problem is: how can I automatically show all the priority values and allow the user to enter the score but not have to pick the Priority. Is it possible to show it like the image below? What I'm trying to do. Views.py class ProjectCreateview(LoginRequiredMixin, CreateView): model = Project form_class = ProjectCreationForm login_url = "/login/" success_url = '/' def get_context_data(self, **kwargs): PriorityChildFormset = inlineformset_factory( Project, ProjectPriority, fields=('project', 'priority', 'score'), can_delete=False, extra=Priority.objects.count(), ) data = super().get_context_data(**kwargs) if self.request.POST: data['priorities'] = PriorityChildFormset(self.request.POST) else: data['priorities'] = PriorityChildFormset() return data def form_valid(self, form): context = self.get_context_data() prioritycriteria = context["priorities"] form.instance.creator = self.request.user self.object = form.save() prioritycriteria.instance = self.object if prioritycriteria.is_valid(): prioritycriteria.save() return HttpResponseRedirect(self.get_success_url()) Models.py class Priority(models.Model): title = models.CharField(verbose_name="Priority Name", max_length=250) def __str__(self): return self.title class Project(models.Model): name = models.CharField(verbose_name="Name", max_length=100) details = models.TextField(verbose_name="Details/Description", blank=False) creator = models.ForeignKey(User, on_delete=models.CASCADE) class ProjectPriority(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE) priority = models.ForeignKey(Priority, on_delete=models.CASCADE) score = models.CharField(max_length=1000, choices=priority_choices) class Meta: verbose_name = "Priority" verbose_name_plural = "Priorities" Template <table … -
Why do you use Stack Overflow? [closed]
For a few weeks I've been busy working on a research of different forum-like websites. A few examples are; Quora, Stack Overflow and of course Reddit. You would help me out a lot if you could fill in this survey (takes 5 min most!) in which I would like your opinion and usage of this platform; Stack Overflow. Your submission will be highly appreciated. PS: I'm sorry for the misusage of this platform, but this is the best way to reach the actual users. https://docs.google.com/forms/d/e/1FAIpQLSeI9ipMOUEmruvpGTFIId9Xgx1f-J-R8lKGoECMDWjPIfENcA/viewform?usp=sf_link -
How to make custom and dynamic forms in django?
i want to make custom and dynamic rendered forms in django , Like i have data , { 'members': [ { 'id': 621, 'name': 'abcd abc', 'relation': 'self', 'dob': datetime.date(1999, 4, 13), 'blood_group': 'A+ve', 'gender': 'male', 'height': 123.0, 'weight': 70.0, 'bmi': 46.27, 'ped': <QuerySet[ ]> }, { 'id': 622, 'name': 'acbd abc', 'relation': 'spouse', 'dob': datetime.date(1999, 4, 13), 'blood_group': 'B+ve', 'gender': 'female', 'height': 123.0, 'weight': 70.0, 'bmi': 46.27, 'ped': <QuerySet[ ]> }, { 'id': 625, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 626, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 627, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 628, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ ]> }, { 'id': 629, 'name': 'dsafa f', 'relation': 'grand_parents', 'dob': datetime.date(1999, 1, 1), 'blood_group': 'B+', 'gender': 'male', 'height': 166.0, 'weight': 66.0, 'bmi': 23.95, 'ped': <QuerySet[ … -
Django: Which takes more time, a query to database or filtering the data we received?
I have a table of questions that have different type of questions (minimum 3 types). I make a query for every type of question. I'm sure this is heavy on the database and takes a lot of time. What I want to do is create a different table for every type, or get all questions from the table that contains all the questions and do the filtering separately. I want to know which is recommended? and which one takes less time? -
how to override method update in Django form?
i have model like that : class BrokerCredential(models.Model): api_key = models.TextField(blank=True, null=True) age = models.IntegerField(blank=True, null=True) def save(self, *args, **kwargs): self.api_key = self.api_key * 3 super(BrokerCredential, self).save(*args, **kwargs) I override method 'save()' because I wanted every time and every where when I need to save record, this method manipulates my input. But there is problem , whenever i update my model ( consider changing the 'age' field), it multiples 'api_key' again. I need a way that saves method works only when I add a new record, not every time I update my model instance. -
Return Model field names via Django rest framework
I am quite new to django and have been struggling to get this for days. I am trying to use the field names of models created in my template for some configurations there. When I use the normal function view where I render the results, I am able to achieve what I want easily: def graph_builder(request): if request.user.is_authenticated: storage_fields = Storage_facility._meta.fields return render(request, 'analytics/dashboard/graph_builder.html',{'storage_fields':storage_fields}) else: return HttpResponseRedirect('login') But I need to use the rest framework to return these fields to my react frontend due to some filtering that needs to be done. In my view, I am able to store the fields in a tuple but I don't know how to return this to the frontend. This is my view: class buildGraphViewSet(ObjectMultipleModelAPIView): storage_serializer = Storage_facilitySerializer storage_fields = Storage_facility._meta.fields fields = ("") list_fields = list(fields) for field in storage_fields: list_fields.append(field.name) fields = tuple(list_fields) querylist=[ {'queryset': fields, 'serializer_class': FieldsSerializer_serializer}, {'queryset': ComplianceValue.objects.all(), 'serializer_class': ComplianceValueSerializer}, ] Below is the latest serializer I've tried: class FieldsSerializer_serializer(serializers.ListField): child=serializers.CharField() Please help me out. I just need to use my model's field names in my react app. -
Field 'id' expected a number but got '127.0.0.1'
I am working on get the number of the video views by ip firstly I creat a views to get the ip of the users and store in this model class UsersByIP(models.Model): ip_user = models.TextField() my video model author = models.ForeignKey(Account, on_delete=models.CASCADE) video = models.FileField(upload_to=get_video_filepath, validators=[validate_file_extension, validate_file_size]) viewers_by_ip = models.ManyToManyField(UsersByIP, default=None, blank=True) class Video(models.Model): Then this is my view that get the current user ip and if it's not store of the video views then store it num_views_by_ip = Video.objects.annotate( num_views_ip=Count('viewers_by_ip'), ).order_by('-viewers_by_ip') data = get_object_or_404(num_views_by_ip, pk=pk) if not request.user.is_authenticated: __, created = Video.viewers_by_ip.through.objects.get_or_create( video=data, usersbyip=self.request.META.get('REMOTE_ADDR') ) if created: data.num_views_ip += 1 -
How to access these tables more efficiently in django
we have the following data base schema to store different types of data. DataDefinition: basic information about the new data. *FieldDefinition: Every DataDefinition has some fields. Every field has a type, title, etc, that information is stored here. Every DataDefinition has more than one FieldDefinition associated. I have put '' because we have a lot of different models, one for every kind of field supported. DataValue, *FieldValues: we store the definition and the values in different models. With this setup, to retrieve a data from our database we need to do a lot of queries: Retrieve the DataDefinition. Retrieve the DataValue. Retrieve the *FieldDefinition associated to that DataDefinition. Retrieve all the *FieldValues associated to those *FieldDefinition. So, if n is the average number of fields of a DataDefinition, we need to make 2*n+2 queries to the database to retrieve a single value. We cannot change this setup, but queries are quite slow. So to speed it up I have thought the following: store a joined version of the tables. I do not know if this is possible but I cannot think of any other way. Any suggestion? Django: 1.11.20 Python: 2.7 -
Django Manager isn't available
AttributeError at /register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.Account' I'm trying to create a registration form but getting the AttributeError. How can to avoid the error? Here is the code in of my custom model in models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') if not username: raise ValueError('Users must have a username') user = self.model( email=self.normalize_email(email), username=username, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email=self.normalize_email(email), password=password, username=username, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) about = models.TextField(('about'), max_length=500, blank=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email # For checking permissions. to keep it simple all admin have ALL permissons def has_perm(self, perm, obj=None): return self.is_admin # Does this user have permission to view this app? (ALWAYS YES FOR SIMPLICITY) def has_module_perms(self, app_label): return True views.py from … -
Custom django mangement command to add/amend views.py, filters.py etc
Django has the built-in command startapp which creates a new app directory and some standard files within. I was wondering whether custom management commands (or something different?) can be used to automate similar repetitive steps. For example I find myself repeating a certain set of steps when creating certain generic new homepages. To name a few: Adding a url to urlpatterns in <app>.urls.py Creating a template in <app>.templates Adding a view, subclassing django.views.generic.TemplateView to <app>.views.py Adding the template to the view Adding ViewSet to <app>.rest.py Register this ViewSet to router in <app>.urls.py Ideally I would like to create a command in the following style createNewPage --viewName <name1> --viewSetName <name2> --url <url> --api <api_url> Is something like this achievable? -
issue with Ajax request & Django
I am trying to parse data from my selected items in the datatable towards my ajax request wich will go to a view in Django: Js: ` $(document).ready(function() { var table var userLang = navigator.language || navigator.userLanguage; if (userLang == "fr-BE") { url = 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/French.json' } else { url = 'https://cdn.datatables.net/plug-ins/1.10.24/i18n/Dutch.json' } table = $('#example').DataTable( { columnDefs: [ { orderable: false, className: 'select-checkbox', targets: 0 } ], select: { orderable: false, style: 'multi', selector: 'td:first-child' }, language: { url: url } } ); } ); $('#submit_phones').click( function() { var info = table.rows( { selected: true } ).data(); var URL = "{% url 'upload_devices' %}"; $.ajax({ type: "POST", url: URL, dataType: "json", data: { info : info , csrfmiddlewaretoken : '{{ csrf_token }}' }, success : function(json) { alert(json); alert("Successfully sent the data to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } }); alert($.ajax) }); ` When i call info just after the assignment it is filled with objects. The button click function gets called but the only thing thats in my request is the middlewaretoken variable -
Weird saving behavior on django user field on save
I have 2 models User and Suspension class Suspension: content_type = models.ForeignKey(ContentType, related_name='suspension', on_delete=models.CASCADE) object_id = models.CharField(max_length=255) content_object = GenericForeignKey('content_type', 'object_id') suspended = models.BooleanField(_("suspended"), default=False) reason = models.TextField(blank=True) I want to change user.is_active based on a related suspension.suspended instance. My code is: def form_valid(self, form): from userprofile.models import User as user model_name = self.get_model_name_from_url_kwargs() model = eval(model_name) suspension, created = Suspension.objects.get_or_create( content_type = ContentType.objects.get(app_label=model._meta.app_label, model=model._meta.model_name), object_id = self.kwargs['pk'], ) suspension.reason = form.cleaned_data['reason'] suspension.suspended = form.cleaned_data['suspended'] suspension.content_object.is_active = not form.cleaned_data['suspended'] suspension.save() return super().form_valid(form) I can confirm that printing suspension.content_object.is_active returns a correct result, however, it is not saved. What is wrong? -
Django Rest Framework: How to use EXCEPTION_HANDLER with DEBUG = True?
I'm using a custom exception handler for my REST API. I'd like to use my custom exception handler, which responds with JSON data that my front end knows how to handle. The problem is that with the setting DEBUG = True, Django doesn't use my custom exception handler. Instead, it responds with the standard HTML debug page, like this: Here's my settings.py: DEBUG = True REST_FRAMEWORK = { # I still get the default Django 'EXCEPTION_HANDLER': 'stripe_app.utils.custom_exception_handler' } ... I know that I could just set DEBUG = False, but if I did that I'd also have to change many other things that use the DEBUG variable. So, How can I use my custom exception handler with the DEBUG = True setting? I've already looked for answers in the DRF docs: https://www.django-rest-framework.org/api-guide/settings/#exception_handler and the Django docs: https://docs.djangoproject.com/en/3.1/ref/settings/#debug but I can't find the answer I'm looking for.