Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Heroku Deployment : ModuleNotFoundError: No module named 'django_summernote'
During the deployment for my python django blog app, this happening keeps continuing! so I don't know how to deal with it anymore. Actually I've found the sticking error ModuleNotFoundError: No module named 'django_summernote'. I solved many previous errors, h10, h14 but the ModuleNotFoundError still exists. in my Installed App in setting.py, it doesn't have any problem with it. So I couldn't catch up.. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'articles', 'templates', 'django_summernote', 'sorl.thumbnail', 'gunicorn', ] and below is the Error part State changed from crashed to starting 2018-12-10T13:25:48.417441+00:00 heroku[web.1]: Starting process with command `gunicorn djangoblog.wsgi:application --log-file - --log-level debug` 2018-12-10T13:25:48.000000+00:00 app[api]: Build succeeded 2018-12-10T13:25:51.553811+00:00 app[web.1]: [2018-12-10 13:25:51 +0000] [4] [DEBUG] Current configuration: 2018-12-10T13:25:51.553836+00:00 app[web.1]: config: None 2018-12-10T13:25:51.553838+00:00 app[web.1]: bind: ['0.0.0.0:47277'] 2018-12-10T13:25:51.553839+00:00 app[web.1]: backlog: 2048 2018-12-10T13:25:51.553841+00:00 app[web.1]: workers: 2 2018-12-10T13:25:51.553842+00:00 app[web.1]: worker_class: sync 2018-12-10T13:25:51.553844+00:00 app[web.1]: threads: 1 2018-12-10T13:25:51.553845+00:00 app[web.1]: worker_connections: 1000 2018-12-10T13:25:51.553847+00:00 app[web.1]: max_requests: 0 2018-12-10T13:25:51.553848+00:00 app[web.1]: max_requests_jitter: 0 2018-12-10T13:25:51.553850+00:00 app[web.1]: timeout: 30 2018-12-10T13:25:51.553851+00:00 app[web.1]: graceful_timeout: 30 2018-12-10T13:25:51.553852+00:00 app[web.1]: keepalive: 2 2018-12-10T13:25:51.553854+00:00 app[web.1]: limit_request_line: 4094 2018-12-10T13:25:51.553855+00:00 app[web.1]: limit_request_fields: 100 2018-12-10T13:25:51.553857+00:00 app[web.1]: limit_request_field_size: 8190 2018-12-10T13:25:51.553858+00:00 app[web.1]: reload: False 2018-12-10T13:25:51.553859+00:00 app[web.1]: reload_engine: auto 2018-12-10T13:25:51.553861+00:00 app[web.1]: reload_extra_files: [] 2018-12-10T13:25:51.553862+00:00 app[web.1]: spew: False 2018-12-10T13:25:51.553864+00:00 app[web.1]: check_config: False 2018-12-10T13:25:51.553865+00:00 app[web.1]: preload_app: False … -
django-rest-framework: int() argument must be a string, a bytes-like object or a number, not Deferred Attribute
I am creating sample rest API using django-rest-framework, I refereed the tutorial on there website https://www.django-rest-framework.org/tutorial/1-serialization/ I api is working fine when list and create new object but it throwing the exception during detail view(http://127.0.0.1:8000/cars/1) of object. I have added my code snippet below, Please let me know what wrong i am doing Models.py class Car(models.Model): created = models.DateTimeField(auto_now_add=True) name = models.CharField(max_length=100, blank=True, default='') price = models.TextField() class Meta: ordering = ('created',) serializers.py class CarsSerializer(serializers.ModelSerializer): class Meta: model = Car id = serializers.IntegerField(read_only=True) fields = ('id', 'created', 'name', 'price') Views.py @csrf_exempt def car_list(request): """ List all code cars, or create a new car. """ if request.method == 'GET': cars = Car.objects.all() serializer = CarsSerializer(cars, many=True) return JsonResponse(serializer.data, safe=False) elif request.method == 'POST': data = JSONParser().parse(request) serializer = CarsSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) @csrf_exempt def car_detail(request, pk): """ Retrieve, update or delete a code cars. """ try: car = Car.objects.get(pk=pk) except Car.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = CarsSerializer(Car) return JsonResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = CarsSerializer(Car, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) elif request.method == 'DELETE': Car.delete() return HttpResponse(status=204) Urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), path('cars/', … -
Django and Javascript Dictionary with variable
I'm been looking all over but can't find how to write/access value from a dictionnary in javascript while writing the key dynamically. The below is a dictionnary of Json objects corresponding to specials itinaries. This is working : var geojson1 = {{ mydict["USA2019"]|safe }}; map.getSource('data-update').setData(geojson1); What I would like to do is pass as variable the name of the dictionnaries. I can select in my HTML several trip name and would like to get the json of the selected trip thanks to the value of "mysavedtrip" let mysavedtrip_select = document.getElementById('mysavedtrip'); mysavedtrip.onchange = function() { mysavedtrip = mysavedtrip_select.value; Is there a way to pass the variable in the dictionary in Javascript ? something like the below code ? var geojson = {{ mydict[ + mysavedtrip + ]|safe }}; map.getSource('data-update').setData(geojson); any idea ? -
Django default at database
So as I recently came to understand, the default that we specify in a Django field is merely for filling up pre-existing rows, and doesn't function as a "real" default value at the database level. This can be verified by looking up column_default from the database shell. If I understand correctly, default is used by Postgres to put in values when there is no input. If that is so, then we shouldn't be able to create a new object in Django without providing the default value, right? For ex - class MyModel(models.Model): name = models.CharField(max_length=255) status = models.BooleanField(default=True) # new field added For the above model, the default is used for only backfilling the newly added field for pre-existing rows. It doesn't actually set a default at the database level. column_name | column_default -------------+---------------- mymodel | But if that is so, I shouldn't be able to run this query - MyModel.objects.create(name='test') since there's no "real" default. But I can, and I don't understand why. Thank you! -
Connecting Django to MongoDB using Djongo Connector throws SSL Handshake exception
I'm trying to connect to MongoDb from my django application, but it throws [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777) Exception. This is the same exception, that pymongo throws, when I connect to MongoDB., but I can get the connection working by appending &ssl_cert_reqs=CERT_NONE , at the end of my connection uri. Basically, the MongoDb that I'm trying to connect to, has ssl implemented in it, and I don't want to pass certificates to get the connection. However, in dango, it expects us to pass a dictionary of key-value pairs in the database configuration section of settings.py file. I tried specifying the same 'SSL':True,'SSL_CERT_REQS':'CERT_NONE' connection settings from my application, but it keeps on throwing same exception. Any help, how to configure certificates or just simply bypassing certificate check on client side to make the connection work is highly appreciated. Thanks ! -
request.FILES empty, though file is present in request
Following the example on the django website I'm trying to upload a file, perform checks on the contents, then feedback to the user and store the file contents. However, I'm having trouble with the request.FILES which is always empty. My code is as follows (note the output after the print statements): **forms.py** class UploadFileForm(forms.Form): data_import = forms.FileField() class Meta: model = Recipe fields = ('data_import',) **view** def recipes_list(request): template = 'recipes/recipes_list.html' if request.method == 'GET': user = request.user queryset = Recipe.objects.filter(user=user) form = UploadFileForm() return render(request, 'recipes/recipes_list.html', context={'recipes': queryset, 'form': form}) elif request.method == 'POST': print(request.FILES) # <MultiValueDict: {}> print(request.POST) # <QueryDict: {'csrfmiddlewaretoken': ['...'], 'data_import': ['recette.json']}> form = UploadFileForm(request.POST, request.POST.data_import) if form.is_valid(): return HttpResponseRedirect(template) else: print(form.errors) **template** <form method="post"> {% csrf_token %} {{ form }} <button type="submit">submit</button> </form> The error I'm getting is: <ul class="errorlist"><li>data_import<ul class="errorlist"><li>This field is required.</li></ul></li></ul> But i can see that the file is uploaded, and is in the request.POST.get('data_import'). I would like to run validation on the form, but I can't do this if request.FILES is empty. I'm clearly doing something wrong, can someone please point me in the right direction? -
Is it okay to have a model property and a Django queryset annotation with the same name
Summary It appears we can create a property on a Django model, and add a queryset annotation with the exact same name. This appears to work, at least in our initial tests, effectively allowing us to filter a model property. However, I wonder if this is could lead to problems later on... Background We have an existing database with a FooBarModel with field bar, which is used in many places in our project code, e.g. in queryset filters. Now, for some reason, we need to add a new field, foo, which should be used instead of the bar field. The bar field still serves a purpose, so we need to keep that as well. If foo has not been set (e.g. for existing database entries), we fall back to bar. Implementation Now to make this work, we implement the model with a foo property, a _foo model field, a set_foo method and a get_foo method that provides the fallback logic (returns bar if _foo has not been set). However, as far as I know, a property cannot be used in a queryset filter, because foo is not an actual database field. _foo is, but that does not have the fallback … -
Define model permission in django raise error
I defined this in my djang model : class Meta: permissions = ( ("view_sth", "Can view sth"), ) but when I try to migrate this error raise: The permission codenamed 'view_sth' clashes with a builtin permission for model 'myapp.sth'. I couldn't find a solution on the internet for it -
Trouble with understanding a queryset in Django
I have a user profile page connected to a model which amongst other fields contain the following: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default='default.jpg', upload_to='profile_pics') That works like it should; the profile image connected to the user in question is loaded, and the distinction between users is made. What I'm trying to do now is connect a separate gallery model to the profile page, that the users may have a small image gallery to goof around with. The gallery model looks like this: class GalleryModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) img_1 = models.ImageField(default='default.jpg', upload_to='images') img_2 = models.ImageField(default='default.jpg', upload_to='images') img_3 = models.ImageField(default='default.jpg', upload_to='images') The views.py file looks like this: class ProfileDetailView(DetailView): model = Profile # Is something iffy here? Should this refer to the GalleryModel as well? template_name = 'account/view_profile.html' def get_object(self): username = self.kwargs.get('username') if username is None: raise Http404 return get_object_or_404(User, username__iexact=username, is_active=True) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) username = self.object.username context['person'] = GalleryModel.objects.get(user__username=username) #loads username string context['img_1'] = GalleryModel.objects.last().img_1 context['img_2'] = GalleryModel.objects.last().img_2 context['img_3'] = GalleryModel.objects.last().img_3 return context I've tried a bunch of ideas (i.e. various approaches to the filter() and get() methods) and scrutinizing https://docs.djangoproject.com/en/2.1/topics/db/queries/ and sifting through what I could find on SO, but I … -
function get_form_kwargs() not being called
I'm trying to pass a parameter from a redirect to the CreateView and to the form. I have no problem retrieving the value from the redirect to the CreateView. But my issue is when trying get the value to the form. I'm overriding get_form_kwargs function of my CreateView but when I try to do operations from that function, I'm not able to get any result. I tried to do a print but the print won't display anything. class NoteCreate(LoginRequiredMixin, CreateView): login_url = 'login' model = Note form_class = NoteForm success_url = reverse_lazy('note:list') def get_form_kwargs(self): kwargs = super(NoteCreate, self).get_form_kwargs() kwargs.update({'file_id' : self.kwargs['file_id']}) print("im alivveeeeeeeEeeeeeeeeeeeee!") return kwargs the print statement doesn't seem to be working. It does not show anything in the console. I'm able to render the form with no errors in the console. -
Selenium with Django. Error import webdriver
I am using Selenium, inside a Django Project. I am using it in views.py, inside to my app, and I link it by url. from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException def allyears(br): global browser path = os.environ['PATH'] browser = webdriver.Chrome(executable_path="/"+path+"/chromedriver) browser.get('https://www.address.com/recipes/)) I am trying to install Webdriver Chrome in a Django project. I linked to path environment, but not working. Anyway, when I will update it to a server, I can not link to a physical route. So, how can import webdriver.Chrome or webdriver.Firefox in Django? -
django-admin "ModuleNotFoundError:" after change in settings structure for development & production
Background I have recently started to learn Python Django. I read that it was good practice to have separate settings file for different environments. Consequently I have tried to implement something similar to what is describe in the "Simple Package Organization for Environments" section of this wiki: https://code.djangoproject.com/wiki/SplitSettings Problem When I now run a django-admin command I get a ModuleNotFoundError. Below I have copy pasted the error log I get for "django-admin check --deploy". "python manage.py runserver --settings=CollegeComp.settings.development" works fine. Things I've tried I was reading that I may have to reset the DJANGO_SETTINGS_MODULE environment variable in my virtual environment. I entered "set DJANGO_SETTINGS_MODULE=CollegeComp.settings.development" but I still get the same error. Python path When I type the following in the shell with my virtual environment activated: import sys print(sys.path) I get the following: ['C:\\Users\\myusername\\Documents\\UdemyDjango\\MyPersonalProject\\College-Project-master\\CollegeComp', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\python37.zip', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\DLLs', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv', 'C:\\Users\\myusername\\Anaconda3\\envs\\MyDjangoEnv\\lib\\site-packages'] Error log During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\Scripts\django-admin-script.py", line 10, in <module> sys.exit(execute_from_command_line()) File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\core\management\base.py", line 329, in run_from_argv connections.close_all() File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 220, in close_all for alias in self: File "C:\Users\myusername\Anaconda3\envs\MyDjangoEnv\lib\site-packages\django\db\utils.py", line 214, in __iter__ return … -
Run django-admin
I'm new to django and I would like to follow this tutorial: https://docs.djangoproject.com/en/2.1/intro/tutorial01/ Unfortunately, django-admin is not in my path. When I try to run the django-admin.py script directly, I have the following error: $ /usr/local/lib/python3.7/site-packages/django/bin/django-admin.py Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/bin/django-admin.py", line 2, in <module> from django.core import management ImportError: No module named django.core Here is my configuration: System: macOS 10.13 Python: 3.7.0 (installed via Homebrew Django: 2.1.4 What am I doing wrong? -
Can not save an instance object of a manytomany relationship implemented with inlines
In my app I would like to implement the feature that a user could choose to create a preorder with more than one products. My problem is that despite the fact that I can create the inline form it is not possible to save the instance referring to preorder in my view.py My form appears the Preorder model and my formset appears the Preorder_Has_Products relationshp. Preorder and Product are models with the relationship below: models.py class Preorder(models.Model): client = models.ForeignKey(Client,verbose_name=u'Πελάτης') preorder_date = models.DateField("Ημ/νία Προπαραγγελίας",null=True, blank=True, default=datetime.date.today) notes = models.CharField(max_length=100, null=True, blank=True, verbose_name="Σημειώσεις") preorder_has_products=models.ManyToManyField(Product,blank=True) def get_absolute_url(self): return reverse('preorder_edit', kwargs={'pk': self.pk}) my form.py class PreorderForm(ModelForm): class Meta: model = Preorder fields=('preorder_date','notes',) def __init__(self, *args, **kwargs): super(PreorderForm, self).__init__(*args,**kwargs) self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) class PreorderHasProductsForm(ModelForm): class Meta: model=Preorder.preorder_has_products.through exclude=('client',) def __init__(self, *args, **kwargs): super(PreorderHasProductsForm, self).__init__(*args, **kwargs) #self.fields['preorder_date'].widget = MyDateInput(attrs={'class':'date'}) self.fields['product'].label = "Ονομα Προϊόντος" PreorderProductFormSet = inlineformset_factory(Preorder,Preorder.preorder_has_products.through, form=PreorderHasProductsForm, extra=1) my view.py class PreorderProductCreateView(LoginRequiredMixin, CreateView): model = Preorder fields=['preorder_date','client',] template_name='test/test.html' def get_success_url(self, **kwargs): return reverse('client_list) def form_valid(self, form): context = self.get_context_data() Preorder_Preorder_Has_ProductsFormset = context['Preorder_Preorder_Has_ProductsFormset'] if Preorder_Preorder_Has_ProductsFormset.is_valid() and form.is_valid(): self.object = form.save() # saves Father and Children #products = Preorder_Preorder_Has_Products_CreateView.save(commit=False) products=Preorder_Preorder_Has_ProductsFormset.save_m2m() print(len(products)) for instance in products: instance.preorder = self.object instance.save() #douleuei, to self.object anaferetai sto preorder #Preorder_Preorder_Has_Products_CreateView.save_m2m() print(instance.id) … -
Cloud system with local printers
I'm developing a new software. Actually i'm using python with django to develop backend and a framework javascript to design frontend. Today I'm using local installation because the software needs to handle some local termal printers. Besides the software I have "mobile app" that is not but a internet page. This mobile app makes a order and it's printed in the printers. In my pilot clients the system are running in a raspberry pi 3 model b+ with fixed IP, S.O raspbian and CUPS managing printers, to use the software it's necessary only open a internet browser and enter the Raspberry IP address. My problem is that I want to have a low cost software to be installed by the customers themselves (they don't have a raspberry pi, they have a machine with windows usually) and in this case, the problem is: How will the software connect to the printers directlly, once the mobile need to send orders without any question about printers as we can see usually on a internet page. -
Save two forms data with OneToOneField in Django
i have two models class Client(models.Model) : Code_Client=models.CharField(max_length=200) ...... and class Adr(models.Model) : client = models.OneToOneField(Client,on_delete=models.CASCADE) I created two forms: one for Client and another for Adr in order to use it in one template I could do that with no problem but when I try to save the data from both form it gives me an error if form.is_valid() and form_Adr.is_valid(): #pdb.set_trace() new_client=form.save() Adr0 = form_Adr.save(commit=False) Adr0.client= new_client Adr0.save() the error is Client: this field is mandatory. -
Django2 queries not written to log
I'm trying to learn Django, but finding it quite hard. Likely because my C++/PHP/Symfony experience is making it difficult to 'think Python'. While most issues tend to be solved in an 'D'oh!' moment after some hours of mumbling profanities, this one is proving to be very resilient. I've got Django2 installed, configured with a MariaDB 10.2 database and the django-debug-toolbar. DEBUG is true and my IP (localhost) is added to INTERNAL_IPS I'd like to see the queries that the Django ORM is producing, but the debug toolbar is only showing me input and output. The actual queries are displayed as 'None' The same thing happens when attempt to log the queries to the console using https://stackoverflow.com/a/20161527/3883632 I'm probably missing something obvious, but can't find it nor any reference to this issue. Relevant version information: Python 3.7.1 Django 2.1.4 Mysqlclient 1.3.14 django-debug-toolbar 1.11 -
Get all urls in django project
I need to make a request to every page of my django project and check its db connections. Is there a way to get list of them? Is this possible to do without using any third-party libraries? -
AttributeError: 'ContactUs' object has no attribute 'model'
can any body help me, i try create contact form on python-django, and when i try make migrations on data base i recieve error "AttributeError: 'ContactUs' object has no attribute 'model'" vievs.py from django.shortcuts import render from .forms import ContactForm, ContactUs from django.core.mail import EmailMessage from django.shortcuts import redirect from django.template.loader import get_template def contact(request): form_class = ContactForm # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = request.POST.get('first_name', '') last_name = request.POST.get('last_name', '') date = request.POST.get('date', '') month = request.POST.get('month', '') year = request.POST.get('year', '') sender = request.POST.get('sender', '') message = request.POST.get('message', '') licence = request.POST.get('licence', '') phoneNumber = request.POST.get('phoneNumber', '') zipCode = request.POST.get('zipCode', '') cdlType = request.POST.get('cdlType', '') # Email the profile with the # contact information template = get_template('contact_template.txt') context = { 'first_name': first_name, 'last_name': last_name, 'date': date, 'month': month, 'year': year, 'sender': sender, 'message': message, 'licence': licence, 'phoneNumber': phoneNumber, 'zipCode': zipCode, 'cdlType': cdlType, } content = template.render(context) email = EmailMessage( "New contact form submission", content, "Your website" + '', ['youremail@gmail.com'], headers={'Reply-To': sender} ) email.send() return redirect('contact') return render(request, 'email.html', { 'form': form_class, }) def contact_us(request): form_class = ContactUs # new logic! if request.method == 'POST': form = form_class(data=request.POST) if form.is_valid(): first_name = … -
I do not know how to activate register for foreign key in relationship in the database
I'm Brazilian then in the table Veiculo == vehicle and Pessoa == person and as a person can have several cars plus one car only one person when registering a new monthly check-in in the parking lot, I need to select the person only the cars that he owns appear as an option. I need that when registering a Pessoa and a Veiculo they are realacionamos in a way that when registering using Views Mensalista when I put Pessoa soment the Veiculo that is owned by it appears in a forum gave me the idea to use the code below, but I do not know how to implement it proprietarioId = id queryList = Veiculo.objects.filter(proprietario__id = proprietarioId) Models.py TATE_CHOICES = ( ('AC', 'Acre'), ('AL', 'Alagoas'), ('AP', 'Amapá'), ('AM', 'Amazonas'), ('BA', 'Bahia'), ('CE', 'Ceará'), ('DF', 'Distrito Federal'), ('ES', 'Espírito Santo'), ('GO', 'Goiás'), ('MA', 'Maranhão'), ('MT', 'Mato Grosso'), ('MS', 'Mato Grosso do Sul'), ('MG', 'Minas Gerais'), ('PA', 'Pará'), ('PB', 'Paraíba'), ('PR', 'Paraná'), ('PE', 'Pernambuco'), ('PI', 'Piauí'), ('RJ', 'Rio de Janeiro'), ('RN', 'Rio Grande do Norte'), ('RS', 'Rio Grande do Sul'), ('RO', 'Rondônia'), ('RR', 'Roraima'), ('SC', 'Santa Catarina'), ('SP', 'São Paulo'), ('SE', 'Sergipe'), ('TO', 'Tocantins') ) class Pessoa(models.Model): nome = models.CharField(max_length=50, blank=False) email … -
Django - How to properly stream a matrix in a RESTful API?
After computing some values from on the server side. The result is a matrix (i.e a pandas.DataFrame) with the following format: 0 1 2 3 4 5 6 0 1 0 0 0 2 0 6 100 0 0 0 0 0 0 0 200 0 0 0 0 0 0 0 300 0 0 0 0 0 0 0 Where first row/column represents row/column indexes, and (just in this case) some of the values are zero. What would be a popper JSON format to stream this matrix? Is there any standard way to do it? -
django email attachment of an uploaded file using modelname.filevariable.url
I have a Django library application, wherein from a list of books, the customer can email a particular book's pdf file link that was originally uploaded using FileField by the admin. Now, the email is being sent/received successfully, however the pdf file is not getting attached. I have also looked into other stackoverflow references for the same, but I am unable to interpret the correct solution: Django email attachment of file upload On clicking the email button, the form is submitted as follows: Three hidden values are also being submitted on submitting the form. , one of which is the book.file.url <form method="POST" action ="{% url 'email_book' %}" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="book_title" value="{{ book.title }}"> <input type="hidden" name="book_author" value="{{ book.author }}"> <input type="hidden" name="book_pdf" value="{{ book.file.url }}"> <button type="submit" class="btn btn-info"><span class="glyphicon glyphicon-envelope"></span>&nbsp;&nbsp;Email</button> </form> The urls.py urlpatters=[....path('email_book/', views.send_email, name='email_book'),...] In views.py, I have used Django's EmailMessage class as follows: def send_email(request): book_title = request.POST.get('book_title') book_author = request.POST.get('book_author') book_pdf = request.POST.get('book_pdf') # i.e book.file.url email_body = "PDF attachment below \n Book: "+book_title+"\n Book Author: "+book_author try: email = EmailMessage( 'Book request', email_body, 'sender smtp gmail' + '<dolphin2016water@gmail.com>', ['madhok.simran8@gmail.com'], ) # this is the where the error occurs email.attach_file(book_pdf) … -
Find the model name from a Django Rest framework Serializer
I have a serializer from which I need to find the associated model name.This is how i did it: In [30]: from my_app.serializers.PolicySerializer import PolicyCreateSerializer In [31]: model_name = PolicyCreateSerializer.Meta.model In[32]: model_name Out[32]: my_app.models.Policy.Policy What i need is the last part of that value separated by dots(Policy).However, the type of model_name is not a string and converting it to a string gives a weird string as follows: In [33]: type(model_name) Out[33]: django.db.models.base.ModelBase In [34]: str(model_name) Out[34]: "<class 'my_app.models.Policy.Policy'>" Is there an easier way to avoid this gnarly string and this get the Model name ? -
Generic Views for passing multiple data to template
Field values are not shown in template only extrainfo is displayed. I want to display both (fields) and (extrainfo) values class CompanyUpdateView(UpdateView): model = Company fields = ['company_name', 'company_description','company_email', 'company_phone', 'company_address', 'company_website' , 'company_status', 'company_monthly_payment'] def get_context_data(self, **context): context[self.context_object_name] = self.object context["extrainfo"] = "Processador123123" return context -
Update method on Django Rest framework nested serializer for M2M fields
I have three models in my models.py as follows: class Service(models.Model): name = models.CharField(max_length=50, unique=True) port = models.PositiveSmallIntegerField() protocol = models.CharField(max_length=50) class ServiceGroup(models.Model): name = models.CharField(max_length=50, unique=True) services = models.ManyToManyField(Service, through=ServiceToServiceGroup) class ServiceToServiceGroup(models.Model): service = models.ForeignKey(Service) service_group = models.ForeignKey(ServiceGroup) My JSON payload to create a new service group is as follows: { "name": "test_service_group1", "services":["service_1", "service_2"], } Since I have a M2M through table, my strategy to create a new ServiceGroup is to first pop out the services list, create the ServiceGroup with the name and then create the M2M realtionships. My serializer to create a new ServiceGroup is as follows: class ServiceGroupCreateUpdateSerializer(serializers.ModelSerializer): services = serializers.SlugRelatedField(queryset=Service.objects.all(), slug_field='name', many=True) class Meta: model = ServiceGroup fields = ['id', 'name', 'services'] def create(self, validated_data): # Pop the services list out services = validated_data.pop('services', None) # Create the ServiceGroup with the name service_group = ServiceGroup.objects.create(name=validated_data['name']) #Create M2M associations for service in services: service_id = Service.objects.get(name=service) ServiceToServiceGroup.objects.create(service_id=service_id, service_group_id= service_group.id) My question is how do I now write the update method ? My JSON payload remains the same, the only difference being that I pass the instance id in the URL.The pseudo code is as follows: Pop the services list. Save the name to the instance …