Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LEFT JOIN on two Django Querysets
I've been searching SO and Google for two days now and haven't found a solution to my specific problem. I have a SQL query that I am trying to convert into Django ORM (if even possible). In SQL, the query looks something like this: SELECT * FROM( SELECT max(effective_date) AS effective_date, floorplan_id FROM floorplan_counts GROUP BY floorplan_id) s1 LEFT JOIN ( SELECT floorplan_id AS fc_floorplan_id, units AS fc_units, beds AS fc_beds, expirations AS fc_expirations, effective_date FROM floorplan_counts) s2 ON s1.floorplan_id = s2.fc_floorplan_id ) I am able to use Django ORM to generate subqueries s1 and s2: s1 = FloorplanCount.objects.values('floorplan_id').annotate(effective_date=Max('effective_date') s2 = FloorplanCount.objects.values('effective_date').annotate( fc_floorplan_id=F('floorplan_id'), fc_units=F('units'), fc_beds=F('beds'), fc_expirations=F('expirations')) Currently, the solution I have in place is using Django .raw(), but would like to use Django ORM. Also would like to not use .extra() since documentations says it will be deprecated in the future. How can I left join s1 to s2? -
Find odd and even and both values
It takes an input n and outputs the numbers from 1 to n. For each multiple of 3, print "Hello" instead of the number. For each multiple of 5, prints "World" instead of the number. For numbers which are multiples of both 3 and 5, output "HelloWorld". -
django-import-export - Export one to many relationship with ForeignKeyWidget - returns an empty Field
I am trying to use the dajngo-import-export package to export data from two tables with a one to many relationship. I have a custom ForeignKeyWidget class that overrides the get_queryset method. The problem is that the export returns an empty field - no errors, just an empty field. I also tried just using the ForeignKeyWidget without the custom class/get_queryset - but I get the same result. Does anyone see what I'm doing wrong here? #admin.py from import_export import resources from import_export.fields import Field from import_export.widgets import ForeignKeyWidget class SlateDocResource(resources.ModelResource): actbreaks = Field( column_name="actbreaks", attribute="id", widget=ActBreaksForeignKeyWidget(ActTimecodes, "slatedoc_id"), ) class Meta: model = SlateDoc fields = [ "actbreaks", ] class ActBreaksForeignKeyWidget(ForeignKeyWidget): def get_queryset(self, value, row, *args, **kwargs): qs = ActTimecodes.objects.filter(slatedoc_id=self.pk) print(qs.values()) return qs #models.py class SlateDoc(models.Model): #primary Model - fields not listed here. class ActTimecodes(models.Model): #Secondary model - every slatedoc can has multiple instances of ActTimecodes slatedoc = models.ForeignKey( SlateDoc, on_delete=models.CASCADE, related_name="acts" ) act_number = models.IntegerField(verbose_name="Act", default=1) tc_in = models.CharField(max_length=11, default="00:00:00:00") tc_out = models.CharField(max_length=11, default="00:00:00:00") dur = models.CharField(max_length=11, default="00:00:00:00") objects = ActTimecodesQuerySet.as_manager() class Meta: ordering = ["act_number", "tc_in", "tc_out"] #version info "python_version": { "version": ==3.10" } "django": { "version": "==4.1.1" }, "django-import-export": { "version": "==2.8.0"}, -
Gunicorn Nginx Django static files
I've been digging through articles and posts about this subject but can't seem to get my images to load. For some reason the CSS on my pages seems to load just fine. DJANGO settings.py file BASE_DIR = Path(__file__).resolve().parent.parent STATIC_URL = '/static/' I've tried: STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_ROOT = '/var/www/myname/' HTML Page <img src="{% static 'picture.jpg' %}" class="img-fluid"> NGINX /etc/nginx/sites-enabled/django_project server { listen 80; server_name mywebsite.com; location /static/ { alias /var/www/myname/static/; } } DIR TREES /var/www/myname └── static └── admin ├── css │ ├── styles1.css │ └── styles2.css ├── images │ ├── picture.jpg │ └── python.jpg └── js └── scripts.js /home/myname/myprojectdir ├── django_project │ ├── django_project │ │ └── __pycache__ │ ├── etc │ ├── index │ │ ├── migrations │ │ │ └── __pycache__ │ │ ├── __pycache__ │ │ └── templates │ │ └── index │ │ └── backups │ ├── __pycache__ │ └── static │ ├── admin │ │ ├── css │ │ │ └── vendor │ │ │ └── select2 │ │ ├── fonts │ │ ├── images │ │ │ └── gis │ │ ├── img │ │ │ └── gis │ │ └── js │ │ ├── admin │ │ └── vendor │ │ … -
Publishing on heroku
I uploaded my website, created in the django library, to heroku using this guide - https://habr.com/ru/post/523308 /. And when I go into my application, I see the inscription "Application error or There's nothing here, yet". I am a beginner and for the first time I upload a website to hosting and admit that I have not seen or done something, please help. For convenience, I uploaded the code to this repository - https://github.com/krutpik/help enter image description here Here is the error that appears when running in the console - at=error code=H10 desc="App crashed" method=GET path="/" host=serene-journey-43437.herokuapp.com request_i d=f44421b6-9192-423c-9710-72cbedfdd348 fwd="87.117.61.239" dyno= connect= service= status=503 bytes= protocol=https – -
How to reference an object in a class using a decorator
I have a list of dicts defined in setUpClass in a Django TestCase: class MyTest(TestCase): @classmethod def setUpClass(cls): myobj = MyModel.objects.create() MY_LIST = [ ({ 'key1': {'a': myobj.id, 'b': 2}},), ({ 'key2': {'a': myobj.id, 'b': 2}},), ] How do I reference MY_LIST using parameterized? E.g. @parameterized.expand(MyTest().setUpClass().MYLIST): def test_mytest(self, dict_item): print(dict_item.items()) Results in AttributeError: 'NoneType' object has no attribute 'MYLIST'. -
adding info in django many-to-many table
I created many-to-many connection in models.py between two tables and the third one appeared. I've stuck into the problem that i dont know how to add some info to this table. I've been trying to import this table in shell mode but i dont know how to do it. For instance, to change table based on class 'User' i wrote: from club.models import User new = User(name='Maksym') new.save() So i'm interested in how to add some info in the table 'club_event1_users', i have attached screenshots -
In the views.py when we insert models or forms why we don't use "from . import models" instead of "from .models import Model1,Model2?
we import views in urls.py urls.py from django.urls import path from . import views urlpatterns = [ path('',views.index,name='index'), path('posts',views.all_posts,name='all'), path('posts/<slug:slug>',views.post_details,name='post_details') ] in views.py models and forms are imported like views.py from django.shortcuts import render from .models import Post,Author,Tag,Comment from .forms import CommentForm def index(request): posts = Post.objects.all() print(posts) return render (request,'mblog/index.html',{'all_posts': posts}) def all_posts(request): posts = Post.objects.all() return render (request,'mblog/all-posts.html',{'all_posts': posts}) -
Creating an Image with Foreign Key to model instance does not return Image URL in serializer.data
I have two models that are connected through a foreign key. An article can have 0, 1 or many images. Both height_field and width_field are autocalculated. is_title_image is set in the POST request. class Article(models.Model): slug = models.SlugField(null=True, default=None, unique=True, max_length=255) heading = models.CharField(max_length=2550) summary = models.CharField(max_length=25500) class Image1(models.Model): height_field=models.PositiveIntegerField(default=0) width_field=models.PositiveIntegerField(default=0) file = models.ImageField(storage=PublicMediaStorage(), height_field='height_field', width_field='width_field') is_title_image = models.BooleanField(default=False) article = models.ForeignKey(Article, related_name='images', null=True, on_delete=models.DO_NOTHING) First I create the article in the DraggableArticleSerializer and use the pk to create the images. Here I am not sure, if this is the optimal way. I use the ImageSerializer to receive all fields from the image instance. Article and image are both being created correctly in the db. But I am not able to use that data in the views.py in order to return it to the frontend. The images property is empty in serializer.data, and serializer.validated_data just returns the input InMemoryUploadedFile: serializer.validated_data['images'][0]['file'] returns OrderedDict([('file', <InMemoryUploadedFile: husky4.jpg (image/jpeg)>), ('is_title_image', True)]) I dont know how my view should be changed from the regular CreateAPIView. Do I have to give some extra data to serializer.save() or is my problem located somewhere else. class DraggableArticleSerializer(serializers.ModelSerializer): images = ImageSerializer(many=True, required=False) class Meta: model = Article fields = … -
Paginator works slow
I work with large database (over 23,000,000 records) and find out that Django Paginator works too slow. So basically is it a problem with database (perhaps, we should do some optimizations in db) or Django Paginator is a bad solution in this case? -
Find annotated list of siblings in Django
I have a simple database with two models that define a parent-child relationship. In it, a child can have two possible gender, "Male" or "Female". class Parent(models.Model): id = models.UUIDField(primary_key=True, editable=False, unique=True, ) name = models.CharField(max_length=64) MALE = "MALE" FEMALE = "FEMALE" class Child(models.Model): id = models.UUIDField(primary_key=True, editable=False, unique=True, ) name = models.CharField(max_length=64) parent = models.ForeignKey( Parent, null=True, on_delete=models.SET_NULL) GENDER = [ (MALE, 'Male'), (FEMALE, 'Female'), ] status = models.CharField( max_length=8, choices=GENDER ) For the purposes of this question, a parent will only ever have zero or one male children, and zero or one female children. (Though this is not enforced in the database model definition.) What I would like to achieve is an annoted query, that returns all Parent objects, annoted with their male child and female child. I can't quite figure out how to produce this: I can get a list of all parents, all male and all female children, but I don't know how to put them together so that the right children are with the right parent. This is far as I get: annotated_parent_set = Parent.objects.get_queryset() brothers = Child.objects.filter(gender=MALE) sisters = Child.objects.filter(gender=FEMALE) annotated_parent_set = annotated_parent_set.annotate( brother=F(???)) ) annotated_parent_set = annotated_parent_set.annotate( sister=F(???)) ) How can I now … -
Django,update the same row field in model getting data from serializer
I have this model: class AgentDetail(MethodID): first_name = models.CharField(max_length=50, blank=True, null=True, unique=True) last_name = models.CharField(max_length=50, unique=True, null=True) email = models.EmailField(null=False) authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE) country_code = models.BigIntegerField(default=1) mobile_number = models.BigIntegerField(null=False) sms_provider = models.CharField(max_length=50, null=True) active_status = models.BooleanField(default=True) created_time = models.DateTimeField(default=now, editable=False) created_by = models.CharField(max_length=50) updated_time = models.DateTimeField(auto_now=True) updated_by = models.CharField(max_length=50) and this serializer: class AgentSerializer(serializers.ModelSerializer): class Meta: model = AgentDetail fields = [ "first_name", "last_name", "email", "authen_method", "mobile_number", "sms_provider", ] and this views.py: @api_view(["POST"]) def create_agent(request): if request.method == "POST": serializer = AgentSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() request_data = serializer.data # AgentDetail.objects.update_or_create( # created_by=request_data["first_name"] + request_data["last_name"], # updated_by=request_data["first_name"] + request_data["last_name"], # ) return Response(status=status.HTTP_200_OK) error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return error As in serializer I'm not passing created_by field and I need that field gets value of first_name+last_name which are coming from serializer data.I'm new to DRF. -
React Native (expo) + Django JWT axios error
Trying to make Login Screen. Using axios to get data from Django JWT url('http://127.0.0.1:8000'). Tried to find url works from Postman and also from terminal and both worked, but I got AxiosError from simulator. Does anyone know why my base url not work on React Native App? I tried 'http://localhost:3000/' and 'http://10.0.2.2:8000'too but not worked. This is my Codes... LoginScreen.js const LogInScreen = () => { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const handleSubmit = (e) => { e.preventDefault(); const config = { headers: { "Content-Type": "application/json", }, }; const body = JSON.stringify({ email, password }); axios .post("http://127.0.0.1:8000/api/token/", body, config, console.log(body)) .then((res) => { console.log("token"); AsyncStorage.setItem("access_token", res.data.access); AsyncStorage.setItem("refresh_token", res.data.refresh); axiosInstance.defaults.headers["Authorization"] = "JWT " + AsyncStorage.getItem("access_token"); navigate("Home"); console.log(res); console.log(res.data); }) .catch((error) => console.log("error", error)); }; console.log(body) showed up {"email":"test@mail.com","password":"Test1234"} console.log('token') not showed up, and 'error' part pop up. Django urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from rest_framework_simplejwt.views import ( TokenObtainPairView, TokenRefreshView, ) urlpatterns = [ path('admin/', admin.site.urls), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/user/', include('api_user.urls')), path('api/flashcard/', include('api_card.urls')), ] settings.py ALLOWED_HOSTS = ["*"] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'corsheaders', # … -
How can one display contents of a database to a template from a non Django project
I am working on a Django project to display data from an existing database. The database was created by PHP language. How should I get the models into the views to pass the context into the template? Kindly note, that the database already exists hence I haven't created any models in the models.py file. Therefore no migrations have been made. -
django render project information from linked site
project site in my Django-project with a link which links to conversation. Is it possible to render out project-information like project.category from single-project.html in the url conversation. single-project.html <div> <span> <small>{{project.category}}</small> </span> </div> <div> <a href="{% url 'conversation' project.owner.user %}">Send message</a> </div> -
How to convert different rss feed dates with Python so they can be ordered
Trying to make an RSS feed reader using django, feedparser and dateutil Getting this error: can't compare offset-naive and offset-aware datetimes I just have five feeds right now. These are the datetimes from the feeds.. Sat, 10 Sep 2022 23:08:59 -0400 Sun, 11 Sep 2022 04:08:30 +0000 Sun, 11 Sep 2022 13:12:18 +0000 2022-09-10T01:01:16+00:00 Sat, 17 Sep 2022 11:27:15 EDT I was able to order the first four feeds and then I got the error when I added the last one. ## create a list of lists - each inner list holds entries from a feed parsed_feeds = [feedparser.parse(url)['entries'] for url in feed_urls] ## put all entries in one list parsed_feeds2 = [item for feed in parsed_feeds for item in feed] ## sort entries by date parsed_feeds2.sort(key=lambda x: dateutil.parser.parse(x['published']), reverse=True) How can I make all the datetimes from the feeds the same so they can be ordered? -
from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django'
S C:\Users\pande\anaconda3\WebApp> python.exe .\manage.py runserver Traceback (most recent call last): File ".\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception:Traceback (most recent call last):File ".\manage.py", line 22, in main() File ".\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? my manage.py is: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'WebApp.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() -
Is it possible to implement Django-allauth using Apache Cassandra as default database
Explanation: I know Apache Cassandra is a NoSQL database and I have been figuring a way out to use this. However when I run sync-db command, it doesn't create tables in the database. Django-allauth works fine in a RDBMS but not working in Cassandra. Before anyone downvote this question, I want to tell that I have done proper research but I couldn't find a single post on the internet regarding this. So if anyone can help, it would be highly appreciated. Also here is a link for this issue opened on GitHub by someone. -
Django UnboundLocalError: local variable 'tags' referenced before assignment
Why do I face this problem? I am trying to get the tags from the Post table.Post and tags are two tables with Many to Many relation. in models.py class Tag(models.Model): caption = models.CharField(max_length=40) class Post(models.Model): tags = models.ManyToManyField(Tag) in views def post_details(request,slug): post = Post.objects.get(slug=slug) tags = Post.objects.filter(tags) comment = post.comments.all() return render (request,'mblog/post_detail.html',{'post': post ,'tags': tags,'comment': comment}) -
AttributeError: 'User' object has no attribute 'user' while trying to verify user's email
I have django web app with authentication and email verification. I have two options of authentication. One is authenticating with Customer or with Employee. I have User(AbstractUser) to connect them both. models.py from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) signup_confirmation = models.BooleanField(default=False) class Customer(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20) location = models.CharField(max_length=20) class Employee(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) phone_number = models.CharField(max_length=20) designation = models.CharField(max_length=20) views ...employee_register... class customer_register(CreateView): model = User form_class = CustomerSignUpForm template_name = '../templates/customer_register.html' def form_valid(self, form): user = form.save() # current_site = get_current_site(request) current_site = '127.0.0.1:8000' subject = 'Please Activate Your Account' message = render_to_string('activation_request.html', { 'user': user, 'domain': current_site, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail( subject, message, 'from@example.com', ['to@example.com'], fail_silently=False, ) # login(self.request, user) return redirect('/') def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.user.signup_confirmation = True user.save() login(request, user) return redirect('index') else: return render(request, 'activation_invalid.html') In my views first I have class which is triggered … -
how to allow throttle only if the response was successful
I'm trying to make throttling on OTP authentication so user can only send one message every minute class BurstRateThrottle(AnonRateThrottle, UserRateThrottle): scope = 'burst' REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',), 'DEFAULT_THROTTLE_CLASSES': [ 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ], 'DEFAULT_THROTTLE_RATES': { 'burst': '1/min', 'anon': '200/min', 'user': '250/min', }, @api_view(['POST']) @permission_classes([AllowAny]) @throttle_classes([BurstRateThrottle]) def login_send_token(request): ... The problem with this is that the api gets throttled even when the phone number is wrong so I'm trying to only throttle when the OTP message is send or when the response is 200 or 201 is there anyway to access the response status code in allow_request method? or to manually execute the throttle from the function that call twilio api? -
In django,Use one field from one model in other model
I'm trying to use auth_method field from MethoID model in AgentDetails Model.But when I enter the value of primary key id in serializer for authen_method it is not being validated. Models: class MethodID(models.Model): auth_method = models.CharField(max_length=50, default="Google") def __str__(self): return self.auth_method class AgentDetail(MethodID): authen_method = models.ForeignKey(AuthMethodID, on_delete=models.CASCADE) Serializer: class AgentSerializer(serializers.ModelSerializer): class Meta: model = AgentDetail fields = [ "authen_method", ] and in views I use POST request. Views: @api_view(["POST"]) def create_agent(request): if request.method == "POST": serializer = AgentSerializer(data=request.data, many=False) if serializer.is_valid(): serializer.save() return Response(status=status.HTTP_200_OK) error = Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return error -
I want to make my site can be accessed only through redirect from paypal django
I want to make my site can be accessed only through redirect from paypal in django and cannot be accessed through url i tried if request.META.get('HTTP_REFERER') == 'paypal' but not work because it returns none value i'm using ajax is there any working alternative that i can use please help me. -
Django: Select count of foreign key field
I have the following models: class System(models.Model): # ... class Page(models.Model): # ... system = models.ForeignKey(System) I want to perform the following SQL query: select s.*, (select count(*) from page p where p.system_id = s.id) as NUM_OF_PAGES from system s; How do I perform the above query with Django's ORM without having to use a for loop? I do not want a result based on one system, I want to retrieve all systems with their page counts. -
I want to have a user select multiple events from another table in django. How do i achieve it?
I am making a Django project. I want that my users table field should automatically update when they register for an event. I Have used ForeignKey in my Events model to achieve this. But the problem here is, I can select only 1 user in the events model when creating a new event or editing it(since the relationship is manyToOne). What I want is my events model should show every user that has registered for that event (Something like this). Am I using the right relationship? If Not, what should be the correct relationship that I should use? I am attaching my models for Users and Events. Kindly Look it through. accounts/models.py class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(db_index=True, unique=True, max_length=254) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255, null=True, blank=True) mobile = models.CharField(max_length=50, null=True, blank=True) address = models.CharField(max_length=200, null=True, blank=True) short_description = models.CharField(max_length=180, null=True, blank=True) instagram_url = models.URLField(null=True, blank=True) linkedin_url = models.URLField(null=True, blank=True) # is_member = models.BooleanField(default=False) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name'] class Meta: verbose_name = 'User' verbose_name_plural = 'Users' models.py class Event(models.Model): banner_image = models.ImageField(upload_to="Events/", max_length=400) event_name = models.CharField(max_length=150, null=False) organiser_of_event = models.CharField(max_length=200) format_of_event = models.CharField(max_length=300, null=True, blank=True) …