Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Display a results from using foreign key - django
I'm looking to display clients information. A client is registered then they can fill out different forms, I need those forms to be attached to the client and display the latest 4 forms in an area on the same page as the client details. model.py class Casenotes(models.Model): FORMREG = models.ForeignKey(Register_Client, blank=True, null=True, on_delete=models.CASCADE) FORMREGCOUN = models.ForeignKey(Register_Counsellor, blank=True, null=True, on_delete=models.CASCADE) DATEADDED = models.DateField(auto_now=True) NOTES = models.TextField(blank=True) def get_absolute_url(self): return f"/case/{self.id}/" class Register_Client(models.Model): DATEADDED = models.DateField(auto_now=True) TITLES = ( ('MR', 'Mr'), ('MISS', 'Miss'), ('MRS', 'Mrs'), ('OTHER', 'Other') ) TITLE = models.CharField(max_length=5, choices=TITLES, blank=True, default=None) FIRST_NAME = models.CharField(max_length=50) LAST_NAME = models.CharField(max_length=50) views.py def registerclient(request): #register a client if request.method == 'POST': form = RegisterClientForm(request.POST) if form.is_valid(): form.cleaned_data saved = form.save() return redirect(saved.get_absolute_url()) else: print("Invalid form") print(form.errors) else: form = RegisterClientForm() return render(request, 'HTML/ClientRegistration.html', {"form":form}) def registeredclient(request, id): #display the registered client obj = get_object_or_404(Register_Client, id=id) content = { "obj": obj, } return render(request, 'HTML/Client.html', content) -
Creating a csv from request data and saving it into a model field - Django
I have a model that includes a text field and a file field. A user can either upload a csv file or some text which I should parse into a csv and save it in the file field. It goes something like this class UserUpload(models.Model): ...... ...... filefield = file_uploaded = models.FileField(upload_to='media/', validators= FileExtensionValidator(allowed_extensions=['csv'])], blank=True, null=True) datafield = models.TextField(blank=True, null=True) In the serializer import csv class UserUploadSerializer(serializers.ModelSerializer): ..... def csv_parser(self, datastream): with open('test,csv', 'w') as csv_file: data_writer = csv.write(csv_file) for x in datastream: data_writer.writerow(x) return csv_file def create(self, validated_data): if 'datafield' in validated_data: output_file = self.csv_parser(validated_data['data_uploaded'].split(", ")) return UserUpload.objects.create(filefield=output_file, **validated_data) else: return UserUpload.objects.create(**validated_data) Upon working with this logic I always get an error saying _io.TextIOWrapper object has no attribute '_committed' which i figured it might do with the Django FileContent class but when I tried that, it didn't succeed. Any help on how I can figure this out? -
How to call a app endpoint from within app django
Let's say I have a django app that is running on http://127.0.0.1:8000/ That app has an endpoint called homepage which renders a view and on the view there is a button. When that button is pressed, I want to call an API endpoint (button_pressed) within my django app, for example http://127.0.0.1:8000/button_pressed (this should return JSON) Would I have to just do a normal XMLHttpRequest to http://127.0.0.1:8000/button_pressed in JS when the button is pressed? Or is there another, better way to do it? -
IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint
django rest framework post request error Here is the image model class Img(models.Model): created_at=models.DateTimeField(auto_now_add=True) author=models.ForeignKey(User,on_delete=models.CASCADE,related_name="img") picture=models.ImageField(upload_to='fake_picture',null=True,blank=True) tags = TaggableManager(blank=True) Here is the image serializer for model Img class ImgSerializer(serializers.ModelSerializer): tags = TagListSerializerField(required=False) author = serializers.StringRelatedField(read_only=True) # post = serializers.StringRelatedField(read_only=True) class Meta: model=Img fields='__all__' views.py class ImgViewSet(viewsets.ModelViewSet): parser_class = (FileUploadParser,) permission_classes =[IsAuthenticatedOrReadOnly,IsAuthorOrReadOnly] authentication_classes =(TokenAuthentication,JSONWebTokenAuthentication) queryset = Img.objects.all() serializer_class=ImgSerializer but when ever a post request to that particular api endpoint is triggered from the post man with key value pair as picture:image.jpg this is what the response is IntegrityError at /api/img/ null value in column "author_id" violates not-null constraint DETAIL: Failing row contains (4, fake_picture/2019-06-27_at_10-04-59.png, 2020-05-05 23:06:00.16071+00, null). Request Method: POST Request URL: http://localhost:8000/api/img/ -
Why does the view function render more than one instance of the form field?
Please I need help with the code below. I'm trying to make an ajax call that renders the create_post view on a modal page. But it renders multiple instances of the form fields, instead of one. def save_room_form(request, form, template_name): data = dict() if request.method == 'POST': if form.is_valid(): form.save() data['form_is_valid'] = True rooms = list(Room.objects.all().values()) data['html_room_list'] = render_to_string('sharespace/includes/partial_room_form.html', {'rooms': rooms}) else: data['form_is_valid'] = False context = {'form': form} data['html_form'] = render_to_string(template_name, context, request=request) print(data.items()) return JsonResponse(data) def create_post(request): if request.method == 'POST': form = RoomForm(request.POST) else: form = RoomForm() return save_room_form(request, form, 'sharespace/shareform.html') ajax call: $(function () { var loadForm = function () { var btn = $(this); console.log("before ajax") $.ajax({ url: btn.attr("data-url"), type: 'get', dataType: 'json', beforeSend: function () { $("#modal-room").modal("show"); }, success: function (data) { $("#modal-room .modal-content").html(data.html_form) console.log("clicked"); } }); }; //Create room $(".js-create-room").on("click", loadForm); }); My sanity check suggests the problem is from the view(i think). Any help will be appreciated. Thanks -
Multiple for loops (not nested) in Django Template and the second one not working
I'm facing the following problem: On the view.py I send to the view template a list, such as: return render(request, 'template.html', {'images': list}) Then on the template I make a for like: {% for img in images %} {{ img }} {% endfor %} and on other part of the template again I do: {% for img in images %} {{ img }} {% endfor %} but this second time the code doesn't even enter inside the loop, it looks like the cursor of the for is pointing to the last element of the array, is that right? how to fix it, I mean, move this cursor to the first position, supposing this is the case. -
Can't get my Django Build to deploy on Heroku. i
-GitHub link to my project- I've followed every link and tutorial I can find. I'm operating under a virtual environment. I've tried to pip install Heroku, tried to run the commands you see in the errors... I'm stumped and can't find anyone else with a problem like mine? Help me see the silly error I'm making. -----> Python app detected -----> Installing python-3.6.10 -----> Installing pip -----> Installing SQLite3 -----> Installing requirements with pip Collecting bcrypt==3.1.7 Downloading bcrypt-3.1.7-cp34-abi3-manylinux1_x86_64.whl (56 kB) Collecting cffi==1.12.3 Downloading cffi-1.12.3-cp36-cp36m-manylinux1_x86_64.whl (430 kB) Collecting Django==2.2.3 Downloading Django-2.2.3-py3-none-any.whl (7.5 MB) Collecting pycparser==2.19 Downloading pycparser-2.19.tar.gz (158 kB) Collecting PyMySQL==0.9.3 Downloading PyMySQL-0.9.3-py2.py3-none-any.whl (47 kB) Collecting pytz==2019.1 Downloading pytz-2019.1-py2.py3-none-any.whl (510 kB) Collecting six==1.12.0 Downloading six-1.12.0-py2.py3-none-any.whl (10 kB) Collecting sqlparse==0.3.0 Downloading sqlparse-0.3.0-py2.py3-none-any.whl (39 kB) Building wheels for collected packages: pycparser Building wheel for pycparser (setup.py): started Building wheel for pycparser (setup.py): finished with status 'done' Created wheel for pycparser: filename=pycparser-2.19-py2.py3-none-any.whl size=111031 sha256=46327781c9ae2fca04d15bc02ca6a1f09a2624442730fdc7b492f1431e81c4de Stored in directory: /tmp/pip-ephem-wheel-cache-xz8b2s9m/wheels/c6/6b/83/2608afaa57ecfb0a66ac89191a8d9bad71c62ca55ee499c2d0 Successfully built pycparser Installing collected packages: six, pycparser, cffi, bcrypt, sqlparse, putz, Django, PyMySQL Successfully installed Django-2.2.3 PyMySQL-0.9.3 bcrypt-3.1.7 cffi-1.12.3 pycparser-2.19 pytz-2019.1 six-1.12.0 sqlparse-0.3.0 -----> $ python burnett_portfolio/manage.py collectstatic --noinput Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/init.py", line 204, in fetch_command app_name = commands[subcommand] KeyError: 'collectstatic' … -
KeyError Post DjangoRestFramework
I'm new on Django Rest Framework and when I want to POST data I get a error: KeyError: 'id_area' I do not know what I'm doing wrong. Here's my code: in my models.py class Area(models.Model): id_area = models.AutoField(primary_key=True) APM = 'apm' BUSINESS = 'business' DESARROLLO = 'desarrollo' SISTEMAS = 'sistemas' ATENTUSIANOS_CHOICES = ( (APM, 'Apm'), (BUSINESS, 'Business'), (DESARROLLO, 'Desarrollo'), (SISTEMAS, 'Sistemas'), ) nombre = models.CharField(max_length=255, choices=ATENTUSIANOS_CHOICES) class Meta: verbose_name = 'Área' verbose_name_plural = 'Áreas' def __str__(self): return self.nombre class Atentusiano(models.Model): id_atentusiano = models.AutoField(primary_key=True) nombre = models.CharField(max_length=255, blank=False, null=False) apellido = models.CharField(max_length=255, blank=False, null=False) correo = models.CharField(max_length=255, blank=False, null=False, unique=True) anexo = models.CharField(max_length=255, blank=True, null=True) area = models.ForeignKey(Area, related_name='areas', on_delete=models.CASCADE) class Meta: verbose_name = 'Atentusiano' verbose_name_plural = 'Atentusianos' ordering = ['nombre'] def __str__(self): return self.nombre + ' ' + self.apellido in my serializers.py class AreaSerializer(serializers.ModelSerializer): areas = serializers.CharField(read_only=True) class Meta: model = Area fields = ('id_area', 'nombre', 'areas') class AtentusianoSerializer(serializers.ModelSerializer): atentusianos = serializers.CharField(read_only=True) area = serializers.CharField(source='area.nombre', read_only=True) id_area = serializers.CharField(source='area.id_area') class Meta: model = Atentusiano fields = ['id_atentusiano', 'nombre', 'apellido', 'correo', 'anexo', 'id_area', 'area', 'atentusianos'] def create(self, validated_data): area_data = validated_data.pop('id_area') area = models.Area.objects.create(**area_data) atentusiano = models.Atentusiano.objects.create(area=area, **validated_data) return atentusiano And in my views.py class AtentusianoView(viewsets.ModelViewSet): queryset = Atentusiano.objects.all() serializer_class = … -
Django admin not allowing blank on foreign relation
I have a model a foreign relation class M(models.Model): f_key = models.ForeignKey(FModel,blank=True,null=True,) name = models.CharField(max_length=250, blank=False, null=False) When i add objects through the command line or programmatically I can add objects that have a null f_key but in the admin GUI it forces me to fill out this field. Is there a way to make it nullable in the GUI? -
Django: NOT NULL constraint failed even with `null=True`
I have a problem while trying to create a child. I have a model Work parent to a model Price. Here is my work_model: from django.db import models from django.contrib.auth import get_user_model User = get_user_model() class Work(models.Model): user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=200) length = models.IntegerField(null=True) width = models.IntegerField(null=True) def __str__(self): return "{}".format(self.id) My price_model: from django.db import models from .model_work import * from djmoney.models.fields import MoneyField class Price(models.Model): work = models.OneToOneField(Work, null=True, on_delete=models.CASCADE, related_name='price') price = MoneyField(max_digits=19, decimal_places=4, default_currency='USD', null=True) total = models.IntegerField(null=True) def __str__(self): return "{}".format(self.price) And my work_serializer: from rest_framework import serializers from ..models.model_work import Work from .serializers_user import * class WorkIndexSerializer(serializers.ModelSerializer): """ Serializer listing all Work models from DB """ user = UserIndexSerializer() class Meta: model = Work fields = [ 'id', 'user', 'name', 'image', 'length', 'width', ] class WorkCreateSerializer(serializers.ModelSerializer): """ Serializer to create a new Work model in DB """ user = UserIndexSerializer() class Meta: model = Work fields = [ 'user', 'name', 'length', 'width', ] def create(self, validated_data): work = Work.objects.create(**validated_data) return work class WorkDetailsSerializer(serializers.ModelSerializer): """ Serializer showing details of a Work model from DB """ user = UserDetailsSerializer() class Meta: model = Work fields = [ 'id', 'user', 'name', 'length', 'width', … -
Django How to add class media with condition
How to add class media with condition ,only in add form and change form , but not in the view page ( where fields are readonly )? or add media class with condition by user group id ? my model admin class CooperationBilateraleAdmin(ManyToManyAdmin): fieldsets = [ ( '', { 'fields': ['paysPartenaires', 'instrumentJuridique',('partenaire','gouvernement','paysP','etat','adefinir'),'objet', 'axeCooperation'] }), ('Autres élements à rajouter ?', { 'fields': ['infoPlus', ] }), ('', { 'fields': [ 'acteJuridique',('dateSignature','dateEntreeVigueur' ),('duree','dureeplus5ans', 'renouvellement'), ('pays', 'villeSignature')] }), ('Base Documentaire', { 'fields': [], 'description': 'Joindre le(s) fichier(s) '}), ] class Media: js = ( '//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js', # jquery '/static/admin/js/CooperationBilaterale.js', # project static folder ) css = { 'all': ('/static/admin/css/CooperationBilaterale.css',) } def render_change_form(self, request, context, *args, **kwargs): user = get_user_model() group = request.user.groups.values_list('id', flat=True).first() if request.user.has_perm('system.edit_CooperationBilaterale') or request.user.has_perm('system.add_CooperationBilaterale'): context['adminform'].form.fields['partenaire'].queryset = PartenaireInternational.objects.filter( caneva__contains=',2,') context['adminform'].form.fields['etat'].queryset = Etat.objects.filter(type__exact=3) context['adminform'].form.fields['duree'].queryset = DureeCooperation.objects.all().order_by('order') if group==2: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=1) | Q(region=2)).distinct() if group==3: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(region=6).distinct() if group == 4: context['adminform'].form.fields['paysPartenaires'].queryset = Pays.objects.filter(Q(region=3) | Q(region=4)).distinct() return super(CooperationBilateraleAdmin, self).render_change_form(request, context, *args, **kwargs) -
Separate from through model
Django==3.0.6 django-taggit==1.2.0 I'd like to organize special tagging for myself. It is not for users and will not be used in templates. class SpecialAdminTaggedPost(TaggedItemBase): # https://django-taggit.readthedocs.io/en/v0.10/custom_tagging.html # Used at admin site only (for sorting, filtering etc.). content_object = models.ForeignKey('Post', on_delete=models.PROTECT) class Post(models.Model): tags = TaggableManager() admin_tags = TaggableManager(SpecialAdminTaggedPost) When I run the program, I got this error: "You can't have two TaggableManagers with the" ValueError: You can't have two TaggableManagers with the same through model. Documentation: https://django-taggit.readthedocs.io/en/v0.10/custom_tagging.html I seem to have failed to separate from "through model". Could you help me here? -
Exception Type: OperationalError Djano Although I executed makemigrations and migrate
I am really confused for the reason of this error although I read several times that an error named: "OperationalError" to be fixed by makemigrations and migrate I did it several time but I am not sure what is the reason for still coming up with this error: Here is the Model.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() discount_price = models.FloatField(blank=True, null=True) category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) def __str__(self): return self.title class Variation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length=120) image = models.ImageField(null=True, blank=True) price = models.FloatField(null=True, blank=True) def __str__(self): return self.title here is the admin.py from.models import Variation admin.site.register(Variation) here is the error OperationalError at /admin/core/variation/ no such column: core_variation.item_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/core/variation/ Django Version: 2.2 Exception Type: OperationalError Exception Value: no such column: core_variation.item_id -
How can I get my css to render correctly? Is my file path correct?
So I'm a newbie and I'm having trouble getting my css to render in Django. I am attempting to create a red notification like in Facebook for my unread messages. But my css isn't rendering. I am thinking it's something to do with where I placed the css file, but I'm not sureWhat am I doing wrong here? Here's my code: settings.py/Static STATIC_URL = '/static/' STATICFILES_DIRS = [ "/DatingAppCustom/dating_app/static", ] notification.css .btn { width:100px; position:relative; line-height:50px; } .notification { position:absolute; right:-7px; top:-7px; background-color:red; line-height:20px; width:20px; height:20px; border-radius:10px; } base.html/notification section <link href="{% static 'notification.css' %}"> <button class="btn">message counter <div class="notification">{% unread_messages request.user %}</div> </button> directory project path . ├── 11_env │ ├── bin │ │ ├── __pycache__ │ │ ├── activate │ │ ├── activate.csh │ │ ├── activate.fish │ │ ├── django-admin │ │ ├── django-admin.py │ │ ├── easy_install │ │ ├── easy_install-3.7 │ │ ├── pip │ │ ├── pip3 │ │ ├── pip3.7 │ │ ├── python -> python3 │ │ ├── python3 -> /Library/Frameworks/Python.framework/Versions/3.7/bin/python3 │ │ └── sqlformat │ ├── include │ ├── lib │ │ └── python3.7 │ └── pyvenv.cfg ├── dating_app │ ├── __init__.py │ ├── __pycache__ │ │ ├── __init__.cpython-37.pyc │ │ … -
How to properly serve a Django application throught Twisted's Web server?
I am building a system that was some components that will be run in its own process or thread. They need to communicate with each other. One of those components is a Django application, the internal communication with the Django app will not be done through HTTP. Looking for networking libraries I found Twisted (awesome library!), reading its documentation I found that Twisted implements the WSGI specification too, so I thought its Web server could serve WSGI applications like Django. Following the docs I come with the following script to serve the Django app: from twisted.web import server from twisted.internet import reactor, endpoints from twisted.web.wsgi import WSGIResource from twisted.python.threadpool import ThreadPool from mysite.wsgi import application as django_application # Create and start a thread pool to handle incoming HTTP requests djangoweb_threadpool = ThreadPool() djangoweb_threadpool.start() # Cleanup the threads when Twisted stops reactor.addSystemEventTrigger('after', 'shutdown', djangoweb_threadpool.stop) # Setup a twisted Service that will run the Django web app djangoweb_request_handler = server.Site(WSGIResource(reactor, djangoweb_threadpool, django_application)) djangoweb_server = endpoints.TCP4ServerEndpoint(reactor, 8000) djangoweb_server.listen(djangoweb_request_handler) reactor.run() I made a django view that does a blocking call to time.sleep() to test it, it worked fine. Since it's multithread, it did not block other requests. So I think it works well with … -
what is the correct way to override the save method in django?
I have an image model where I can upload images and I want to optimize them with pillow, I did that but there is three problems: the images doesn't get saved in the correct folder. django has a feature when there is two files with the same name django adds a random string to its name but now with two images with the same name only one gets uploaded. the original images gets uploaded too. class Images(models.Model): image1 = models.ImageField(upload_to='images/%Y/', validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])]) image2 = models.ImageField(upload_to='images/%Y/', validators=[FileExtensionValidator(allowed_extensions=['png', 'jpg', 'jpeg', 'gif'])]) def save(self, *args, **kwargs): im = Image.open(self.image1).convert('RGB') im2 = Image.open(self.image2).convert('RGB') im.save(self.image1.path,"JPEG",optimize=True,quality=75) im2.save(self.image2.path,"JPEG",optimize=True,quality=75) super(Images, self).save(*args, **kwargs) -
How to create user groups for permissions within code (not in admin)
I'm wanting to create user groups for permissions and am wondering how to do this in the code as it sounds like the more proper way to do it (or not?). I have done some searching and have found a few completely different pieces of code, but I am not even sure in which file this code should be located? Here is one example that I found: from django.contrib.auth.models import Group, Permission from django.contrib.contenttypes.models import ContentType from api.models import Project new_group, created = Group.objects.get_or_create(name='new_group') # Code to add permission to group ??? ct = ContentType.objects.get_for_model(Project) # Now what - Say I want to add 'Can add project' permission to new_group? permission = Permission.objects.create(codename='can_add_project', name='Can add project', content_type=ct) new_group.permissions.add(permission) Thank you. -
Generate configuration templates using django forms and jinja template
Need help on how can I give data in django forms and pass the values to jinja template to generate configuration using python -
DataTables: Retain rows/data even after page refresh
I am using DataTables version 1.10.20 in my Django project. I have two DataTables in a page, one for Products and another for Cart. The data in Products table is sourced by AJAX call. The user will add the products from products table to cart table by clicking on a add button. User should be able to modify the quantity in the cart table and when satisfied, finally click on a checkout button. The checkout button will call some view for next steps to save the transaction. The problem is, before clicking on checkout, if the user refreshes the page after adding a couple of products or navigates to a different page, the Cart DataTable is loosing all the data and the user will have to add them all over again. The data in Cart DataTable should be only cleared when "Checkout" is clicked. Is this possible ? I have tried using StateSave: true as documented here but it did not help. Here is my code.. DataTable for "Products" <script defer type="text/javascript" language="javascript" class="init"> // This function will initialilize the 'Products' datatable. $(document).ready(function () { $('#productstable').dataTable({ "ajax": { "url": "{% url 'getproductsdata' %}", "dataSrc": '' }, // Datatable customization options … -
Retrieving pdf file when converted from docx
I have a web app that has a feature of converting docx documents to pdf.I am using Python/Django on Ubuntu server and for conversion i am using lowriter. My code is: args = ['lowriter', '--convert-to',' pdf ','/path/input.docx'] p = subprocess.Popen(args, stderr=subprocess.PIPE, stdout=subprocess.PIPE) Everything works fine when downloading the pdf, but i want to process the pdf created in python before downloading it, so i need to retrieve the pdf in code but it doesn't seem to save it in the folder '/path/'. Do you have any idea why it doesn't save it or what i can do? -
How to select related with existing object in Django?
I have existing user object that have many-many fields through select_related and prefetch_related: user = models.User.objects.first().select_related(...).prefetch_related(...) I need to select articles of this user through Article model (no user.article_set): articles = models.Article.objects.filter(user=user) And i want articles to have the existing user object, for example: articles = models.Article.objects.filter(user=user).select_related(user) or articles = models.Article.objects.filter(user=user).annotate(user=user) How is this possible to do? -
AttributeError: Got AttributeError when attempting to get a value for field `user` on serializer `RegisterSerializer`
I am trying to Register a User using a Serializer.I hava UserSeriaizer in RegisterSerializer, thought the user is created and able to access serializer.validated_data but i am not able to access serializer.data Here is my serializer classes: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'username', 'first_name', 'last_name', 'email', 'password'] extra_kwargs = { 'id' : {'read_only' : True}, 'password' : {'write_only' : True} } class RegisterSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Token fields = ['user', 'key'] extra_kwargs = { 'key' : {'read_only' : True} } depth=1 def create(self, validated_data): user = User.objects.create_user(**validated_data['user']) user.is_active = False token = Token.objects.create(user = user) user.save() return(user) And the View is : serializer_class = RegisterSerializer(data={'user' : request.data}) try: serializer_class.is_valid(raise_exception = True) except Exception as e: return(Response(serializer_class.errors, status=404)) else: user = serializer_class.save() print(serializer_class.data) Models are as follows: class User(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=15, unique=True) first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=15, blank=True) email = models.EmailField(max_length=254, unique=True) password = models.CharField(max_length=254) #is_active = models.BooleanField(default=True) #is_admin = models.BooleanField(default=True) USERNAME_FIELD = 'username' objects = UserManager() def __str__(self): return self.username and the Token is created using 'from rest_framework.authtoken.models import Token' -
UWSGI log to multiple locations
I'm a bit new to uwsgi so this may be a dumb question, I'm trying to get uwsgi to write logs to multiple locations and have not been able to find a way to do this. I'm want to setup uwsgi so it writes to both my logfile (/tmp/uwsgi.log) and stdout (so I can see it in the logs in my k8s pod). But I can't get both to work. I can only get one or the other to work. Here is my uwsgi.ini file: [uwsgi] root = %d/../test chdir = %(root) module=test.wsgi:application socket=/tmp/uwsgi_test.sock master=True pidfile=/tmp/uwsgi_test.pid vacuum=True max-requests=2000 logto=/tmp/uwsgi.log chmod-socket = 666 vacuum = true processes = %(%k * 4) enable-threads = True single-interpreter = True limit-as = 4056 buffer-size=65535 stats=/tmp/uwsgi_test_stats.sock Running this uwsgi file with /opt/conda/bin/uwsgi --ini /home/docker/uwsgi/k8s-sandbox-webserver.ini sends log files to only /tmp/uwsgi as specified by the logto parameter in the uwsgi.ini. If I remove the logto parameter completely then the logs only go to stdout. How can I make these uwsgi logs appear in both stdout and /tmp/uwsgi.log? So far I've tried logto2 and and daemonize so far but haven't had any luck with getting those to work for this purpose. -
How do I Upload a file using Django Rest Framework?
While posting file in the form, the 415 error is thrown detail: "Unsupported media type "application/json;charset=UTF-8" in request. serializer: class PrescriptionSerializer(serializers.ModelSerializer): class Meta: model = Prescription fields = '__all__' def to_representation(self, instance): data = super().to_representation(instance) data['medicine'] = MedicineSerializer( Medicine.objects.get(pk=data['medicine'])).data data['doctor'] = DoctorSerializer( Doctor.objects.get(pk=data['doctor'])).data if(data['address_of_opd'] != None): data['address_of_opd'] = AddressSerializer( Address.objects.get(pk=data['address_of_opd'])).data else: data['address_of_opd'] = {} return data ViewSet: class PriscriptionViewSet(viewsets.ModelViewSet): queryset = Prescription.objects.all() permission_classes = [ permissions.AllowAny, ] serializer_class = PrescriptionSerializer What am I missing in here? -
How do I let my django server print a receipt using my client's printer?
I'm working on a web application that allows users to add items to their cart. What I want to do is to print the items in the cart to a kitchen impact receipt printer on my clients side (I'm using the TM-U220 Receipt Printer). Currently, I am using my own computer to run the server but in the future, I hope I can get it working online so anyone can visit the website. I can't seem to find any solution on how to do that and if it is possible? I've only recently started Django and I can't seem to find a good solution. Any tips, help or idea on how to writing data to the printer on the client side from Django server?