Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Confusion about Heroku Dyno hours
I am all set to launch my app and its backend is Django and hosted on Heroku. I have so many questions about the Heroku dyno hours, As per the Heroku website I will get free 1000 dyno hours but what are these hours, I mean maximum number of hours in a month is 744 so how does it work? Is it based on number of users using the app or something else? Thanks -
I have an error when I ran the Django Code
I followed the tutorial on https://simpleisbetterthancomplex.com/series/2017/09/25/a-complete-beginners-guide-to-django-part-4.html#adding-the-email-field-to-the-form. When I ran python manage.py test, I got this error, AttributeError: SignUpTests has no attribute 'response' Here is where the error is occurring in my accounts/tests.py class SignUpTests(TestCase): def test_signup_status_code(self): url = reverse('signup') response = self.client.get(url) self.assertEquals(response.status_code, 200) def test_signup_url_resolves_signup_view(self): view = resolve('/signup/') self.assertEquals(view.func, signup) def test_contains_form(self): form = self.response.context.get('form') self.assertIsInstance(form, SignUpForm) ---> the error occurs right here. I got the error with this test, but without it, it works just fine. Can you show me what this error means, and what I can do to fix it with that test in it. I need to know why this test is failing, and I am frustrated at it. I do Django just for fun, by the way. -
Elastic Beanstalk Aws Django static and media files
I'am having troubles to access to my media files after uploading them, i have a store website where the admin can add items and their images, i have two separated root folders: /static : for static files /Prod : for the product files Here is my setting.py: ... BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) ... ... STATIC_ROOT = os.path.join(PROJECT_DIR, 'static', 'Prod') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] MEDIA_ROOT = os.path.join(PROJECT_DIR, 'Prod') MEDIA_URL = '/Prod/' when i check the images URL they are correct: mywebsitw.com/prod/image.jpg but they are not displayed and the direct url do not display any image, knowing that the image is uploaded in the correct directory PS: in my local virtual envirenment it works perfectly -
Django rest framework, override the viewset create method raises Assertion error
I have the following model: class Month(models.Model): month = models.IntegerField(null=False) year = models.IntegerField(null=False) date = models.DateField(null=True) days = models.DurationField(default=0, ) I'm trying to set the date field to be based on the month and year fields. I'm having difficulty understanding where is best to do this action. I tried overriding the create method, I want it to have the same behaviour just change the field's value beforehand. class MonthsViewSet(ModelViewSet): authentication_classes = (TokenAuthentication,) def get_queryset(self): query_set = Month.objects.all() return query_set serializer_class = MonthSerializer def create(self, request, *args, **kwargs): instance = self.get_object() date = datetime.date(instance.year, instance.month, 1) instance.date = date instance.save() serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) This code raises the following error: AssertionError: Expected view MonthsViewSet to be called with a URL keyword argument named "pk". Fix your URL conf, or set the `.lookup_field` attribute on the view correctly. My second problem with this is that I've set the model's fields to be integers is there a way to set them to date fields as well and perform this action? My serializer: class MonthSerializer(serializers.ModelSerializer): date = serializers.DateField(input_formats=['%m-%Y'], format='%m-%Y') class Meta: model = Month exclude = ['date'] -
Assign the same value to object keys from lambda in Python (Django)
When trying to assign the same value to starting_bid and price from the Listing model in my Django project the below approach always yields different values. How can I assign the same value while still having the lambda return a random integer whenever the test runs? tests.py SEEDER = Seed.seeder() # from django_seed AMOUNT = 15 MIN = 5 MAX = 84 PRICE = lambda x: random.randint(MIN, MAX) SEEDER.add_entity( Listing, AMOUNT, { "starting_bid": PRICE, "price": PRICE }) SEEDER.execute() Result: {"starting_bid": 80, "price": 45} Expected: {"starting_bid": 80, "price": 80} models.py class Listing(models.Model): CATEGORIES = (("LAP", "Laptop"), ("CON", "Console"), ("GAD", "Gadget"), ("GAM", "Game"), ("TEL", "TV")) user = models.ForeignKey(User, null=True, on_delete=models.CASCADE) title = models.CharField(max_length=64) description = models.CharField(max_length=256) starting_bid = models.PositiveSmallIntegerField() price = models.PositiveSmallIntegerField() image_url = models.URLField(max_length=200) category = models.CharField(max_length=8, choices=CATEGORIES) active = models.BooleanField(default=True) -
How to show folder structure on UI which are fetched from remote server(GCP) in django..Just like SFTP Client/FileZilla
I have a remote server(Linux) on GCP. By using paramiko library in django, I have fetched the folders and files from the server in list format. I want to show this folder structure as it is on UI in django integrated templates. Just like SFTP Client/FileZilla, I want to access the file system of remote server. And to show the file structure as it is on UI. So how to achieve this? For any clarification, please reach out to me on vrbhandari1995@gmail.com. Any leads are highly appreciated..Thanks in advance.. below is the Code snippet for fetching the folders and files from remote server. def create_ssh(host=host, username=username, password=password): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) try: print("creating connection") ssh.connect(host, username, password) sftp = ssh.open_sftp() dir_structure = sftp.listdir() for i in dir_structure: lstatout=str(sftp.lstat(i)).split()[0] if 'd' in lstatout: print (i, 'is a directory') elif 'd' not in lstatout: print(i, 'is a file') finally: print("closing connection") -
Cannot send JSONs from an external app but my Django test works
Tl;dr: Im trying to send a JSON over http with python, is my first script alright? Im trying to build a django app where I would send information to add to the database by POSTing json strings from another python application. To do that, I run this code to send the json (trimmed to the important part) out_data = { 'session_id': session_id, 'count': count, 'gas_reading': gas_received, 'latitude': latitude, 'longitude': longitude, 'date_time': date_time.strftime("%Y-%m-%d %X") } out_json = json.dumps(out_data) url = 'http://localhost:8000/sessions/post/' response = requests.post(url, headers={'Content-type':'application/json'}, json=out_json) print("Posted to ",url," and got ",response) And this is the definition of the view that catches it. def post(request): if request.method=='POST': received_data=json.loads(request.body) session_id = int(received_data['session_id']) if Session.objects.filter(session_id=session_id): session = Session.objects.get(session_id=session_id) else: session = Session(session_id=session_id) session.save() session.measurement_set.create( gas_reading=int(received_data['gas_reading']), count=int(received_data['count']), latitude=float(received_data['latitude']), longitude=float(received_data['longitude']), date_time = parse_datetime(received_data['date_time']) ) return HttpResponseRedirect(reverse('index')) elif request.method=='GET': return HttpResponse("This is only for posting data") I tried the View by using this test, which works: class PostViewTests(TestCase): def test_post_into_database(self): data = { 'session_id': 69, 'count':100, 'gas_reading': 420, 'latitude': 4.13, 'longitude': 80.08, 'date_time': '2020-07-13 20:30:00' } headers = {'content-type':'application/json'} self.client.post(reverse('readings:post'), content_type='application/json',data=data) session=Session.objects.get(session_id=69) measurement=session.measurement_set.last() local_date_time = timezone.localtime(measurement.date_time) self.assertEqual(session.session_id, 69) self.assertEqual(measurement.count, 100) self.assertEqual(measurement.gas_reading,420) self.assertEqual(measurement.latitude,4.13) self.assertEqual(measurement.longitude,80.08) self.assertEqual(local_date_time.day,13) self.assertEqual(local_date_time.month,7) self.assertEqual(local_date_time.year,2020) self.assertEqual(local_date_time.hour,20) self.assertEqual(local_date_time.minute,30) self.assertEqual(local_date_time.second,00) I get a TypeError: string indices must … -
Filter table data depending on select dropdown
At first please see the image Result that I want There result will look like this. There are two select dropdowns, Series and episodes. Initially, the episode filed is empty. When a series is selected, the episode will fetch the data depending on the series. And there are series and episode data on the table. At first, all data will visible. When someone selects a series or episode, table data will be filtered depending on the selected field. I have tried some code, please have a look <select class="selectpicker" data-live-search="true" id="seriesID"> <option>Select Series</option> {% for series in series_context %} <option value="{{series.id}}">{{ series.lesson_title }}</option> {% endfor %} </select> <select id="episodeID"> <option>Select Series</option> {% for ep_context in episode_context %} <option value="{{ep_context.series_of.id}}">{{ ep_context.title }}</option> {% endfor %} </select> Table: <div class="table-responsive" data-toggle="lists" data-lists-sort-by="js-lists-values-orders-name" data-lists-values='["js-lists-values-orders-name", "js-lists-values-orders-date", "js-lists-values-orders-amount"]'> <table class="table mb-0 table-nowrap thead-border-top-0"> <thead> <tr> <th>SL </th> <th> Episode </th> <th> Price </th> </tr> </thead> <tbody class="list" id="episodeTable"> {% for l_context in series_context %} {% for ep_context in episode_context %} {% if l_context == ep_context.series_of %} <tr> <td> <p>{{ forloop.counter }}</p> </td> <td> <div class="d-flex align-items-center"> <a class="js-lists-values-orders-name" onclick="changeVideo('{{ep_context.video}}')" href="#" id=" video-link-{{ ep_context.id}}"> <b>{{ ep_context.title }}</b> </a> </div> </td> <td> <p><b>${{ ep_context.price }}</b></p> </td> </tr> … -
Get parent by its children in Django Queryset
I have this model: Department(models.Model): title = models.CharField(max_length=128) reference = models.ForeignKey('self', related_name='reference') As you see, each object of this model can have parent and conversely. For example, these are department's objects: id = 1 , title = 'dep 1' , reference_id = Null id = 2 , title = 'dep 2' , reference_id = 1 id = 3 , title = 'dep 3' , reference_id = Null id = 4 , title = 'dep 4' , reference_id = 1 id = 5 , title = 'dep 5' , reference_id = 3 id = 6 , tiltl = 'dep 6' , reference_id = 3 id = 7 , title = 'dep 7' , reference_id = 3 id = 8 , title = 'dep 8' , reference_id = 9 id = 9 , title = 'dep 9' , reference_id = Null id = 10, title = 'dep 10', reference_id = 9 Now I want to get list of objects that has this condition: Each parent by its children. like this: - dep 1 dep 2 dep 4 - dep 3 dep 5 dep 6 dep 7 - dep 9 dep 8 dep 10 How can I do that? (Can I create this … -
Pillow failing to import Image on Synology Nas
I'm trying to run a django site as a personal project. In Windows it runs fine, so I'm trying to test it on my Synology DS916+. I installled successfully this: Python 3.8.3 Django 3.0.7 Pillow 7.2 But when I run python manage.py runserver, it returns this: File "/volume1/WEBMI/webmi/lib/python3.8/site-packages/PIL/Image.py", line 93, in <module> from . import _imaging as core ImportError: cannot import name '_imaging' from 'PIL' (/volume1/WEBMI/webmi/lib/python3.8/site-packages/PIL/__init__.py) As you can see I ran it also in virtualenv with no success. Also tried to uninstall and install pillow several times without success. It seems some dependency is broken but don't know which. I run out of ideas. Thanks in advance -
Django website appearance suddenly changed
Last week my django website is showing the design I coded until now it suddenly changed. The font size, type and even the button suddenly changed. My code remains the same and I don't know if this is just my browser's problem. For example, my login page should look like this and now it looks like this -
How do I put a css class selector on select form in django?
I'm trying to put a .class selector to a select option in my django website but it doesnt seem to be working. This is how the select option looks like in my forms.py # this is only a guess. I added this to try and add the class selector degree = forms.ChoiceField( widget=forms.Select(attrs = {'class':'degree'}) ) class Meta: model = Student fields = ("degree") I've already set up all the choices in my models.py. Here's how I display the forms in my html template: {{ form | crispy }} -
404 not found as the URL takes only the last portion in Django
[][1] It takes id as a current Path instead of the edit/id due to which I get 404 not found while editing and deleting. [1]: https://i.stack.imgur.com/PUJvO.png -
how can we import PIL and Pytesseract modules in django views?
i want to design OCR web application using Django framework, So we need import PIL and Pytesseract modules in views.py, please help me out. -
Getting this error:Manager isn't available; 'auth.User' has been swapped for 'app.MyUser'. I have created a custom user model using docs
I have seen several threads on this problem but wasnt able to figure out the correct way to solve my problem becoz in most solutions there was a reference to forms.py which i dont even have in my files. This is my views.py. from django.shortcuts import render, redirect from django.conf.urls import url from .models import Category,Product from django.contrib.auth.models import User, auth def signup(request): if request.method == "POST": first_name=request.POST['first_name'] last_name=request.POST['last_name'] email=request.POST['email'] mobile=request.POST['mobile'] password=request.POST['password'] cpassword=request.POST['cpassword'] user=User.objects.create_user(first_name=first_name,last_name=last_name,email=email,password=password,mobile=mobile) user.save(); return redirect('/') else: return render(request,"signup.html") Please help me in figuring out the changes that i have to make to succeed -
Django raising TypeError when using DecimalField in Decimal context
I use geoposition library to put google map in my Django Admin Panel. I already have a decent database with latitude and longitude of an objects and my purpose is to use GeopositionField with existing arguments, stored in latitude and longitude of an existing objects. This is my code: latitude = models.DecimalField(max_digits=9, decimal_places=6) longitude = models.DecimalField(max_digits=9, decimal_places=6) position = GeopositionField(default=Geoposition(latitude, longitude)) And this is the error it raise when i am trying to make migrations: TypeError: conversion from DecimalField to Decimal is not supported -
Vendor id where to place in ecommerce app Django
class Product(models.Model): title = models.CharField(max_length =120) slug = models.SlugField(blank=True) description = models.TextField() price = models.DecimalField(decimal_places=2, max_digits=20, default=39.99) image = models.ImageField(upload_to=upload_image_path,null=True, blank=True) featured = models.BooleanField(default=False) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) class OrderItem(models.Model): item = models.ForeignKey(Product, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) item_cart = models.CharField(max_length=20, null=True, blank=True) class Cart(models.Model): user = models.ForeignKey(User,null=True, blank=True,on_delete=models.CASCADE) products = models.ManyToManyField(OrderItem, blank=True) subtotal = models.DecimalField(default=0.00, max_digits=100, decimal_places=2) total = models.DecimalField(default=0.00,max_digits=100,decimal_places=2) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) where to place the vendor id in this model and how to implement for many shops with this datamodel i did ecom website with this data model for a single shop -
Iterating over model constraints in bulk data create on Django
I am trying to save data from an API with constant live updates. Hence, the data from the API will always container an existing dataset on my database. So I created a unique_together to prevent duplicate. The model looks like: class Autodamb(models.Model, Activity): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='highlight', null=True) title = models.CharField(max_length=300) url = models.URLField(null=True) embed_donotuse = models.CharField(max_length=1000) date = models.CharField(max_length=300) thumbnail = models.URLField() home_team_name = models.CharField(max_length=100) away_team_name = models.CharField(max_length=100) class Meta: unique_together = ["title", "date"] The views.py: def save_damb_video(request): r = requests.get('https://www.brainxo.com/com-api/v1/?apid=xxxxxxxxxxx') # data = json.loads(r) data = r.json() for x in data: title = x["title"] embed_donotuse = x["embed"] url = x["url"] date = x["date"] thumbnail = x["thumbnail"] home_team_name = x["side1"]["name"] away_team_name = x["side2"]["name"] user = request.user damb_data = Autodamb.objects.create(title=title, embed_donotuse=embed_donotuse, url=url, date=date, thumbnail=thumbnail, home_team_name=home_team_name, away_team_name=away_team_name, user=user) damb_data.save() return HttpResponse("DAMP API data successfully saved") The problem is that the entire process would fail with a unique_together as some data already exist. Any Idea how to iterate and only save data not already existing while maintaining the unique constraint? -
template does not exist Django using heroku
I made a portfolio website using djano,its working perfectly on localhost server, but not after deploying on heroku, it says template does not exist at/ . PLEASE HELP! This is my github repo, please have a look at it: https://github.com/The-Nightwing/Portfolio-01.git -
Problem Saving ManytoManyField using ModelForm Django
models.py from django.db import models from django.contrib.auth.models import User class Elements(models.Model): element = models.CharField(max_length=10, unique=True) def __str__(self): return self.element class Hero(models.Model): added = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) name = models.CharField(max_length=10, unique=True) element = models.ManyToManyField(Elements, blank=True) def __str__(self): return self.name forms.py from django import forms from .models import Elements, Hero class HeroForm(forms.ModelForm): class Meta: model = Hero exclude = [ 'added' ] widgets = { 'element': forms.CheckboxSelectMultiple } views.py from django.shortcuts import render from .forms import HeroForm def home(request): form = HeroForm(request.POST or None) if form.is_valid(): hero = form.save(commit=False) hero.added = request.user hero.save() form = HeroForm() return render(request, 'home.html', {'form': form}) whenever I try to manipulate the modelform beforesaving like I've shown above in views.py, element's(manytoamyfield) data automatically set to null. However, if I save the form as it is the element's data saved which is selected by the user. How can I manipulate form data before saving the form and retain manytomanyfield data as it is ? Thanks in advance -
how to make a django rest api like quora?
I am trying to develop a REST API which is a little bit like quora where a user can ask a question and other users can answer. Now the problem I am facing is how do I make that in models, serializers and views? can anyone give me code to start with on how to make this using django rest framework? thanks! -
why am i getting error : while migrations in django
i am not able to migrate this code after makemigrations when I am typing python manage.py migrate ,it is showing me no migration to apply. '''class MyUserManager(BaseUserManager): def create_user(self,email,firstname,lastname,password=None): if not password: raise ValueError("user must have password") if not email: raise ValueError("User must have an email address") user = self.model( email=self.normalize_email(email) ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, date_of_birth, password=None): user = self.create_user( email, password=password, ) user.is_admin = True user.save(using=self._db) return user class MyUser(AbstractBaseUser): email = models.EmailField(max_length=100,default="emaple@exampll.com",unique=True) firstname = models.CharField(max_length=100,default="FirstName") lastname = models.CharField(max_length=100,default="LastName") date_of_birth = models.DateField(default=timezone.now) active = models.BooleanField(default=True) admin = models.BooleanField(default=False) staff = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIERD_FIELDS = [] objects = MyUserManager() def __str__(self): return self.firstname + self.lastname @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active ''' -
how can I run telethon within Django?
i followed this tutorial https://python.gotrained.com/scraping-telegram-group-members-python-telethon/, and the code ran successfully on a single python script. so i decided to implement the same code into django views.py. form.py, html templates and urls.py are properly connected. whenever i runserver and enter details it raises runtime error saying "There is no current event loop in thread 'Thread-1'." views.py import asyncio from django.shortcuts import render,redirect from telethon.sync import TelegramClient from .form import DetailForm,CodeForm from .models import Detail,Code # Create your views here. def home(request): form = DetailForm context = {'form':form} if request.method=='POST': form = DetailForm(request.POST) if form.is_valid(): form.save() details = Detail.objects.all().last() api_id = int(details.api_id) api_hash = details.api_hash phone_number = details.phone_number loop = asyncio.new_event_loop() client = TelegramClient(phone_number, api_id, api_hash, loop=loop) client.connect() if not client.is_user_authorized(): client.send_code_request(phone_number) # global client, phone_number return redirect('code') return render(request, 'teleapp/home.html', context) def codeview(request): code=CodeForm # codemodel = Code.objects.all().last() if request.method == 'POST': codes = CodeForm(request.POST) if codes.is_valid(): codes.save() #what next... return redirect('scrapy') context = {'code':code} return render(request, 'teleapp/code.html', context) def scrappy(request): details = Detail.objects.all().last() context = {'details':details} return render(request, 'teleapp/scrappy.html', context)``` **error raised** Internal Server Error: / Traceback (most recent call last): File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\django\c ore\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\User\PycharmProjects\telegram\venv\lib\site-packages\django\c ore\handlers\base.py", line 115, in _get_response response = … -
Issues with views.py in django to create comments
I want to create a blog where I have posts and comments which are connected to spesific posts. Now I can list my posts and also have a detail view for them and my comments are also appearing under the posts. However it works only if I am creating the comments under the admin site. If I am commenting and click on submit nothing happens. Can you please help me. Here are my files. views.py class PostList(LoginRequiredMixin,generic.CreateView): template_name = 'home.html' form=PostForm model = PostModel fields=['post'] success_url="/home" def form_valid(self, form): form.instance.author=self.request.user return super().form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context ['postmodel_list'] = PostModel.objects.order_by('-created_on') return context class PostDetail(LoginRequiredMixin,ModelFormMixin,generic.DetailView): model = PostModel template_name = 'post_detail.html' form_class=CommentForm def get_context_data(self, **kwargs): context = super(PostDetail,self).get_context_data(**kwargs) context ['commentmodel_list'] = CommentModel.objects.filter(post=self.object).order_by('-created_on') return context def get_success_url(self): return reverse('post_detail',kwargs={'slug':self.object.slug}) def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.instance.post=self.object.post form.instance.author = self.request.user return super(PostDetail,self).form_valid(form) models.py from django.db import models from django.contrib.auth.models import User from django.utils.text import slugify # Create your models here. class PostModel(models.Model): post = models.TextField(max_length=256, unique=True) slug = models.SlugField(max_length=20, unique=True) author = models.ForeignKey(User, on_delete= models.CASCADE,related_name='post_author') created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def save(self, *args, … -
User model in django is not extending to other models
I have created user model using AbstractBaseUser and BaseUserManager. The user model is connected with OneToOneField other three models(Employee, WorkExperience, Eduction). If I create a superuser, the user is extending to all three models. But if I create staffuser or admin user, the user is only extending to Employee model not to other three models. models.py: class UserProfileManager(BaseUserManager): """ Creates and saves a User with the given email and password. """ def create_user(self, email, username, password=None): if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), username=username ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email,username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user def create_superuser(self, email, username, password): user = self.create_user( email, password=password, username=username ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class UserProfile(AbstractBaseUser): """ Creates a customized database table for user """ email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) username = models.CharField(max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['email',] objects = UserProfileManager() def get_full_name(self): # The user is identified by their email address return self.email def get_short_name(self): # The user is identified by their …