Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: Annotate with field from another table (one-to-many)
Good day. I wish to annotate my model with information from a different table. class CompetitionTeam(models.Model): competition_id = models.ForeignKey('Competition', on_delete=models.CASCADE, to_field='id', db_column='competition_id') team_id = models.ForeignKey('Team', on_delete=models.CASCADE, to_field='id', null=True, db_column='team_id') ... class Team(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) teamleader_id = models.ForeignKey('User', on_delete=models.CASCADE, to_field='id', db_column='teamleader_id') ... class Competition(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=30) ... Looping through my competitions, I wish to retrieve the list of competitionteam objects to be displayed with the relevant team's name. I tried: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=...) -where instead of the ellipses I put Subquery expressions in. However, I'm unsure of how to match the team_id variable. eg. *.anotate(name=Subquery(Team.objects.filter(id=competitionteam.team_id)).values('name')) Related is the question: Django annotate field value from another model but I am unsure of how to implement that in this case. In that case, in place of mymodel_id, I used team_id but it only had parameters from the Team object, not my competition team object. I didn't really understand OuterRef but here is my attempt that failed: CompetitionTeam.objects.filter(competition_id=_competition.id).filter(team_id__in=joined_team_ids).annotate(name=Subquery(Team.objects.get(id=OuterRef('team_id')))) "Error: This queryset contains a reference to an outer query and may only be used in a subquery." -
Installation failed of resume-parser 0.6 Package in system
I tried to install this package but it didn't install on my system. Then trying from virtual environment but same things happen. -
Group object has no attribute user_set
I'm using a custom User created with AbstractBaseUser and I tried to add users to a specific group using the django admin. But there were no option to add users to a group. So I found a solution from the stack overflow and It gave me the capability to add users to the group I created. But after saving the user It gives me an error saying Group object has no attribute user_set My User Model class MyAccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("Users must have an email address") 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): user = self.create_user( email=self.normalize_email(email), username=username, password=password, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(verbose_name='email', max_length=80, unique=True) username = models.CharField(max_length=30, unique=True) first_name = models.CharField(max_length=100,null=True) last_name = models.CharField(max_length=100,null=True) phone_no = models.CharField(max_length=12,null=True) date_joined = models.DateField( verbose_name='date joined', auto_now_add=True) last_login = models.DateField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = MyAccountManager() def __str__(self): return self.email def has_perm(self, perm, obj=None): return … -
How Do I Undo Some Bad Architecture In Order To Avoid Circular Import
I have posted the similar question previously due to this circular import issue: ERROR: api.serializers (unittest.loader._FailedTest) ---------------------------------------------------------------------- ImportError: Failed to import test module: api.serializers Traceback (most recent call last): File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 470, in _find_test_path package = self._get_module_from_name(name) File "/usr/local/Cellar/python@3.8/3.8.6/Frameworks/Python.framework/Versions/3.8/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name __import__(name) File "/Users/nick/work/shiftwork_backend/api/serializers/__init__.py", line 1, in <module> from .default import * File "/Users/nick/work/shiftwork_backend/api/serializers/default.py", line 10, in <module> from api import views File "/Users/nick/work/shiftwork_backend/api/views/__init__.py", line 1, in <module> from .base import * File "/Users/nick/work/shiftwork_backend/api/views/base.py", line 10, in <module> from api.serializers import ConfigSerializer ImportError: cannot import name 'ConfigSerializer' from partially initialized module 'api.serializers' (most likely due to a circular import) (/Users/nick/work/shiftwork_backend/api/serializers/__init__.py) And I got some comments. Most of them did not work at the end so I started paying attention to the one that pointed out some architectural flaws, thanks to Klaus D. Look, at the traceback, your import goes: serializers → serializers.default → views → views.base → serializers. You have to break that circle by reorganizing imports or restructuring your code. – Klaus D. So I was trying to figure out how to break this circular import chain. First thing I did was look for some hints online. Such as this: Can't import serializer from other serializer … -
How to remove Extra dots from Django-filters?
I am filtering data using django-filters, but i am getting an extra dots in my dropdown, Please let me know How I can remove that Extra dots from my dropdown filters, I want to give the lable there but I am unable to do that, Please check my code and let me know How I can solve thsi issue. here is my filters.py file... class MyFilter(django_filters.FilterSet): type = django_filters.ChoiceFilter(choices=Data_TYPE, field_name='data_type') class Meta: model = Project fields = ['category', 'type'] here is my test.html file where I am displaying the filters in dropdown... <form method="GET" action=""> <div class="dropdown bootstrap-select hero__form-input form-control custom-select"> {% render_field projectlist.form.category|attr:"type:select" class="hero__form-input form-control custom-select" onchange="this.form.submit()" %} </div> <div class="dropdown bootstrap-select hero__form-input form-control custom-select"> {% render_field projectlist.form.type|attr:"type:select" class="hero__form-input form-control custom-select" onchange="this.form.submit()" %} </div> </form> here is the image, where iwant to remove the dots and i want to replace with filter lable... Plase check this https://prnt.sc/vkif04 -
DRF serializers, different field type
Is it possible to archive such situations using drf serializers, when field can be different type. I'm using such API, and field positions can be both dict or list, depends on content. How the serializer should look like. I've tried something like class PositionCreateSerializer(SapPositionSerializer): positions = serializers.ReadOnlyField(required=False) but it doesn't work -
How do I take a variable from views.py in Django and display it on my HTML page
I'm new to Django and need help with views.py. I'm trying to call on a variable from views.py on my HTML template but have no idea how to do so. The following is my views.py function: def scheduleAlgo(request): givenData=pd.read_csv('~\OneDrive\Desktop\example.csv') df = pd.DataFrame(givenData) df['Mean']=df.mean(axis=1) df = df.sort_values(by="Mean", ascending=False) df.set_index("Subject", inplace = True) firstSubject = df.index[0] secondSubject = df.index[1] thirdSubject = df.index[2] fourthSubject = df.index[3] fifthSubject = df['Mean'].idxmin() if fifthSubject==fourthSubject: fourthSubject=df.index[4] subjectList=[fifthSubject,fourthSubject,thirdSubject,secondSubject,firstSubject] subjectSelection = random.choices(subjectList, weights=(20,18,17,16,15),k=5) return render(request, 'main/testml.html', { 'firstItem': subjectSelection[0], 'secondItem':subjectSelection[1], 'thirdItem':subjectSelection[2], 'fourthItem':subjectSelection[3], 'fifthItem':subjectSelection[4], }) #assigning values for calling in template And this is my HTML code: <table> <tr> <td>{{ firstItem }}</td> </tr> </table> Also, my urls.py: path("testml", views.scheduleAlgo, name="scheduleAlgo"), I'm quite sure the function itself works since I tested it out on an iPython notebook. Essentially, I want to be able to call an index from the list (subjectSelection) and display it in my HTML code. How do I go about doing this? -
Question an about ''django dropbox'' static upload error occur " cStringIO "
I follow as https://pypi.org/project/django-dropbox-storage/; when create model class and set the dropbox error occur in cStringIO; so how to do and upload? Model.py import io from io import StringIO from cStringIO import StringIO from django.db import models from django_dropbox_storage.storage import DropboxStorage store = DropboxStorage() class Brands(models.Model): Brand_Name = models.CharField(max_length=100) photo = models.ImageField(upload_to='photos', storage=store) Error traceback C:\Users\user\Documents\django\go\go\db\models.py changed, reloading. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\users\user\appdata\local\programs\python\python39\lib\threading.py", line 950, in _bootstrap_inner self.run() File "c:\users\user\appdata\local\programs\python\python39\lib\threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\user\Documents\django\go\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\user\Documents\django\go\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\user\Documents\django\go\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\user\Documents\django\go\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\user\Documents\django\go\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "c:\users\user\appdata\local\programs\python\python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in … -
How to save() an argument in a Django Model
I am learning Django, and I decided to simulate an ATM. When I run, my code works, and it says that the deposit to the Card was successful, but it does not save it, the original balance stays the same. Here's what I have: models.py class Card(models.Model): card_number = models.PositiveIntegerField(primary_key=True) #account_number = models.ForeignKey(Account, to_field='account_number',on_delete=models.CASCADE) pin = models.PositiveIntegerField(default=False) card_name = models.CharField(max_length=30) issue_date = models.DateField() exp_date = models.DateField(default=datetime.now() + timedelta(days=1095)) balance = models.PositiveIntegerField() address = models.CharField(max_length=60) phone_number = models.PositiveIntegerField() #card_status = models.CharField(max_length=30, default='Active') def __str__(self): return self.card_name views.py def deposit(request): if request.method == 'POST': user_pin = request.POST.get('Pin') user_card_number = request.POST.get('Your Card Number') # gets user input for card number amount = request.POST.get('Amount') # gets user input for amount # Cash deposit: Validatation - checks if card number and pin exist and verify user's balance if Card.objects.filter(card_number=user_card_number).exists(): # gets user pin,balance, card name based on user's card number input #pin_number = Card.objects.filter(card_number=user_card_number).pin # error if use this user_balance = Card.objects.get(card_number=user_card_number).balance user_card_name = Card.objects.get(card_number=user_card_number).card_name # performs deposit user_balance += int(amount) # updates database in user's card Card.objects.get(card_number=user_card_number).save() messages.success(request, 'Deposit Success! ' + '$'+ amount + ' has been depositted from card: ' + user_card_name) else: messages.error(request, 'Card Number or Pin is incorrect') return render(request, … -
how to use my base.html template in a view for another app in Django?
I'm trying to implement a newsletter in my footer. My footer is stored in my base.html file, the problem is I need to render this template for a view in another app. Here is my code: @csrf_exempt def new(request): if request.method == 'POST': sub = Subscriber(email=request.POST['email'], conf_num=random_digits()) sub.save() message = Mail( from_email=settings.FROM_EMAIL, to_emails=sub.email, subject='Newsletter Confirmation', html_content='Thank you for signing up for the StockBuckets email newsletter! \ Please complete the process by \ <a href="{}/confirm/?email={}&conf_num={}"> clicking here to \ confirm your registration</a>.'.format(request.build_absolute_uri('/confirm/'), sub.email, sub.conf_num)) sg = SendGridAPIClient(settings.SENDGRID_API_KEY) response = sg.send(message) return render(request, 'index.html', {'email': sub.email, 'action': 'added', 'form': SubscriberForm()}) else: return render(request, 'index.html', {'form': SubscriberForm()}) I want to replace both instance of index.html in the return statements from this view, to base.html. How would I go about doing that? -
Django Rest framework filter many to many through model
I had an issue about filtering retrieving data in relation many to many through model. My corresponding models are: class Product(TimeStamp): brand = models.CharField(max_length= 50) attribute = models.ManyToManyField(Attribute, through='ProductAttribute') model_no = models.CharField(max_length=100) def __str__(self): return self.model_no class Attribute(TimeStamp): name = models.CharField(max_length=200) product_type = models.ForeignKey(ProductType, on_delete=models.CASCADE) def __str__(self): return self.name class AttributeValue(TimeStamp): attribute = models.ForeignKey(Attribute, on_delete=models.CASCADE) value = models.CharField(max_length=200) def __str__(self): return self.value My serializers are: class ProductAttributeSerializer(serializers.ModelSerializer): name = serializers.CharField(source='attribute.name', read_only=True) class Meta: model = ProductAttribute fields = ['name', 'value', ] class ProductSerializer(CreatorUpdatorSerializer): attribute = serializers.SerializerMethodField(read_only=True) class Meta: model = Product fields = ['id', 'model_no', 'attribute'] def get_attribute(self, obj): data = obj.productattribute_set serializer_data = ProductAttributeSerializer(data, many=True) return serializer_data.data My viewset is: class ProductViewSet(CreatorUpdatorViewSet): http_method_names = ('get',) serializer_class = ProductSerializer queryset = Product.objects.all() filter_backends = [DjangoFilterBackend, ] filterset_fields = ['attribute__ame', 'attribute__value'] Now I ant to filter products with attribute and their correspponding values like color:red But I'm getting this error: TypeError at /api/product/ 'Meta.fields' must not contain non-model field names: attribute__value What should I do? -
Django Rest Framework: Page Not Found 404 Error while displaying an image
I am trying to use images in my api using django rest framework but I am still getting the error 404 Page not found. Here's my code - Models.py class SampleModel(models.Model): text = models.CharField(max_length=100, null=True, blank=True) image = models.ImageField(upload_to='images/', null=True, blank=True) serializers.py class SampleSerializer(serializers.ModelSerializer): image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = SampleModel fields = ['text', 'image'] views.py class SampleView(generics.ListAPIView, generics.CreateAPIView): queryset = SampleModel.objects.all() serializer_class = SampleSerializer urls.py urlpatterns = [path('sample/', SampleView.as_view(), name='sample')] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "assets") MEDIA_URL = '/assets/' I tried googling the solution on google and tried few things too but I still get the same error. I tried to create another project and used the same code as above and it is still giving me the same error. -
is it a better idea to learn Django through a 4 years old tutorial
Recently i have finished a python course now want to learn Django, By searching a bit, I got a 'django tutorial' on the you tube channel 'thenewboston' and i just love the way bucky(you tuber) explaining everything, but the problem is this tutorial is approximate 4 years old, so is it a better idea to go throught it and learn programming stuff ? -
Allowing user to Submit form once in Django
i want that user can submit a particular form only once. Is it possible without any js,react.. actually by using django only ?? i have tried something like that -- def apply(request): p=0 if request.method=="POST": p=1 ...do something.. else: ...do something... i have tried to catch the value of p=1, and try to not return the html is it's submitted once , but each time reload makes the value of p=0. i have to save the session ?? or what will be the right way to do this ? can anyone suggest anything please? -
How do I activate python virtual environment from a different repo?
So am working in a group project, we are using python and of the code is on GitHub. My question is how do I activate the virtual environment? Do I make one on my own using the "python virtual -m venv env" or the one that's on the repo, if there is such a thing. Thanks -
Running django app on http/2 or http/2 protocol instead of http/1
Our website is developed using Django 2.1 and it is serving on http/1 protocol, We have set up it on shared Cpanel hosting, So Cpanel gives a graphical interface to handle it. Is there any way, we can switch protocol programmatically or any other ways to do this? Please advice, Thanks -
Django - How to parse result of query from timestamp into format ('%Y-%m-%dT%H:%M:%SZ')
This is my code: now= datetime.now() rts_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') query = FlightSchedule.objects.filter(departure_time__gt = rts_time) I got this result: 'flight_number': 'VJ141', 'departure_time': datetime.datetime(2020, 11, 17, 13, 10), I want it like this 'flight_number': 'VJ141', "departure_time":"2020-11-17 13:10:00+07:00" Currently, using PostgreSQL database: My models: class FlightSchedule(models.Model): .... departure_time = models.DateTimeField(blank=True, null=True) .... class Meta: managed = False db_table = 'flight_schedule' -
Django - my database include " / " so when return it got parsed (changed) into something else
My data base with ID like this: ID : "y8sh7ZQhk\u00a5Ig08R7pzA8bpei2gUa8n69132NmTXb\u00a5lk=" When I do query: Database.objects.filter It returns something like this ID: 'y8sh7ZQhk¥Ig08R7pzA8bpei2gUa8n69132NmTXb¥lk=' My models: ID = models.CharField(primary_key=True, max_length=200) -
Append html code with variables using jquery / javascript
I am having trouble generating html code from jqavascript/jquery in a html template rendered in django. I have to append html code and also insert some values in between. Right now I am doing a crude string append like this var features =['a','b'] for (var i=0;i<features.length;i++){ var html_code = "<div class = 'feature' <h2>"+features[i]+"</div> $("#features").append(html_code) } For html code <div id="features"></div> What is the right and cleanest way to do this. I know templating is the way to go but there seem to be so many different ways - inline javascript, external library like mustache,handlebar, using django's own template solution - it's very confusing -
Problem deploying certain button if current user is in group userList (django)
In one of my templates in django I'm attempting to have a certain button displayed if the current user is in a certain group or not. If the user is in a group the button "unjoin" should dispay, if they are in a group, "Join" button displays. I start by creating isUser and setting it to false. Then I have a for statement which grabs all the groups from the database, and for each group a grab the userlist of that group and check if that user is equal to the current user. If the user from the userList is equal to the current user, I set isUser="true". Once that is done I have an if statement that will deploy the Unjoin button if isUser is equal to true, or it will deploy the Join button if isUser is false. As of right no buttons are being deployed, whether the user is in a groups userList or not. I'm not sure what is going wrong, but I think that the issue is in the if-comparisons? Any thoughts and ideas appreciated! {% with isUser="false" %} {% endwith %} {% for users in allgroups.userList.all %} {% if users.user == user %} {% … -
Browsable Django REST API wrapper for external API calls
I'm building a RESTful interface to a Django project, and I need to leverage external APIs to allow the client and frontend to reference just the one Django API without needing the details of the external APIs. Therefore, I want the external API data to be returned to the browsable API pages as I would my own view-based API. How do I serialize a JSON response from an external API to the browsable API web-page renderer? For example, I want mysite.fake/thing/details to return the same JSON that is returned by externalapi.fake/thing/details, which looks like: {"thing_id": "900404", "description": "Thing description", "value": "100.00", "location": "Bin 401"} And have that show up in the browsable API for DRF. Currently, I'm using: @api_view(('GET',)) @renderer_classes((JSONRenderer,)) def thing_finder(request, thing_id): """ Get the current location for a thing http://localhost:8000/thing/find/9900404 :param request: HTTP Request object :param thing_id: String - the thing ID :return: JSON - The Thing location JSON """ a, b = THING_API_AUTH if request.method == 'GET': payload = {'thing_id': thing_id} r = requests.get(THING_API_AUTH, auth=HTTPBasicAuth(a, b), params=payload) if r.status_code == 200: data = json.loads(r.text) serializer = ThingFinderSerializer(data) return Response(serializer.data, status=status.HTTP_200_OK) else: return Response({"error": "Request failed"}, status=r.status_code) This works (I think), but it doesn't format the results to … -
When do django AUTHENTICATION_CLASSES run with respect to Middleware
I see there is a django.contrib.auth.middleware.AuthenticationMiddleware but reading the documentation I don't think it determines when auth is actually auth is run. Does auth happen before or after middleware? Can that ordering be changed? -
Django Rest Framework Method returns Object of type User is not JSON serializable
So basically I have a django method that I pass into my serializer but it returns the error Object of type User is not JSON serializable Here are my files: models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): first_name = models.CharField(max_length=50, blank=True) last_name = models.CharField(max_length=50, blank=True) user = models.OneToOneField(User, on_delete=models.CASCADE) friends = models.ManyToManyField(User, blank=True, related_name='friends') def friends_list(self): return self.friends.all() def number_of_friends(self): return self.friends.all().count() serialzers.py: from rest_framework import serializers from .models import Profile class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = [ 'id', 'first_name', 'last_name', 'user', 'friends', 'number_of_friends', 'friends_list' ] The issue comes with the "friends_list" method as the "number_of_friends" method works perfectly as intended. The entire model fields are working its just that one method that won't work. How can I resolve this? -
After create a normal user in admin page of a Django website, I could not login using that normal user
I use Django 2.2.6 in python 3.7 in windows 10. After I create a normal user in the admin page in dev mode(127.0.0.0:8000/admin), when I tried to login at front end(127.0.0.0), the normal user I just create could not login. I have tried even the simplest password, but still failed. admin.py: from django.contrib import admin from django.contrib.auth import forms from .models import * from django.contrib.auth.models import Permission # admin.site.register(Carpark) => fired bunch of queries, below to mitigate problems @admin.register(Permission) class PermissionAdmin(admin.ModelAdmin): def get_queryset(self, request): qs = super().get_queryset(request) return qs.select_related('content_type') # Register your models here. admin.site.register(Carpark) admin.site.register(User) # @admin.register(User) # class UserAdmin(admin.ModelAdmin): # form = forms.UserChangeForm @admin.register(Discipline) class DisciplineAdmin(admin.ModelAdmin): list_display = ('code', 'name', 'person', 'person2', 'carpark') @admin.register(CourseInfo) class CourseAdmin(admin.ModelAdmin): list_display = ('code', 'title', 'type', 'carpark', 'discipline', 'person', 'pattern', 'available') def hop(self, obj): return obj.discipline.hop1 if obj.discipline else "-" hop.admin_order_field = 'discipline__person' admin.site.register(Publisher) admin.site.register(Title) admin.site.register(Material) When I tried to debug, the front end form throws an error(form.error): __all__ Please enter a correct username and password. Note that both fields may be case-sensitive. -
I am trying to use my existing login page for my django application for wagtail, butI am still seeing the default wagtail login form
I am using wagtail 2.9.1. I have added the following lines of code to my base.py configuration file. WAGTAIL_FRONTEND_LOGIN_TEMPLATE = 'my_app_name/templates/account/login.html' and WAGTAIL_FRONTEND_LOGIN_URL = '/accounts/login/' I have also tried WAGTAIL_FRONTEND_LOGIN_URL = LOGIN_URL I am still seeing the default wagtail login form when I try and login to the cms. This is the documentation I am triyng to follow. Am I missing something?