Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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}) -
Foreign key missing from migrations
I have the model Trade: from datetime import datetime from django.db import models from home.models import Player class Trade(models.Model): buyer = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyer'), buyee = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='buyee'), date = models.DateTimeField(default=datetime.now) Model Player: from django.contrib.auth.models import User from django.db import models class Player(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='user') value = models.IntegerField(default=1500) owner = models.OneToOneField(User, on_delete=models.CASCADE, related_name='owner', blank=True, null=True) A Trade happens between 2 Players. That is, the buyer and buyee fields in Trade are foreign keys to Player. Now, when I make migrations for the Trade model, this is what I get: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Trade', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateTimeField(default=datetime.datetime.now)), ], ), ] Why are the 2 foreign key fields missing from the migration? -
How to configure Django-AllAuth to login using Facebook without entering password
I’m using Django AllAuth on my website. But, when people register using Facebook, they are asked to enter their password even when the Facebook account is open in the same browser. I’ve seen other websites where the user is signed up without asking for a password. How can I change the AllAuth settings to register without password? Here is the configuration I have: SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': [ 'id', 'email', 'name', 'first_name', 'last_name', 'verified', 'locale', 'timezone', 'link', 'gender', 'updated_time', ], 'EXCHANGE_TOKEN': True, 'LOCALE_FUNC': lambda request: 'en_US', 'VERIFIED_EMAIL': False, 'VERSION': 'v2.12', }, } -
'something here' matching query does not exist
I created a web app and deployed on Heroku successfully even database migrations. When I open the app I see the error like this: 'something here' matching query does not exist. App URL: https://lp7.herokuapp.com/lp7/ App isn't working and if I remove this data feild from model, then app works but no single data is coming from database. But, when I go to heroku database it shows: No. of Tables = 28 No. Rows = 220 Size of data = 9.4Mb It means, the all migrations exists on heroku but not showing on website. Any solution..? -
How to implement a dropdown populated with values from a database
I am very new to Python and Django, thus having this issue. What I want to do is create a behavior of HTML Select tag with a Django form. This dropdown/select has to be populated with values from a database. What I already have is location = forms.ModelChoiceField(queryset = MyModel.objects.all()) which does give me a select/drowpdown control, but I need it to display one value from the database and have a different one as an actual value (both from the same table just different columns) What I mean in HTML code would look like this: <select> <option value="1">Berlin</option> <option value="2">New York</option> <option value="3">London</option> <option value="4">Riga</option> </select> So, using the form I would see a name of the city, eg. London, but when it is selected and submit is called I insert 3 in the database. Looking forward to your suggestions. -
How would I add a dropdown box that contains all the different type of models in my program?
I want a drop down box of all the models in my program. I made a myModels model that has a charfield of 100. I tried to add the choice tuple and then reference it in the model. helper_choices = [] for my_model in django.apps.apps.get_models(): helper_choices.append((my_model._meta.verbose_name, my_model._meta.verbose_name)) MODEL_CHOICES = tuple(helper_choices) model_name = models.CharField(max_length=100, choices=MODEL_CHOICES, default='') However since this is occurring during the loading of the models phase, I get an error "Models aren't loaded yet." What would be a workaround to this problem?