Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why does TinyMCE not remove whitespace after the least element?
I don't get it why TinyMCE editor doesn't remove the blank space after the least element. Is there any default height/length setting that I need to overwrite? This is how it looks in the editor: Which whyever translates to: Source of example posted <div style="width: 100%; height: 0; padding-bottom: 56%; position: relative;"><span style="font-family: 'Varela Round';">Exciting times, exciting times... Amazon is skyrocketing and I was trying to grab some Wirecard longshots which made me end upo like. Nevertheless, lets keep pushing. Manganese Energy might be one for the Pennystock Watchlist! Let's see.</span><hr /><img src="https://media.giphy.com/media/ZGH8VtTZMmnwzsYYMf/giphy.gif" alt="" width="480" height="270" /></div> Settings.py TINYMCE_DEFAULT_CONFIG = { 'cleanup_on_startup': True, 'custom_undo_redo_levels': 20, 'width': 1200, 'selector': 'textarea', 'theme': 'silver', 'plugins': ''' textcolor save link image media preview codesample contextmenu table code lists fullscreen insertdatetime nonbreaking contextmenu directionality searchreplace wordcount visualblocks visualchars code fullscreen autolink lists charmap print hr anchor pagebreak ''', 'toolbar1': ''' fullscreen preview bold italic underline | fontselect | fontsizeselect | forecolor backcolor | alignleft alignright | aligncenter alignjustify | indent outdent | bullist numlist table | | link image media | codesample | ''', 'toolbar2': ''' visualblocks visualchars | charmap hr pagebreak nonbreaking anchor | code | ''', 'contextmenu': 'formats | link image', 'menubar': True, … -
Annotate function give me a wrong result
I have set the following three models in my django app: class SubCategory(models.Model): name = models.CharField('Nome della sottocategoria', max_length=30) class Materials(models.Model): subcategory= models.ForeignKey(SubCategory) quantity=models.DecimalField() price=models.DecimalField() class Costs_materials(models.Model): subcategory= models.ForeignKey(SubCategory) quantity=models.DecimalField() In my views I have set the following code: agg=Subcategory.objects.annotate(giacenza=Coalesce(Sum('materials__quantity'), 0)).annotate( utilizzato=Coalesce(Sum('costs_materials__quantity'), 0)) All works perfectly but If I try to add another annotate function, ad example: agg=Subcategory.objects.annotate(giacenza=Coalesce(Sum('materials__quantity'), 0)).annotate( utilizzato=Coalesce(Sum('costs_materials__quantity'), 0)) The result of giacenza and utilizzato are not right, but the result is double than the right. Ad example if the result must be 10, is 20. Where is the error?? -
Set initial value of form field in Django's admin formfield_for_foreignkey
I have following code in my Django admin: def formfield_for_foreignkey(self, db_field, request, **kwargs): if db_field.name == 'affected_user': kwargs['initial'] = request.user.id return super().formfield_for_foreignkey(db_field, request, **kwargs) and affected_user field in the model looks like this: affected_user = models.ForeignKey(User, on_delete=models.CASCADE) What I'd like to get from this is have affected_user assigned particular initial value. Unfortunately, it seems like it doesn't work. Could someone explain why is that? What I know for sure is that is correctly enters this if statement. But doesn't keep my initial value. -
How to add Hyperlink of another serializer in response
models.py from django.db import models class Album(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) usertype = models.CharField(choices=USERTYPES, max_length=15) contact = models.(max_length=100) class AlbumView(ListAPIView): def get_queryset(self): return User.objects.all() def get(self,request): query = self.get_queryset() serializer=UserSerializer(query,many=True) return Response(serializer.data) which return data of the user table . But I want to also add Album table data as a hyperlink in the response of AlbumView.I want o/p as follows: [{ "id": 1, "email": "abc@abc.com", "username": "ABC", "password": "pbkdf2_sha256$180000$xErnF8P/lIEV9pg=", "author":"http://127.0.0.1:8000/api/album/12/" }, { "id": 3, "email": "abc1@abc1.com", "username": "ABC1", "password":df2_sha256$180000$rtBoxIzAoD8n$6GCVSTIpdP18", "http://127.0.0.1:8000/api/album/13/" },] I was using the Django user table. -
I cannot merge django migrations
Im not sure how to fix this. I have tried over the internet to look for a solution but no luck. This is my repo https://github.com/Prodromosk/resume And this is my blog branch https://github.com/Prodromosk/resume/tree/blog I have delete migrations except init.py i even delete db but still im getting this error. Im not sure how can i fix this.. Some say that there's something in the version history that is conflicting and i should rollback to that or whatever but i m unsure how to do that. python manage.py makemigrations --merge Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 133, in handle return self.handle_merge(loader, conflicts) File "/Users/prodromos.kachrimani/Desktop/personalProD/personalprod/lib/python3.6/site-packages/django/core/management/commands/makemigrations.py", line 260, in handle_merge raise ValueError("Could not find common ancestor of %s" % migration_names) ValueError: Could not find common ancestor of {'0001_initial', '0001_initial 2'} -
Django Ajax: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Im trying to implement ajax to my rate system. Site is not reloading after posting rate. In console I get Failed to load resource: the server responded with a status of 500 (Internal Server Error) Views.py class MovieDetailView(FormMixin, DetailView): model = Movie template_name = 'main/detail_movie.html' context_object_name = 'movie' form_class = RateForm def get_context_data(self, **kwargs): context = super(MovieDetailView, self).get_context_data(**kwargs) context['form'] = RateForm(initial={'movie': self.object}) context['my_rate'] = Rate.objects.filter( sender=self.request.user, movie=self.get_object()).first() return context def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if request.method == 'POST': if form.is_valid(): new_rate = Rate.objects.update_or_create( sender=self.request.user, movie=self.object, defaults={'choice': form.cleaned_data['choice']} ) return JsonResponse({'rate': model_to_dict(new_rate)}, status=200) else: return self.form_invalid(form) Models.py class Rate(models.Model): class Meta: unique_together = (('sender', 'person'), ('sender', 'movie'),) choice = models.IntegerField(null=False, blank=False, choices=RATE_CHOICES) sender = models.ForeignKey(User, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE, null=True) movie = models.ForeignKey(Movie, on_delete=models.CASCADE, null=True) urls.py path('movie/<slug:slug>/', MovieDetailView.as_view(), name='detail_movie'), rate.js $(document).ready(function(){ $("#rateButton").click(function(){ var serializedData = $("#rateForm").serialize(); $.ajax({ url: $("rateForm").data('url'), data: serializedData, type: 'post', }) }); }); Rate is posting but i can see it after refreshing page. -
How to test uniqueness in a Model.clean() function?
I have a model with a UniqueConstraint: class MyModel(models.Model) name = models.CharField() title = models.CharField() class Meta: constraints = [ models.UniqueConstraint( fields=['name', 'title'], name="unique_name_and_title") ] This works fine and raises an IntegrityError when 2 objects with the same values are created. The problem is UniqueConstraint doesn't present a pretty ValidationError to the user. Usually, I would add these in the Model.clean() class, but if I do this then it will fail on an Update because the instance being updated will already be present: def clean(self): if MyModel.objects.filter(title=self.title, name=self.name): raise ValidationError({'title':'An object with this name+title already exists'}) I How do I create a ValidationError that passes if it's an UPDATE not an INSERT? I know I could do this on a ModelForm and use self.instance to check if the instance already exists, but I want to apply this to the Model class and not have to rely on a ModelForm. -
Object has no attribute on a Textfield in Django
I am getting a 'Sponsor' object has no attribute 'adtag' error, when I try to pull data from a foreign key field in Django. When I try to pull CharField data from the same model, that works perfectly fine. Here are my models: class Sponsor(models.Model): name = models.CharField("Name of Sponsor", max_length=120, blank=False) ... adtag = models.TextField(name="Ad Tag") def __str__(self): return self.name and class Merchant(models.Model): name = models.CharField("Name des Betriebs", max_length=120, blank=False) sponsor = models.ForeignKey(Sponsor, on_delete=models.PROTECT) def __str__(self): return self.name I am calling this by doing this: merchant = Merchant.objects.filter(id=merchant) and print(merchant.sponsor.adtag) And of course the data is filled in in the database + foreign key is associated. Thanks for any recommendation. -
How do I deal with a null query in Django?
So let me start with the registration process in my web page. The user would register first, and then right after registration, he/she is redirected to a page where the user has to input his/her personal info, such as self-introduction, full name, etc. When the user completes filling his/her personal info in, then the user will be redirected to home page. So what I wanted to do is this : When the user tries to access home page, check if he/she is logged in. If yes, check if he/she has filled in the personal info. If no, redirect the user to register page. If the user has filled in (=matching query exists), redirect him/her to the home page. If not, redirect him/her to the personal info page, to fill the fields in. And here's my code in views.py def userHome(request): if request.user.is_authenticated: current_user = request.user if PersonalInfo.objects.get(authuser_id=current_user.id).exists(): context = { 'thisUser' : thisUser, 'newSeed' : newSeed } return render(request, '/userhome.html', context) else: return redirect('/inputpersonalinfo') else: return redirect('/register') models.py from django.db import models from django.contrib.auth.models import User class PersonalInfo(models.Model): objects = models.Manager() authuser = models.OneToOneField(User, on_delete=models.CASCADE, related_name = 'personalinfo', null=True, default=None) name = models.CharField(max_length=50) ... I keep getting an error saying … -
Django views.PasswordResetView send email not html type
I am trying to reset my password But email doesn't looks like a html urls.py url(r'^password_reset/$', auth_views.PasswordResetView.as_view( template_name='account/password_reset_form.html', email_template_name='account/password_reset_email.html', success_url='/account/password_reset_done' ), name='password_reset'), password_reset_email.html <p>您收到这封邮件是因为您正在重置密码,如果非本人操作请勿略</p> <p>请点击下面网站设置一个新密码:</p> <a href="{{ protocol }}://{{ domain }}{% url 'account:password_reset_confirm' uidb64=uid token=token %}"></a> <p>用户名:{{ user.get_username }}</p> <p>感谢使用我们的网站</p> <p>晶晨羽毛球协会</p> setting.py # 将发送的邮件直接显示在控制台 EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' # smpt服务地址 EMAIL_HOST = 'smtp.qq.com' EMAIL_PORT = 25 # 发送邮件的邮箱 EMAIL_HOST_USER = 'xxxx33928@qq.com' # 在邮箱中设置的客户端授权密码 EMAIL_HOST_PASSWORD = 'xxxxgorrbecd' # 收件人看到的发件人 DEFAULT_FROM_EMAIL = 'xxx3928@qq.com' SERVER_EMAIL ='xxx3928@qq.com' myemail <p>您收到这封邮件是因为您正在重置密码,如果非本人操作请勿略</p> <p>请点击下面网站设置一个新密码:</p> <a href="http://127.0.0.1:8000/account/password_reset_confirm/MQ/5i4-0dfc61d517145c2857dd/"></a> <p>用户名:coco</p> <p>感谢使用我们的网站</p> <p>晶晨羽毛球协会</p> It looks like a txt. Label is not userful . Where is my problem .How can I fix it . -
Django Rest Framework - URL With Query Parameters in Serializer
I have a Story and Post models, where a Post belongs to a Story. I want a URL to get all Posts associated with a given Story. I was able to override the get_queryset of my PostViewSet in order to filter posts by story with URLs like http://localhost:8000/posts/?story=1/. This works beautifully if I type in the URL directly. Now I want to return this kind of url in my StorySerializer. I would like to be able to get Story responses that look like this [ { "url": "http://localhost:8000/stories/1/", "title": "Hero's Journey", "openings": 0, "date_created": "2020-06-28T16:53:35.150630Z", "posts": "http://localhost:8000/posts/?story=1/" }, { "url": "http://localhost:8000/stories/2/", "title": "Halo 3", "openings": 0, "date_created": "2020-06-28T18:17:12.973586Z", "posts": "http://localhost:8000/posts/?story=2/" } ] Is there DRF support for this kind of thing? I was trying to use a HyperlinkedIdentityField with 'post-list' View in my StorySerializer, but I couldn't find a combination of parameters that would work. The current exception I get is AttributeError: 'Story' object has no attribute 'posts' Serializers class StorySerializer(serializers.HyperlinkedModelSerializer): posts = serializers.HyperlinkedIdentityField( view_name = 'post-list', many=True, lookup_field = 'pk', lookup_url_kwarg = 'story', ) class Meta: model = models.Story fields = ['url', 'title', 'openings', 'date_created', 'posts'] class PostSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Post fields = ['url', 'story', 'user', 'text', … -
beginner issue with python : how to make one list of separated lines in a file in python
I have an issue as a beginner that made me exhausted trying to solve it so many times/ways but still feel dump, the problem is that I have a small file that I read in python and I have to make a list of the whole lines to sort it in alphabetical order. but when I try to make it in a list, it makes a separate list for each line. here is my may that I tried to solve the issue using it: file = open("romeo.txt") for line in file: words = line.split() unique = list() if words not in unique: unique.extend(words) unique.sort() print(unique) output: ['But', 'breaks', 'light', 'soft', 'through', 'what', 'window', 'yonder'] ['It', 'Juliet', 'and', 'east', 'is', 'is', 'sun', 'the', 'the'] ['Arise', 'and', 'envious', 'fair', 'kill', 'moon', 'sun', 'the'] ['Who', 'already', 'and', 'grief', 'is', 'pale', 'sick', 'with'] -
Using DJango with Angular :Is there a possibility to get data from databse without using Model at all?
I want to create table in DJango at runtime. I can call SQL statement from DJango for that. But for maintening and extracting data for various reports. screens, I dont want to us direct SQL. I tried using ViewSet but no success. Can you please share if you have done it? -
Generating QR code and saving the QR code image to AWS S3 in Django Rest Framework
Hi I'am generating QR code using qrcode library in Python. I have setup default storage location for images/files to be uploaded into S3 which is working fine if I am taking an input through API. But in case of generating QR code which is new image is not getting saved to the bucket in S3. Models.py class Item(models.Model): name = models.CharField(max_length=30) qr = models.ImageField(upload_to="asset_tags", null=True, blank=True) image = models.ImageField(upload_to="asset_tags", null=True, blank=True) Generate QR code: def generate_qr(self, qr): qr = qrcode.QRCode( version=1, error_correction=qrcode.constants.ERROR_CORRECT_M, box_size=15, border=5 ) qr.add_data(qr) qr.make(fit=True) img = qr.make_image(fill='black', back_color='white') img.save(qr+".png") Here Image field in models.py is the image which is uploaded by the user which gets saved in bucket. But the qrcode image gets saved in the root of project. I am confused if I need to convert this Pillow image object to django image field and it will get saved to bucket automatically. Thanks, Any help will be appreciated. -
ValidationError: ManagementForm is missing while creating update form with ModelFormSet in Django
I have a data adding form which it's been created with BaseModelFormSet. The working logic of my form is as follows: for example, there are 12 attributes in my model class, but the user only uses 8 of them. The users choose this first when they register, then this data adding form is created according to the attributes their chooses. So my forms.py file such as below; class BaseDataFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.queryset = Data.objects.none() and I have created the form in following way; DataFormSet = modelformset_factory(Data, fields=selected_features, formset=BaseDataFormSet) form = DataFormSet(request.POST or None, request.FILES or None) There's no issue while adding a new data but I'm getting trouble when I try to update the exist data. When the user presses the update button, I want the form to be created according to the attributes that the user chooses and to fill the form with the values that the user entered before. So I have created my update form as following; class BaseDataUpdateFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) and my updateData view; @login_required(login_url = "user:login") def updateData(request,id): features = request.user.profile.selected_features instance = get_object_or_404(Data, id = id) queryset = Data.objects.filter(id = instance.id) DataFormSet = modelformset_factory(Data, fields=features, formset=BaseDataUpdateFormSet) … -
ValidationError ignored in Custom Django Crispy Form
I have a rather complex Django form that affects 3 models and part of which includes an inline formset. I found a nice solution to building the form at https://dev.to/zxenia/django-inline-formsets-with-class-based-views-and-crispy-forms-14o6. I extended that solution and added a third model in a similar way that the formset was added (using a custom Django Crispy Form and inserting it using the Crispy Forms Layout features). My problem is that any validation errors raised on either of the two inserted forms (the formset and the small subform) are simply ignored - the main form posts correctly and raised ValidationErrors are displayed in the form as errors allowing the user to correct any mistakes and its data is correctly saved to the database. If the subform and formset are valid, their data gets saved correctly as well. However, if the data in the subform and formset is not valid, the form never shows the errors to give the user a chance to correct their mistake, and the data is simply ignored and never saved to the database - the main model's data saves fine though. My question is, how do I get the form to refresh with errors displayed in the added subform and … -
Django channels and azure
I am trying to deploy django channels in azure. I have already integrated it with azure redis catch and it's working good in local host. I have tried the normal deployment of django apps in asure, everything except sockets are working. CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [(f'redis://:{os.environ["REDISPASS"]}@mywebsite.redis.cache.windows.net:6379/0')], }, }, } It's showing unexpected error website closed unexpectedly. -
How to get the value from the drop down box django? without submit button
How to get the value from the dropDown Box in Django Without Submit Button <div class="single-shorter"> <form action="." method="GET"> <label>Sort By :</label> <select name="val" id="val"> <option selected="selected" value="name">Name</option> <option value="price">Price</option> </select> </form> </div> -
How to get VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY for django webpush implementation?
I want to implement web push notification in django project where frontend is implemented using react. I was following https://www.digitalocean.com/community/tutorials/how-to-send-web-push-notifications-from-django-applications this documentation but i didn't find the way to get VAPID_PUBLIC_KEY and VAPID_PRIVATE_KEY for WEBPUSH_SETTINGS. What is the way to get that? -
Django: Create, Edit and Delete Buttons Throwing Bad Request in Datatables
I recently set up datatable in django using django-rest-framework-datatables. I have been able to figure out data display. Where I am having a bit of challenge is to make the add, edit and delete buttons to work. The current code I have, as seen below, shows bad request (400) anytime I trigger any of these actions. $(document).ready(function() { function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val(); var editor; editor = new $.fn.dataTable.Editor({ ajax: { create: { type: 'POST', headers: { "X-CSRFTOKEN": csrftoken }, url: '/api/employees/?format=datatables', }, edit: { type: 'PUT', headers: { "X-CSRFTOKEN": csrftoken }, url: 'api/employees/_id_/', }, remove: { type: 'DELETE', headers: { "X-CSRFTOKEN": csrftoken }, url: 'api/employees/_id_/', } }, table: '#employeesDataTable', idSrc: 'id', fields: [{ label: "fullname:", name: "fullname", }, { label: "gender:", name: "gender", type: "select", options: [ { label: "male", value: 0 }, { label: "female", value: 1 }, { label: "undisclosed", value: 2 }, ], }, { label: "date of birth:", name: "date_of_birth", type: 'datetime', }, { label: "permanent address:", name: "permanent_home_address", }, { label: "present address:", name: "present_home_address", … -
How to get object from previous view(CBV) in Django?
I tried to get the object value in CreateView from previous DetailView. But Failed. Is there any simple way to do this? In this code, how can I replace this '???'(in CreateView) by an album object where album.pk == id according to 'item-add'(url(r'^(?P<id>[0-9]+)/pic/add/$', views.ItemCreate.as_view(), name='item-add')) models.py class Album(models.Model): credit = models.CharField(max_length=250) album_title = models.CharField(max_length=100) logo = models.FileField() def get_absolute_url(self): return reverse('picture:detail', kwargs={'pk': self.pk}) def __str__(self): return self.album_title + ' - ' + self.credit class Item(models.Model): album = models.ForeignKey(Album, on_delete=models.CASCADE) file_type = models.CharField(choices=TYPE_CHOICES, max_length=1) caption = models.CharField(max_length=100) class Meta: ordering = ('upload_date', 'caption') def get_absolute_url(self): return reverse('picture:item-detail', kwargs={ 'id': self.album_id , 'pk': self.pk}) def __str__(self): return self.caption views.py class DetailView(generic.DetailView): model = Album template_name = 'picture/detail.html' class ItemCreate(CreateView): model = Item fields = ['album', 'file_type', 'caption'] def get_initial(self): album = ??? return { 'album': album, 'file_type': 't', } urls.py urlpatterns = [ # /picture/<album_id>/ url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), # /picture/<album_id>/<pic_id> url(r'^(?P<id>[0-9]+)/(?P<pk>[0-9]+)/$', views.ItemDetailView.as_view(), name='item-detail'), # /picture/<album_id>/pic/add url(r'^(?P<id>[0-9]+)/pic/add/$', views.ItemCreate.as_view(), name='item-add'), ] -
how to write url in a-Tag Django
<a href="{% url 'news-year-archive' %}">2012 Archive</a> Or <a href="/news-year-archive">2012 Archive</a> Both method is work but which method is best for production -
Django send_mail() fails with `getaddrinfo`
I am trying to set up a contact form so that the website visitors can send me an e-mail. When hitting submit, it returns the following error: Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\stocksphere\blog\stocksphere\contact\views.py", line 16, in contactView send_mail(subject, message, email, ['stocksphere@protonmail.com']) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\mail\__init__.py", line 60, in send_mail return mail.send() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\mail\message.py", line 276, in send return self.get_connection(fail_silently).send_messages([self]) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\mail\backends\smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 787, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\socket.py", line 914, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): Exception Type: gaierror at /contact Exception Value: [Errno 11001] getaddrinfo failed This is the views.py from django.core.mail import send_mail, BadHeaderError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .forms … -
Editing page in Django
im new to python and django (as you can probably tell). Im following cs50 web course and im trying to let user edit a page's current title and content. Problem is, the current content is not being displayed. We are not working with databases or sessions yet. form.py: from django import forms class NewEntryForm(forms.Form): title = forms.CharField(label="Title", required=True, max_length=100) content = forms.CharField(label="Content", widget=forms.Textarea, required=True, max_length=1000) views.py, where its not working: def edit_entry(request, title): try: content = util.get_entry(title) #store content of the entry except: return HttpResponseNotFound("Page not found") form = NewEntryForm() form.content = content return render(request, "encyclopedia/new_entry.html", { "form": form, #to create the displayed form "form.content": form.content, "form.title": title, #to fill the form with the stored info "title": title.capitalize(), "messages": None, #page title & warning messages }) same template for creating and editing an entry: {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} {% if messages %} <div class="alert alert-warning" role="alert"> {{ messages }} </div> {% endif %} <div class="content-section" style=" margin: auto; width: 50%; padding: 10px;"> <form method="POST" href="{% url 'new_entry' %}"> {% csrf_token %} {{ form.title.label }} {{ form.title }} {{ form.content.label}} {{ form.content }} <input type="submit" value="Submit"> </form> … -
How to implement user permission assignment module in Django template?
i want to implement a module within Django template where admin user can assign model wise permissions to users/group. Attached is the image user permission for your reference. please check and help