Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Volley ClientError on Video Upload Post Request
I am trying to upload video from android to Django server. I am able to upload bitmap but when comes to video mp4 upload the code is causing errors. I am getting this error 'com.android.volley.ClientError' after calling the following function uploadMP4. Though, the same code works very well on uploading bitmap but on uploading video the same code is causing errors. Please Help. Thanks. private void uploadMP4(final Uri videoUri, final String ext) { if (selected_item_id == null) { // return; } String URL = "http://" + getIP() + "/inventory_apis/uploadMP4File"; VolleyMultipartRequest volleyMultipartRequest = new VolleyMultipartRequest(Request.Method.POST, URL, new Response.Listener<NetworkResponse>() { @Override public void onResponse(NetworkResponse response) { try { JSONObject jresponse = new JSONObject(new String(response.data)); } catch (JSONException e) { e.printStackTrace(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show(); Log.e("GotError", "" + error.getMessage()); } }) { @Override protected Map<String, String> getParams() throws AuthFailureError { Map<String, String> params = new HashMap<>(); params.put("clubbed_item_id", selected_item_id); return params; } @Override protected Map<String, DataPart> getByteData() { Map<String, DataPart> params = new HashMap<>(); long filename = System.currentTimeMillis(); params.put("video", new DataPart(filename + ".mp4", getFileDataFromDrawable(getApplicationContext(), videoUri), selected_item_id)); return params; } }; //adding the request to volley Volley.newRequestQueue(this).add(volleyMultipartRequest); } public byte[] getFileDataFromDrawable(Context context, Uri uri) … -
How to read or write an uploaded file from FileField model in Django 3.0+?
I'm new in python and programming in general. I have this project to create a simple library to add new authors and upload books. I must also display the uploaded book details(total words, most common words, different words, etc.) when I open the book. Now to do this I know that I first must open the uploaded book in readmode, but I don't know how to access the file that I uploaded. This is my models: from django.db import models from authors.models import Author class Book(models.Model): author = models.ForeignKey(Author, on_delete=models.CASCADE) book_name = models.CharField(max_length=50) genre = models.CharField(max_length=50) files = models.FileField(upload_to='books/files/') def __str__(self): return self.book_name() This is my forms: from django import forms from .models import Book class BookForm(forms.ModelForm): class Meta: model = Book fields = ('book_name', 'author', 'genre', 'files') My views: def create(request): if request.method == 'POST': form = BookForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('books:home') elif request.method == 'GET': form = BookForm() return render(request, 'books/create.html', { 'form': form }) def detail(request, pk): book = get_object_or_404(Book, pk=pk) return render(request, 'books/detail.html', context={'book': book}) My details.html: {% extends 'base.html' %} {% block title %} {{ book.book_name }} {% endblock %} {% block content %} <p>Book title: {{ book.book_name }}</p> <p>Genre: {{ book.genre }}</p> … -
erf django restframework Got AttributeError when attempting to get a value for field `image_id` on serializer `SoftwareSerializer' (status code 406)
I am facing this error when trying to open the endpoint (http://127.0.0.1:8000/api/metrics/) I am using django restramework (drf), software and category enpoints are working fine, but the metric endpoint is giving the following error: Error { "message": "Got AttributeError when attempting to get a value for field `image_id` on serializer `SoftwareSerializer`.\nThe serializer field might be named incorrectly and not match any attribute or key on the `Category` instance.\nOriginal exception text was: 'Category' object has no attribute 'image'.", "code": null, "status_code": 406 } Models class Category(models.Model): name = models.CharField(max_length=256, blank=True) created_datetime = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ ایجاد ") update_datetime = models.DateTimeField(auto_now=True, verbose_name="تاریخ بروزرسانی ") def __str__(self): return self.name class Metric(models.Model): title = models.CharField(max_length=254) categorymetric = models.ForeignKey("main.Category",on_delete=models.SET_NULL,null=True) def __str__(self): return self.title class Software(models.Model): software_name = models.CharField(max_length=150, default="software_name", null=False, verbose_name="اسم نرم افزار") created_datetime = models.DateTimeField(auto_now_add=True, verbose_name="تاریخ ایجاد ") update_datetime = models.DateTimeField(auto_now=True, verbose_name="تاریخ بروزرسانی ") image = models.ForeignKey("main.Image", on_delete=models.SET_NULL, blank=True, null=True) created_by = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True) class Meta: verbose_name = "software" verbose_name_plural = "softwares" def __str__(self) : return self.software_name Views class CategoryViewSet(ModelViewSet): serializer_class = CategorySerializer pagination_class = None queryset = Category.objects.all() class SoftwareViewSet(ModelViewSet): serializer_class = SoftwareSerializer pagination_class = None queryset = Software.objects.all() permission_classes = ( IsAuthenticated, ) def perform_create(self, serializer): serializer.save(created_by=self.request.user) class MetricViewSet(ModelViewSet): serializer_class = MetricSerializer pagination_class … -
Passing a value to a modal in Django
I want to add a delete confirmation modal after clicking on a delete button on a table, generated by a number of objects from a Django view: ... {% for i in items %} <tr> <td>{{ i.name }}</td> <td><a href="#" data-bs-toggle="modal" data-bs-target="#modal-delete-item">Delete</a></td> </tr> {% endfor %} .... What I have in the modal is something like this: <div class="modal modal-blur fade" id="modal-delete-item" tabindex="-1" role="dialog" aria-hidden="true"> .... <button href="{% url 'remove_quote_item' i.pk %}" type="button" class="btn btn-danger" data-bs-dismiss="modal">Oui, je confirme.</button> .... </div> How can I use the "i" variable in the modal since I am outside the loop, can I use anything to reference that variable into the modal? Or probably use javascript to perform that action? Or is there something I can do with jinja itself? Thanks! -
How to export a Django-Html web page as an xml file
I need to export (basically a download button) an html page with django syntax in XML format. How do I do this? -
How can I solve this ModuleNotFoundError: No module named 'axes_login_action' Error?
I got this error message: 2021-12-20 14:01:34,788: *************************************************** 2021-12-20 14:01:40,783: Error running WSGI application 2021-12-20 14:01:40,786: ModuleNotFoundError: No module named 'axes_login_action' 2021-12-20 14:01:40,787: File "/var/www/xxx_pythonanywhere_com_wsgi.py", line 18, in <module> 2021-12-20 14:01:40,787: application = get_wsgi_application() 2021-12-20 14:01:40,787: 2021-12-20 14:01:40,787: File "/home/xxx/.virtualenvs/groupu-virtualenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2021-12-20 14:01:40,787: django.setup(set_prefix=False) 2021-12-20 14:01:40,787: 2021-12-20 14:01:40,787: File "/home/xxx/.virtualenvs/groupu-virtualenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2021-12-20 14:01:40,788: apps.populate(settings.INSTALLED_APPS) 2021-12-20 14:01:40,788: 2021-12-20 14:01:40,788: File "/home/xxx/.virtualenvs/groupu-virtualenv/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate 2021-12-20 14:01:40,788: app_config = AppConfig.create(entry) 2021-12-20 14:01:40,788: 2021-12-20 14:01:40,788: File "/home/xxx/.virtualenvs/groupu-virtualenv/lib/python3.8/site-packages/django/apps/config.py", line 223, in create 2021-12-20 14:01:40,788: import_module(entry) 2021-12-20 14:01:40,788: *************************************************** settings.py INSTALLED_APPS = [ 'axes_login_action', ] Installation: pip3.8 install django-axes-login-actions==1.3.0 NB: I installed the dependency too. pip3.8 install django-axes==5.28.0 Furthermore, I keep getting ModuleNotFoundError: No module named **** when I install a new project. -
Django Unable to add WYSIWYG
I am trying to implement WYSIWYG on my page with this link : https://www.geeksforgeeks.org/adding-wysiwyg-editor-to-django-project/ I am currently at point 5, when they want me to add below: # add condition in django urls file if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) but when I added above, I got below error message File "C:\Download\Development\NowaStrona_Django\mysite\my_site\my_site\urls.py", line 6, in <module> path('', include('blog.urls')), File "C:\Download\Development\NowaStrona_Django\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Download\Development\NowaStrona_Django\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Download\Development\NowaStrona_Django\mysite\my_site\blog\urls.py", line 16, in <module> urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) NameError: name 'static' is not defined I am attaching urls.py: from . import views from django.urls import path urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('<slug:slug>/', views.PostDetail.as_view(), name='post_detail'), ] # to jest dla wysiwyg # add condition in django urls file from django.conf import settings if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT) Do you know why I am getting pasted error message? -
Django.db.utils.ProgramingError Relation doesn't exist
I am using Django3 and Postgres as Database, I clone the old project using Django and postgres, I cloned and setup the virtual environment for my project. At the time of runserver, its throws me the error of Django.db.utils.ProgramingError realtion "Table name" doesn't exist There was the migrations file in the project when I cloned it, but I removed them, so can create my own, but this error still there, even I remove the migrations folder, but its still there and can't create my own migrations and not even start the server. I tried it with cloned migrations files and without it but can't runserver -
Error while deploying django project on herokuapp
$ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_41ced892/manage.py", line 22, in main() File "/tmp/build_41ced892/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/init.py", line 395, in execute django.setup() File "/app/.heroku/python/lib/python3.9/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/app/.heroku/python/lib/python3.9/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/admin/init.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/app/.heroku/python/lib/python3.9/importlib/init.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1030, in _gcd_import File "", line 1007, in _find_and_load File "", line 986, in _find_and_load_unlocked File "", line 680, in _load_unlocked File "", line 850, in exec_module File "", line 228, in _call_with_frames_removed File "/tmp/build_41ced892/home/admin.py", line 2, in from home.models import Contact ModuleNotFoundError: No module named 'home.models' ! Error while running '$ python manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed -
hosting django on apache cannot load in numpy
Hello I am hosting a django platform on an Apache server (Ubuntu 20.04). I hosted it like in this tutorial However, each time I try to submit my file the following error occurs: [Mon Dec 20 09:40:40.850837 2021] [wsgi:error] [pid XXX:tid XXX ] [remote XXX] /home/usr/app/backend/controller/appController.py:1: UserWarning: NumPy was imported from a Python sub-interpreter but NumPy does not properly support sub-interpreters. This will likely work for most users but might cause hard to track down issues or subtle bugs. A common user of the rare sub-interpreter feature is wsgi which also allows single-interpreter mode. [Mon Dec 20 09:40:40.850868 2021][wsgi:error] [pid XXX:tid XXX ] [remote XXX] Improvements in the case of bugs are welcome, but is not on the NumPy roadmap, and full support may require significant effort to achieve. [Mon Dec 20 09:40:40.850874 2021] [wsgi:error] [pid XXX:tid XXX ] [remote XXX] import numpy as np [Mon Dec 20 10:38:30.778296 2021] [mpm_event:notice] [pid XXX:tid XXX ] AH00491: caught SIGTERM, shutting down Exception ignored in: <function Local.del at 0x7f65a9b41940> Traceback (most recent call last): File "/home/user/app/env/lib/python3.8/site-packages/asgiref/local.py", line 96, in del NameError: name 'TypeError' is not defined Exception ignored in: <function Local.del at 0x7f65a9b41940> Traceback (most recent call last): File "/home/user/app/env/lib/python3.8/site-packages/asgiref/local.py", line 96, … -
DJANGO Python code returns "None" while trying to get a database value
I am trying to create a program that lists some data. It returns all the data correctly except for when I try to print out the organizer.linkedin_link and I can't seem to figure out what causes this problem. I have 3 models: Organizers, Categories (I left out the Categories in the models.py) and Groups. Groups has a Many to Many field to Organizers. In my views.py I get all objects from Groups and send them to the template through the context. But when I try to print out the linkedin_link belonging to the Organizer it prints out None. groups.html: {% for group in groups %} <hr> <h4>Group name:</h4> <p>{{ group.name }}</p> <h4>Organizers:</h4> <ul> {% for organizer in group.organizers.all %} <li><b>{{ organizer.name }}:</b> {{ organizer.linkedin_link }} </li> {% endfor %} </ul> <h4>Member count:</h4> <p>{{ group.member_count }}</p> <h4>Group location:</h4> <p>{{ group.location }}</p> <h4>Group description:</h4> <p>{{ group.description }}</p> <hr> <br> {% endfor %} views.py: def groups(request): if request.method == 'POST': cat_search_form = CategorySearchForm(request.POST) if cat_search_form.is_valid(): print(cat_search_form.cleaned_data['search_input']) category_data = Categories.objects.annotate( similarity=TrigramSimilarity('name', cat_search_form.cleaned_data['search_input']), ).filter(similarity__gt=0.2).order_by('-similarity') groups_data = Groups.objects.all() cat_search_form = CategorySearchForm() context = { 'groups':groups_data, 'categories':category_data, 'form':cat_search_form } else: cat_search_form = CategorySearchForm() groups_data = Groups.objects.all() category_data = Categories.objects.all() context = { 'groups':groups_data, 'categories':category_data, 'form':cat_search_form, } return … -
Which steps should I take to migrate my django application for using django-tenants
I have been developping an application with django and vue for having only some users for one client and it's almost finished, but now I want to open it for having more of them. The problem comes when we want to share some data between some users of this clients but we also want to preserve privacy for another. Thereby, I tought to use django-tenants to resolve the problem. I have been reading the docs but I'm not still sure about which one is the best way to migrate from the single-client version to multiple-client and not loosing any data from my first version. -
Django - Pass variable to serializer which gets used in calculating a serializers.SerializerMethodField?
So I have this serializer that adds an attribute. Let's say I want to serialize Post data, which is like a post on Facebook or Twitter. When I serialize it lets say I want to pass a variable to the serializer region, because I use that variable to calculate an attribute in the Serializer that I want. So for example I'd like to do something like PostSerializer(post_object, region='Italy') and it'll use region='Italy' for calculating an attribute which is a serializers.SerializerMethodField. How can I pass a variable to my serializer that is used to calculae a serializers.SerializerMethodField()? serializer.py class PostSerializer(serializers.ModelSerializer): post_count_from_region = serializers.SerializerMethodField() class Meta: model = Post fields = ('author', 'body', 'created', 'updated_at', 'post_count_from_region') def get_post_count_from_region(self, post_obj, region:str): return Post.objects.filter(region=region).count() So for a more explicit example of what this use case looks like is: view.py def get_full_post_data_by_uuid(request, post_uuid, region: str): post_obj = Post.objects.get(pk=post_uuid) return Response(PostSerializer(post_obj, region=region).data, status=200) -
Django filter and count in template tag
im trying to filter and count a specific queryset in the template with Django templete enginge. Cant get it to work. The film_list is the context and film is the table and language is a field. Any tips on how to use filter and count at the same time in the template engine? Or should i solve it in another way? {% if filmlist.film.language == "danish" %} {{ film_list.all.count }} {% endif %} -
django-rest-framework: how do I update a nested foreign key? My update method is not even called
I have something like this (I only included the relevant parts): class ImageSerializer(serializers.ModelSerializer): telescopes = TelescopeSerializer(many=True) def update(self, instance, validated_data): # In this method I would perform the update of the telescopes if needed. # The following line is not executed. return super().update(instance, validated_data) class Meta: model = Image fields = ('title', 'telescopes',) When I perform a GET, I get nested data just as I want, e.g.: { 'title': 'Some image', 'telescopes': [ 'id': 1, 'name': 'Foo' ] } Now, if I want to update this image, by changing the name but not the telescopes, I would PUT the following: { 'title': 'A new title', 'telescopes': [ 'id': 1, 'name': 'Foo' ] } It seems that django-rest-framework is not even calling my update method because the model validation fails (Telescope.name has a unique constraint), and django-rest-framework is validating it as if it wanted to create it? Things worked fine when I wasn't using a nested serializer, but just a PrimaryKeyRelatedField, but I do need the nested serializer for performance reason (to avoid too many API calls). Does anybody know what I'm missing? Thanks! -
Room matching query does not exist. django rest framework, Django retsframework
I am new to django. im my project I want to post a photo to a hotel an d aphoto to the room of the hotel: but I am getting the following problem:Room matching query does not exist. django rest framework. Room id does not exist although it does exist in the database In my serializer.py class RoomPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = RoomPicture fields = ['id', 'room', 'location'] class RoomSerializer(serializers.ModelSerializer): roompicture = RoomPictureSerializer(many=True) class Meta: model = Room fields = ['id', 'roompicture'] class HotelPictureSerializer(serializers.ModelSerializer): location = Base64ImageField(max_length=None, use_url=True) class Meta: model = HotelPicture fields = ['id', 'hotel', 'location'] class ComplexSerializer(serializers.ModelSerializer): hotelpicture = HotelPictureSerializer(many=True) roompicture = RoomSerializer(many=True) class Meta: model = Hotel fields = ['id', 'hotelpicture', 'roompicture'] def create(self, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') roompictures_data = validated_data.pop('roompicture') hotel = Complex.objects.create(**validated_data) for hotelpicture in hotelpictures_data: HotelPicture.objects.create(hotel=hotel, **hotelpicture) for roompicture_data in roompictures_data: room = Room.objects.create(hotel=hotel, **roompicture_data) room_pictures_data = room_data.pop('roompicture') for room_picture_data in room_pictures_data: RoomPicture.objects.create(room=room, **room_picture_data) return hotel def update(self, instance, validated_data): hotelpictures_data = validated_data.pop('hotelpicture') roompictures_data = validated_data.pop('roompicture') # Updates for hotel pictures for hoteltpicture_data in hotelpictures_data: hotelpicture_id = hotelpicture_data.get('id', None) if hotelpicture_id: hp = hotelPicture.objects.get(id=hotelpicture_id, hotel=instance) hp.location = hotelpicture_data.get('location', cp.location) hp.save() else: HotelPicture.objects.create(hotel=instance, **hotelpicture_data) # update for residence for room_data … -
django-channels identify client on reconnect
I connect several (anonymous, not logged in) clients via websocket / django-channels (routing.py, consumers.py). When a client reloads the page or reconnects, for whatever reason, he gets a new channel_name. Is there a nice way to identify the reconnecting client as the same client he was on first connect? Is there some kind of identifier? -
How to inject HTML file into another HTML file in Django?
I want to inject(or import html file) into another HTML file in Django. Of course, I tried to do it, but I am getting errors below. http://prntscr.com/23pkqwf TemplateDoesNotExist at / fanduel.html Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.2.10 Exception Type: TemplateDoesNotExist Exception Value: fanduel.html Exception Location: C:\Users\j\Desktop\Project\Python\p\website\webenv\lib\site-packages\django\template\backends\django.py, line 84, in reraise Python Executable: C:\Users\j\Desktop\Project\Python\p\website\webenv\Scripts\python.exe Python Version: 3.8.0 I built the code like this. <div class="section-title"> <h2>FanDuel</h2> </div> <div class="row"> <!-- start row--> <div class="col-lg-6 col-md-6 text-center"> {% include 'fanduel.html' %} </div> <!-- end row --> </div> Of course, there is a fanduel.html file in the same level directory. I am not sure what I am wrong. I hope anyone knows what my issue is. Thank you in advice. -
django reverse relation query from ForeignKey
Let's say I have a couple of simple models defined: class Pizza(models.Model): name = models.CharField() # Get the name of topping here ... class Topping(models.Model): pizza = models.ForeignKey(Pizza) One thing I can do is a query on Topping, but and access that Pizza. But that is not what I want. I want to do a reverse-relation query. I want to get the Topping inside Pizza, if such Topping exists, There may and will be some Pizza without Topping. Using django and drf How can I achieve this? we don't like pineapple pizza -
If statement in Django Model Fields
I want to add these fields to my Store Model, but i wanna include logic that if Let's say WooCoomerce was chosen as a StoreType, i want Access_Token not to be Required. Also when i Choose either Shopify/Shopper i want Consumer_key and Consumer_secret not to be required. Do you have any idea how to get around that? StoreType = models.CharField(blank=True, choices=Storetypes.choices, max_length=12) Api_Url = models.CharField(blank=True) Access_Key = models.CharField(blank=True, max_length=100) Consumer_Key = models.CharField(blank=True, max_length=100) Consumer_Secret = models.CharField(blank=True, max_length=100) -
Django Forms not working. Does not display anything. Any helps?
I was doing some How-To tutorials about Django Forms. But it will not display anything for me. Any ideas why? Picture below illustrates my problem. This is my Login -> index.html <body> <div class="gradient-border" id="box"> <h2>Log In</h2> <form action = "" method = "post"> {% csrf_token %} {{form.as_p}} <input type="submit" value="Submit"> </form> </div> </body> this is forms.py class InputForm(forms.Form): first_name = forms.CharField(max_length = 200) last_name = forms.CharField(max_length = 200) password = forms.CharField(widget = forms.PasswordInput()) Login Page -
Reverse for 'account' not found. 'account' is not a valid view function or pattern name.121
enter image description here enter image description here enter image description here Hello, can you help me? Django gives me this error. Reverse for 'account' not found. 'account' is not a valid view function or pattern name. Inside the photo is a complete explanation -
validate user shift and then show data in Django
I have developed two API "ShiftstartAPI" and "tickettableAPI" when user start the shift only he can able to view the tables in Django. I have tried below approach but its not working as expected all it hides the table even after shiftstart views.py: shift start API # startshift @api_view(['POST', 'GET']) def UserStartShift(request): if request.method == 'GET': users = tblUserShiftDetails.objects.all() serializer = UserShiftStartSerializers(users, many=True) return Response(serializer.data) elif request.method == 'POST': serializer = UserShiftStartSerializers(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) once user click on the shift start the ticket tables needs to populate. Here,I have tried checking the requested user in the "shiftstartAPI" # tickets table @api_view(['GET', 'POST']) def ClaimReferenceView(request, userid): try: userID = Tblclaimreference.objects.filter(userid=userid) except Tblclaimreference.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': if request.user in UserStartShift(): cursor = connection.cursor() cursor.execute('EXEC [dbo].[sp_GetClaims] @UserId= {}'.format(userid,)) result_set = cursor.fetchall() print(type(result_set)) response_data = [] for row in result_set: response_data.append( { "Number": row[0], "Opened": row[1], "Contacttype": row[2], "Category1": row[3], "State": row[4], "Assignmentgroup": row[5], "Country_Location": row[6], "Openedfor": row[7], "Employeenumber": row[8], "Shortdescription": row[9], "AllocatedDate": row[10] } ) return Response(response_data, status=status.HTTP_200_OK) elif request.method == 'POST': serializer = ClaimReferenceSerializer(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) -
Django - Product Details in XML file
I have a task to export all product details such as name, price etc. from db to XML file. Since now i'm exporting most of the fields and save them to an XML file. However i'm a bit confused on how to export images. I have 2 models one for Product and one for ProductImages, see below: models.py class Product(models.Model): category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) name = models.CharField(max_length=50) slug = models.SlugField(max_length=500, null=True, unique=True) sku = models.CharField(max_length=100, unique=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/') created_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) class ProductImage(models.Model): product = models.ForeignKey(Product, related_name='images', on_delete=models.CASCADE) title = models.CharField(max_length=50, blank=True) image = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True, null=True) Also according to requirements there are two fields where images should be exported. If there is one image (product table) should be exported to item_image_link which i exporting it with no problem. And if there are more than one (ProductImage table) to item_additional_image_link and here is where i have issue. I iterate over products table like below and then trying to find all images for specific product id like: products = Product.objects.filter(product_status=True) images = ProductImage.objects.filter(product__id__in=products) for products in products: item = ET.SubElement(channel, "item") g_item_id = ET.SubElement(item, ("{http://base.google.com/ns/1.0}id")).text = products.sku g_item_image_link = ET.SubElement(item, ("{http://base.google.com/ns/1.0}image_link")).text = 'http://127.0.0.1:8000'+products.image.url for image in … -
Django admin create new entry in a different table from an existing entry
New to Django, and I am creating an API using the Django rest_framework. Mainly because I need the preconfigured admin panel. My problem is as follows. I have products and some are active on a site. Those products get inserted into a second table when they are rendered to the final user. So as soon as a product is available the admin inserts that new row to products_live table. My questions is as follows. Is it possible using the admin panel to tick a box in the products admin view and trigger the insert of the product from the product table to the products_live table while keeping the instance of the product in the product table? Hope I made my query clear.