Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
save url to image field in Django Rest Framework
purpose I want to make my input parameter image can be filled with url file base64 but save as a image. code models.py class Item(models.Model): image = models.ImageField(upload_to='item') ... views.py class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer def create(self, request): if request.data.get('type') == 'url': request.POST._mutable = True request.data['image'] = convert_from_url(request.data['image']) serializer = ItemSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I modify the request data when input type is url. convert_from_url is a method to save a image to TemporaryFile and pack in InMemoryUploadedFile serializers.py class ItemSerializer(serializers.ModelSerializer): def create(self, validated_data): item = Item.objects.create( image=validated_data['image'] ) ... item.save() return item Problem serializer = ItemSerializer(data=request.data) this line didn't pass correct request.data (it didn't contain data) validated_data (serializers) didn't get image when I modified it before -
get_queryset for ListCreateAPIView not being called
I have a ListCreateAPIView that I'm trying to override get_queryset, but it is never being called. Here is my view: class DeviceView(generics.ListCreateAPIView): def get_queryset(self): # Threw this and some print statements, but no sign of # the exception or print statement raise Exception return None @swagger_auto_schema( responses={ 201: DeviceSerializer(), }, request_body=DeviceSerializer, ) def post(self, request, format=None): # This code works fine ... @swagger_auto_schema(responses={200: DeviceSerializer(many=True)}) def get(self, request, format=None): # This code DOES get hit and successfully retrieves all the devices Here is the urls.py: urlpatterns = [ path(r"devices/<serialnumber>/abc", views.AbcView.as_view()), path(r"devices/<serialnumber>", views.DeviceDetailView.as_view()), path(r"devices/", views.DeviceView.as_view()), path(r"api-auth/", include("rest_framework.urls", namespace="rest_framework")), path( r"swagger/", schema_view.with_ui("swagger", cache_timeout=0), name="schema-swagger-ui", ), url( r"^swagger(?P<format>\.json|\.yaml)$", schema_view.without_ui(cache_timeout=0), name="schema-json", ), url(r"^api-token-auth/", obtain_jwt_token), path("admin/", admin.site.urls), ] Any thoughts on why the get_queryset isn't being hit/overridden? -
DRF - return JSON from API view in the shell
I feel like I'm missing something simple but... from the shell how do you return the JSON data from a ListAPIView? Using requests you would do something like: r = requests.get(url, params={'status': '5'}) data = r.json() Basically I just want to take a queryset, serialize it, then return the JSON. -
Calling application running on Django Server from Servlet running on Tomcat server
Is it possible to call an application which is running on Django server from a Servlet on Tomcat Server? I tried getRequestDispacher and sendRedirect with the IP address of Django server on which another application is running. No success at all. Are these methods only to forward the request and response to jsp, servlet and html page which are already in the same server or we can redirect them to another server? -
Django - Exception Value: local variable 'form' referenced before assignment
In a definition for saving a search word in a form i got stack. This definition gives the error " local variable 'form' referenced before assignment". on the line ( if form.is_valid():). I tried to reorder it but didn't succeed. Maybe this is very easy for more experienced developers. def SearchCreateView(request): template_name = 'SearchCreateView_form.html' model = Search form_class = SearchCreateViewForm if request.method == 'POST': if form.is_valid(): form = SearchCreateViewForm(request.POST or None, instance=search.user) print(form.errors.as_text()) search = form.save(commit=False) form.instance.search.user = self.request.search.user return render_to_response(request, 'search.html', {'form': form}) else: context = {'form': form} return render_to_response(request, 'save.html', context) else: form = SearchCreateViewForm(request.POST or None) return render(request, 'SearchCreateView_form.html', {'form': form}) -
Django renaming field returns only int id not object
I have the following Django model fields: first_message = model.ForeignKey(FirstMessage) second_message = model.ForeignKey(SecondMessage) whereas only one of those will be filled in the DB, never both of them at the same time. Now I have following filter condtion: # state_model_field can be either 'first_message' or 'second_message' field_filter = {f'{stats_model_field}__isnull': False} objects = (MessageStats.objects .filter(**field_filter) .prefetch_related(stats_model_field) .annotate(message=F(stats_model_field)) .values('message') .order_by('message')) The objects field should contain all MessageStats with the joined FirstMessage or SecondMessage table. In order not to have to distinguish between the fields in the future, I want to rename whichever field state_model_field is to the alias message (with the annotate). However, the results are returned as a dict {'message': 1} but I want the full object of wither FirstMessage or SecondMessage!? -
django: same tabularInline for two foreignKeys
I have these "typical" models that more or less resemble my django application, for which I wanted to use the admin interface, good enough for my purposes (but also after 3 months I'm still not good at all with Django) models.py class genericItem(models.Model): #a genericItem can be a monitor (with its properties) a laptop (with its properties..) etc.. genericItem_ID = models.AutoField( primary_key=True) # Field name made lowercase. genericItemName = models.CharField(max_length=30, blank=True, null=True) category = models.ForeignKey('categories', models.DO_NOTHING, db_column='category_ID', null=True,blank=True) def __str__(self): return self.genericItemName class item(commonFields): #items are goods that may refer to genericItems, e.g. I buy 4 items and 3 of them are monitors (genericItems) item_ID = models.AutoField(db_column='item_ID', primary_key=True) # Field name made lowercase. genericItem = models.ForeignKey('genericItem', models.DO_NOTHING,related_name='genericItem', db_column='genericItem_ID') location = models.ForeignKey('location', models.DO_NOTHING,db_column='room_ID',blank=True, null=True) serialnumber = models.CharField(db_column='serialNumber', max_length=20, blank=True, null=True) # Field name made lowercase. accessory = models.ForeignKey('self', models.DO_NOTHING, db_column='accessory', blank=True, null=True) def __str__(self): return self.genericItem.genericItemName class tblFiles(models.Model): #one could upload files for a item or genericItem file_ID = models.AutoField(primary_key=True) filename = models.FileField(null=False, blank=False, upload_to=("somewhere")) description = models.CharField(max_length=200, blank=True, null=True) item = models.ForeignKey('item', models.DO_NOTHING, db_column='item_ID', blank=True, null=True, related_name="itemFile") genericItem = models.ForeignKey('genericItem', models.DO_NOTHING, db_column='genericItem_ID', blank=True, null=True, related_name="genericItemFile") def __str__(self): return os.path.basename(self.filename.name) admin.py class tblFilesInline(admin.TabularInline): model = tblFiles extra = 0 fields = … -
Django SearchVector on model IntegerField
If I have a simple model like: class Book(models.Model): title = models.TextField() year = models.IntegerField() How can I use SearchVector in postgres to allow for searching on both the title and year fields? E.g. so "Some Book 2018" would query over both the title and year fields. If I try doing this like: q = SearchQuery('Some') & SearchQuery('Book') & SearchQuery('2018') vector = SearchVector('title') + SearchVector('year') Book.objects.annotate(search=vector).filter(search=q) Then I hit the error DataError: invalid input syntax for integer: "" LINE 1: ...|| to_tsvector(COALESCE("book_book"."year", '') || ' '... Is there anyway I can search the Integer field too? -
What is the best way to save images when using docker?
In the same context of the question: Saving images on files or on database when using docker is there any service or better way to make this persistence offline? Another option, other than the database or files. -
React + Django app refreshes for every deletion in Django admin panel
I'm not really sure what to share (i.e. which part of my application code) as I'm still a beginner with React so please bear with me. I have a React application running on top of a Django application. Basically, there are Django Admin Panel URLS, REST API URLS in Django, and one path to catch all paths that don't belong to the first two groups. I have a page (or a React Container) that calls Django's REST API to query all entries in the users DB Table. This part is okay but what I've noticed is, everytime I manually delete a row in the Django Admin Panel, the whole page refreshes. What are possible reasons for this? By the way, I'm using Redux as well to manage the whole application state. -
How do I retrieve data from tables in Django that are not directly joined?
I have a Response table: class Response(models.Model): Question = models.ForeignKey(Question, on_delete=models.CASCADE) Topic = models.ForeignKey(Topic, default=13, on_delete=models.CASCADE) Response = models.TextField() Client = models.ForeignKey(ClientDetail, default=8, on_delete=models.CASCADE) Planit_location = models.ForeignKey(Planit_location, default=1, on_delete=models.CASCADE) Date_added = models.DateField(default=datetime.date.today) Document = models.ForeignKey(Document, default=0, on_delete=models.CASCADE) def __str__(self): return self.Response I am able to retrieve data from other tables that it is directly joined to e.g. Questions, Topic, Client: views.py clientList = ClientDetail.objects.all().order_by('Client_name') topicList = Topic.objects.all().order_by('Topic_name') Now I want to retrieve "Sector Name" from my Sector Table: class Sector(models.Model): Sector_name = models.CharField(max_length=255, default='Sector_name') def __str__(self): return self.Sector_name Which is joined to my Client Table: class ClientDetail(models.Model): Sector = models.ForeignKey(Sector, default=8, on_delete=models.CASCADE) Client_name = models.CharField(max_length=255, default='Client_name') class Meta: ordering = ['Client_name'] def __str__(self): return self.Client_name I cannot use the same method i did with Client as it cannot find a "Sector_id" field in the Response table: sectorList = Sector.objects.all().order_by('Sector_name') **THIS DOES NOT WORK** As of this moment, i am only able to retrieve "Sector_id" from my Client table but i what i want is the "Sector Name" Is there something i should be adding into my documents.py file? As i cannot use the same method i did for previous models: class ResponseDocument20(DocType): Client = fields.NestedField(properties={ 'Client_name': fields.TextField(), 'pk': fields.IntegerField(), }, … -
Can't override my resourcers.py class model attribute
I am using the django-import-export package. I need, everytime the user send a .csv table, to create a column in the .csv file and fill every row with the logged user. What I did is: In my resources.py file: class ProductListResource(resources.ModelResource): class Meta: model = ProductList skip_unchanged = True report_skipped = True exclude = ('id',) import_id_fields = ('sku',) In my models.py file: class ProductList(models.Model): sku = models.CharField(primary_key=True, max_length=200) client = models.ForeignKey(get_user_model(), default=1, on_delete=models.CASCADE) name = models.CharField(max_length=256) description = models.CharField(max_length=1000) storage = models.CharField(max_length=256) cost_price = models.CharField(max_length=256) sell_price = models.CharField(max_length=256) ncm = models.CharField(max_length=256) inventory = models.IntegerField(null=True) And finally in my views.py file: def simple_upload(request): if request.method == 'POST': product_resource = ProductListResource() product_resource.Meta.model.client = request.user.id dataset = Dataset() new_product_table = request.FILES['myfile'] dataset.load(new_product_table.read().decode('utf-8'), format='csv') result = product_resource.import_data(dataset, dry_run=True) # Test the data import if not result.has_errors(): product_resource.import_data(dataset, dry_run=False) # Actually import now context = {'product_list': ProductList.objects.filter(client=request.user.id).all()} #.filter(client=request.user.username) return render(request, 'Clientes/import.html', context) My problem is that in the table appears that the value was changed, but if I click in the object, at admin page, the user that is selected is the first one. -
Custom CSRF Failure View: Referer checking failed - no Referer
I've overridden the Django CSRF_FAILURE_VIEW with the following: def csrf_failure(request, reason="Failed login due to CSRF error"): logger.warning(reason) return render(request, 'csrf_failure.html') However, I've started noticing the following warning since implementing this: Referer checking failed - no Referer It seems like it is trying to show the custom error template when there is a CSRF forbidden error, but there is no referrer. What should I be doing to remove resolve this? -
How to prefetch_related GenericForeignKey with self reference ForeignKey in restframwork
I am going mad with restframework because of the N+1 problem. For example, I have following models: class User(models.Model): username = ... email = ... avatar = ... last_login = ... class Article(models.Model): user = models.ForeignKey(User) title = ... abstract = ... content = ... category = ... class Comment(models.Model): user = models.ForeignKey(User) article = models.ForeignKey(Article) content = ... ## This field! ## reply_to = models.ForeignKey('self', null=True) time = ... That is, user can comment an article or a comment of an article. And now I need to build a notification system, so I add: class Notification(models.Model): actor_type = models.ForeignKey( ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_id = models.PositiveIntegerField() actor = GenericForeignKey('actor_type', 'actor_id') verb = models.CharField(max_length=255) receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notifications') is_read = models.BooleanField(default=False, db_index=True) target_type = models.ForeignKey( ContentType, related_name='notify_target', blank=True, null=True, on_delete=models.CASCADE ) target_id = models.PositiveIntegerField() target = GenericForeignKey('target_type', 'target_id') time = models.DateTimeField(auto_now_add=True) source_type = models.ForeignKey( ContentType, blank=True, null=True, related_name='notify_subject_object', on_delete=models.CASCADE ) source_id = models.PositiveIntegerField() source = GenericForeignKey('source_type', 'source_id') The notification looks like: Yriuns commented Article 1: good job <actor> <verb> <target> <source> or: Yriuns commented Your Comment of Article 1: I doubt it <actor> <verb> <target> <source> And the serializers: class UserSeriazlier(serializers.ModelSerializer): class Meta: model = User fields = ('username', … -
Invalid email in Django Password Reset
I am implementing Django Password Reset to send a recovery password link when the user type his/her email id using django.contrib.auth.urls, which works as perfectly. This is from Django Documentation, If the email address provided does not exist in the system, the user is inactive, or has an unusable password, the user will still be redirected to this view but no email will be sent. My question is, If I add something like EmailValidation to check if the user typed email exists in the database or not and raise ValidationError, will that be a security problem? -
Extending the Django User Model OneToOne - User profile not saving
I am trying to build an application that allows users to register and meet other users with similar interests. I am extending the user model using a OneToOne field but I run into a problem when I try to register some users: The profile does not save. The user data saves, but the profile data does not. I do not understand what I am doing wrong, as I followed a tutorial to write the program. This is my Models.py file: class Profile(models.Model): GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=254, blank=True) gender = models.CharField(choices=GENDERS, max_length=1, null=True, default='') dob = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) hobby = models.ManyToManyField(Hobby) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() post_save.connect(create_user_profile, sender=User) This is my forms.py file: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password', 'first_name', 'last_name') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('email', 'gender', 'dob', 'hobby') This is my view function: def register(request): if request.method =="POST": userForm = UserForm(request.POST) profileForm = ProfileForm(request.POST) if userForm.is_valid() and profileForm.is_valid(): userForm.save() profileForm.save() return redirect('/') else: return render(request, 'QMLove/register.html', {'userForm': userForm, 'profileForm': profileForm}) else: … -
implementing video streaming with django
I am trying to implement this project using django. What I want to do is once the server is started, I should be able to start the camera from any system that is connected to network and display the feed in that system. I am using Django because I have written other modules of my project with django This is my code so far views.py def index(request): return render(request, 'index.html') # the gen() is part of the server.py code. This has to be added to the start_server() function. # the start_server() function should be rectified def gen(): streamer = Streamer('localhost', 8000) streamer.start() while True: if streamer.client_connected(): yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + streamer.get_jpeg() + b'\r\n\r\n') def start_server(request): return render_to_response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') def start_client(request): cap = cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8000)) while(cap.isOpened()): ret,frame=cap.read() memfile = StringIO() np.save(memfile, frame) memfile.seek(0) data = json.dumps(memfile.read().decode('latin-1')) clientsocket.sendall(struct.pack("L", len(data))+data) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow('frame', frame) cap.release() The client.py file from the repo is placed under start_client() function in views.py I have made a small change to the client.py file from the repo. I added cv2.imshow('frame', frame) to display the feed in the client's system index.html <html> <head> </head> <body> <div class='container'> <a href='/start_server'><button>Start Server</button></a> <a href='/start_client'><button>Start Client</button></a> … -
Create Activity Logs in Django Social Auth Login
I want to trace login/logout Logs for Students.How to trace if student login through Social Auth? -
reading json getting null values using jquery django python
Here is the template and the sample file : <html> {% load static %} <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $.getJSON("{% static "logging/log0.json" %}", function (data) { <!-- $.each(data, function (index, value) { --> <!-- console.log(value); --> <!-- }); --> console.log(data) }); </script> </head> <body> Hello </body> </html> To get the sample file click. The output when I see the console log I get the following: The highlighted part is missing in the output. The json file has values for that. But the reading is not showing the output. Please help. -
django Edit records in Listview
I have a ListView that lists all questions from the Question model. the models.py is: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = models.DateField(verbose_name='date published') def __str__(self): return self.question_text now I want users can edit question_text. I tried this in views.py: class UpdateDirectry(generic.list.ListView, generic.edit.FormMixin): model = Question template_name = 'accounts/editable_directory.html' form_class = forms.EditListForm def get_context_data(self, *, object_list=None, **kwargs): context = super(UpdateDirectry, self).get_context_data() context['object_list'] = Question.objects.filter(question_text__startswith='Who') return context and in the template: <form method="post"> {% csrf_token %} <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Q</th> <th scope="col">D</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><input type="text" value="{{ object.question_text }}"></td> <td>{{ object.pub_date }}</td> </tr> {% endfor %} </tbody> </table> <input type="submit" value="Submit"> </form> I can edit the question_text but when I click submit button nothing happens (just a white page) and no records change in the database. How can I really edit records with the submit button? This is what the template shows: enter image description here -
Django: Validate GET parameter
I offer discount codes in my checkout. I created form where users can type in the discount code and click on apply. The form checks if the discount code is valid and then applies it. Now I want to add the functionality to add to the url domain.com/event/?discount=ABC I want to check if request.GET is set an then somehow redirect it to the 'form' / transform it into a request.POST, so I can validate it. I am currently struggling to find the right approach to do that. Do you have any suggestions on how I could use the GET-parameter and validate it the same way as I would use the form? views.py def dispatch(self, request, *args, **kwargs): # Provide discount_code to all functions self.discount_code = None # Check if discount code is saved as a session self.discount_code_session = request.session.get( request.event.discount_code_cookie(), None) if self.discount_code_session: self.discount_code = Discount.objects.filter( code=self.discount_code_session, event=self.request.event.pk ).first() @transaction.atomic def post(self, request, *args, **kwargs): # Discount Code if self.discount_form.is_valid(): discount_code = self.discount_form.cleaned_data['code'] request.session[request.event.discount_code_cookie()] = discount_code return redirect('events:detail', request.organizer.slug, request.event.slug) forms.py class DiscountFormEventPage(forms.ModelForm): # Remove required attribute from HTML elements use_required_attribute = False class Meta: model = Discount fields = ( 'code', ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') … -
Django CSS is displayed different on local and production environment
Edit Form is not editable on production and the image button in the left, while on development it is editable and image button on the right. What could be the issue? The code is exactly the same. Checked on Chrome, IE and Firefox - same issue Cleaned cache - didn't help. -
Should my soft-deletion-honouring model manager be my model's default manager?
I am building soft-deletion functionality for my Django project. I have implemented this using a custom model manager (i.e. performing an initial filter on get_queryset(), plus overriding Model / Manager / QuerySet delete(). Django documentation (1.11): If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which they’re defined in the model) has a special status. Django interprets the first Manager defined in a class as the “default” Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, it’s a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects you’d like to work with. My soft delete-honouring manager is currently my model's default manager (first manager declared on the model class). It's also assigned to objects. This is convenient for me as a lot of Django code uses the default model manager (e.g. MultipleObjectMixin.get_queryset() if your MultipleObjectMixin-inheriting View just has the model attribute defined). However the fact that dumpdata also uses the custom model manager has scared me off. In the event that I perform … -
django application giving 404 error while reading json file python
Here is the code: views.py: @csrf_exempt def post_list(request): return render(request, 'blog/post_list.html', {}) @csrf_exempt def show(request): return render(request, 'tt/readjson.html', {}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.post_list), path('test/', views.data_return), path('tt/', views.show), ] readjson.html: <html> <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $.getJSON("log0.json", function (data) { $.each(data, function (index, value) { console.log(value); }); }); </script> </head> <body> Hello </body> </html> The output I am getting is hello on the screen. But in the console log I see this: jquery-1.10.2.js:8706 GET http://127.0.0.1:8000/tt/log0.json 404 (Not Found) send @ jquery-1.10.2.js:8706 ajax @ jquery-1.10.2.js:8136 jQuery.(anonymous function) @ jquery-1.10.2.js:8282 getJSON @ jquery-1.10.2.js:8265 (anonymous) @ (index):5 jquery-1.10.2.js:8706 XHR failed loading: GET "http://127.0.0.1:8000/tt/log0.json". The json file is in the same folder where the html template is kept, that is in the tt folder. Please let me know what might I do to avoid the missing part. -
How to filter and all the categories in a single statement using django
I have prog, associateprof, assistantprof, research scholar and mtech categories and to get count of those I am using each statement for each. Instead is there any chance to know in a single statement or using for loop. I am doing like this : count= Snippet.objects.all().count() count1 = Snippet.objects.filter(designation = 'Prof').count() count2 = Snippet.objects.filter(designation = 'RA').count() count3 = Snippet.objects.filter(designation = 'MTech').count() count4 = Snippet.objects.filter(designation = 'Asstprof').count() count5 = Snippet.objects.filter(designation = 'Assocprof').count()