Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python: How to convert json comma separated key to a dictionary
I have a JSON in below format: { '166, 175': 't2', '479': 't3' } I want to convert this to a map: 166: 't2' 175: 't2' 479: 't1' -
How to fix FieldError at /?
I've been trying to get my categories set up for a blog, I've tried deleting the "migrations" directory and db.sqlite3 to recreate my models and now I am receiving a FieldError. FieldError: Cannot resolve keyword 'categories' into field. Choices are: category, category_id, comment_count, comments, content, featured, id, overview, post_img, slug, timestamp, title Models.py from django.db import models from django.urls import reverse from tinymce import HTMLField from django.utils import timezone class CategoryTag(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique=True) class Meta: verbose_name = ('category') verbose_name_plural = 'categories' def __str__(self): return self.title class Post(models.Model): title = models.CharField(max_length=250) overview = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) content = HTMLField('Content') comment_count = models.IntegerField(default=0) post_img = models.ImageField() category = models.ForeignKey('CategoryTag', on_delete=models.CASCADE) featured = models.BooleanField() slug = models.SlugField(max_length=250, unique=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={ 'id': self.id }) ``` -
chained dropdown menu is not working properly
I have three chained dropdown menus which are not working properly. these three menus based on three variables passed from previous page. I want to connect them together. So when one item is selected other menu will have option based on this item. The three menus are for city, category, and subcategories. This is ads-classified website. I used Django 1.11.4 as a frame work combined with ajax to do this feature. For now, I connect only the second menu with the third one (category with sub-category). When I changed the second menu, the third one gives me an empty menu. I tried to figure it out but with no luck. Following is the code I wrote: The url: # url for the load_subcategories url(r'^ajax/load-subcategories/$', views.load_subcategories, name='ajax_load_subcategories'), # url for list page: url(r'^(?P<post_city>[\w\ ]+)/(?P<category_name>[\w\ ]+)/(?P<sub_category_name>[\w\ ]+)$', views.list_page, name='list_page'), The view functions are as follow: def load_subcategories(request): category_name_id = request.GET.get('category_id') sub_categories = Post_Sub_Category.objects.filter(category_name_id=category_name_id).order_by('sub_category_name') return render(request, 'towns/salehslist/sub_categories_dropdown_list_options.html', {'sub_categories': sub_categories}) def list_page(request, post_city, category_name, sub_category_name): template = 'towns/salehslist/list_page.html' if post_city is None: post_city = 'الرياض' if category_name is None: category_name = 'للبيع' if sub_category_name is None: sub_category_name = 'سيارات' # main (header) search query_fc = request.GET.get('h_qc') query_fcc = request.GET.get('h_qcc') query_fsc = request.GET.get('h_qsc') if query_fc: … -
How to relate an object and feild in django?
Actually i didn't know how to ask this question. Say i have choices for subjects in my code with a subject code and subject name where i will use the get_object_display ORM to display the subject name. ... SUBJECTS = (('MA8151','Engineering Mathematics'),('PH8151','Physics-1'),...) subject = models.CharField(max_length=10, choices=SUBJECTS) What I want is, i want to add another feature to the choice, that each choice has subject name, subject code and a credit point for it. I thought of creating a model ... subname = models.CharField(max_length=100) subcode = models.CharField(max_length=6) credit = models.SmallPositiveInteger() But since i'm new to django, i don't know how this will work on linking an object the name of a choice? On the whole, if i assign a subcode for a student, i want his records to be updated with relevant subname and relevant credit points. Help me out reaching the solution. Thanks in advance! -
Django ORM and GROUP BY
Newcommer to Django here. I'm currently trying to fetch some data from my model with a query that need would need a GROUP BY in SQL. Here is my simplified model: class Message(models.Model): mmsi = models.CharField(max_length=16) time = models.DateTimeField() point = models.PointField(geography=True) I'm basically trying to get the last Message from every distinct mmsi number. In SQL that would translates like this for example: select a.* from core_message a inner join (select mmsi, max(time) as time from core_message group by mmsi) b on a.mmsi=b.mmsi and a.time=b.time; After some tries, I managed to have something working similarly with Django ORM: >>> mf=Message.objects.values('mmsi').annotate(Max('time')) >>> Message.objects.filter(mmsi__in=mf.values('mmsi'),time__in=mf.values('time__max')) That works, but I find my Django solution quite clumsy. Not sure it's the proper way to do it. Looking at the underlying query this looks like this : >>> print(Message.objects.filter(mmsi__in=mf.values('mmsi'),time__in=mf.values('time__max')).query) SELECT "core_message"."id", "core_message"."mmsi", "core_message"."time", "core_message"."point"::bytea FROM "core_message" WHERE ("core_message"."mmsi" IN (SELECT U0."mmsi" FROM "core_message" U0 GROUP BY U0."mmsi") AND "core_message"."time" IN (SELECT MAX(U0."time") AS "time__max" FROM "core_message" U0 GROUP BY U0."mmsi")) I'd appreciate if you could propose a better solution for this problem. Thanks ! -
Djano inineformset save and delete
I am trying to do something really simple. But, there is a problem I cannot figure out, so I appreciate any help. Here is my code: # in views.py def post(self, request, *args, **kwargs): assembly_id = kwargs.get('assembly_id', None) active_assembly_project = assembly_instance = Assembly.objects.get(id = assembly_id) # Second, if the specified assembly does not belong to the active development project, then PartTypeInlineFormSet = inlineformset_factory(Assembly, PartType, formset = BasePartTypeInlineFormSet, fields = __all__ can_delete = True ) kwargs = {'assembly_project': active_assembly_project, } part_type_formset = PartTypeInlineFormSet(request.POST, request.FILES, instance = assembly_instance) if part_type_formset.is_valid(): part_types_cd = part_type_formset.cleaned_data forms_marked_for_deletion = part_type_formset.deleted_forms # <== Correctly identifies the forms marked for deletion part_type_formset_kwargs = {'assembly_project': active_assembly_project,} assembly_development_types = part_type_formset.save(**part_type_formset_kwargs) # forms.py class BaseDevelopmentTypeInlineFormSet(BaseInlineFormSet): def clean(self, *args, **kwargs): forms = self.forms if any(self.errors): errors = self.errors return for form in self.forms: should_delete_form = form.cleaned_data.get('DELETE', False) print ('should_delete_form: ', should_delete_form) # <= Correctly shows the forms that have 'DELETE': on if self.can_delete and should_delete_form: continue def save(self, commit = True, *args, **kwargs): ''' Custom save to save the development projects when saving development types''' the_assembly_project = kwargs.pop('assembly_project', None) instances = super(BasePartTypeInlineFormSet, self).save(commit=False, *args, **kwargs) assert False #<== gives me instances = [] !!! for instance in instances: if commit: instance.save() else: … -
Update FielField of an existing model
I have this model class TravelRequests(models.Model): mission_order = models.FileField(blank=True, null=True, upload_to='mission_order') where the mission order filefield is not required for the creation of the model but than it will be updated by an another user so he can upload the file. The problem is that when i upload the file when the model is created it doesn't save the file in the /media folder and in the filefield it self it save only the name of the file this is the ajax request : var data = new FormData($('.facilities_form').get(0)); var pk = $(this).val() $.ajax({ type: "POST", url: '/approve_facilities/' + pk + '/', data: data, cache: false, processData: false, contentType: false, success: function(response) { if (response == 'request_updated') { Swal.fire({ title: 'The request is approved!', type: 'success', allowOutsideClick: false, }).then((result) => { if (result.value) { window.location.href='/' } }); } } }); this is the view that handle the request @login_required def FacilitiesApproveRequest(request, pk): cordinator_comment = request.POST.get('cordinator_comment', '').strip() mission_order = request.FILES.get('mission_order') request_toApprove = TravelRequests.objects.filter(pk=pk) request_toApprove.update(mission_order=mission_order, facilities_approve_case=True, facilities_comment=cordinator_comment, facilities_comment_time=timezone.now(), request_updater=request.user, request_update=timezone.now(), request_status='facility_approve', facilities_aprove=request.user) return HttpResponse('request_updated') this is the html input : <form class="facilities_form" method="post" enctype="multipart/form-data"> <input type="file" name="mission_order" id="id_mission_order" accept=".pdf,.jpeg,.png,.msg"> </form> when i use the form to update the field i get this … -
Manually populate the ImageField remotely
Let me start off by explaining how my program works. I have model in Django like, class Attendance(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to=func_that_returns_path) Now, I have done this so that I can view the Attendance table rows from Django Admin, but I'm not going to be populating it from the Django Admin. See, I want to populate this table outside of Django. I'll have two programs. One, my Django app and another python script that connects to the server manually and does it's magic. My Django app will be hosted on a server and the script will be kept on my computer. The very first idea I had was to manually connect to the database using mysql-connector and just put the image in the database through it but then I realized that Django models don't actually hold the file itself but the file location. This complicated things. I don't really have any idea other than putting the file in the server through a TCP socket connect and putting the file in the media folder and adding the path to that file in the database. Please let me know if you have any other ideas or what else might work. -
How to paginate external API in Django Rest Framework
I'm learning to use Django Rest Framework, so as exercise I want to consume Github User REST API listing the users and save on a local database a specific user info, also I want that listing to be paginated. I have the following viewsets file: import requests from rest_framework.decorators import action from rest_framework.response import Response from rest_framework.viewsets import ModelViewSet from users.models import User from .serializers import UserSerializer class UserViewSet(ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer @action(detail=False, methods=['GET']) def github(self, request): data = requests.get('https://api.github.com/users') return Response(data=data.json()) I'm able to list my users, and I know how to paginate the queryset but how do I paginate the github response ? another question, in this snippet my routes stay like: api/user api/user/github ​ Is there a way to create a separate view just for the github so I can something like: api/user api/github/user api/github/repository ​ and then be able to use filter field on api/user and api/github/user. -
Saving data inside and outside a form into a database
I'm learning to code with Django. So I have a form that displays quizzes and a JavaScript file that computes these quizzes. The quizzes are displayed in a , and I have other details like course still displayed on the form. To the best of my knowledge, POST only takes data withing the form. What if I have the score outside the form, how do I go about it? This is what I've done already: The JavaScript that computes the results: `` function submitAnswers(answers) { var total = answers.length; var score = 0; var choice = [] //new dynamic method 1 for (var i = 1; i <= total; i++) { choice[i] = document.forms["quizForm"]["q" + i].value; } for (i = 1; i <= total; i++) { if (choice[i] == null || choice[i] == '') { alert('You skipped question ' + i); return false; } } // new dynamic method for checking answer for (i = 1; i <= total; i++) { if (choice[i] == answers[i - 1]) { score++; } } //Display Result var results = document.getElementById('results'); results.innerHTML = "<h3>You scored <span>" + score + "</span> out of <span>" + total + "</span></h3>" alert("You scored " + score + " … -
Call Django on HTML button click Part 2
My question is basically this question: Call Django on HTML button click To summarize: in Django, how do you call a function after clicking a button? I followed the answer in the above link, however, whenever I click on the button it takes me to the URL of /actionUrl, which I do not want. I simply want the function I have to be called when the button is clicked. Any help would be appreciated because I do not have enough rep to comment on that post. -
django init value change after form submit
I am trying to change user LoginView, for some reason i want to use mobile number as username, and after user input phonenumber i will send a code to mobile via SMS. before sending SMS i want to be sure spam but don't attack to my form. I know, I can use google captcha and other plugin. but for my training I wan't to use my own way. there for I create a model name question, there are many question and answer inside table. every time page refresh a random question shows to visitor. this works fine without any problem. but my problem is when i want to validate form self.question chose another random question each time. this is very confusing. I tried to validate inside view and form, no difference question always return another question. model.py class Question (models.Model): question = models.CharField(max_length=100, null=False) answer = models.CharField(max_length=100, null=False) secend_answer = models.CharField(max_length=100,blank=True, null=True) KIND_CHOISE = ( ('I', 'idoms'), ('M', 'mathematic'), ('K', 'knowledge'), ) question_kind = models.CharField(max_length=1, choices=KIND_CHOISE) def __str__(self): return "quest => {}, answer is ==> {}".format(self.question, self.answer) views.py class LoginnView( FormView): form_class = UserLoginForm template_name = 'accounts/login.html' success_url = 'accounts/login.html' def bquestion(self): ques = None max_id = Question.objects.all().aggregate(max_id=Max("id"))['max_id'] while ques … -
Nested serialization for JSON
I'm trying to return a JSON like this after a successful post request. { "ip": "127.0.0.1", "ports": [ {port: "", service: ""} ], "first_scan": "date", "last_updated": "date" } I'm trying to make my serializer so that whenever my nmap function which returns data in this way on the console: Host : 127.0.0.1 (localhost) State : up port : 631 service : CUPS port : 902 service : VMware Authentication Daemon port : 6463 service : port : 8000 service : WSGIServer/0.2 CPython/3.7.3 It would parse it like the JSON mentioned. I have tried making a model like this in my models.py class nmapScan(models.Model): ip = models.CharField(max_length=13, blank=True) ports = models.CharField(max_length=5) service = models.TextField() first_scan = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['first_scan'] But I'm still confused by this nested serialization concept. How would I go on making the data get parsed from my function, return it like that certain JSON and have it stored in the database (assuming my model is right) properly? -
Multiple forms with one FormView
Is it possible to use a FormView for 2 forms ? I know the class accepts one form_class by default but is there a workaround ? class MyForm(FormView): template_name = 'index.html' form_class = ThisIsMyForm success_url = '/list' context_object_name = 'user_id' def save(self, *args, **kwargs): if not self.timeout: self.timeout = 10 super(MyModel, self).save(*args, **kwargs) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['user_id'] = self.request.user.id return context def form_valid(self, form): form.save() return HttpResponseRedirect(self.success_url) I don't suppose I could pass it through in the context variable ? -
attaching information to a form in its GET request
I am using this code inside my template to attach info to a GET request "{% url 'foo_create'%}?fooHolder_pk={{fooHolder.pk}}" and I have a form. now I want to use fooHolder.pk to attach it as a Foreign key to foo in the form GET request. But when I do that. The POST request still shows that the foreign key is null. Note: I am using function Based Views -
How to query a model made up of multiple Foreign Keys
I'm doing the CS50 Web programming course, learning to use Django. The learning exercise basically has you recreating this pizza restaurant menu with django. I've created some models for the data, and now I'm trying to use Django templating to create a menu page for the pizzas. Here are my models: from django.db import models class intToppings(models.Model): name = models.CharField(max_length=16) intToppings = models.IntegerField() # 0 Cheese, 1/2/3, 5 Special def __str__(self): return f"{self.name}" class Size(models.Model): size = models.CharField(max_length=16) def __str__(self): return f"{self.size}" class PizzaBase(models.Model): base = models.CharField(max_length=16) def __str__(self): return f"{self.base}" class Toppings(models.Model): topping = models.CharField(max_length=32) def __str__(self): return f"{self.topping}" class Pizza(models.Model): size = models.ForeignKey(Size, on_delete=models.CASCADE) # CASCADE will delete all Regular Pizzas if their size is deleted (as opposed to .SET_NULL) base = models.ForeignKey(PizzaBase, on_delete=models.CASCADE) intToppings = models.ForeignKey(intToppings, on_delete=models.CASCADE) price = models.IntegerField() # price in cents def __str__(self): return f"{self.size} {self.base} {self.intToppings} Pizza" There's an entry "small" and "large" in the Size db, and for intToppings there is one entry with name "cheese" and an int of 0, another for "1 topping" with an int of 1, etc. And for the Pizza model, I made an entry for every combo on the menu, ie: <QuerySet [<Pizza: small Regular Cheese … -
webcam Live Stream from HTML webpage to Django server for processing the stream with OpenCV python
I have just started showing my interest in computer since couple of months ago . I'm working on project called face detection , which will basically use OpenCV Harrcascades for frontal face detection . Though there are lot of tutorials available for face detection using javascript on client side , but I want to implement the same thing using Python . I'm using Django server in backend , since it will be easier to implement the opencv python code . So far I have only created a simple HTML webpage that access the user WebCam (The script s included below). I want to stream this video from HTML webpage to Django server so that I can further process the video for face detection . Any kind of help and suggestions will be appreciated . Thank you in Advance. navigator.mediaDevices =(navigator.mediaDevices.getUserMedia||navigator.mediaDevices.webkitGetUserMedia||navigator.mediaDevices.mozGetUserMedia||navigator.mediaDevices.msGetUserMedia|navigator.mediaDevices.oGetUserMedia); var video; var webcamstream; function startWebcam() { var canvas = document.getElementById('output'); var context = canvas.getContext('2d'); video = document.getElementById('input'); if (navigator.mediaDevices) { navigator.mediaDevices.getUserMedia({ video: true }) .then(function (stream) { video.srcObject = stream; webcamstream = stream; }) .catch(function (err0r) { console.log("Something went wrong!"); }); } video.addEventListener('play',function(){ draw(this, context, 300, 150); }, false); function draw(video, context, width, height) { context.drawImage(video, 0, 0, width, … -
Recieving an Attribute error when trying to add a new view
Im learning django, and following a tutorial online, im trying to create a new view for "home" but i keep recieving an attribute error. AttributeError: module 'pages.views' has no attribute 'home' Ive checked that I'm not doing anything wrong, and so I thought maybe the tutorial is outdated etc, but in the urls.py file, it says to do the exact same thing. Ive searched around google and tried removing spaces before the comas, changing the import name to a ".", Ive tried changing the name of the function and in the urls. views.py: from django.http import HttpResponse from django.shortcuts import render # Create your views here. def home(*args, **kwargs): return HttpResponse("<h1>Hello World!</h1>") urls.py: """trydjango URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from pages … -
Django rest framework: omit dict where field is empty
At the moment I get this response from a request: { "count": 1000, "results": [ { "name": "name 1", "description": "long text", "youtube": "" }, { "name": "name 2", "description": "long text", "youtube": "youtube.link" } ... ] } And I would like that I only get dicts back, where the youtube field is not empty. For example like this: { "count": 20, "results": [ { "name": "name 2", "description": "long text", "youtube": "youtube.link" } ... ] } Is there a way to realize this? I only found solution with where it was possible to skip only the fields, but I need a solution where the hole object will skip. -
flask or django for OOAD and DB project?
I would like some recommendations on what to use when creating a semester project for Object Oriented Analysis and Design(OOAD) and Database(Db). I know that Django comes with many modules and does alot of work behind the scene where as Flask is a lightweight framework. I think Django is not such a good choice because it provides many abstractions, making it difficult for newbies to understand what is going on under the hood. As a CS undergrad student, I should know about each and every component of my application. Therefore, I am more inclined to use Flask. If you think otherwise, kindly share your opinion. -
Using transactions in Django
I'm using django 1.11 on python 3.7 In a method I want to execute some database queries, mainly updating links between objects and I want to use this method to perform a check on what needs to be updated in a sync-operation. The following is an implementation: results = {} with transaction.atomic(): sid = transaction.savepoint() for speaker_user in speaker_users: # here my code checks all sorts of things, updates the database with # new connections between objects and stores them all in the # results-dict, using a lot of code in other classes which # I really dont want to change for this operation if sync_test_only: transaction.savepoint_rollback(sid) else: transaction.savepoint_commit(sid) return results This snippet is used in a method with the sync_test_only parameter that should only fill the results-dict without doing the database changes that go along with it. So this method can be used to do the actual work, when sync_test_only is False, and also only report back the work to-be-done, when sync_test_only is True Is this what the transaction.atomic() is designed for? Does this actually work in my use-case? If not, what would be a better way to achieve this behaviour? -
How do I create a table with inlineformset?
I made out the modelform in the table. How do I change the look of the table so that there would be two columns in the left - the field responsibility (textfield) and in the right under each other date input fields? Or do it without using the table on the bootstrap . form looks like templates.html <table class="table table-responsive"> {{ project_form.management_form }} {% for form in project_form.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle 'row1' 'row2' %} formset_row"> {% for field in form.visible_fields %} <td> {# Include the hidden fields in the form #} {% if forloop.first %} {% for hidden in form.hidden_fields %} {{ hidden }} {% endfor %} {% endif %} {{ field.errors.as_ul }} {{ field }} </td> {% endfor %} </tr> {% endfor %} </table> -
Multiple HTML option selection not working
I am developing a task management system using the django framework where supervisors can log in and assign tasks to multiple users using Django many to many field. When I log in to the admin portal, I can select multiple users at the same time which saves to the database well. But when I use the front end template, I am able to select multiple users but the selected options never get saved in the database and instead the field will be blank when viewing from the database table. Here is my Model: from django.contrib.auth.models import User class Task(models.Model): task_title = models.CharField(max_length=30, blank=True, null=True) unit = models.ForeignKey(Unit, blank=True, null=True) audit_phase_choice = ( ('Pre Engagement', 'Pre Engagement'), ('Understanding Entity', 'Understanding Entity'), ('Risk Assessment', 'Risk Assessment'), ('Performing Audit', 'Performing Audit'), ('Report', 'Report'), ) audit_phase = models.CharField(max_length=30, blank=True, null=True, choices=audit_phase_choice) assigned_by = models.CharField(max_length=30, blank=True, null=True) assigned_to = models.ManyToManyField(User, blank=True) date_assigned = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) status = models.CharField(max_length=30, blank=True, null=True) completed = models.BooleanField('Task Completed', default=False) date_completed = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) start_date = models.DateTimeField(auto_now_add=False, auto_now=False, blank=True, null=True) due_date = models.DateField(auto_now_add=False, auto_now=False, blank=True, null=True) comment = models.TextField('comments', max_length=3000, default='', blank=True, null=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False, blank=True) def __unicode__(self): return self.task_title def get_absolute_url(self): return reverse("taskmis:user_task_edit", … -
Python / DRF - error when trying to serialize a dictionary
I have the following dictionary: <type 'dict'>: {u'user2': {'username': u'user2', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': None, 'videos_overall': None, 'problems_overall': None, 'problems_attempts_overall': None, 'correct_problems_overall': None, 'forum_posts_last_week': 2, 'forum_posts_overall': 13, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': None}, u'user3': {'username': u'user3', 'problems_attempts_last_week': None, 'videos_last_week': None, 'correct_problems_last_week': 6, 'videos_overall': None, 'problems_overall': 18, 'problems_attempts_overall': 3, 'correct_problems_overall': 15, 'forum_posts_last_week': None, 'forum_posts_overall': None, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 6}, u'user1': {'username': u'user1', 'problems_attempts_last_week': 4, 'videos_last_week': 1, 'correct_problems_last_week': None, 'videos_overall': 3, 'problems_overall': 8, 'problems_attempts_overall': 4, 'correct_problems_overall': 4, 'forum_posts_last_week': 2, 'forum_posts_overall': 2, 'date_last_active': datetime.datetime(2019, 8, 23, 0, 0, tzinfo=<UTC>), 'problems_last_week': 4}} And the following Serializer for it: class UserEngagementSerializer(serializers.Serializer): """ Serializes row data """ username = serializers.CharField() videos_overall = serializers.IntegerField() videos_last_week = serializers.IntegerField() problems_overall = serializers.IntegerField() problems_last_week = serializers.IntegerField() correct_problems_overall = serializers.IntegerField() correct_problems_last_week = serializers.IntegerField() problems_attempts_overall = serializers.IntegerField() problems_attempts_last_week = serializers.IntegerField() forum_posts_overall = serializers.IntegerField() forum_posts_last_week = serializers.IntegerField() date_last_active = serializers.DateTimeField(format=settings.DATE_FORMAT) When I try to return the results from my REST service, the following error is displayed: AttributeError: Got AttributeError when attempting to get a value for field username on serializer UserEngagementSerializer. The serializer field might be named incorrectly and not match any attribute or key on the unicode instance. Original exception text was: 'unicode' … -
I can't upload images with django
I am creating an image upload function with django. However, it is not uploaded. I don't know the code mistake, so I want to tell you. I tried variously, but if I specify default for imagefiled, default will be applied. #form class RecordCreateForm(BaseModelForm): class Meta: model = URC fields = ('image',) def __init__(self, *args, **kwargs): user = kwargs.pop('user') super(RecordCreateForm,self).__init__(*args, **kwargs) self.fields['URN'].queryset = UPRM.objects.filter(user=user) #view class RecordCreate(CreateView): model = URC form_class = RecordCreateForm template_name = 'records/urcform.html' success_url = reverse_lazy('person:home') def get_form_kwargs(self): kwargs = super(RecordCreate, self).get_form_kwargs() # get users, note: you can access request using: self.request kwargs['user'] = self.request.user return kwargs def form_valid(self, form): user = self.request.user form.instance.user = user form.instance.group = belong.objects.get(user=user).group return super().form_valid(form) #model def get_upload_path(instance, filename): n = datetime.now() prefix = "records/" ymd='/'.join([n.strftime('%Y'), n.strftime('%m'), n.strftime('%d'), ""]) + "/" directory=str(instance.user.id) + "/" name=str(uuid.uuid4()).replace("-", "") extension=os.path.splitext(filename)[-1] return ''.join([prefix, directory, ymd, name, extension]) class URC(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(group, on_delete=models.CASCADE, null=True) URN = models.ForeignKey(UPRM, on_delete=models.CASCADE) UPRC = models.CharField(max_length=300) image = models.ImageField(upload_to=get_upload_path) def __str__(self): return self.UPRC #urls if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I will post any other necessary code. Sorry for the poor English.