Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DRF + JWT Partial Image Update and GET filtering
I have a Rest API for my Django 'Time Management' app. Which has two models, an Employee model and an Attendance model. Here's what my serializers.py looks like: class EmployeeSerializer(serializers.ModelSerializer): class Meta: model = Employee fields = ('employee_id', 'employee_code', 'employee_first_name', 'employee_last_name', 'image_front', 'image_side_one', 'image_side_two') class AttendanceSerializer(serializers.ModelSerializer): class Meta: model = Attendance #Fields: #employee (Foreign Key of Employee) #starttime (Datetime Field, required) #startimage (Image Field, requried) #endtime (Datetime Field, null) #endimage (Image Field, null) #date (Date Field, automatically added of the date of startime.) fields = "__all__" Problem 1 - I want to check if an employee_code exists or not. Do I get all the Employees and iterate through all fields where if employee_code == Desired of each Employee? Or is there a way to filter while sending a get request? Here are my views: class EmployeeView(viewsets.ReadOnlyModelViewSet): queryset = Employee.objects.all() serializer_class = EmployeeSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) class AttendanceView(viewsets.ModelViewSet): queryset = Attendance.objects.all() serializer_class = AttendanceSerializer permission_classes = (permissions.IsAuthenticatedOrReadOnly,) parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): file_serializer = AttendanceSerializer(data=request.data) if file_serializer.is_valid(): file_serializer.save() return Response(file_serializer.data, status=status.HTTP_201_CREATED) else: return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Problem 2 - I've added the multi-file parser. What now? I'm not using POSTMAN, I'm using the Python Requests Library to update … -
Django signals: db inconsistency while testing
Quite similarly to Django test case db giving inconsistent responses, caching or transaction culprit?, I'm having an inconsistent behavior from the database during unit-tests. More precisely, the failing test class goes as follow: during setup, creation of an instance of a model signal on that model is triggered, and populates the field in SQL (cursor.execute...) at the end of the signal function, I check that the field has been populated -> no issue, everything works fine next line in setup, I reload the model from the database, and test the field -> no value I'm really at a loss here, so if anyone has any idea about what is going on, feel free to share ;) -
Django multiple upload, add user
based on this example, Im trying to add the user https://github.com/Chive/django-multiupload I changed the model to: class Attachment(models.Model): file = models.FileField(upload_to='attachments') timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) And the view to: class UploadView(FormView): template_name = 'upload/attachment_form.html' form_class = UploadForm def form_valid(self, form): form.instance.user = self.request.user.id for each in form.cleaned_data['attachments']: Attachment.objects.create(file=each) return super(UploadView, self).form_valid(form) #return super().form_valid(form) And I get this error: 'UploadForm' object has no attribute 'instance' But, how can I save the user ID also to the model? -
Django background task add attributes to Task class
I have background tasks for which I would like to add attributes, like some notes, or the name of the task, or other attributes related to the task. I am quite new to object oriented programming and have trouble framing my question. What I did is defined the class Task like so, however it simply overwrites the Task class. I would like to have the task class with some more arguments. from django.db import connection, models class Task(models.Model): status = models.CharField(choices=[("created","Created"),("pending","Pending"),("running","Running"),("completed","Completed"),("error","Error")],max_length=30) notes = models.CharField(max_length=200) start_scrape = models.DateTimeField() end_scrape = models.DateTimeField() -
Zappa Update failing in CircleCI
I am trying to deploy my Python project to AWS Lambda using Zappa and circleci. its throwing error Error: Zappa requires an active virtual environment! #!/bin/bash -eo pipefail zappa update dev (PyYAML 3.13 (/usr/local/lib/python3.6/site-packages), Requirement.parse('PyYAML>=4.1'), {'cfn-flip'}) Calling update for stage dev.. Error: Zappa requires an active virtual environment! Learn more about virtual environments here: http://docs.python-guide.org/en/latest/dev/virtualenvs/ Exited with code 1 I am installing venv using the below commands. pip install virtualenv virtualenv venv source venv/bin/activate Is there something that I am missing. Could someone help me. -
How Make A Variable As A Placeholder In A HTML Template In Flask?
So, I was making an HTML template in Flask And Wanted To Put The Form Label As The PlaceHolder Of A TextBox, But when I try to do so, Flask gives an error. My Code: <div class="input"> {{ form.username(class="txtb", placeholder={{ form.username.label }}) }} The Error Flask Gives: jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}' And when I try to print the label normally like <h4>{{ form.username.label }}</h4> It works completely fine. Also, this also works perfectly. <div class="input"> {{ form.username(class="txtb", placeholder="Username") }} I Don't Know Where I Went Wrong. Thanks In Advance! -
Less file wasn't found. Tried ... Django
First, I want to say that I only want less files to compile to css. I have my Django project with app, static files and other stuff. Due Django convention, static files should store like this: C:. └───myProject └───myApp └───static └───myApp ├───about ├───custom_stuff └───index Now, if I want to import presets.less from custom_stuff folder to index.less, in index folder, I need type whole path from myProject to index.less. But, instead, it throws me an error: '/myProject/myApp/static/myApp/custom_stuff/presets.less' wasn't found. Tried - /myProject/myApp/static/myApp/custom_stuff/presets.less What? How it can't be found if it is here? -
How to have create statement respect the "from_db_value" in custom Django fields?
Lets say I have a custom field, like this: class Temperature: pass class TemperatureField(models.DecimalField): def from_db_value(self, value, expression, connection): if value is not None: return Temperature(value) return None def to_python(self, value): if isinstance(value, Temperature): return value if value is None: return value kelvin = super().to_python(value) return Temperature(kelvin) def get_prep_value(self, value): if isinstance(value, Temperature): value = value.kelvin return super().get_prep_value(value) def get_db_prep_save(self, value, connection): if isinstance(value, Temperature): return connection.ops.adapt_decimalfield_value(value.kelvin, self.max_digits, self.decimal_places) elif isinstance(value, (float, int)): return connection.ops.adapt_decimalfield_value(Decimal(value), self.max_digits, self.decimal_places) elif isinstance(value, (Decimal,)): return connection.ops.adapt_decimalfield_value(Decimal(value), self.max_digits, self.decimal_places) Test(models.Model): temp = TemperatureField(max_digits=10, decimal_places=2) The following works as expected when loading data from the database, for example: >>>t = Test.objects.first() >>>t.temp <extra_fields.fields.Temperature object at 0x10e733e50> >>> type(t.temp) <class 'extra_fields.fields.Temperature'> The problem is that the logic for from_db_value does not extend to create statements: >>>t = Test.objects.create(temp=1) >>>t.temp 1 >>>type(t.temp) <class 'int'> Is there a way to extend this logic to the create method, without overriding the model manager? IE, can I do this within my field class? I don't think the specifics about what the Temperature class does are relevant, but if you would like to know, see the answer to my other question. -
Django REST API Regex on filter set
I am trying to get regex to work with my Django views using the rest API. The API seems to be working fine but I am not able to get it to perform searches using regex. I have the back end filters included in my settings. 'DEFAULT_FILTER_BACKENDS': ( 'rest_framework_datatables.filters.DatatablesFilterBackend', 'django_filters.rest_framework.DjangoFilterBackend', 'rest_framework.filters.OrderingFilter', 'rest_framework.filters.SearchFilter', ), Example views. queryset = Server.objects.all().order_by('hostname') serializer_class = ServerSerializer filterset_fields = ( 'hostname', 'region', 'system_model', ) search_fields = ( 'hostname', ) I have tried adding $ to the hostname in filterset however I get an error that no field matches. It does seem to be reading the $ as regex. Not sure if that only works in SEARCH fields. Still a bit confused between filter fields and search fields. Essentially I am trying to get it to allow me to perform a search like /api/servers/?hostname=.name.&system_model=.hp. Basically allow regex searching against the filter fields if that makes sense. -
Perform function in django after rendering page
I would like to know if there is how I execute a command after rendering the Django page. I have a system where I set the telephony training variable to False and run a command line with subprocess.Popen and I have to wait for the command to finish with .communicate () and say that the telephony training variable is True, but the command takes about 15 minutes to execute, so I would like to render the page as soon as the command is executed. My code is as follows: def GerarTreinoTelefonia(request): global treinamentotelefonia if treinamentotelefonia == False: if request.method == 'POST': treinamentotelefonia = True treinotelefonia = subprocess.Popen(shlex.split('python -m rasa_nlu.train -c chatbot/config/config_nlu.yml --data chatbot/dados/ilhas/telefonia/ -o /code/chatbot/models/telefonia --fixed_model_name nlu --project current --verbose')) return render(request, 'website/PainelGerenciamento.html') treinotelefonia.communicate() treinamentotelefonia = False Any idea how I can do it? -
Django: Does "primary_key=True" also mean "unique"?
Hello i am testing Django authentication and nesting user data. I created a simple MyProfil model for my users. I wanted to test making a custom id and set the primary_key=True as id = models.UUIDField. models.py class MyProfil(models.Model): id = models.UUIDField(primary_key=True, default=uuid4, editable=False) owner = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) aboutme = models.TextField(max_length=300, blank=True) city = models.TextField(max_length=300, blank=True) so far everything works in my favor but i have a question, that i could not answer myself even after reading the django doc. Question Does primary_key=True on my id Field also mean unique or do i have to declare it? -
Showing ( 'Figure id ='1001'...) as Output On Plotting Graph using Bokeh on HTML page with CSV and DateTime
I want to Plot Graph Containing Multiple Companies( Mult-line Graph ), But Getting output as Figure(id='1001', ...) gref = ref.head() p = figure(x_axis_type='datetime') gref['Date'] = pandas.to_datetime(ref['Date']) group = gref.groupby(pandas.Grouper(key='Date', freq='D'))['Open', 'Close', 'High'].sum() group = group / 1000 source = ColumnDataSource(group) p.line(x='Date', y='Open', line_width=2, source=source, legend='High') p.line(x='Date', y='Close', line_width=2, source=source, color=Spectral3[1], legend='Close') p.line(x='Date', y='High', line_width=2, source=source, color=Spectral3[2], legend='Open') p.title.text = 'Stock Analysis' p.yaxis.axis_label = 'Values' return render(request,'result.html',{'company':fetch,'tabcontent':temp,'last_20':last_20f,'graph':p}) -
Django: Select matching foreign keys during filter
We have the following example models and are wondering if it's possible to select the foreign keys that match during the same query, possibly as an annotation. class BaseProduct(models.Model): date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) name = models.CharField(max_length=255) sub_title = models.CharField(max_length=255, blank=True, null=True) identifier_retailer = models.CharField(max_length=255) tags = models.CharField(max_length=255, blank=True, null=True) has_multiple_variants = models.BooleanField(default=False) class BaseProductVariant(models.Model): product = models.ForeignKey(BaseProduct) name = models.CharField(max_length=128, blank=True, null=True) sub_title = models.CharField(max_length=255, blank=True, null=True) date_created = models.DateTimeField(auto_now_add=True) date_updated = models.DateTimeField(auto_now=True) description = models.TextField(blank=True, null=True, help_text='Product description') features = models.TextField(blank=True, null=True, help_text='One feature per line') content = RedactorField(allow_image_upload=True, allow_file_upload=True, blank=True, null=True, help_text='Use this for rich HTML on featured products') warranty_string = models.CharField(max_length=255, blank=True, null=True) identifier_retailer = models.CharField(max_length=255, blank=True, null=True) identifier_upc = models.CharField(max_length=255, blank=True, null=True) identifier_model = models.CharField(max_length=255, blank=True, null=True) We can query the results easily with BaseProduct.objects.filter()... but would like to select the list of matching BaseProductVariant's at the same time, otherwise we have to query the database in an unconventional fashion, and joining in python with prefetch_related on BaseProductVariant.objects.filter(product__in=[]).prefetch_related(product), select_related works on this too, but it a bit slower due to the extra deserialization on each row. -
Display All the facebook friends or current user in django
I want to display all the friends of the current user in a list (and then also want to check which are on the website and which are not) I used python-social-auth for Django for logining in. What I am getting is an empty list. Here is the main code SOCIAL_AUTH_FACEBOOK_SCOPE = [ 'email', 'user_friends', ] The displaying function. @login_required(login_url='/accounts/login/') def allfriends(request): social_user = request.user.social_auth.filter( provider='facebook' ).first() # we only need the data from the facebook obviously we only are using the facebook to get it. # oururl = u'https://graph.facebook.com/{0}/' \ u'friends?fields=id,name,picture' \ u'&access_token={1}'.format( social_user.uid, social_user.extra_data['access_token'], ) request = urllib.request.Request(oururl) friendslist = json.loads(urllib.request.urlopen(request).read()).get('data') return render(request, 'description/friends_list.html', {friendslist}) The error they are showing me is: TypeError at / unhashable type: 'list' It is showing me that the friendlist is empty: localvariables friendslist [] oururl 'https://graph.facebook.com/520966375368471/friends?fields=id,name,picture&access_token=EAANTv4ZA4iGgBAKveRjMivl8124j6JpuACFIZCkQqwYVNwT5b9J0xTEQQmpdpgZBbOJZBszvFLIs4a9Y2ZAcBfTqzLGkFhq1WlX25o1vF0C3q6brhuJazREXZAuz1lZAPZCb44QF0DYSd95GGWxgRqNEZAcv6QgZB2f6rxCUuSHYfDXwZDZD' request <urllib.request.Request object at 0x7f4851ff2da0> social_user <UserSocialAuth: RishabhJain> I am not able to get what really I am doing wrong You can ask for more code if you want to. If I don't use this friendlist thingy everything is working fine. -
How to structure Django project and implement views into index.html
I have my frontend set up using html and css. Now I would like to use Python/Django to make http requests on a third party API (views.py) and return the data to my html containers within the index.html site which represents my dashboard. My goal is to enable the user to choose the soccer team of his choice within the sidebar to update the dashboard with the according data that is sourced via third party API and manipulated via Python afterwards before displaying it on the frontend. Is there any way to do this or do I have to change my entire frontend development to python/django now? (since I can't find any resource/tutorial that suggest to link views.py functions to .html files). Still trying to figure out how these spheres are connected to each other. This is my current project setup: Project structure Any hints are much appreciated. Thanks. -
Django deepcopy a model instance to memory
I want to write a test for a Django view that modifies an instance of a model. In the past there was a problem with the view's code, it was writing on other unconcerned model instances too. I am looking for a way to "copy" a model's instance in memory, run the view, then compare the memory and database version of the instance. Pseudo code : def test_some_view: url = reverse('some_view') unconcerned_model = MyModel.objecs.get(id=X) concerned_model = MyModel.objects.get(id=Y) cpy = deepcopy_of(unconcerned_model) # how can we do that ? self.client.post(url, {'mymodel_id':concerned_model.id}) unconcerned_model.refresh_from_dbs() self.assertEqual(cpy, unconcerned_model) How can the deepcopy be done ? How to compare the 2 versions ? -
creating a django model that has a relationship with its own class
I want to create a model called task, it has some fields and a relationship with itself it means the task itself can be created of some other tasks, the code: from django.db import models class Task(models.Model): ... name = models.CharField(max_length=100) ... tasks = models.ForeignKey(Task, -
Django testing, after login still get response 302, expecting 200
I'm testing django app login part. my work flow is client.get('/run/experiment/1') -> response 302, redirect to login page -> client.post('loginpage', {'username': 'tester', 'password': 'tester'}) -> client.get('/run/experiment/1') -> response 200. I have tested this flow in shell (type and execute the command line by line), and it worked as expected. But when I write the test file, even after post the login, I still got the status 302 when trying to client.get. Here is my code: from django.test import TestCase, Client class TestRunRequireLogin(TestCase): def setUp(self): self.client = Client() def test_rerun_not_login(self): response = self.client.get('/experiment/1') self.assertEqual(response.status_code, 302) def test_rerun_login(self): self.client.post('/accounts/login/?next=/run/experiment/1', {'username': 'tester', 'password': 'tester'}) response = self.client.get('/experiment/1') self.assertEqual(response.status_code, 200) -
print query not working in django filterset
views.py def Search_list(request): movies_list = Movies_list.objects.all() print(movies_list) movies_filter = SearchFilter(request.GET, queryset=movies_list) print(movies_filter) return render(request, 'movies_list/search_details.html', {'filter': movies_filter}) forms.py import django_filters from django.contrib.auth.models import * from django.contrib.admin.widgets import FilteredSelectMultiple class SearchFilter(django_filters.FilterSet): name = django_filters.CharFilter(lookup_expr='icontains') language = django_filters.ModelMultipleChoiceFilter(queryset=Language_list.objects.all(),widget=forms.CheckboxSelectMultiple) cast = django_filters.ModelMultipleChoiceFilter(queryset=Cast_list.objects.all(),widget=forms.CheckboxSelectMultiple) class Meta: model = Movies_list fields=['name','language','cast'] Everything work fine without any error but doesn't print anything on terminal for in views print(movies_list) print(movies_filter) I just want to create pagiantion by adding modifying views.py as def Search_list(request): movies_list = Movies_list.objects.all() movies_filter = SearchFilter(request.GET, queryset=movies_list) print(movies_filter) paginator = Paginator(movies_filter.movies_list, 5) page = request.GET.get('page') print(page) try: pub = paginator.page(page) except PageNotAnInteger: pub = paginator.page(1) except EmptyPage: pub = paginator.page(paginator.num_pages) movies_filter = SearchFilter(request.GET, queryset=movies_list) return render(request, 'movies_list/search_details.html', {'filter': pub}) It doesn't gives any error execute just fine but doesn't paginate my queryset result. movies_list/search_details.html {{filter.qs.count}} {% for movies in filter.qs %} {{movies}} {%endfor%} -
Creating related objects on create with DRF
Basically, I'm trying to create an object with realted objects in one request in DRF, something I thought would be quite simple. In the example below, I want to create a Race with multiple RaceCars The research and other questions I've looked at all say the following should work, can anyone tell me what's going wrong? I'm gettting a KeyError for racecars when trying to pop from validated_data, in other words validated_data doesn't contain racecars. I can do the logic in the create method on the view, but this seems the more sensible place to do it and I want to know what I'm doing wrong. The setup is as follows: models.py class Driver(models.Model): name = models.CharField() team = models.CharField() class RaceCar(models.Model): color = models.CharField() driver = models.ForeignKey() race = models.ForeignKey(related_name='racecars') class Race(models.Model): name = models.CharField() serializers.py class RaceCarSerializer(models.Model): driver = PrimaryKeyRelatedField(queryset=Driver.objects.all()) class Meta: model = RaceCar fields = 'driver', 'color' class RaceCreateSerializer(models.Model): racecars = RaceCarSerializer(many=True) class Meta: model = Race fields = 'name', 'racecars' def create(self, validated_data): racecars = validated_data.pop('racecars') instance = Race.objects.create(**validated_data) for racecar_data in racecars: RaceCar.objects.create(race=instance, **racecar_data) return instance POST data { 'name': 'Gold Cup', 'racecars': [ {'driver': 1, 'color': 'blue'}, {'driver': 4, 'color': 'red'} ] } … -
problem getting text data in angular and Django
I'm trying to get data to print in the text boxes , I added an image so you can see that you get the data correctly with the button, but you don't print it in the text boxes component html nombre examen <input type="text" [(ngModel)]="selectedExamen.nombreExa"><br> detalle examen <input type="text" [(ngModel)]="selectedExamen.descripcionExa"><br> creacion del registro <input type="text" [(ngModel)]="selectedExamen.release_date"><br> fecha del examen<input type="text" [(ngModel)]="selectedExamen.fechaExa"><br> categoria examen<input type="text" [(ngModel)]="selectedExamen.categoriaExa"><br> component ts I made the import of the necessary model for this component ts examenes: Examen[]; constructor(private dataService: dataService) { this.getExamenes(); this.selectedExamen = {id: -1, nombreExa: '' , descripcionExa: '', release_date:'', fechaExa: '', categoriaExa:'' }; } examenClicked = (exa) => { this.dataService.getOneExamen(exa.id).subscribe( data => { console.log( this.selectedExamen = data); }, error => { console.log(error); } ); } the service getOneExamen(id): Observable<any> { return this.http.get(this.baseurl + '/examen/' + id , {headers: this.headers}); }[enter image description here][1] -
Django Command(manage.py) ignore DATABASE
I created some django commands so I can execute it like python manage.py my_custom_task. That works locally. But looks like it will not work in the build server because it will require a database connection when running a django command. Can I run a python manage.py my_custom_task that will ignore checking a database connection since my_custom_task does not really require a DB? -
Dockerizing: django-reactjs
I have just completed a test project with backend API's in Django an front-end in reactjs on different ports. I've gone through a lot of blogs but haven't been able to find one that teaches how to dockerize this application now. I have different repositories for both backend and front-end as well. at the moment, the Django app is on PORT 8200 and the reactjs front-end is on 3200. Any help would be very much appreciated. Thank you! -
How to actually use DRF with Python Requests
So, I have a rest API for my Django 'Time Management' app. I am using the JWT(JSON Web Token) Authorization for my API. I have all the settings and views configured but I didn't clearly grasp the concept of how it actually works. I have a client for my application that will be using these auth tokens to add attendance. Here's my project's url.py: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView urlpatterns = [ path('', admin.site.urls), path('time/', include('timemanagement.urls')), path('api-auth', include("rest_framework.urls")), path('api/token/', TokenObtainPairView.as_view()), path('api/token/refresh/', TokenRefreshView.as_view()), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Problem 1 - Basically, when my app first starts up, what do I want it to do? I'm assuming I need to first make a request to 'myserver.com/api/token/' with my username and password as headers but I don't know how I would do this with the Python Requests library. Problem 2 - Let's say my token expired. How would my client app know that? (By sending a request with that token then I'm guessing I would get an error?) If so, how do I handle this error to get a new token? And what if that token … -
Cannot view tooltip data using chart.js
I have little problem using chart.js . I can see graphs on screen but when i use aggregation method then i cannot see tooltip and please guide me how can i use looping function with graph here is my views.py def get(self, request, format=None): qs = Add.objects.all().aggregate(Sum('expense')) a = qs.values() print(a) labels = ["budget", "Pink", "Yellow", "Green", "Purple", "Orange"] default_items = [a, 10, 10, 10, 10, 10] # PROBLEM IS HERE data = { "newlabels": labels, "newdata": default_items, } return Response(data) template t var endpoint = '/api/chart/data/' var labels = [] // ADDES var defaultData = []; // ADEED TO VIEW DATA ON SCREEN $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, // CHANGED datasets: [{ label: 'sum', data: defaultData, // CHANGED }] } }) },