Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Like button back end logic using Django Rest Framework
I have a Blog app where users can add new Post and any users can like the post. models.py class Post(models.Model): title = models.CharField(max_length=60) class PostLikes(models.Model): likeusers = models.ManyToManyField(User) likepost = models.ForeignKey(Post,on_delete=models.CASCADE,null=True,related_name='likepost') serializers.py class PostSerializers(serializers.ModelSerializer): #likepost = serializers.SerializerMethodField() **I have to mention like count here** class Meta: model = Post fields = '__all__' class PostlikeSerializer(serializers.ModelSerializer): class Meta: model = PostLikes fields = '__all__' views.py class LikeListCreate(APIView): def get(self,request,pk):#function to get total number of likes to particular post post = Post.objects.filter(pk=pk) # find which post's likes are to be extracted like_count = post.likepost.count()# counts total user likes ,besides my code is wrong serializer = PostlikeSerializer(like_count,many=True) return Response(serializer.data) def post(self,request,pk):#function to add likes to post # how do I check if user is already liked the post ? likeusers = request.user likepost = Post.objects.filter(pk=pk) serializer = PostlikeSerializer(data=request.data) if serializer.is_valid(): serializer.save(likeusers,likepost) return Response(serializer.data,status=status.HTTP_201_CREATED) return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST) urls.py path('posts/<int:pk>/like/',LikeListCreate.as_view(),name = 'post_likes'), I am unable to implement logic in views.py module and serializers.py section too. Please help, thanks in advance Git link to my project https://github.com/Anoop-George/BlogApp.git -
Unable to display image in template (Django 3.0)
Unable to display profile_pic image in template I know i m doing something very terrible. model.py class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='basic_app/profile_pics',blank=True) def __str__(self): return self.user.username index.html {% block body_block %} <div class="container"> <div class="jumbotron"> <h1>Django Level Five</h1> {% if user.is_authenticated %} <h2>Welcome {{ user.username }}!</h2> <div> <img src="{{ user.profile_pic.url }}" alt="user-image"> </div> {% else %} <h2>Welcome to the site!</h2> {% for b in users %} {% endfor %} {% endif %} </div> </div>{% endblock %} views.py def index(request): #commented: userpro = UserProfileInfo() #commented: var={'userz': userpro} #commented: return render(request, 'basic_app/index.html',context=var) return render(request, 'basic_app/index.html') User authentication is fine and name is getting displayed in template but not the image. I have tried lot of things but image didn't show. Div and Alt-name getting displayed but not the profile_pic. -
if comment.name == user not working correctly
I want users to be able to delete comments they have written. Unfortunately though I can not get the if statement to work. {% if comment.name == user %} <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I could see the value of user and comment.name I included the below code. This was for testing purposes and would not be included in the sites final design. <h3 class="article-content">{{ user }}</h3> <p class="article-content">{{ comment.name }}</p> I also wanted to test to make sure the inside of the if statement was work. <a href="{% url 'delete_own_comment' comment.id %}">delete this comment-</a> {% endif %} So I included the below code. Again this would not be included in my final sites design. {% if post.author == user %} <a href="{% url 'delete_own_comment' comment.id %}">-------delete this comment---------</a> {% endif %} But by looking at the screenshot you can tell the code is not working properly. The 30th comment is a 'Test comment for StackOverflow purposes.' The comment was written by RossSymonds. The user currently logged in is RossSymonds. If everything was working properly you would see 'delete this comment' (which is different to '------delete this comment---------'). Does anyone have a suggestion? … -
How to access related model object in vuejs component with django rest framework
I am building a full-stack web application, using Django, Django Rest framework and Vue.js as the frontend. I am working with a Post model that has an author column, which is related to the Django User model by foreign key, like so; class Post(models.Model): title = models.CharField(max_length=50, unique=True) body = models.TextField() author = models.ForeignKey(User, on_delete=models.CASCADE) I have set up my serializers, viewsets and the urls like so; serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username', 'email'] class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Post fields = ['url', 'title', 'body', 'author'] In my vews.py; class UserViewSets(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class PostViewSets(viewsets.ModelViewSet): queryset = Post.objects.all() serializer_class = PostSerializer In my urls.py; router = routers.DefaultRouter() router.register('users', UserViewSets) router.register('posts', PostViewSets) urlpatterns = [ path('admin/', admin.site.urls), path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ] I can access my Post model on the rest framework console on my browser. Now in my Vuejs component, i can also get the list of my posts if i make a request to the post api endpoint i.e. http://localhost:8000/posts. However, i also want to get the related model, i.e User (the author of individual post), as an object so i can do something like post.author.username or post.author.email … -
Pytest django - Multiple application, multiple database - not able to access any DB other than default db
Problem I have a Django(1.8) project running 2 applications: App1, App2. Both of the applications run with their own databases: app1db and app2db, sharing the defaultdb for users and groups. I am trying to integrate pytest-django as part of the unit testing. This is where I am hitting with problem as Pytest do not support multiple databases. My use case is I would be needing the unit tests only on app1 and I am pretty much sure I won't be needing it on app2. And I can mock my users and groups objects from defaultdb for this unit tests and I won't be needing access to defaultdb. But the problem is I always see the unit tests access the defaultdb and I don't see a way of making the app1db accessible from unit test cases. When I try to access any object form app1db, I get the following error: E ProgrammingError: relation "app1_table" does not exist E LINE 1: INSERT INTO "app1_table" ("field1", "field2", "... E ^ Database Settings 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'USER': 'postgres', 'NAME': 'defaultdb', 'PASSWORD': 'pass', 'HOST': localhost, }, 'app1': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'app1db', 'USER': 'postgres', 'PASSWORD': 'pass', 'HOST': localhost, }, "app2": { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': … -
Django Management Command - Write All or Nothing
I have a django custom management command. This is how the handle and other methods in BaseCommand looks: def first_function(data_point): another_model = AnotherModel(data=data, related_data= data_point) another_model.save() def second_function(data_point): yet_another_model = YetAnotherModel(data=data, related_data= data_point) yet_another_model.save() def handle(self, *args, **options): data_cursor = DataPoint.objects.filter(ready_for_migration=True) for data_point in data_cursor.iterator(): with transaction.atomic(): self.first_function(data_point) self.second_function(data_point) data_point.complete=True data_point.save() sleep(20) raise Exception("Testing Exeception") I expect the AnotherModel, YetAnother Model table to be loaded and after Exception is raised I want the data that was loaded in the respective tables to be erased. Instead what I am observing is that the tables get loaded fine, the exception is thrown but after the execption, the data remains in the table. Essentially I want all the related data for a given data point to be loaded but if any of the related tables fail, the transaction for the data point should rollback. What am I missing? -
Receiving 'TypeError: expected string or bytes-like object' when saving object
I have an issue with uploading data from excel to a db using Django. When this function runs, it is suppose to get the data in specified range and upload it to db when 'q.save' is ran. def scrapeExcel(excel): uploadQuery = [] wb = load_workbook(excel) for sheet in wb.worksheets: last_row = sheet.max_row if sheet == wb.worksheets[0]: fullName = sheet.cell(row = 16, column = 4).value for row in sheet.iter_rows(min_row = 20, max_row = last_row - 1): curRow = [] for cell in row: curRow.append(cell.value) uploadQuery.append( time( file = excel, fullname = fullName, cdate = get_date(curRow[3]), dayname = curRow[4], units = curRow[9], submitteddate = get_date(curRow[11]), approveddate = get_date(curRow[15]), project = curRow[21], name = curRow[22], comment = curRow[25], locationname = curRow[26], status = 1 ) ) for q in uploadQuery: q.save() When I run this, it gives me the following error. TypeError: expected string or bytes-like object When I checked each value via print or sys.stderr.write, I know they are getting the right value. But inside the for loop, if I check what q is, with for q in uploadQuery: sys.stderr.write(' query--{} '.format(q)) q.save() it just says query--time Object (none) So I am assuming, it is not getting appended to uploadQuery? or is …