Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is is possible to pass two kwargs in DRF viewsets?
I am trying to get pass two kwargs in urls pointing to a viewset which lists and retrieves accordingly. i have tried getting self.kwargs as in generic views so i followed up same process for viewset but couldnot succeed. router = routers.DefaultRouter() router.register('v1/outlet/<outlet_id>/stock/<stock_id>', StockViewSet, basename='stock') urlpatterns = \ [ path('api/', include(router.urls)) ] viewset class StockViewSet(viewsets.ViewSet): def list(self, request, pk=None ,*args, **kwargs): # outlet_id = self.kwargs['outlet_id'] outlet_stock = OutletStock.objects.filter(outlet=outlet_id) def retrieve(self,request,pk=None,id=None,*args, **kwargs): # outlet_id = self.kwargs['outlet_id'] # stock_id = self.kwargs['stock_id'] -
what are the issues if I change django app name?
I know there are questions regarding how to change django app name but none of them talk about what are the downstream effects of changing the name of django app. Is it possible to keep the old table and migration names ? -
How to apply join and group by together on tables in django ORM?
I have two models, class model_1(models.Model): id = models.IntegerField(primary_key=True) tableName = models.CharField(max_length=20, default=None) class Meta: db_table = "table1" class model_2(models.Model): id = models.IntegerField(primary_key=True) tableId = models.ForeignKey(model_1, on_delete=models.CASCADE, db_column='tableId') class Meta: db_table = "table2" i am performing, queryset = Leads.objects.select_related('tableId').annotate(tcount=Count('tableId')) which is giving me the result, SELECT `table2`.`id`, `table2`.`tableId`, COUNT(`table2`.`tableId`) AS `tcount`, `table1`.`id`, `table1`.`tableName` FROM `table2` INNER JOIN `table1` ON (`table2`.`tableId` = `table1`.`id`) GROUP BY `table2`.`id` ORDER BY NULL; this is applying group by on table2.id , but i have specified annotate on tableId, in my ORM query hence it should apply group by on table2.tableId what am i doing wrong here ? Thank you for your suggestions -
How to group by over related model count in Django ORM
Let's say I have the following models: class Conversation(Model): ... class Message(Model): conversation = models.ForeignKey(Conversation) The following code counts the number of messages for each conversation: Conversation.objects \ .filter(...) \ .annotate(size=Count("message")) \ .values("size") and returns a query set of {'size': 0}, {'size': 1}, {'size': 0}, {'size': 0} etc. But how do I aggregate over the conversation sizes? That is, obtaining a result something like this: (0, 3), (1, 1), where the first element in each pair is the conversation size and the second element is the number of conversations of this size? -
how to serializers django 3 related model and create instance
My Modes.py look like below they have 3 related models all three model connect with one to one field so I am trying to make one serializers for all 3 model, and I want to create instance of 3 model at a time because of they are connected with each other with one to one field I am able to do with 2 models can anyone help me thanks in advance. class UserProfile(models.Model): # some field telephone = models.CharField(max_length=12) class User(AbstractUser): username = None email = models.EmailField(_('email'), unique=True) first_name = models.CharField( _('first name'), max_length=250) last_name = models.CharField(_('last name'), max_length=250) profile = models.OneToOneField(UserProfile, on_delete=models.CASCADE, null=True) class Genre(MPTTModel): user = models.OneToOneField(User, on_delete=models.CASCADE) parent = TreeForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name='reporting_manager') serializers.py class UserProfileModifySerializer(ModelSerializer): class Meta: model = UserProfile fields = ['telephone'] class EmployeeCreateSerializer(ModelSerializer): profile = UserProfileModifySerializer() id = PrimaryKeyRelatedField(read_only=True) class Meta: model = User fields = [ 'id', 'email', 'first_name', 'last_name', 'profile', ] # def create(self, validated_data): # profile_data = validated_data.pop('profile') # instance_profile = UserProfile.objects.create(**profile_data) # instance_user = User(profile=instance_profile, **validated_data) # password = randomStringDigits() # instance_user.set_password(password) # instance_user.save() # return instance_user class GenreModifySerializer(ModelSerializer): user = EmployeeCreateSerializer() class Meta: model = Genre fields = ['user', 'parent'] def create(self, validated_data): user_data = validated_data.pop('user') instance_user = … -
django.db.utils.ProgrammingError: relation "cms_cmsplugin" already exists
While upgrading an old project to django 1.8 and djangocms 3.5 I am getting an error that says: django.db.utils.ProgrammingError: relation "cms_cmsplugin" already exists Does anyone understand what is wrong and can help with that? Thanks. I have tried some solution propositions on other titles but none worked. did --fake-initial, tried migrating commenting out all other plugins of cms etc but none worked. -
Django Rest Serializer Foreign Key Is Required Error
I am trying to have a client have a 1 to many relationship with emails and phones. class Client(models.Model): class Email(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='emails') email = models.CharField(null=True, blank=True, max_length=50) class Phone(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, related_name='phones') phone = models.CharField(null=True, blank=True, max_length=50) And this is my serializer class ClientSerializer(serializers.ModelSerializer): emails = EmailSerializer(required=False, allow_null=True, many=True) phones = PhoneSerializer(required=False, allow_null=True, many=True) I cannot pinpoint why the post will not proceed because it keeps saying client is required. While i got it to work by adding read_only=True, even if i define a def create(self, validated_data) in the ClientSerializer i cannot get hold of the emails and phones array in the json data. This is how I called the serializer in the views.py serializer = ClientSerializer(data=request.data) Thoughts? -
[Django][channels][python] How is it possible to upload static files (image, documents)?
I have just finished the tutorial of channels and straggled to write codes for uploading static files for almost a week. Could you help me to write both js and consumer.py? Thank you in advance. I especially do not understand: 1. how to write js to send static data to consumer.py 2. how to get static data in consumer.py from js. My codes are: js <script> var obj = document.getElementById('talk_element'); obj.scrollTop = obj.scrollHeight; var roomName = {{ room.pk }}; var chatSocket = new WebSocket( 'ws://' + window.location.host + '/ws/room/' + roomName + '/'); chatSocket.onmessage = function(e) { var data = JSON.parse(e.data); var message = data['message']; var file = data['file']; var created_by = data['created_by'] var user = `{{ user }}`; if (created_by == user) { document.getElementById('talk_element').innerHTML += ` <li class="container card-text text-right text-black"> <span class="speech-bubble-user text-left">${message}</span> <img src="${file}" max-width="350" height=auto/> </li>`; } else { document.getElementById('talk_element').innerHTML += ` <li class="container card-text text-left text-black"> <span class="container speech-bubble text-left">${message}</span> </li>`; } }; chatSocket.onclose = function(e) { console.error('Chat socket closed unexpectedly'); }; document.querySelector('#chat-message-input').focus(); document.querySelector('#chat-message-input').onkeyup = function(e) { if (e.keyCode === 13 && e.shiftKey) { // enter, return document.querySelector('#chat-message-submit').click(); } }; document.querySelector('#chat-message-submit').onclick = function(e) { var messageInputDom = document.querySelector('#chat-message-input'); var message = messageInputDom.value; var userInputDom = … -
what is xs and ns attributes in suds?
I use suds.client for soap web service connection. from suds.client import Client Web=Client('http://webapi.ihio.gov.ir/hdkcore/api/services/authenticationservice?wsdl') now when I print 'Web' i have this method: Suds ( https://fedorahosted.org/suds/ ) version: 0.6 Service ( AuthenticationServiceImplService ) tns="http://impl.service.hdk.avihang.ir/" Prefixes (1) ns0 = "http://auth.sei.service.hdk.avihang.ir" Ports (1): (AuthenticationServiceImplPort) Methods (4): doOpenCitizenSession(ns0:dtoClientInfo dtoClientInfo, ns0:dtoIdentifierWrapper dtoIdentifierWrapper) doOpenUserSession(ns0:dtoClientInfo dtoClientInfo, ns0:dtoIdentifierWrapper dtoIdentifierWrapper) fetchAgentDailyToken(xs:int terminalId, xs:string userName, xs:string password) fetchUserInfoBySessionId(ns0:dtoClientInfo dtoClientInfo) Types (8): ns0:EXCP_AuthenticationGeneral ns0:dtoAuthenticationInfoWrapper ns0:dtoClientInfo ns0:dtoIdentifier ns0:dtoIdentifierWrapper ns0:dtoSessionWrapper ns0:dtoUserForIHIO ns0:dtoUserSessionAndAccessWrapper it has 4 methods. third one that contains 'xs', I'm ok with that and I can connect with it. but others that contain 'ns0' make a problem for me! what is the difference between 'xs' attributes and 'ns0' ones? -
How can exceptions in graphene-django be conditionally logged?
Whenever exceptions are raised they're logged in the console (and in Sentry if it's used). Many of these exceptions are only intended to be shown to the user. For example, django-graphql-jwt raises the PermissionDenied exception for the login_required decorator. The problem is this pollutes the console output during testing/development and logs valid errors to Sentry during production. For exceptions such as the example above, that's only intended to be shown to the user, not logged. As a workaround I've tried writing middleware that catches any exceptions thrown: class ExceptionFilterMiddleware: IGNORED_EXCEPTIONS = ( # Local exceptions ValidationException, # Third-party exceptions JSONWebTokenExpired, PermissionDenied, ) def on_error(self, error): if not isinstance(error, self.IGNORED_EXCEPTIONS): return error def resolve(self, next, *args, **kwargs): return next(*args, **kwargs).catch(self.on_error) But if an exception is caught or not returned, it no longer populates the errors field in query/mutation output. Therefore all errors are logged, there's no way to conditionally log exceptions. This means the only solution is to create a logging filter like the following: def skip_valid_exceptions(record): """ Skip exceptions for errors only intended to be displayed to the API user. """ skip: bool = False if record.exc_info: exc_type, exc_value = record.exc_info[:2] skip = isinstance(exc_value, valid_exceptions) return not skip But this … -
Load template based on domain
There are two sites with different domains (first_example.com, second_example.com). They have a common database and common logic. The task is what needs to be done so that for each of the sites its own template is loaded. For example, there will be a file structure __landing ____templates ______landing ________site_1 __________ index.html ________site_2 __________ index.html It is necessary that when opening the first domain, templates from site_1 are loaded. And when opening the second domain, templates from site_2 were loaded. I think I need to write somehow template_loader, but I don’t understand yet how to do it. -
Sort list of objects by date, where objects don't have name
I'm trying to to join two querysets and sort the final list by dates. The thing that querysets don't have names. So I am not really sure how to do reference them with lambda. ur_dates =list(unavailable_rooms_prices.values('checkin','checkout').distinct().order_by('checkin')) ar_dates=list(available_rooms_prices.values('checkin','checkout').distinct().order_by('checkin')) if ur_dates is not None: ar_dates.extend(ur_dates) sorted_list = ar_dates.sort(key=lambda r: r.checkin) It's the way I am trying to do it, but I get error saying that dict object doesn't have attribute 'checkin'. As I understand, it should be Foo.checkin. but in this case, what is my foo? I think Monday morning is putting a mist on my mind. Thank you! -
I am trying to import/export a model that has a taggit field to/from a CSV file
I am trying to write a script that can create models in my database from a CSV file. One of my fields is a django-taggit manager, and I cannot figure out how to represent the data in my csv file. I have tried exporting the field, and I receive an error AttributeError: '_TaggableManager' object has no attribute 'name' Any help would be much appreciated. Thanks -
Python Populating ManyToManyField automativally using same model instance
I am screwed up to solve a problem for last 7 days, yet i couldn't solve this problem! so much frustrated now!!! I want when i create new GroupMess with an admin, the same admin should automatically added to members field, this is my models: class GroupMess(models.Model): admin = models.OneToOneField( User, on_delete=models.CASCADE, related_name='mess_admin' ) members = models.ManyToManyField(User, related_name='mess_members', blank=True) def save(self, *args, **kwargs): self.members.add(self.admin) super(GroupMess, self).save(*args, *kwargs) If i try to create new GroupMess, it throws me this error: "<GroupMess: GroupMess object (None)>" needs to have a value for field "id" before this many-to-many relationship can be used. If i override save method like this: def save(self, *args, **kwargs): super(GroupMess, self).save(*args, *kwargs) self.members.add(self.admin) then it doesn't throws any error but the problem is, the members field remain blank Can anyone help to fix this? I want when i create GroupMess, i will add the admin during creating groupmess and the members filed should filled automatically with the admin I mean, A group admin also will be a group members -
Error with reverse function in django. Can't match a pattern
I am creating my first website using Django. While creating a form and returning the website to the details page of the just created page I came with this NoReverseMatch problem at /books/books/add/ Reverse for 'detail' with keyword arguments '{'pk': 39}' not found. 1 pattern(s) tried: ['books/(?P[0-9]+)/$ I have tried fixing my URL in my urls.py file but being new to this I couldn't get it working. urls.py file from django.conf.urls import url from django.contrib import admin from . import views app_name = 'books' URL patterns = [ url(r'^books/$', views.index, name='index'), url(r'^$', views.index, name='index'), url(r'^(?P<book_id>[0-9]+)/$', views.detail, name='detail'), url(r'books/add/$',views.BookCreate.as_view(),name='book-add'), ] model.py file from django.db import models # Create your models here. from django.core.urlresolvers import reverse class Books(models.Model): def get_absolute_url(self): return reverse('books:detail', kwargs={"pk":self.pk}) def __str__(self): return self.name + '-' + self.author name = models.CharField(max_length=100) author = models.CharField(max_length=100) price = models.CharField(max_length=100) book_image = models.CharField(max_length=1000) -
After Django uses `mysql.connector.django` as the database ENGINE, how to print the executed SQL statement
The database configuration is as follows: https://dev.mysql.com/doc/connector-python/en/connector-python-django-backend.html As the title? Previously django.db.backends, I added the following configuration in setting.py, print execution SQL statement。 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console':{ 'level':'DEBUG', 'class':'logging.StreamHandler', }, }, 'loggers': { 'django.db.backends': { 'handlers': ['console'], 'propagate': True, 'level':'DEBUG', }, } } -
django - user profile is used as foreign key in another model. how to show the logged in user in the form?
I have a form to upload files and am using a foreignkey to route the files to a specific folder the user is grouped under. Now in my upload form the users are listed in a dropdown menu. Could someone help me to show only the current logged in user name This is my models.py for the uplaod form class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, unique=True, verbose_name='Username') tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") # validators=[FileExtensionValidator(allowed_extensions=['tar', 'zip'])] def get_absolute_url(self): return reverse('file_list', kwargs={'pk': self.pk}) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Assigned_Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username forms.py class uploadmetaform(forms.ModelForm): count = Metadataform.objects.all().latest('id').id #To know the id of latest object data = Metadataform.objects.all().filter(id=count) #return the queryset with only latest object path = forms.ModelChoiceField(queryset=data, initial=0, label='Meta ID') def __init__(self, *args, **kwargs): super(uploadmetaform, self).__init__(*args, **kwargs) count = Metadataform.objects.all().latest('id').id data = Metadataform.objects.all().filter(id=count) self.fields['path'] = forms.ModelChoiceField(queryset=data, initial=0, label='Meta ID') class Meta: model = uploadmeta fields = ['path', 'user_profile','tar_gif',] -
How can i get WalkSerializer all data in WalkDetailSerializer?
I am trying to get all data from walkserializer to walk detailserializer i did like this but i could not see any data so please help me how to implement this that i will see my data. Here it is my serializer field that i created so how to implement that i will get all walk serializer dat to walk detail serializer class WalkSerializer(serializers.ModelSerializer): total_milage=serializers.SerializerMethodField() total_movingtime=serializers.SerializerMethodField() total_kg=serializers.SerializerMethodField() total_boxes=serializers.SerializerMethodField() total_letter = serializers.SerializerMethodField() total_ship_weight = serializers.SerializerMethodField() total_pack = serializers.SerializerMethodField() user = serializers.SerializerMethodField() def get_user(self, obj): return obj.user.username class Meta: model = User fields = ['user', 'id', 'total_letter','total_milage','total_movingtime','total_kg','total_boxes', 'total_ship_weight', 'total_pack' ] def get_total_letter(self, obj): totalpieces = Delivery.objects.filter(user_id=obj.user.id, mode="foot").aggregate( total_letter=Sum('letteritems')) return totalpieces["total_letter"] def get_total_ship_weight(self, obj): totalpieces = Delivery.objects.filter(user_id=obj.user.id, mode="foot").aggregate( total_ship_weight=Sum('shipweight')) return totalpieces["total_ship_weight"] def get_total_pack(self, obj): totalpieces = Delivery.objects.filter( user_id=obj.user.id, mode="foot").aggregate(total_pack=Sum('package')) return totalpieces["total_pack"] def get_total_milage(self, obj): totalpieces = Delivery.objects.filter( user_id=obj.user.id, mode="foot").aggregate(total_milage=Sum('milage')) return totalpieces["total_milage"] def get_total_movingtime(self, obj): totalpieces = Delivery.objects.filter( user_id=obj.user.id, mode="foot").aggregate( total_movingtime=Sum('movingtime')) return totalpieces["total_movingtime"] def get_total_kg(self, obj): totalpieces=Delivery.objects.filter( user_id=obj.user.id, mode="foot").aggregate(total_kg=Sum('kgtrasported')) return totalpieces["total_kg"] def get_total_boxes(self, obj): totalpieces=Delivery.objects.filter(user_id=obj.user.id, mode="foot").aggregate( total_boxes=Sum('additionalbox')) return totalpieces["total_boxes"] class WalkDetailSerializer(serializers.ModelSerializer): detail = DeliverySerializer(many=True, read_only=True) walk = WalkSerializer(read_only=True) user = serializers.SerializerMethodField() def get_user(self, obj): return obj.user.username class Meta: model = User fields = '__all__' -
How to call model method at admin page? [duplicate]
This question already has an answer here: Django admin foreign key dropdown with custom value 1 answer In my model have a field (models.ForeignKey(A)). A is model inside library and there is not __str__ method. So when I try to select object of model A in my admin page I have a list of results with objects' ids. But in model I have method like get_title() which return good result. So the question is how to use this method to get readable results in my admin page. I should to make new template for this, or I can do something in admin.py ? -
mail chimp error ConfigParseError: Unable to parse config file: C:\Users\Draftss/.aws/credentials
botocore.exceptions.ConfigParseError: Unable to parse config file: C:\Users\Draftss/.aws/credentials this error is reflecting when i treid to do active the mail, service through aws and i also located the .aws folder on c://user//user_name//.aws//CREDETIAL_FILE I TRIED LOTS OF THINGS I WILL PUT THE IMAGE enter image description here I WANT THAT THE MAIL SUCCEFULLY TRIGGER TO THE RECIVER -
How can I reach second level natural keys on django query?
I have this models on django with natural_keys functions declared. class Comments(models.Model): profile = models.ForeignKey('Profiles', models.DO_NOTHING) book = models.ForeignKey(Books, models.DO_NOTHING) date = models.DateTimeField() text = models.TextField() class Meta: managed = False db_table = 'comments' class Profiles(models.Model): alias = models.CharField(max_length=40) mail = models.CharField(max_length=255) mainimg = models.ForeignKey(Multimedia, models.DO_NOTHING) birthdate = models.DateTimeField(blank=True, null=True) country = models.CharField(max_length=30, blank=True, null=True) password = models.CharField(max_length=255) terms = models.IntegerField(blank=True, null=True) device_token = models.CharField(max_length=500) def natural_key(self): return (self.pk, self.alias, self.country, self.mainimg) class Meta: managed = False db_table = 'profiles' class Multimedia(models.Model): url = models.CharField(max_length=255) title = models.CharField(max_length=100) alt = models.CharField(max_length=150, blank=True, null=True) description = models.CharField(max_length=150, blank=True, null=True) mytype = models.CharField(max_length=20, blank=True, null=True) extension = models.CharField(max_length=6, blank=True, null=True) def natural_key(self): return (self.pk, self.url) class Meta: managed = False db_table = 'multimedia' When I do a get comments query, I want a full response with the comment details, some book details, and profile details (including the picture). Everything goes fine except when I whant the profile mainimg being serialized with natural keys. The error response is <Multimedia: Multimedia object (80)> is not JSON serializable when executing this: def getcomments(request): #Book get all comments - returns all comments on a book. profilelogged = validtoken(request.META['HTTP_MYAUTH']) if not profilelogged: return HttpResponse('Unauthorized', status=401) else: index … -
Which method should i use in Model (Django)
which method should i use and Is there any plus to using an abstract class? I wonder if I will have problems in the future using abstract class (i have never used abstract class in models) Subclass count can increase (Sub 4,5,6...) class Type(models.Model): name=models.CharField(max_length=120) ... class Meta: abstract = True class Sub1(Type): extra=models.CharField(max_length=255) ... class Sub2(Type): extra=models.CharField(max_length=255) ... class Sub3(Type): extra=models.CharField(max_length=255) ... class Example(models.Model): type=models.ForeignKey('Sub1',on_delete=models.CASCADE,null=True,blank=True) ... class Example1(models.Model): type=models.ForeignKey('Sub2',on_delete=models.CASCADE,null=True,blank=True) ... OR class Sub1(models.Model): name=models.CharField(max_length=120) ... class Sub2(models.Model): name=models.CharField(max_length=120) ... class Sub3(models.Model): name=models.CharField(max_length=120) ... class Example(models.Model): type=models.ForeignKey('Sub1',on_delete=models.CASCADE,null=True,blank=True) ... class Example1(models.Model): type=models.ForeignKey('Sub2',on_delete=models.CASCADE,null=True,blank=True) ... -
pip install MOD_WSGI error on docker-compose build
I am getting the following error I have a Dockerfile and trying to build it with docker-compose. When building there is an error on mod_wsgi docker-compose build error -
How to fix "Truncated incorrect INTEGER value: 'UUID'" in Django
I'm creating an app for my web-app, and Django raises this error when I try to migrate my model to the MySQL database. All migrations were working perfectly before. I discovered that CarInstance id was tied to the primary key (pk) which was incompatible with the simple url schema I was going for ("/" which would be (showroom/car/2). I tried to moving the 'id' variable to another class with a simple copy/paste which would link to CarInstance as a foreign key similar to what MDN does with their book & BookInstance models here. I thought this would help create a separate primary key, but here I am. :-) Here is my url path: path('car/<slug:uuid>/', views.CarDetailView.as_view(), name="car-detail"), This is the model code (with the other code omitted): class CarInstance(models.Model): manufacturer = models.ForeignKey('Manufacturer', on_delete=models.SET_NULL, null=True) car_model = models.CharField('Model', max_length=50, null=True) description = models.TextField(max_length=4000) vin = models.CharField('VIN', max_length=17, help_text='Enter the 17 character VIN number.', blank=True, null=True) mileage = models.IntegerField(verbose_name='Mileage') car_images = models.ImageField(help_text='Upload pictures', upload_to=image_directory_path, storage=image_storage) date_added = models.DateField(auto_now_add=True) engine_displacement = models.CharField(default=2.0, max_length=3, help_text="Engine displacement in Liters (E.g. 2.0, 4.2, 6.3)") price = models.IntegerField(default=0) id = models.UUIDField(primary_key=True, default=uuid.uuid4, help_text="Unique ID for this car.", editable=False) I expected the migration to go as normal, but it … -
How to generate a thumbnail from a uploaded video in django rest framework?
I am creating a api for social networking application and I need to create thumbnails from uploaded video files and then show it to the response. Here's my view def get_queryset(self): video = self.queryset.values_list('video', flat=True).get(pk=12) ff = FFmpeg(inputs={video: None}, outputs={"media/"+video+"_thumbnail1.png": ['-ss', '00:00:4', '-vframes', '1']}) #print(ff.cmd) ff.run() return Response({'video_thumbnail': video})