Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Getting Posts from Instagram in Python Django
I am making a Django Project in which I need to download images from all the instagram posts of an account and save it in a model and once daily check for new post. Can someone show me how can I extract all the posts from instagram and also download the images and save them in a model. Right now my models is : class ImageModel(models.Model): img = models.ImageField(upload_to='photos/') class Post(models.Model): title = models.CharField(max_length=100, null=True, blank=True) text = models.TextField(null=True, blank=True) image = models.ForeignKey(ImageModel, on_delete=models.CASCADE) url = models.URLField(unique=True) tag = models.CharField(max_length=100, null=True, blank=True) date = models.DateTimeField(default=timezone.now, null=True, blank=True) class Meta: verbose_name_plural = "Publications" def __str__(self): return self.text Thank you. -
how to display Django model based form to the center of page(Crispy form)
I am trying to use the crispy form for Django model-based form. I have referred a few questions already asked but no luck I did not found the way how to centralize the Crispy form. Please find the below code. forms.py class SignUpForm(forms.ModelForm): username = forms.CharField(label=' Enter Username',widget=forms.TextInput(attrs={'placeholder': 'LDAPID/AppleConnect'})) password = forms.CharField(label='Enter Password',widget=forms.PasswordInput(attrs={'placeholder': 'alphanumeric password'})) User._meta.get_field('email')._unique = True email = forms.CharField(label='Enter Email ID', widget=forms.EmailInput(attrs={'placeholder': 'abc@apple.com'})) # username = forms.CharField(label=_("Enter LDAP ID"), widget=MyPasswordInput def __init__(self, *args, **kwargs): super(SignUpForm, self).__init__(*args, **kwargs) # If you pass FormHelper constructor a form instance # It builds a default layout with all its fields self.helper = FormHelper(self) self.helper.form_class = 'vertical-form' # You can dynamically adjust your layout self.helper.layout.append(Submit('save', 'save')) class Meta: model = User fields = ['username', 'password', 'email', 'first_name', 'last_name'] help_texts = { 'username': None,} HTML file: <div class="jumbotron"> <div class="container" align=''> <div class="alert warning"> <span class="closebtn" onclick="this.parentElement.style.display='none';">&times;</span> Please Read the below Instruction Carefully.<br> <strong>Alert!</strong> <br> 1. In <span2> Username</span2> enter your ldap ID and in <span2>Email</span2> field enter apple Email.<br>&nbsp&nbsp 2.Once the Account created user will not have Access to the respective Portal.To get Access please file radar with business justification(User should be part of vendor Company group). </div> <br> <div class="col-md-12 well"> <div … -
django owner permission in detail view
I that there many materials on the subject, i checked many, but i can't find slick and simple way to deal with the problem. This is very frustrating (because the problem is not complicated at all). So this my code in the view class EnrollmentDetail(generic.DetailView): model = Enrollment template_name = 'enrollments/enrollment_detail.html' context_object_name = 'enrollment Simple django generic detail view. I want only the owner of this detail view to has access to it. Everyone else i don't wont go get it, i try to limit their access to it. I think for raising some error in that case, but don't know which one exactly is accurate. I checked some posts on that matter. There is solutions with queryset, super, decoratos etc. but they seem chaotic and not working form me. Thanks for help! -
Creating new user with random password in django
I have been working on a project where admin registers users to use the website. say in my case admin registers teachers and students of the school. I need some way to create random password for every new user and a email will be sent using registered email with the password. I am using custom user model. class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have email Id") if not username: raise ValueError("Users must have an username") user = self.model(email=self.normalize_email(email), username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password=None): user = self.create_user(email=self.normalize_email(email), username=username, password=password) user.role = 'ADM' user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractUser): email = models.EmailField(verbose_name="Email", unique=True) ROLE_CHOICES = [ ('STD', 'STUDENT'), ('THR', 'TEACHER'), ('ADM', 'ADMIN') ] role = models.CharField(max_length=3, choices=ROLE_CHOICES, default='STD') username = models.CharField(max_length=50, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) date_of_birth = models.DateField(null=True) description = models.TextField(null=True) image = models.ImageField(default='default.jpg', upload_to='profile_pics') date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email'] objects = MyAccountManager() here my register view. @login_required def register(request): if not request.user.is_superuser: return HttpResponse('Unauthorized', status=401) if request.method == … -
storing a QR Code png image in a django database
I'm trying to store a QR Code image in a .png file in a django database model. It is created using the qrcode python module (pip install qrcode). However, my problem is I get an error when trying to migrate the models, getting an error saying: ValueError: Cannot serialize: <qrcode.image.pil.PilImage object at 0x7f89c1f9b760> I read the django documentation and it mentioned something about a migration serializer but wasn't very helpful with the implementation. Here is my code as it stands: from qrcode import make # models.py def create_qr_code(id): # this line creates the qr code image which in production will be a url return make(id) class PDFDoc(models.Model): id = models.IntegerField(primary_key=True) account_id = models.ForeignKey(Account, on_delete=models.CASCADE) name = models.CharField(max_length=15, default="", blank=True) num_requests = models.IntegerField() document = models.FileField(upload_to="documents/") qr_code = create_qr_code(id) qr_code = models.ImageField(blank=False, upload_to="pdf-qrcodes/", default=qr_code) def __str__(self): return f"Name: {self.name}\nNumber of requests: {self.num_requests}\n" Any help would be greatly appreciated :) -
In permissions.py "has_object_permission" obj's ManyToManyField is being None
Project Model has relation with ManyToManyField to User Model. class Project(models.Model): user = models.ManyToManyField(User, related_name="projects") Serializing the data in serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id"] class ProjectSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Project fields = [... "user" ...] depth = 1 There is no problem. I nest the ManyToManyField User field into the Projects. BUT in permissions.py, when I try to reach the user field like below. def has_object_permission(self, request, view, obj): print(obj.user) It returns ...User.None and I am not sure what is the reason. The way I serialize the User field in ProjectSerializer() is wrong? By the way I can check on browser that User field is nested. But in terminal I can't reach it trough obj -
Django command: how to schedule properly on Windows Server
coming from Linux I have to build a Django application on Windows Server. Everything works fine, but I have a Django command that needs to be run every hour. In Linux I would create a cronjob. I wrote a batch file that activates the virtual env and runs the django command, scheduled it with windows, but the command jobs fails, despite task scheduler says it executed properly. What is simple on Linux on Windows it seems to be rocket science... I feel that task scheduler / batch file approach isn't the right way to do that. Is there a more pythonesque way to run a django command on windows server every hour? thanx in advance, Jan -
DRF Token Authentication - not able to retrieve Token
I'm trying to retrieve a token for the user using the following request through Postman. http://127.0.0.1:8000/api-token-auth/ JSON Body - { "username": "user1", "password": "Test#1234" } The following is the error response - { "detail": "CSRF Failed: CSRF token missing or incorrect." } I've checked the instructions provided in the official DRF Authentication document as well as various other question posts and implemented the following code. settings.py INSTALLED_APPS = [ ... 'rest_framework', 'rest_framework.authtoken', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth', 'rest_auth.registration', .... ] AUTH_USER_MODEL = 'users.CustomUser' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } signals.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) urls.py urlpatterns= [ path('admin/', admin.site.urls), path("accounts/", include("django_registration.backends.one_step.urls")), path("accounts/", include("django.contrib.auth.urls")), path("api-auth/", include("rest_framework.urls")), path("api-token-auth/", authtoken_views.obtain_auth_token, name="api-token-auth"), path("api/rest-auth/", include("rest_auth.urls")), path("api/rest-auth/registration/", include("rest_auth.registration.urls")), ] Have I missed something? -
Error when trying to update the group that a user belongs to
I am developing an application that has different users, for that I am using the groups, but I am having a problem and that is that when a user is updated to belong to another different group, it is added and another and the one that has is to preserve: @receiver(post_save, sender=User) def set_role_user(sender, instance, *args, **kwargs): if instance.role: if instance.role == 'administrador': group = Group.objects.get(name='administradores') instance.groups.add(group) else: group = Group.objects.get(name='desarrolladores') instance.groups.add(group) It is preserved because I am adding the group, so what I tried was only to update: @receiver(post_save, sender=User) def set_role_user(sender, instance, *args, **kwargs): if instance.role: if instance.role == 'administrador': group = Group.objects.get(name='administradores') instance.groups.update(group) else: group = Group.objects.get(name='desarrolladores') instance.groups.update(group) But doing this generates an error which says that update () takes 1 positional argument but 2 were given, which I don't understand because when displaying the instance.role by console, it only shows me one. -
vs code is showing this error, have installed django 2.1 in the system but still it is showing this error , can anyone suggest how to solve
Import "django.db" could not be resolved from source Pylance from django.db import models- while importing models module above said error message was showing. -
Missing "dnspython" error for django + gninx + gunicorn app, even after installing it to the correct virtual environment
Getting the following Error: The "dnspython" module must be installed to use mongodb+srv:// URIs Exception location: ../python3.7/site-packages/pymongo/uri_parser.py, line 428, in parse_uri When trying to use pymongo with django app. I tried to install dnspython with pip3 to the correct virtual environment but still got the error. I also tried to re-start gninx. -
how to create django form from dictionary
I have dictionary like this p_dic = { 'Frequency': ['8kHz', '9kHz', '3.6kHz', '2.8kHz', '1.2kHz', ], 'Voltage - Input (Max)': ['-', '15V p-p', '80V p-p', '30V p-p'], 'Type': ['Feedback', 'Standard'], 'Impedance': ['500 Ohms', '400 Ohms', '350 Ohms', ], 'Capacitance @ Frequency': [ '25000pF @ 1kHz', '93000pF @ 1kHz'], } I want to create form where name will be key and options will be values as given in the list, how to do so. -
django: Auto populate m2m field of a model
I have a category kind of model (called Tag): class Tag(models.Model): name = models.CharField(...) slug = models.SlugField(unique=True) #... Used as m2m field in another model: class Order(models.Model): user = models.ForeignKey(...) type = models.CharField(...) tag = models.ManyToManyField(Tag, blank=True) Now, suppose an order is created and program wants to assign some tags to it automatically. Say, program wants to add Order.type to itsOrder.tag list. (Suppose Order.type happens to be same as a valid Tag.name) I tried Order's post_save to no luck: def order_post_save_reciever(sender, instance, *args, **kwargs): #... instance.tag.add(Tag.objects.filter(name=instance.type)) instance.save() Apparently, I have to use signals, but I don't know how. Your help is much appreciated. -
How to load django installed apps staticfiles in production?
This is probably a really simple adjustment that I've lost enough time searching for a solution. I built a project using Django + React and deployed it on Heroku. Everything works perfectly excepts for the static files from the INSTALLED_APPS: /admin and de Django Rest Framework views. In these urls, django throws a 500 server error. django.contrib.staticfiles is in my INSTALLED_APPS. I'm using whitenoise. My allowed hosts are correct. My STATIC_ROOT path is also correct. STATIC_URL = "/static/" STATIC_ROOT = os.path.join(FRONTEND_DIR, "build", "static") I've tried to add an empty directory in the STATICFILES_DIRS but it didn't work. What am I missing? Why django isn't collecting the static files from the INSTALLED_APPS? -
502 Bad Gateway nginx/1.18.0 django
var/log/nginx/error.log 2020/12/04 12:46:29 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com" 2020/12/04 12:46:30 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com", referrer: "http://uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com/" 2020/12/04 12:46:36 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8000/", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com" 2020/12/04 12:46:36 [error] 3938#0: *1 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.14.128, server: , request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com", referrer: "http://uma-env.eba-hi5j8ufq.ap-south-1.elasticbeanstalk.com/" 2020/12/04 12:48:11 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /TP/public/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/TP/public/index.php", host: "15.207.142.142" 2020/12/04 12:48:12 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /TP/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/TP/index.php", host: "15.207.142.142" 2020/12/04 12:48:13 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to upstream, client: 172.31.47.53, server: , request: "GET /thinkphp/html/public/index.php HTTP/1.1", upstream: "http://127.0.0.1:8000/thinkphp/html/public/index.php", host: "15.207.142.142" 2020/12/04 12:48:15 [error] 3938#0: *27 connect() failed (111: Connection refused) while connecting to … -
Why can't Django via nginx find static files although manage.py findstatic is successful?
I deployed a Django app via nginx and this worked without any problem for the last few months. However now without any change that I know of Django can't find any static files anymore, so no images are displayed and the django admin page has no stylesheet. In my settings.py I have used the following setting: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ... STATIC_ROOT = os.path.join(BASE_DIR,'static/') STATIC_URL = 'http://[ip.of.hosting.server]/[name_of_app]/static/' When I run e.g. manage.py findstatic --verbosity 2 img/logo.png Django is able to find the image file however in the deployed website the logo is not displayed and I get a 404 file not found error for the image. I also tried to run manage.py collectstatic however that added no new static files and the files are still not found. How can this suddenly happen. I have no idea what I might have touched to break -
ImportError: cannot import name 'APIView' from 'rest_framework.views'
ImportError pycharm I am trying to make a simple REST API using Django. I installed djangorestframework using pip and I am using Pycharm IDE for my work. When I try to import APIView from rest_framework using:from rest_framework.views import APIView I get this ImportError: ImportError: cannot import name 'APIView' from 'rest_framework.views' I am unable to solve this issue and need help -
slash ('/') is being automatically added to path ,even i havn't included it to my URLs and this is why it is giving PAGE NOT FOUND error
I have created a small project, and if i go to registration section. slash (/) gets added to URL automatically and says page not found. I have not included '/' in my code though This is my urls.py from django.urls import path from . import views urlpatterns = [ path('register',views.register, name = 'register'), # no slash over here path('login',views.login,name = 'login'), path('logout',views.logout,name='logout'), path('checkPincode',views.check,name `enter code here`= 'check'), ] this is navigation section of index.html <div class="topnav"> <a href="/" style="background-color:black; color:#54dfd8;">VIVER FOODS</a> <a href="#menu">Food Menu</a> <a href="cart/your-cart">Cart</a> <a href="help/questions">Help</a> {% if user.is_authenticated %} <a href="/" style="float: right;">Hello, {{ user.first_name }}</a> <a href="accounts/logout" style="float:right;">LogOut</a> {% else %} <a href="accounts/register" style="float:right;">SignUp</a> <a href="accounts/login" style="float:right;">logIn</a> {% endif %} </div> The thing is LOGIN working fine 🤷♂️. -
Django3: dynamically generating js which I can use in HTML page
As we know in Django framework we can generate the HTML page based on some predefined template files. Inside those templates we can use and some specific django keywords/operators/functions. Like: {% block stylesheets %} <link href="{% static 'js/jquery/jquery-ui.css' %}" rel="stylesheet"> <link href="{% static 'vendor/chosen/chosen.css' %}" rel="stylesheet"> {% endblock stylesheets %} But most important things which I want to touch in this question are related to tag 'translate' "{% trans 'List of all available masters' %}" So I can be sure that the final content of my page will use some predefined language. And the places where I am using such tags are different: "simple" html content with / and etc tags AND inline javascripts blocks. Like: <script type="text/javascript"> $('#datepicker_value').on('change', function(){ .... var dialog = BootstrapModalWrapperFactory.createModal({ title: '{% trans 'Extended information about the event' %}', message: '<pre>'+JSON.stringify(info.event.extendedProps.description, null, 4)+'</pre>', buttons: [ { label: '{% trans 'Close' %}', cssClass: "btn btn-secondary", action: function (button, buttonData, originalEvent) { return this.hide(); } } ] }); .... </script> So my main question here is such: HOW correctly I can move ALL <script>...</script> blocks from html template into the external JS file? To keep all the functionality of the django framework working! And my 1 variant … -
Docker and Django: how to render templates in a right way
Hi guys how are you? I started with Docker and Django a little while ago and I already ran into a problem. Scenario: I want to create an application in Django using docker. I found this guide on the Docker website itself and followed the steps. My Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt /app/ RUN pip install -r requirements.txt COPY . /app/ Here is the docker-compose.yml version: "3.8" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - .:/app web: build: . command: python manage.py runserver 0.0.0.0:5000 volumes: - .:/app ports: - "5000:5000" depends_on: - db The problem occurs when I want to start using Django templates. Currently, my file structure looks like this . ├── docker-compose.yml ├── Dockerfile ├── manage.py ├── requirements.txt ├── sao_app │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── __pycache__ │ │ ├── __init__.cpython-39.pyc │ │ ├── urls.cpython-39.pyc │ │ └── views.cpython-39.pyc │ ├── templates │ │ └── sao_app │ │ └── index.html │ ├── tests.py │ ├── urls.py │ └── views.py └── sao_project ├── asgi.py ├── __init__.py ├── __pycache__ │ ├── __init__.cpython-39.pyc │ ├── settings.cpython-39.pyc │ … -
how to normalize this below json using panda in django
here is my json {"pages":[{"name":"page1","title":"SurveyWindow Pvt. Ltd. Customer Feedback","description":"Question marked * are compulsory.", "elements":[{"type":"radiogroup","name":"question1","title":"Do you like our product? *","isRequired":true, "choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]},{"type":"checkbox","name":"question2","title":"Please Rate Our PM Skill","isRequired":false,"choices":[{"value":"High","text":"High"},{"value":"Low","text":"Low"},{"value":"Medium","text":"Medium"}]},{"type":"radiogroup","name":"question3","title":"Do you like our services? *","isRequired":true,"choices":[{"value":"Yes","text":"Yes"},{"value":"No","text":"No"}]}]}]} this is my view.py jsondata=SurveyMaster.objects.all().filter(survey_id='1H2711202014572740') q = jsondata.values('survey_json_design') qs_json = pd.DataFrame.from_records(q) datatotable = pd.json_normalize(qs_json['survey_json_design'], record_path=['pages','elements']) qs_json = datatotable.to_html() -
ElasticSearch DSL DRF - Field Collapsing and Pagination
I am currently doing field collapsing using ElasticSearch DSL DRF - although that breaks the pagination completely; for example: Originally 19 items are matched After collapsing 18 items are left Pagination is set for 18 items per page Pagination still recognizes 19 items Is there anyone who knows a clean way of actually doing this? - making the count take into consideration the field collapsing? -
The wrapper over the database does not "fit” on the MVC schema in Django
I am writing a mini project on Django that performs certain manipulations with the database. There was a need to write a small wrapper for clickhouse, which will give me the result of the request, and give a report in json format to GUI. The scheme of work is as follows: Ajax sends a request to a specific url, python calls this wrapper and returns the result in the form of json-a, then some magic happens. Question: What is the wrapper in this case? It does not fit on the model-view-controller scheme. How do I correctly add it to the Django app? (perhaps this is a separate application or a global singleton?) -
JSON problems ajax
me.addEventListener('change', (e) => { if (me.checked) { fetch("/demande/transporter/", { body: JSON.stringify({ cin_mle: cin_mle }), method: "POST" }).then(res => res.json()).then(data => { tn.value = data['email']; tn.disabled = true }); } }); code js class ReturnCredentilasView(View): def post(self, request): data = json.loads(request.body) cin_mle=data["cin_mle"] print(cin_mle) user=get_object_or_404(User, cin_mle=cin_mle) if not user: return JsonResponse({"User_status": "inexistant"}) return JsonResponse({"email":user.email}) the view The error : moi.js:10 POST http://127.0.0.1:8000/demande/transporter/ 404 (Not Found) (anonymous) @ moi.js:10 127.0.0.1/:1 Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 I need to retrieve some data from the serer using ajax, but the errors above appears. the view is working good on postman me is checkbox element -
Passing in date string to Django management argument
I have a Django management command, which I pass like this: python manage.py tenant_command generate_weekly_invoice --start_date 2020-11-30 00:00:00 --end_date 2020-12-06 23:59:00 --schema=schema_name This doesn't work and I get an error saying that: argument 1 must be str, not None I suspect this is to do with the way the actual string of the date 2020-11-30 00:00:00 is being formatted. My management command code is below generate_weekly_invoice.py class Command(BaseCommand): help = 'Generates weekly invoice' def add_arguments(self, parser): parser.add_argument('--start_date', nargs='+') parser.add_argument('--end_date', nargs='+') def handle(self, *args, **options): start_str = options.get('--start_date') end_str = options.get('--end_date') start_date = datetime.datetime.strptime(start_str, '%Y-%m-%d %H:%M:%S') end_date = datetime.datetime.strptime(end_str, '%Y-%m-%d %H:%M:%S') ___Logic goes here___