Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' for celery task
My Celery configuration is as follows: app = Celery('track_rides_application',backend='rpc://', broker='amqp://guest:guest@127.0.0.1/' ) I am getting this error: AttributeError: 'DisabledBackend' object has no attribute '_get_task_meta_for' Even though I provided backend attribute I am getting the above error -
Django annotate, access current row to traverse foreign keys
I have these models: class Sale(models.Model): date = models.DateField() profit = models.FloatField() expenses = models.FloatField() seller = models.ForeignKey(Seller) class Seller(models.Model): name = models.CharField() store = models.ForeignKey(Store) class Store(models.Model): name = models.CharField() country = models.ForeignKey(Country) given ids = [a list of seller ids...], I need a table like this: Store 1 -> sum of profits - sum of expenses of all sellers in ids and in store 1 Store 2 -> sum of profits - sum of expenses of all sellers in ids and in store 2 ... I can get all the stores like this: sellers = Seller.objects.filter(id__in=ids) q = Store.objects.filter(id__in=sellers.values("store_id")) At this point I'd iterate over q but that would defy the point of having an ORM. The alternative is using .annotate() but how can I tell .annotate to grab the sum of all profits of all sellers in store N? -
Kubernetes build django + uwsgi + nginx show failed (111: Connection refused) while connecting to upstream
when I create my.yaml, then nginx will show failed (111: Connection refused) while connecting to upstream have any sugesstion about this? Is there pod network do not connnect? uwsgi: [uwsgi] module = myapp.wsgi master = true processes = 10 socket = 127.0.0.1:8001 chmod-socket = 777 vacuum = true enable-threads = True nginx: upstream django_api { server 127.0.0.1:8001 max_fails=20 fail_timeout=10s; } server { listen 80; #location /media { # alias /media; # your Django project's media files - amend as required #} location /static { alias /usr/share/apps/static; # your Django project's static files - amend as required } location / { uwsgi_read_timeout 60; uwsgi_pass django_api; include ./uwsgi_params; # the uwsgi_params file you installed uwsgi_param Host $host; uwsgi_param X-Real-IP $remote_addr; uwsgi_param X-Forwarded-For $proxy_add_x_forwarded_for; uwsgi_param X-Forwarded-Proto $http_x_forwarded_proto; } } -
User can switch account to another user
I have an url path('dashboard/<int:user_id>/', views.dashboard, name='dashboard'), The problem is when User is logged in He can change user_id variable in url and switch to another user account. My question is how to prevent that behaviour. Should I change something in template or somewhere else ? -
django handling comments form in same page
i want know ,if is there any way where we could handle two form on a single template & view where one form doesnt take any arguments where as the other form takes arguments yeah one form is the post form to create a post while the other one is the comment form which actually takes an argument(pk) to get that particular post id and add create that object i have tried to add two forms which will create two objects in single view the post object and its post form actually works fine but whereas the comment object requires a pk argument to filter the post object to be created and when i tried changing my view from post_create(request) to def post_create(request,pk) it fired up an error saying that pk value has not been given def post_create(request): if request.method=='POST': form = PostCreateForm(request.POST,request.FILES) comment=CommentForm(request.POST) post=Post.objects.get(id=pk) # comment= # print(form) if request.FILES: print('there is a file') else: print('no file') # if re if form.is_valid() or comment.is_valid(): # c=comment.save(commit=False) psts = form.save(commit=False) psts.author = request.user # if comment: # psts.comment.add(comment) # else: # print('there is nothing') # psts.image = print(psts.image) psts.save() if comment.is_valid(): comment = comment.save(commit=False) comment.post= post comment.user = request.user comment.save() … -
How to create a form that adapts to the number of users with django 2?
I am biginner wiht django, and I would like to create a form that could adapt him to the number of user. The goal is to declare the presence or not of employees and the number of hours they worked during the day, knowing that the number of employees can change from one day to another. So I thought of creating two variables : an integer counting the number of hours performed during the day, and another boolean corresponding to the presence or not of the employee, and being reproduced as many times as there are employees. So, I tested that : forms.py : class HoursDeclarationForm(forms.Form): number_of_hours = forms.FloatField(required=True) for user in User.objects.all(): presence = forms.BooleanField(label="{0} {1}".format( User.first_name, User.last_name ) ) views.py : def hours_declaration (request): form = HoursDeclarationForm(request.POST or None) return render ( request, 'HoursDeclaration/hours_declaration.html' , locals() ) hours_declaration.html : <h1>Ceci est la page ou tu peux attribuer à chaque salarié le nombre d'heure qu'il a effectué.<h1> <form action="{% url "hours_declaration" %}" method = "post"> {% csrf_token %} {{ form.as_p }} <input type="submit" value="submit"> </form> But I get a single checkbox preceded by: "django.db.models.query_utils.DeferredAttribute object at 0x00000255505DEF98 django.db.models.query_utils.DeferredAttribute object at 0x00000255505DEFD0" :, no matter the number of users. Please … -
Django-Channels trying to understand
I was working with django to display some data and i was using refresh page to read the new data then after i looking around the internet how to make the data streamable i saw about channels. the thing is im newbe with python and after reading for hour i cant understand how channels works. it was very simple because was adding the data to a list and then i display one by one from the list to the webpage like this: {% block content %} <ul class="list-data-panel"> {% for s in stats %} <li data-header="{{ s.0 }}"> ........... my question is a posible to make this with channels1 or 2 version and if there is anyone can explain how to do it or if there is any tutorial exept the chat. thank you for reading and sorry for my poor english -
I need a plugin for authipay on the python django project
I am going to implement the Authipay on my django project. Is there any opensource for this? I need your help as soon as possible. Any advice would be appreciated. Thanks for your time. Regards. -
TypeError: can't pickle psycopg2.extensions.Binary objects (after having switched to Python 3)
I just switched my Django app (Django 1.11.20) from Python 2.7 to Python 3.6.6 and the following line now generates a bug : caches['pgcache'].set(id, mydict, 10000) Here is the error message : Internal Server Error: /trip/province-oristrano-2138 Traceback (most recent call last): File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 249, in _legacy_get_response response = self._get_response(request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\terradiem\terradiem\trip\views.py", line 320, in trip caches['pgcache'].set(targetobjectid, mydict, 10000) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\cache\backends\db.py", line 87, in set self._base_set('set', key, value, timeout) File "C:\terradiem\terradiem\venvpython\lib\site-packages\django\core\cache\backends\db.py", line 114, in _base_set pickled = pickle.dumps(value, pickle.HIGHEST_PROTOCOL) TypeError: can't pickle psycopg2.extensions.Binary objects I don't understand what is the problem. Any clue ? Thank you -
Django how to generate short random slug?
I'm implementing photo sharing web application where the link of each photo will be different. "localhost.com/fggcxdf" how to generate a short random slug that should be unique. -
How to return user details in response after login in django rest_framework
Hi I am beginner in Django Here I want user email and name in response after user login using api. Thanks in advance for your help. models.py I want user email and user name in response only getting auth token in response class UserManager(BaseUserManager): def create_user(self, email, password, **extra_fields): if not email: raise ValueError('Users must have an email address') if not password: raise ValueError('Users must have a password') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user(email,password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' serializers.py I want user email and user name in response only getting auth token in response class UserSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) class Meta: model = get_user_model() fields = ('email', 'password', 'name') extra_kwargs = {'password': {'write_only': True, 'min_length': 6}} def create(self, validated_data): user = User.objects.create_user('name',validated_data['email'], validated_data['password'],) return user class AuthTokenSerializer(serializers.Serializer): email = serializers.CharField() password = serializers.CharField( style = {'input_type':'password'}, trim_whitespace = False ) def validate(self, attrs): email = attrs.get('email') password = attrs.get('password') user = authenticate( request = self.context.get('request'), username = email, password = password … -
Import and save thumbnailphoto from ldap to django imagefield
I am trying to save the picture of a user retrieved from active directory using django ldap library, but i am unable to store it in the write way, i have spent hours searching this issue, if any one can help me i will be grateful, this the format of the thumbnail photo b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb\x00C\x00\x08\x06\x06\x07\x06\x05\x08\x07\x07\x07\t\t\x08\n\x0c\x14\r\x0c\x0b\x0b\x0c\x19\x12\x13\x0f\x14\x1d\x1a\x1f\x1e\x1d\x1a\x1c\x1c $.\' ",#\x1c\x1c(7),01444\x1f\'9=82<.342\xff\xdb\x00C\x01\t\t\t\x0c\x0b\x0c\x18\r\r\x182!\x1c!22222222222222222222222222222222222222222222222222\xff\xc0\x00\x11\x08\x00`\x00`\x03\x01!\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x1c\x00\x00\x01\x04\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x02\x01\x03\x06\x07\x00\x04\x05\x08\xff\xc4\x00:\x10\x00\x01\x03\x03\x02\x03\x05\x06\x04\x03\t\x00\x00\x00\x00\x00\x01\x00\x02\x03\x04\x05\x11\x06!\x121a\x07\x14AQq\x13"2\x81\xa1\xc1#BR\x91\x15$r5C\x82\xa2\xb1\xb2\xc2\xd1\xe1\xff\xc4\x00\x19\x01\x00\x02\x03\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x05\x04\xff\xc4\x00\x1d\x11\x01\x01\x01\x00\x03\x01\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x01\x02\x03\x04\x11!\x12"1\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xb3\x02 \x10\x04\x02\\&E\xc2\xcc 3\t0\x80B\x85\x00$ !\x00\xe0\x08\xc0H\xca\x02,&LP\xbb\xd6\xbem1\x11Y-\xf2\\\xe4$\x83)\xcb"\x1e\x87\x9b\xbdF\xddTu\xb9\x99\xedO\x18\xbb\xbeCt\x1a\xf2\xae9\xf8/\xd6gQ\xc3\x8c\x9a\x9aw\x99X\xde\xaen2\x07Q\x9c)\xa43ES\x04s\xc1#%\x86F\x871\xec9\x0e\x07\x91\x05,o;\x9e\xc1\xbe=b\xf9DP\xa9\xa0\x12\x84\x84\x19\xc0\x11\x00\x90\x10\x08\xb0\x99!z\xf6\xe9$r[\xec\xac\xda*\xde9*\x1c\x0e\t\x8d\x98\xf7=\x1cy\xf4\x18\xf1Z\xf6\xc0\xc7G\x82\xdc\x11\xcb\x03\x92\xcf\xed_w#C\xa9\x9f1i\xcb\x88\x02"Z\xd3\x9f4\xc6\x85\xac}%\xe2\xba\xccO\xf2\xcfgz\xa6g\x83\x0eq#GL\x90q\xea\x8e\xad\xf3~\x1fk>\xe3\xd4\xf0\xa1!h3\x82P\x90\x80p\x04a \x12\xa6\x15\xce\xb9"MM\x03\xa2s^\xf8h\xdc\xc2?C\x8b\xb3\xbf\xa8!E(\xefwjz\xa6\x96T\xcb;G\xc6\xce\xee\x18\xdf\x91\xe6\xb8y|\xbb\xad\x0e\x19\xa9\x88\xdd\xd4\xb5u\xf3U63%S kZ\xe3\xdd\xcf\tv|\x13\xbab\xa9\xb6\xfb\xc5\xbe\xb2\xa9\xf3\xfb6:H\xcb\xa4\x19v\x1e\xdc\x0c\xf9\x8c\xe1G\x8f^yj\\\x98\xba\xf6E\xb8\xed\x8a\x12\xb4\x19\xa1(J\x01\xc0\x8c$\n\x11&\x15\xe6\xb6\x87\xb8\xdec\xadtn\xf6U\x1c,/\x03`q\x8d\xff\x00a\xfb\xae}EM\x0cT.\x99\xac\x19\xc7\xbcZ\x06@\xf1Y\xdc\xd9\xb3u\xab\xc1\xb9s\x03O|\xb6\\\xebOv\xcc\x91\xb66\x87\xf1\x01\x80G$\x0c?\xc4\xf5\x1d%\r$>\xd7$\xbd\xe0~V\x0ed\xf4\xdc(\xe7\x17\xf5\xf9K|\x92g\xf5\xea\xd4w2\x9b+M\x92D\x88\x07B \x91\t*a\x1f\xd6\x94o\xaf\xd2W8"\x19\x90Bd`\xf3,!\xdfe@\xc5^+e\x8e9\x9f#\xe3\x03\xe0\xe2\xd8\x95W$\xf7\xea\xde=y\xf2\xb7k\xe9{\xac\x1e\xdd\xd1\x1ag\xe31\xba9\x83\xb8\xbdp\x06\x02\x96\xf6E\xc5[~\xb9W8\x93\xeci\xc4c>ov\x7f\xe2\xa3\xc7\xf7\xea\xcek?\xc8\xb8\nl\xab I have stored first the image bytes string in a field and then save it into the imagefield, but when i open it i have a message as if the format is not recognized by the photo editor. This is the code that i have tried : current_user = CustomUser.objects.filter(username=user).first() current_user.user_image.save('{0}/photos/{1}.jpg'.format(settings.MEDIA_ROOT, username), ContentFile(current_user.user_image_string)) What is the newt step that i have to do ? -
How generate a DOC and a PDF from html <div> in Django
Good day, In Django project I have an html file with a div in which some fields(like p) change the content by radiobutton choice (using JavaScript). Need to turn the div with the changed content (by radiobutton choice) into pdf and doc (with saving of all styles). Any help is appreciated. I tried "wkhtmltopdf" but it generates pdf only with model contents from db and without result of radiobutton work. <!--Choice radiobuttons--> function Display(obj) { fioid=obj.id; if(fioid=='exampleRadios1'){ document.getElementById("fiz").style.display='block'; document.getElementById("ip").style.display='none'; document.getElementById("ur").style.display='none'; } else if(fioid=='exampleRadios2'){ document.getElementById("ip").style.display='block'; document.getElementById("fiz").style.display='none'; document.getElementById("ur").style.display='none'; } else if(fioid=='exampleRadios3'){ document.getElementById("ur").style.display='block'; document.getElementById("fiz").style.display='none'; document.getElementById("ip").style.display='none'; }} <div class="col-12"> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios1" value="FIZ" onclick="Display(this);" checked> <label class="form-check-label" for="exampleRadios1"> FIZ </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios2" value="IP" onclick="Display(this);"> <label class="form-check-label" for="exampleRadios2"> IP </label> </div> <div class="form-check"> <input class="form-check-input" type="radio" name="exampleRadios" id="exampleRadios3" value="UR" onclick="Display(this);"> <label class="form-check-label" for="exampleRadios3"> UR </label> </div> </div> <div> <p style="text-align: justify; font-family: Times New Roman;"> <span style='display: block;' id="fiz">This is FIZ</span> <span style='display: none;' id="ip">This is IP</span> <span style='display: none;' id="ur">This is UR</span> </p> <div> -
In Django, how to add creator of a group to that group instantly?
I'm creating a 'social' app in Django, where the users can create groups (Alliances) and others can join these groups. User Profiles and Alliances are connected through Membership model. I´d like the creator of such group to be a member of it instantly. I'm inexperienced in Django, in fact, this is my first project. But I figured that this maybe could be solved by signals? My user Profile model: class Profile(models.Model): ... user = models.OneToOneField(User, on_delete=models.CASCADE) alliances = models.ManyToManyField('Alliance', through='Membership') ... My Alliance model: class Alliance(models.Model): ... name = models.CharField(max_length=10, unique=True) members = models.ManyToManyField('Profile', through='Membership') ... My Membership model: class Membership(models.Model): ... profile = models.ForeignKey('Profile', on_delete=models.CASCADE) alliance = models.ForeignKey('Alliance', on_delete=models.CASCADE) ... The solution I figured could work (using signals) would look something like this: @receiver(post_save, sender=Alliance) def create_membership(sender, instance, created, **kwargs): if created: Membership.objects.create(profile=???, alliance=instance) Where the '???' should be the creators profile. I'll be really glad for any help. -
How to keep the bootstrap 4 datetimepicker plus widget on top
Is it really not possible to keep the date time picker widget on top - or so it seems at this point. I am using the "django-bootstrap-datepicker-plus" (source) I find it difficult to keep the datepicker widget in view when I am using it in an inline formset. The first image shows in a normal form render, whereas the second shows the situation when being used in inline formsets. As can be seen the one in the inline formset, the widget is only partly visible (a scroll bar appears whenever the date field is clicked or gets focus and I am able to scroll up or down and select the date I want). For the normal form what I have done is this: A. In the template I have this in the css (in the head section): .tablehdr-wrapper-scroll-y { display: block; max-height: 400px; min-width:550px; max-width:550px; overflow-y: auto; -ms-overflow-style: -ms-autohiding-scrollbar; overflow: visible!important; } B. And in the form section, I have this: {% if field.name == "docdate" %} <div style="z-index: 99999;" {{ field }}</div> {% else %} ------- ------ {% endif %} I can't make it more obvious that the idea used here has been the fruit(!) of labor of skimming … -
How to call a function when the user POSTs an image in django rest api
I am making a face detection api that will take image as an input from a user. How can i call a function when the user creates a POST request? I have the face detection code that was made using opencv i want to integrate it in my api. models.py from django.db import models import uuid from .validators import validate_file_extension def scramble_uploaded_filename(instance,filename): extension = filename.split(".")[-1] reformated = "{}.{}".format(uuid.uuid4(),extension) return reformated def scramble_uploaded_filename1(instance,filename): extension = filename.split(".")[-1] return "{}.{}".format(uuid.uuid4(),extension) class UploadVideo(models.Model): video = models.FileField('Uploaded Video',upload_to=scramble_uploaded_filename1, validators=[validate_file_extension] ) class UploadImage(models.Model): image = models.ImageField('Uploaded Image', upload_to=scramble_uploaded_filename) urls.py in resp api from django.conf.urls import url, include from rest_framework import routers from imageupload_rest.viewsets import UploadImageViewSet, UploadVideoViewSet router = routers.DefaultRouter() router.register('images', UploadImageViewSet, 'images') router.register('videos', UploadVideoViewSet, 'videos') app_name = 'reviews' urlpatterns = [ url(r'^',include(router.urls)), ] serializers.py from rest_framework import serializers from imageupload.models import UploadImage, UploadVideo class UploadImageSerializer(serializers.ModelSerializer): class Meta: model = UploadImage fields = ('pk', 'image', ) class UploadVideoSerializer(serializers.ModelSerializer): class Meta: model = UploadVideo fields = ('pk', 'video' , ) viewsets.py from rest_framework import viewsets from imageupload_rest.serializers import UploadImageSerializer, UploadVideoSerializer from imageupload.models import UploadImage, UploadVideo class UploadImageViewSet(viewsets.ModelViewSet): queryset = UploadImage.objects.all() serializer_class = UploadImageSerializer class UploadVideoViewSet(viewsets.ModelViewSet): queryset = UploadVideo.objects.all() serializer_class = UploadVideoSerializer I want a message that will say … -
how to access any static file through functions in views.py in django?
I need to open an image file stored under static folder in views.py file. I am using PIL from PIL import Image im=Image.open('home/..../static/images/download.jpeg') it is giving error of no such file exits -
Django only get the data associated with that specific User (get_queryset)
So I have a django project were users can log in, when they have logged in I want them to see the data associated with them. Let's say an assignment is connected to a user with a ManyToManyField. That User should be able to se it, but people who are not connected should not. class UserProfile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'All Users' def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_data(sender, update_fields, created, instance, **kwargs): if created: user = instance profile = UserProfile.objects.create(user=user) class Assignment(models.Model): name = models.CharField(max_length=100) canview = models.ManyToManyField(UserProfile, blank=True, related_name="canview") @login_required def DetailAssignment(request): obj = Assignment.objects.all() username = request.user.username context = { 'object': obj, 'MyName': username } return render(request, 'nav-side-project.html', context) def UserDetailAssignment(DetailAssignment): def get_queryset(self): return Assignment.objects.filter(canview__user=self.request.user) -
Having problem to migrate from fbv to cbv in django CreateView which my model is not submitted in my models
I'm trying to migrate from FBV to CBV and I encountered a problem which I completely don't know how to solve it, which is after enter a submit to insert a new news to my model, it doesn't do that, and it doesn't show anything. news/views from django.shortcuts import render , get_object_or_404 # Create your views here. from django.views.generic import ListView, DetailView , CreateView from .models import PreNews class NewsListView(ListView): model = PreNews template_name = 'news/main_news.html' queryset = PreNews.objects.order_by('-date') class NewsDetailView(DetailView): model = PreNews template_name = 'news/sub_news.html' #slug_url_kwarg = 'slug' def get_object(self): slug_ = self.kwargs.get('slug') return get_object_or_404(PreNews,slug=slug_) class NewsCreateView(CreateView): model = PreNews template_name = 'create/news_create.html' fields = '__all__' succes_url = '/news/' news/models from django.db import models from pages.models import LoginFormModel from django.urls import reverse # Create your models here. class PreNews(models.Model): hardware = 'chw' software = 'csw' politics_iran = 'pir' politics_international = 'pin' news_choice = [ (hardware,'computer hardware news'), (software,'computer software news'), (politics_iran,'iran politics'), (politics_international,'international politics'), ] author = models.ForeignKey('pages.LoginFormModel', on_delete = models.CASCADE ,) title = models.TextField(max_length=100,null=False) tags = models.TextField(default='sobhan esfandyari,') choice = models.CharField(max_length=3 , choices=news_choice , default=software) slug = models.SlugField(unique=True,blank=False,null=False) date = models.DateTimeField(auto_now_add=True) main_pic = models.ImageField(upload_to='images/',null=False) brief = models.TextField(max_length=255,null=False) article = models.TextField(null=False) def __str__(self): return (self.title," ---- ",self.date.year ,self.date.month … -
SQLite3 Database Locked When Deploying Django Project on Azure App Services
I'm attempting to deploy a Django project to Azure App Services (Linux), following this tutorial: https://stories.mlh.io/deploying-a-basic-django-app-using-azure-app-services-71ec3b21db08. The deployment works, but every time I try to write or read from the database, I get a 500 error something along the lines of: OperationalError at /api/articles/↵no such table: articles_article↵↵Request Method: GET↵Request URL: http://liquidplanet.azurewebsites.net/api/articles/... The sqlite3.db file in /wwwroot shows a size of 0. When I try to manually apply migrations through SSH, I get the following message in terminal: django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (database is locked) I'm skeptical that this is a concurrency issue, as suggested in Django docs, as this happens even on the most basic Django projects. Worth noting: when I first access the SSH terminal, I need to install Django and everything else in my requirements.txt (even though it says in logs that everything installs during deployment). Not sure if this is normal. Tried: - Redeploying, - Running simpler Django projects in different configurations, including just the basic webpage you get when you create a new Django project, - Deleting DB file and reapplying migrations, - Increasing the timeout in Django settings.py file Have not tried: - Switching to a different DB What am I doing … -
How To Use BeautifulSoup In Django?
So, I was trying to create a website in Django, which basically scrapes the data from google news and puts it on my website. But I didn't know how to use the data that I extracted from google news in my Django HTML file. Is there a way that I could do that. Also, It slows the website very much, so is this the best way to do it? The web scraping code: from bs4 import BeautifulSoup import requests url = "https://news.google.com/?hl=en-IN&gl=IN&ceid=IN:en" headers = { "User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36' } page = requests.get(url, headers=headers) soup = BeautifulSoup(page.content, 'html.parser') n = 1 for link in soup.findAll('h3', {'class', 'ipQwMb ekueJc RD0gLb'}): title = link.string for a in link.findAll('a', {'class', 'DY5T1d'}): href = a.get('href') link_href = href.replace(".", "") print("(" + str(n) + ")" + title + "\n" + "https://news.google.com" + link_href) n += 1 -
How can I reach a subclass in HTML using django?
https://docs.djangoproject.com/en/2.2/intro/tutorial02/ link tells me that: Each Choice is associated with a Question. But how can I reach in HTML these each Choices values? I have Gallery model associated with Post model, but when I save each images from gallery model. Post model only shows the last image. It is saved in the media. I checked all are saved there and my settings file are ok. class Post(models.Model): author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1 ) title = models.CharField(max_length= 100, null=True, blank=True, default="Başlık") content = models.TextField() image = models.ImageField(upload_to=user_directory_path, blank =True, null=True, default = "/") date_posted = models.DateTimeField(default=timezone.now) document = models.FileField(upload_to='{{ {nop} }}'.format(nop = "something"), default = "media/") thumbnail = models.FileField(upload_to='posts/', null = True, blank= True, default = "") status = models.CharField(max_length=10, choices=STATUS_CHOICES, default="draft") # category = models.ManyToManyField(Category, default = 0) # thumbnail = models.FileField(upload_to='posts/' gallery and thumbnail is different folders objects = models.Manager def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Gallery(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=user_directory_path, blank =True, null=True, default = "/") author = models.ForeignKey(User, on_delete = models.CASCADE, default = 1) objects = models.Manager Views.py class PostCreateView(FormView, LoginRequiredMixin, CreateView): form_class = PostForm model = Post # category = Category.objects.all() def post(self, request, … -
How do I not redirect to a success_url in Django after I make a post using a modal form and stay on the current page?
Here is my problem, I have a model medication that has a foreignkey field drug. In the create view of medication if a certain drug is not found in the record, I would like to create it on the go. So I tried using django-bootstrap-modal-forms from PyPi which basically does what it says. However, when I make a post to create a new drug, I get redirected to the DetailView of the drug even I did not explicitly specify success_url in the DrugCreateView. I have tried searching for probable solutions on the internet and also some similar problems people have in stackoverflow. I have not found an answer to my question so far. I do not want this behavior. What I want is to stay in the medication create view and reload the page if necessary to update the foreignkey drug field as I have just added it in the database. I would really appreciate if you can help or at least give me a clue on how am I going to accomplish this. Please tell what other information I have to give and I will gladly provide it immediately. -
Is omitting imprts in python for performance reasonable?
So I've been wondering weather neglecting DRY rule instead of importing is good for performance in python and django. I know that when something is imported in python it needs to run it to search for bugs, so what I do here seems reasonable, but I also know that User is imported elsewhere in my project so do I actually gain anything by aproach shown below? # from django.contrib.auth.models import User class RegistrationForm(forms.ModelForm): """ Registration form for User. Import omitted for performance. """ password_1 = forms.CharField(required=True, widget=forms.PasswordInput) password_2 = forms.CharField(required=True, widget=forms.PasswordInput) username = forms.CharField() email = forms.CharField(widget=forms.EmailInput) # class Meta: # model = User # fields = ('username', 'email') -
In the Wagtail admin how to disable summary items of Images and Documents?
I know that I can get rid of the Pages summary by using the hook, however Images and Documents still remain. @hooks.register("construct_homepage_summary_items") def hide_images_and_documents_from_partners(request, summary_items): if request.user.groups.filter(name="Partners").exists(): summary_items.clear()