Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: ascii' codec can't decode byte 0xc3 in position 63: ordinal not in range(128)
i'm use an UpdateView cbv to make updates via custom form depending on the domain. Code below class UpdateForm(UpdateView): model= MaliModel template_name= 'mali_project/crud/update.html' domain= None def dispatch(self, *args, **kwargs): """Set the domain as the rest depend on it""" self.domain= self.request.subdomain.name return super(UpdateView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): """Put pk in the context in order to display corresponding QRCode on the front""" context= super(UpdateView, self).get_context_data(**kwargs) context['pk']= self.kwargs['pk'] return context def get_form_class(self): self.model = MaliModel if self.domain == 'Mali' else RDCModel return FormML if self.domain == 'Mali' else FormRDC def get_object(self): """Function use kwargs to access url args like pk """ # model = MaliModel if self.domain == 'Mali' else RDCModel obj= get_object_or_404(self.model, pk= self.kwargs['pk']) return obj In my form i use third-party plugin in the (django-country) for the country selection and django-semanticui to render form. class FormBase(forms.ModelForm): genre = forms.ChoiceField(choices=ICON_GENRE, widget=forms.TextInput(attrs={"_override": "IconSelect"})) type_voyage= forms.ChoiceField(choices= TYPE_VOYAGE, initial='Vol', widget=forms.TextInput(attrs={"_override":"IconSelect", "id":"id_type_voyage"})) class Meta: fields = '__all__' model= BaseModel widgets={ 'domain': forms.HiddenInput(attrs=({'readonly': 'readonly'})), 'identifiant': forms.TextInput(attrs=({'readonly': 'readonly'})), 'venant_de': CountrySelectWidget(), 'allant_a': CountrySelectWidget(), 'genre': forms.TextInput(attrs={'_icon': 'genderless'}), 'numero_matricule': forms.TextInput(attrs={'class':'Voiture_input'}), 'nom_compagnie': forms.TextInput(attrs={'class':'Voiture_input'}), 'nom_bateau': forms.TextInput(attrs={'class':'Navire_input'}), 'numero_cabine': forms.TextInput(attrs={'class':'Navire_input'}), 'numero_siege': forms.TextInput(attrs={'class':'Vol_input'}), 'numero_vol': forms.TextInput(attrs={'class':'Vol_input'}) } But when i submit the form i get the error in described in the title. Traceback: Internal Server Error: … -
First name, last name and image not showing
I'm new to python and django. I have a custom django model and a profile model that is working perfectly. But i have a challenge. When a user is logged in, he can view his profile completely, but when users try ro view other users profile, the first_name, last_name and the image of the user to be accessed is not showing. How do i resolve this. -
django jinja template display python dictionary on a bootstrap table
I have a django view that returns this dictionary args={'Residential': 'N/A', 'School': ('481 address', 600), 'Park': 'N/A', 'Religious': 'N/A', 'Childcare': ('123 address', 5)} I have this code that correctly displays it on the HTML page <h5><b>Nearest Childcare Parcel</b> = {{ Childcare }}</h5> <h5><b>Nearest Park Parcel</b> = {{ Park }}</h5> <h5><b>Nearest Religious Parcel</b> = {{ Religious }}</h5> <h5><b>Nearest Residential Parcel</b> = {{ Residential }}</h5> <h5><b>Nearest School Parcel</b> = {{ School }}</h5> this outputs which is okay but its ugly and messy. I want to nicely put it into a table. So here is my html code using the django jinja template <div class="container"> <h2>Property Search Results</h2> <table class="table"> <thead> <tr> <th>Layer</th> <th>Address</th> <th>Distance to Property</th> </tr> </thead> <tbody> <tr> {% if args %} <td>Childcare</td> <td>{ args['Childcare'][0] }</td> <td>{ args['Childcare'][1] }</td> {% endif %} </tr> <tr class="success"> {% if args %} <td>Park</td> <td>{ args['Park'][0] }</td> <td>{ args['Park'][1] }</td> {% endif %} </tr> <tr class="danger"> {% if args %} <td>Religious</td> <td>{ args['Religious'][0] }</td> <td>{ args['Religious'][1] }</td> {% endif %} </tr> <tr class="info"> {% if args %} <td>Residential</td> <td>{ args['Residential'][0] }</td> <td>{ args['Residential'][1] }</td> {% endif %} </tr> <tr class="warning"> {% if args %} <td>School</td> <td>{ args['School'][0] }</td> <td>{ args['School'][1] }</td> {% endif %} … -
How to confirm before saving a ModelAdmin form with Django?
I'm working on a webapp, based on Django framework. Django, is good, Django is powerfull, Python is wonderfull, but Django is pis..ng me off. Ok, I'm a newbie in Django (but not with Python). Here we go, basically I have modelized the database of my applications and started to write the ModelAdmin components for the CRUD interface. One of my models Assembly contains a m2m relationship. I have also written the related ModelAdmin class. Everything is working file, adding, updating, deleting an Assembly object. What I need to achieve is: if the users attempts to modify the fields related to the m2m relationship, and clicks on "Save", I just need to notify him within an html page like the Deletion page: "Are you sure to modify the field xxxx ?" If Yes => continue saving as usual If No => go back to the previous page. I tried to override the change_form() in the ModelAdmin class, but finally it does not work. I'm struggling with this issue for 5 days and I still haven't found any existing issue. Suggestions are welcome. Thanks. Z. -
Matching django table foreign keys with filter function
I'm trying to upload a csv into a django table. I am not able to match the data to the foreign keys. 'cpt' is the foreign key from price to service model. There are many price rows that map to one cpt row, but each individual row has only one cpt. Here is my upload code. path = "/Users/joannerodrigues/Documents/csv_import/" os.chdir(path) from catalog.models import Service, Price with open('price.csv') as csvfile: reader = csv.DictReader(csvfile) for row in reader: p = Price(com_desc=row['com_desc'], service=Service.objects.filter(cpt=str(row['cpt']))[0]) p.save() This is the error that I get: site-packages/django/db/models/query.py", line 303, in __getitem__ return qs._result_cache[0] IndexError: list index out of range Here is what the data loooks like: Price data: (header included in csv file) com_des, cpt "desc 1", '57647' "desc 2", '87654' Service data: (header included in file) desc_us, cpt, price "desc1....", '57647', '89.95' "dsc2.....", '87654', '875.87' Here are the models.py Price class Price(models.Model): com_desc = models.CharField(max_length = 200, blank = True, null = True) service = models.ForeignKey("Service", on_delete=models.SET_NULL, null=True) Service class Service(models.Model): desc_us = models.TextField(blank=True, primary_key = True) cpt = models.IntegerField(default= 10000) -
how to declare a variable in django template and change the value of that variable in if condition?
I'm trying to add a profile image in django template for comments for the post... If profile image is not there in the model then I want to replace with the styled text in place of Image. But I'm getting worried about how to tell the django template that if image exists or not... <div class="comment-author"> {% for image in profile %} {% if image.profile|slugify == comment.author %} {% with "exist" as img %} <!-- if image exist create img variable --> <img src="{{ image.profileImg.url }}" alt="{{ image.profile }}"> {% endif %} {% endfor %} {% if not img %} <!-- using img variable for checking --> <span class="userImg"><b>{{ comment.author|make_list|slice:':2'|join:'' }}</b></span> {% endif %} {% endwith %} <!-- closing the with statement --> In the above code I have tried to create a variable img using 'with' but getting error in template... What should I do with this? -
Django: Manager isn't accessible via MyModel instances
I am building a chat in django and I have a problem getting objects from the Chat model in django. For the objects I get a traceback with the message: Manager isn't accessible via Chat instances when I try to access it. Traceback: Exception inside application: Manager isn't accessible via Chat instances File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/sessions.py", line 179, in __call__ return await self.inner(receive, self.send) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/utils.py", line 52, in await_many_dispatch await dispatch(result) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/asgiref/sync.py", line 108, in __call__ return await asyncio.wait_for(future, timeout=None) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/tasks.py", line 339, in wait_for return (yield from fut) File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/concurrent/futures/thread.py", line 56, in run result = self.fn(*self.args, **self.kwargs) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/db.py", line 13, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/asgiref/sync.py", line 123, in thread_handler return self.func(*args, **kwargs) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/consumer.py", line 105, in dispatch handler(message) File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/channels/generic/websocket.py", line 39, in websocket_connect self.connect() File "/Users/fokusiv/Projects/django-multichat-api/chat/consumers.py", line 60, in connect is_participant_in_chat(self.room_name, self.scope['user']) File "/Users/fokusiv/Projects/django-multichat-api/chat/models.py", line 24, in is_participant_in_chat test = chat.objects File "/Users/fokusiv/Projects/django-multichat-api/venv/lib/python3.6/site-packages/django/db/models/manager.py", line 176, in __get__ raise AttributeError("Manager isn't accessible via %s instances" % cls.__name__) Manager isn't accessible via Chat instances Here is relevant code: chat/model.py from django.shortcuts import get_object_or_404 from django.db … -
DJANGO API REST FRAMEWORK: schema methods
Django 1.11.3, python 3.6 I have 2 classes in my view.py: class ProductList(generics.ListAPIView): class SampleList(generics.ListAPIView): Please note the same superclass. Might be relevant: Product is an actual model, Sample is not, SampleList is just a method that calls Product.objects.all() (same code as in ProductList) All the code inside those classes besides class names is IDENTICAL (including serializer, I just copied the clase and renamed the copy). The client before it hits urls for those two gets the schema schema = self.client.get(self.myAppApiUrl) #works, returns the results result1 = self.client.action(schema, ["products", "list"]) params = {"id" : some_id, } #fails with this: coreapi.exceptions.LinkLookupError: Index ['samples']['list'] did not reference a link. Key 'list' was not found. result2 = self.client.action(schema, ["samples", "list"], params) When I print "schema", I see products: { list([page]) } samples: { read(id) } My questions are: what makes it to add "list" to schema in the first case and "read" in the second case? And how can I add "list" to the second case? What does that message "Key 'list' was not found" mean? Does this failure have something to do with the params passed? Removing params from the client call does not change anything. I am also somewhat curious about … -
Django Request - Catching # prefixed QueryParams
Take a url like so: http://localhost:8000/auth/twitch/#access_token= Using request.get['access_token'] won't catch this because it is invalid. Changing to http://localhost:8000/auth/twitch/?access_token= resolves the issue, but I wouldn't expect Twitch to do this unintentionally, so how do I catch this & what is the purpose? -
User Manager object has no attribute create_superuser
Problem: When using manage.py i’m unable to create a super user and it responds with the error AttributeError: 'UserManager' object has no attribute 'create_superuser’. I then tried to manually import all of the necessary models and run it in a python shell and was met with the same roadblock. Goal: Properly create super user using inherited class of base manage Code: from django.contrib.auth.models import AbstractUser, BaseUserManager, Group class UserManager**(**BaseUserManager**)**: def get_by_natural_key**(**self, username**)**: return self.get**(**username__iexact=username**)** class User**(**AbstractUser**)**: objects = UserManager**()** … … def __str__**(**self**)**: return **’{}’**.format**(**self.id**)** def save**(**self, *args, **kwargs**)**: self.full_clean**()** super**(**FollowUser, self**)**.save**(***args, **kwargs**)** -
How to use Django Bulk Add to Database Feature
I am trying to add around 40-50k rows to pgsql Database from Django from a Text File Dump from an Application for Data Processing Following is my Function def populate_backup_db(dumpfile): sensordata=sensorrecords() **** This is the Model start_time = time.time() file= open(dumpfile) filedata = file.readlines() endcount=len(filedata) i=0 imagecount=0 while i<endcount: lineitem = split_entry(filedata[i]) if (lineitem[0]== "HEADER"): imagecount=imagecount+1 sensordata.Sensor = lineitem[1] sensordata.Date1 = lineitem[2] sensordata.Date2 = lineitem[3] sensordata.Version = lineitem[4] sensordata.Proxyclient = lineitem[8] sensordata.Triggerdate = ctodatetime(lineitem[13]) sensordata.Compression = lineitem[16] sensordata.Encryption = lineitem[17] sensordata.Fragments = lineitem[21] sensordata.Pbit = lineitem[37] sensordata.BlockIntFT = lineitem[38] sensordata.OriginServer = lineitem[56] sensordata.save() i=i+1 elapsed_time = time.time() - start_time print(imagecount ,'entries saved to database from ',dumpfile,'. Time Taken is ',elapsed_time,' seconds.') file.close() This is taking around 2-3 minutes to save all data to Database. This Dumpfile is likely to Increase in size, and if this Function is to be used, It can take a couple of minutes to Save All data to Database How can I fetch all Data from Dump File and then save it all to the Database in single go. I see a DJANGO Method called bulk_create() bulk_create()¶ bulk_create(objs, batch_size=None, ignore_conflicts=False)¶ This method inserts the provided list of objects into the database in an efficient manner (generally … -
Django migrations- "no such table"
I recently tried to remove a few models for upvoting/downvoting posts by manually dropping the tables for the models in SQLite. This worked fine, except for now when I go to migrate after removing the models for the tables, Django raises a "no such table" error for the deleted tables. What can I do about this? -
Django User Profile doesn't update
I am setting up a website, where users can see their profiles and update details (like email, password, etc)/delete account. But updating the form is not acknowledged at all by the user. I am using the standard built-in User model. forms.py: class UserDetailsForm(forms.ModelForm): password = forms.CharField(widget = forms.PasswordInput()) class Meta: model = User fields = ('first_name','last_name','email','password','is_active') views.py: @login_required def edit_profile(request): user = User.objects.get(username=request.user) form = UserDetailsForm(request.POST or None, initial={'first_name':user.first_name, 'last_name':user.last_name, 'email':user.email, 'password':user.password, 'is_active':user.is_active,}) if request.method == 'POST': if form.is_valid(): user.save() messages.info(request, 'This is a debug message') return HttpResponseRedirect(reverse('account')) context = {"form": form} return render(request, "iFood/user-account.html", context) user-profile.html: ... <form method="POST" action="{% url 'account' %}" class="" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit" name="" value="Edit and Save"> {% if messages %} <ul class="messages"> {% for message in messages %} <li class="{{ message.tags }}"> {{ message }} </li> {% endfor %} </ul> {% endif %} -
Django tests error: django.db.utils.ProgrammingError: (1146, "Table 'test_mydb.mytable’ doesn't exist")
I’m trying to write test cases using python’s TestCase class. While I run python manage.test, I get the following error: Operations to perform: Synchronize unmigrated apps: messages, rest_framework, staticfiles Apply all migrations: admin, auth, contenttypes, genes, sessions Running pre-migrate handlers for application admin Running pre-migrate handlers for application auth Running pre-migrate handlers for application contenttypes Running pre-migrate handlers for application sessions Running pre-migrate handlers for application rest_framework Running pre-migrate handlers for application files Synchronizing apps without migrations: Creating tables... Running deferred SQL... Running migrations: Applying contenttypes.0001_initial... OK (0.031s) Applying auth.0001_initial... OK (0.272s) Applying admin.0001_initial... OK (0.082s) Applying admin.0002_logentry_remove_auto_add... OK (0.011s) Applying contenttypes.0002_remove_content_type_name... OK (0.064s) Applying auth.0002_alter_permission_name_max_length... OK (0.029s) Applying auth.0003_alter_user_email_max_length... OK (0.028s) Applying auth.0004_alter_user_username_opts... OK (0.012s) Applying auth.0005_alter_user_last_login_null... OK (0.035s) Applying auth.0006_require_contenttypes_0002... OK (0.006s) Applying auth.0007_alter_validators_add_error_messages... OK (0.011s) Applying auth.0008_alter_user_username_max_length... OK (0.046s) Applying auth.0009_alter_user_last_name_max_length... OK (0.040s) Applying files.0001_initial... OK (0.024s) Applying files.0002_auto_20190303_1656... OK (0.005s) Applying sessions.0001_initial... OK (0.028s) Running post-migrate handlers for application admin Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Running post-migrate handlers for application auth Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' Adding permission 'Permission object (None)' … -
Django rest framework password security for <script>
I have implemented user registration in Django Rest Framework but I don't know how to check for sql injection and etc. For example a password like this: "< script>" class UserRegisterSerializer(serializers.ModelSerializer): def validate(self, data): password = data['password'] password2 = data['password2'] data.pop('password2') if password != password2: raise serializers.ValidationError({"password": "Passwords must match."}) errors = dict() try: # validate the password and catch the exception validators.validate_password(password) # the exception raised here is different than serializers.ValidationError except exceptions.ValidationError as e: errors['password'] = list(e.messages) if errors: raise serializers.ValidationError(errors) return data This code is in my settings: AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', #=> Default (8 characters) 'OPTIONS': { 'min_length': 4, } }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, -
Combine Tensorflow script with Django application
I have a Django application which stores inputs into the model and I have a tensor flow script that trains data and also gives an output depending on the input. I need to now integrate both of them together so that the script gets input from the Django model in one app and stores the result in another app model. I am not sure how to integrate it, as of now I have created a new app in my project "common" to store the scripts there. Any help would be appreciated. -
adjust forms that are generated by django generic editing views
I am trying to understand the process of generating generic form views in django. I have a generic view class with just class BookUpdate(UpdateView): model = Book fields = [ 'name', 'pages', 'categorys' ] which automatically generates a working html form from my model data. But now, I want to modify the field that is shown for categorys, is there any way to do this, or do I have to create a complete working BookForm class and custom BookUpdate class? Here its just 3 fields, but in my real case there are maybe 15 fields that I would need to code by myself, just because of a tiny change in the category field. Cant I just overwrite the single field, using any class method? -
Django: get drop-down values for a FormField
Aim is to get the drop-down to work. Normally no problems when feeding the whole Model / ModelForm into the html template as {{ form }} Below html code snippet is my aim, but instead of {{ form }}, I would like to feed the subset {{ form.car_model_make }} and let Django automatically create all Options <option value="BWM">BMW</option> ... etc class Product(models.Models): car_model_make = models.CharField(default='B',max_length=1,blank=True,choices=CAR_TYPE) The choices CAR_TYPE is a list containing "BMW, Mercedes, Audi". Trying to achieve this: When I replace: <option value="BWM">BWM</option> <option value="Mercedes">Mercedes</option> <option value="Audi">Audi</option> in the HTML code snippet below with {{ form.car_model_make }} I get "No results found" with <option> {{ form.car_model_make }} </option> I get a list of the choices (BMW, Mercedes, Audi) but they are not selectable However, with <option {{ form.car_model_make }} </option> It works but I get a warning Tag start is not closed. If I close the Tag, I get the tag character ">" also printed in the drop down. same result is produced for: <option value=" {{ form.car_model_make }} "></option> I am in the dark and the trial and error does not give me the desired solution. How do I do it? <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta … -
How to Run Subprocess in Views.py -- Django
I am trying to run a script with the source scripts/earnings.py with the symbol argument that is generated from the user. The output is a matplotlib graph that I am trying to put in my template. from django.shortcuts import render import subprocess from backtests.scripts import earnings def index(request): if 'symbol' in request.GET: symbol = request.GET.get('symbol','Invalid Symbol') request.session['symbol'] = symbol else: symbol = request.session['symbol'] process = subprocess.run(["python earnings", "symbol"], stdout=subprocess.PIPE) output = process.stdout return render(request, 'backtests/earnings.html', {'symbol' : symbol, 'output' : output}) As of now, I get the error FileNotFoundError: [Errno 2] No such file or directory: 'python earnings': 'python earnings' -
Limiting number of Django Tests from command line to 1
I'm currently running my Django tests from the command line with: $ python3 manage.py test tutorial.tests.Logger.log_event "event" "event-type" "user" My goal is to have the selenium testing script use the dynamic arguments provided as command line arguments. They're subject to change on each test. I'm using LiveServerTestCase instead of unittest. The test is successful, but the Django testing suite also views the command line arguments as other test modules to be run and then provides me with the following error for each argument: ====================================================================== ERROR: event (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: event Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/unittest/loader.py", line 153, in loadTestsFromName module = __import__(module_name) ModuleNotFoundError: No module named 'event' How can I limit the number of tests Django runs to just the first one? -
Sending an image as an argument in render() in Django views
I'm trying to build a web app which shows the user the variation of his weight over time. Therefore I'm trying to plot a line graph. I want to make use of matplotlib or a similar library inside my views file to plot the graph. This answer explains how the graph can be plotted through Django views. My code in views.py file looks like this:(no need to read in detail, it's working fine) from django.shortcuts import render, HttpResponseRedirect, HttpResponse from .forms import DiabetesForm from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib as plt from matplotlib.dates import DateFormatter import datetime import random import io def mplimage(request): f = Figure() ax = f.add_subplot(111) x = [] y = [] now = datetime.datetime.now() delta = datetime.timedelta(days=1) for i in range(10): x.append(now) now += delta y.append(random.randint(0, 1000)) ax.plot_date(x, y, '-') ax.xaxis.set_major_formatter(DateFormatter('%Y-%m-%d')) f.autofmt_xdate() buf = io.BytesIO() canvas = FigureCanvas(f) canvas.print_png(buf) response=HttpResponse(buf.getvalue(),content_type='image/png') # if required clear the figure for reuse f.clear() # I recommend to add Content-Length for Django response['Content-Length'] = str(len(response.content)) # return response And the code in urls.py is: from django.urls import path, include from . import views urlpatterns = [ path('', views.mplimage, name='home'), ] However, this code shows only … -
Django cannot setup when not using manager
I am having a strange issue, hopefully someone has encountered it before. I have a custom script located at my_project/my_app/scripts/custom_script.py -- My desired use case is to feed this script a filepath and have it process the file and load/modify some data within my database. Here is a snippet from that script: import django def setup_django(env): if env == 'dev': settings = "my_project.my_project.dev_settings" elif env == 'stg': settings = "my_project.my_project.staging_settings" elif env == 'prod': settings = "my_project.my_project.prod_settings" else: raise ValueError("Invalid choice for --env argument: {}".format(env)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', settings) django.setup() def main(): env = 'dev' setup_django(env) # Do stuff with my script When I run the above from within the same virtualenv as my project, I get the error ModuleNotFoundError: No module named 'my_app' It seems that, when I call django.setup(), it goes and parses my my dev_settings file and finds my_app in the INSTALLED_APPS list, then tries to import it directly (e.g. import myapp). This will never work, because my_app is a sub-module of my_project. Here is a sample of the directory structure: my_project ├── my_project │ ├── __init__.py │ ├── dev_settings.py │ ├── prod_settings.py │ ├── staging_settings.py │ ├── urls.py │ └── wsgi.py ├── my_app │ ├── __init__.py │ ├── … -
Is there any way to edit the request user in django middleware?
I am creating a way for Superusers to assume control of another user's account, but allow logging to show that all actions performed in this time are done by the superuser. The idea I have currently is to process the request in middleware and look for a specific header. If that header exists I will replace the current request.user with the user specified in the header. Currently the middleware looks like this: class ControlledUserMiddleware(MiddlewareMixin): def process_request(self, request): controlled_user = request.META.get('HTTP_CONTROLLED_USER', None) if controlled_user: request.user = User.objects.get(uuid=controlled_user) I have found that - despite the fact I have placed this after the auth middleware in my settings file - the user in the request is always 'anonymous user' when it reaches this function. This method is not working currently and I was wondering if it was possible at all to edit the request.user before it reaches view logic. -
DRF - Serializer Multiple Models
please help! How can I can get this JSON { "campaign": 27, "campaignName": "Prueba promo", "promotionType": 999, "items": [ { "item_nbr": 1234567890123, "plu": 2}, { "item_nbr": 12345678901, "plu": 3} ] } Because , with my code I only retrive this JSON { "items": [], "campaign": 27, "campaignName": "Prueba promo", "promotionType": 999, "start_date": "2019-03-04T12:02:16.574874-03:00", "end_date": null, "active": true } How can I do it? I read the drf documentation but it didn't work, what I'm doing wrong? here is my code my models.py class Item(models.Model): promocion = models.ForeignKey(Promocion, related_name='items', on_delete=models.CASCADE, null=True) item_nbr = models.IntegerField(primary_key=True, help_text="Numero de Item") modular = models.ForeignKey(Modular, on_delete=models.CASCADE, null=True) price = models.FloatField() q_min = models.PositiveIntegerField(default=1, help_text="Cantidad mínima") q_mul = models.PositiveIntegerField(default=1, help_text="Multiplo de cajas cerradas") vensil1 = models.CharField(max_length=30, help_text="Atributo item relevante") vensil2 = models.CharField(max_length=30, help_text="Atributo item relevante") vensil3 = models.CharField(max_length=30, help_text="Atributo item relevante") FG = "Fleje grande, 1/3 Carta" FP = "Fleje pequeño 1/6 Carta" CP = "Carteleria media Carta" opciones = ((FG, "Fleje grande, 1/3 Carta"), (FP, "Fleje pequeño 1/6 Carta"), (CP, "Carteleria media Carta"),) print_type = models.CharField(choices=opciones, help_text="Fleje a imprimir", max_length=255) depto = models.IntegerField(default=1, help_text="Departamento") descri = models.CharField(max_length=100, help_text="Descripción producto") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, null=True) vendor_pack = models.IntegerField(default=1) container = models.CharField(max_length=6, default="MAY") size = models.CharField(max_length=20, help_text="Tamaño pack") … -
SQL Query in Django yielding different result
I'm running a query in my PostgreSQL db and in Django using django.db.connection. But for some reason, my query in Django yields completely different results. Here are my queries and their corresponding results. Query in PostgreSQL WITH calendar AS ( SELECT d FROM generate_series(date_trunc('day', CURRENT_DATE - INTERVAL '6 day'), CURRENT_DATE, '1 day'::interval) d) SELECT n.device_name AS dev_name, c.d::date AS dev_date, COUNT(mc.id) FROM (SELECT DISTINCT device_name FROM machine_counter) n CROSS JOIN calendar c LEFT JOIN machine_counter mc ON mc.device_datetime >= c.d + INTERVAL '7 hour' AND mc.device_datetime < c.d + INTERVAL '1 day 7 hour' AND n.device_name = mc.device_name GROUP BY n.device_name, c.d ORDER BY c.d, n.device_name; views.py def getMachineCount(request): cursor = connection.cursor() cursor.execute( ''' WITH calendar AS ( SELECT d FROM generate_series(date_trunc('day', CURRENT_DATE - INTERVAL '6 day'), CURRENT_DATE, '1 day'::interval) d) SELECT n.device_name AS dev_name, c.d::date AS dev_date, COUNT(mc.id) FROM (SELECT DISTINCT device_name FROM machine_counter) n CROSS JOIN calendar c LEFT JOIN machine_counter mc ON mc.device_datetime >= c.d + INTERVAL '7 hour' AND mc.device_datetime < c.d + INTERVAL '1 day 7 hour' AND n.device_name = mc.device_name GROUP BY n.device_name, c.d ORDER BY c.d, n.device_name; ''' ) records = cursor.fetchall() col_list = [desc[0] for desc in cursor.description] print(records) result = bindQueryColumnDescription(records, …