Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fetch date and gender field from Django model for updating purpose I tried following code
models.py from django.db import models class All_Patients(models.Model): CATEGORY_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=200, choices=CATEGORY_CHOICES) date = models.DateField() views.py def edit_patient(request, id): patient = All_Patients.objects.get(id=id) print(patient) return render(request, 'editnew.html', {'patient': patient}) editnew.html Male Female <div class="form-group col-md-3"> <input type="date" value="{{patient.date}}" class="form-control" id="inputDate4" name="Date" required> </div> -
Accordion in django include template
**Hi,i am using include django template to get another template into main.html. here is the line of code that i used to get appendix.html. ** {% include "appendix.html" %} After i use this line of code, my accordion doesn't work. any idea on how to fix this? here are my full code for main.html {% extends 'adminlte/barebase.html' %} {% load crispy_forms_tags %} {% block content %} <style type="text/css"> [data-toggle="collapse"]:after { -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; content: '\f107'; font-family: 'Font Awesome\ 5 Free'; font-weight: 900; /* Fix version 5.0.9 */ transform: rotate(180deg) ; transition: all linear 0.25s; float: right; } [data-toggle="collapse"].collapsed:after { transform: rotate(0deg) ; } </style> <div class="card"> <div class="" style="width:20%,height:20%"> <div id="accordion" class="card-body" style="width:20%,height:20%"> <div class="title-section m-3"> <h5 style="display:inline-block;" class="title-section">Client Information</h5> <a data-toggle="collapse" href="#collapseOne" aria-expanded="true"></a> <hr> </div> <content> <div id="collapseOne" class="row m-2 collapse show" role="tabpanel" aria-labelledby="headingOne"> <div class="col-lg-3"> <label>{{form.ClientName|as_crispy_field}}</label> </div> <div class="col-lg-3"> <label>{{form.TaxRef|as_crispy_field}}</label> </div> <div class="col-lg-3"> <label>{{ form.Period_Employement|as_crispy_field }}</label> </div> <div class="col-lg-3"> <label> {{ form.Basis_Period|as_crispy_field }}</label> </div> </div> </content> <div class="title-section mt-4 m-3"> <h5 style="display:inline-block;" class="title-section">Testing</h5> <a data-toggle="collapse" href="#collapseTwo" aria-expanded="true"></a> <hr> </div> <content> {% include "appendix.html" %} </content> </div> </div> </div> {% block content %} -
Django Custom User Model add property
My model is relatively simple, but I want users to be member of a club. Superusers are not members of a club. I decided to use a Custom User Model Extending AbstractBaseUser and created the models, managers and everything works fine. Now I want to extend the model by a property. models.py: from .managers import MyUserManager class K2User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) date_joined = models.DateTimeField(_('date joined'), auto_now_add=True) is_active = models.BooleanField(_('active'), default=True) is_staff = models.BooleanField(_('active'), default=True) # club_name = models.ForeignKey(Clubs, null=True, objects = MyUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] def get_club_name(self): return self.club_name def __str__(self): return self.email class Clubs(models.Model): club_name = models.CharField(max_length=32, unique=True) club_create_date = models.DateTimeField('date created') club_address = models.CharField(max_length=200) email = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, verbose_name=_('user'), on_delete=models.CASCADE) managers.py from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class MyUserManager(BaseUserManager): use_in_migrations = True def _create_user(self, email, password, **extra_fields): if not email: raise ValueError('The given email must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) # club_name = club_name user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password=None, **extra_fields): extra_fields.setdefault('is_superuser', False) extra_fields.setdefault('is_staff', False) return self._create_user(email, password, **extra_fields) def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_staff', True) if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') if extra_fields.get('is_staff') is not … -
Docker for deploying djano application
I have seen some pages with title deploy django with docker . I deploy just with nginx & gunicorn and its awesome . Is docker good for deploying django app ? Does it make application faster or with better performance ? So whats the main purpose ? -
Authorization in Graphene Django
I am creating an API using Django and GraphQL (graphene django). To authenticate users, I use JWT (https://django-graphql-jwt.domake.io/en/latest/). Next, I am also using Relay. Now, what is the best way to handle permissions in queries and mutations? Let's say I have two models (Products and Transactions). Regular users can do both queries and mutations on products. Transactions however should be restricted and only be accessible by admins/staff. On the Graphene Django web pages (https://docs.graphene-python.org/projects/django/en/latest/authorization/) they (amongst others) discuss the following two options: def get_queryset(cls, queryset, info) - Is it OK to check for authorization here (by using: if info.context.user.is_anonymous: raise GraphQLError('You do not have permission to access this information') return queryset )? And for mutations, we could do a similar thing in mutate_and_get_payload. use the LoginRequiredMixin - This blocks off the whole API. I only want to block of parts of the API. -
Passing Context into django-wagtail base.html
i know there is a way to inject context into base.html using the context processors methodology. However , since i am using wagtail , i wish to know if there is a way that wagtail can handle this. The scenario is that im trying to inject context from my HomePage model, into the navigation bar and footer that resides in my base.html. -
How to use ebay sdk in django? How to add items using ebay trading api in django?
i want to know how to use ebay sdk in django, i downloaded and installed ebaysdk but getting error as:- ConnectionConfigError at /add_item/ 'config file ../ebay/ebay.yaml not found. Set config_file=None for use without YAML config.' 'add_item' is the function in views.py, called when button addItem button is clicked. def add_item(request): api = Connection(config_file="../ebay/ebay.yaml", domain="api.sandbox.ebay.com", debug=True) request = { "Item": { "Title": "Professional Mechanical Keyboard", "Country": "US", "Location": "IT", "Site": "US", "ConditionID": "1000", "PaymentMethods": "PayPal", "PayPalEmailAddress": "nobody@gmail.com", "PrimaryCategory": {"CategoryID": "33963"}, "Description": "A really nice mechanical keyboard!", "ListingDuration": "Days_10", "StartPrice": "150", "Currency": "USD", "ReturnPolicy": { "ReturnsAcceptedOption": "ReturnsAccepted", "RefundOption": "MoneyBack", "ReturnsWithinOption": "Days_30", "Description": "If you are not satisfied, return the keyboard.", "ShippingCostPaidByOption": "Buyer" }, "ShippingDetails": { "ShippingServiceOptions": { "FreeShipping": "True", "ShippingService": "USPSMedia" } }, "DispatchTimeMax": "3" } } api.execute("AddItem", request) -
Retrieve data related to one table from other table without a relation
I have two models user and recordings, But I don't have any relation between them I have stored user id in recordings (there can be multiple recordings of one user). and I want the latest recording of user with user object how can I achieve that -
Django call function on object return value to phrase on template
I have this model: class Church(models.Model): # The Category table name that inherits models.Model name = models.TextField() #Like a varchar logo = models.TextField(blank=True) #Like a varchar class Event(models.Model): # The Category table name that inherits models.Model name = models.TextField(blank=True) #Like a varchar desc = models.TextField(blank=True) #Like a varchar address = models.TextField(blank=True) date = models.DateField(default=timezone.now) reservation_date = models.DateField() event_participant = models.IntegerField(blank=False,default=0) church_id = models.ForeignKey(Church, on_delete=models.CASCADE) class Visitor(models.Model): # The Category table name that inherits models.Model name = models.CharField(max_length=200) #Like a varchar mail = models.TextField() #Like a varchar church_id = models.ForeignKey(Church, on_delete=models.CASCADE) class Reservation(models.Model): # The Category table name that inherits models.Model event_id = models.ForeignKey(Event, on_delete=models.CASCADE) visitor_id = models.ForeignKey(Visitor, on_delete=models.CASCADE) church_id = models.ForeignKey(Church, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) In my template file I want to show only the left event_participant. For that I will take the Event and got to Reservation take there the quantity from every row that matches the event_id. Then I will remove that number from event_participant and return that number. In my views.py I tried it with this: @property def count_event_participant(event): return int(event.event_participant) - int(Reservation.objects.filter(event_id=event)) def events_list(request): events = Event.objects.all().order_by('date') return render(request, 'events_list.html', {'events': events}) And at my template file I tried this: <i class="fas fa-users"></i> {{ count_event_participant(event) }} … -
django post method create record using ListApiView
I am a beginner to django rest-framework and trying to create new record using POST method in ListAPIView. Here's my serializer: from scheme.models import ProjectScheme, ProjectSchemeMaster from rest_framework import serializers class SchemeDetailSerializer(serializers.ModelSerializer): class Meta: model = ProjectScheme fields = ('id', 'name', 'parent_scheme_id', 'rule', 'created_on', 'created_by', 'updated_on','updated_by') depth=1 And view: class ProjectSchemeList(ListAPIView): """ List all Schemes """ serializer_class = SchemeDetailSerializer # pagination_class = ProjectLimitOffsetPagination def get_queryset(self, *args, **kwargs): comp_logger.info('invoked scheme list all') schemes = ProjectScheme.objects.all().order_by('-id') return schemes def post(self, request, *args, **kwargs): if serializer_class.is_valid(): serializer_class.save() return Response(serializer_class.data, status=status.HTTP_201_CREATED) return Response(serializer_class.errors, status=status.HTTP_400_BAD_REQUEST) I get this error: NameError at /scheme/schemes/ name 'serializer_class' is not defined How do I pass request data to serializer_class? -
div tag doesn't have a name attribute but I need it for form.post
I am making a drop-down button which contains the languages I have so that I can pass this language (the chosen) to the view but apparently there is not a name attribute so I don't know what to do can anyone please help me. here is what I'm trying to do <form action="" method="post" id="languageForm">{% csrf_token %} <input name="next" type="hidden" value="{{ redirect_to }}"> <div class="dropdown show"> <a class="btn btn-secondary dropdown-toggle" href="#" role="button" id="dropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Language </a> <div class="dropdown-menu" aria-labelledby="dropdownMenuLink" name="language" id="selectLanguage" onchange="this.form.submit()"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for language in languages %} <a class="dropdown-item" value="{{ language.code }}" {% if language.code == LANGUAGE_CODE %} selected{% endif %}> {{ language.name_local }} ({{ language.code }})</a> {% endfor %} </div> </div> <!-- <input type="submit" value="Go">--> </form> -
optional not equals filter in DJango
I want to use a not filter while I'm unpacking arguments. So, I have an optional filter that only needs to filter CS_roles. So no users with CS roles are listed. I was thinking to do this by a Q object like this: ~Q(roles__role=Role.CS) so my argument looks like: staff_arguments = {~Q(roles__role=Role.CS)} My filter is: site.users.all().filter(*staff_arguments,) When I do this, I still get users with CS roles. What am i doing wrong? -
django how to get status count in single dictionary
In my user table i have many user type and status (pending = 0,1 = approved). i am getting the count like. user = {} user['pending'] = User.objects.filter(type=3,status='0').count() user['approved'] = User.objects.filter(type=3,status='2').count() user['blocked'] = User.objects.filter(type=3,status='4').count() print(user) Using this i am getting result in this way like : {'pending': 0, 'approved': 1, 'blocked': 0} what actually i need is i want this same result through a single query can any one please help me related this ?? thanks in advance -
How to test unmanaged models using pytest-django
In my django project, I have 5 applications, with total 15 models,and all of them are unmanaged. I've written some tests in pytest-django, and when I run them, they fail due to not being able to find tables. How can I create database entries for all these models so that the tests don't fail? -
How can I implement the dash.callback_context function in django_ploty_dash environment?
I would like to know which Input is requiring the callback. This solution works well with dash. @app.callback( Output('medcode', 'value'), [Input('pie-toptenR', 'clickData'), Input('pie-toptenM', 'clickData')]) def update_medcode(clickData, clickData2): ctx = dash.callback_context if (clickData==None) & (clickData2==None): return '' else: pie = ctx.triggered[0]['prop_id'].split('.')[0] if pie == 'pie-toptenR': return clickData['points'][0]['label'] else: return clickData2['points'][0]['label'] -
ImportError: cannot import name 'UserForm' from apps.common.forms
I'm using a code for a project and the code has worked before and I can't seem to make it work. It looks like there is a problem in forms.py being not able to draw information. Other than that I'm not really sure why I'm getting this error. I have tried to work on this for quiet a long time and seems to me a fresh pair of eyes might be able to figure out the solution. Please help. Error Traceback: Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check all_issues = self._run_checks( File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks return checks.run_checks(**kwargs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 407, in check for pattern in self.url_patterns: File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns patterns = … -
How to add scopes to explicit HTTP requests to Google Calendar API?
I am try to called the Calendar REST api using python's requests library in a django web application. I have made use of django-social-auth to login the user using Google accounts. Following the related code for requests - def index(request): if request.user.is_authenticated: social = request.user.social_auth.get(provider='google-oauth2') response = requests.get('https://www.googleapis.com/calendar/v3/users/me/calendarList', params={'access_token': social.extra_data['access_token']}) print(response.text) return render(request, 'main/index.html') I am getting the following error message in the response body - Insufficient Permission: Request had insufficient authentication scopes. I am guess we have to add a scopes variable to the request but not quite sure how to do that. -
Django URL pattern For Category > Subcategory > Sub-subcategory, and so on
I want to keep this question very simple. Can re_path be used to represent the below patterns in a single URL pattern? I'm at the juncture now where I want to add blog post slug names to the end of these patterns and that will duplicate them all which seems unweildy and just not good. urlpatterns = [ path('<slug:topic1>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/<slug:topic4>/', MyView.as_view(), name='user_home'), path('<slug:topic1>/<slug:topic2>/<slug:topic3>/<slug:topic4>/<slug:topic5>/', MyView.as_view(), name='user_home'), ] I have considered getting all the topics as one long string, splitting by /, but that approach more python and less Django-best-practices. Looking for the most logical and best-practiced approach to this problem. -
Django inheritance and OneToOneField problems: Field defines a relation with model 'Dish', which is either not installed, or is abstract
I have a parent class Dish and a child Pizza (among other dish types). I am trying to make Dish abstract now, have deregistered it from admin.py, because ultimately every Dish is of some type and every Pizza is exactly one Dish (corresponds to 1 dish ID) - hence my OneToOneField logic (if that makes sense). I had Dish concrete first, but when I add class Meta: abstract = True, I get the following errors: orders.Pizza.dish: (fields.E300) Field defines a relation with model 'Dish', which is either not installed, or is abstract. orders.Pizza.dish: (fields.E307) The field orders.Pizza.dish was declared with a lazy reference to 'orders.dish', but app 'orders' doesn't provide model 'dish'. I read other SO posts suggesting I should include the app name (orders) here: dish = models.OneToOneField('orders.Dish', etc.., but that doesn't work either and besides all models are in models.py in the same app orders. Below is my code. What's the issue here? class Dish(models.Model): PIZZA = 'PIZZA' SUB = 'SUB' PASTASALAD = 'PASTASALAD' PLATTER = 'PLATTER' TYPE_CHOICES = ( (PIZZA, 'Pizza'), (SUB, 'Sub'), (PASTASALAD, 'PastaSalad'), (PLATTER, 'Platter') ) name = models.CharField(max_length=64, blank=True) # blank makes name optional type = models.CharField(max_length=64, choices=TYPE_CHOICES, blank=True) size = models.CharField(max_length=1, choices=SIZE_CHOICES, default=SMALL, … -
Django unit tests - querying test database content
Can someone point me to a resource, which shows how to query a Django test Database's specific table, during a unit test? I have the following test code: from django.test import TestCase from users.models import User class DisputeAssignerTestSuite(TestCase): databases = [ 'default', 'read_replica', ] @classmethod def setUpTestData(cls): cls.users = UserFactory.create_batch(50) def test_firstOne(self): print(users) print(User.objects.all()) UserFactory code: import factory from faker import Factory import pytz from users.models import User faker = Factory.create() class UserFactory(factory.DjangoModelFactory): class Meta: model = User django_get_or_create = ('first_name', 'last_name', 'timezone', 'locale') first_name = factory.LazyAttribute(lambda _: faker.first_name()) last_name = factory.LazyAttribute(lambda _: faker.last_name()) display_name = factory.LazyAttribute(lambda _: _.first_name + " " + _.last_name) timezone = factory.LazyAttribute(lambda _: faker.timezone()) locale = factory.LazyAttribute(lambda _: faker.random_choices(elements=('en-au', 'en-us', 'de-de', 'fr-fr'), length=1)) password = factory.LazyAttribute(lambda _: faker.password(length=12)) last_login = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-60d", tzinfo=pytz.timezone(faker.timezone()))) is_superuser = factory.LazyAttribute(lambda _: faker.boolean(50)) email = factory.LazyAttribute(lambda _: faker.email()) username = factory.LazyAttribute(lambda _: _.email) is_staff = factory.LazyAttribute(lambda _: faker.boolean(50)) is_active = factory.LazyAttribute(lambda _: faker.boolean(50)) date_joined = factory.LazyAttribute(lambda _: faker.past_datetime(start_date="-1y", tzinfo=pytz.timezone(faker.timezone()))) I do not understand, how I can query User table in the test Database created by Django for this TestCase run, and e.g. verify its contents to some specific requirement (e.g. presence of users by a specific first name etc.). … -
Django ManyToMany relationship avoid duplicates
I have been thinking about this issue for two days and I cannot wrap my head around it. So let say that I have a model called "Car" that has many to many relationships with my User model "Profile" meaning in my user model (Called Profile) I have: cars = models.ManyToManyField(Cars, related_name = 'profiles') Now the car model has many to many relationships called likes so whenever a user likes a car it will be added to the likes of that car by: car.likes.add(user) Now my "Car" model will have 4 fields which are model, year, name, color The issue is I want to query the database so that I can get the number of likes for all cars with certain models and years only. Meaning regardless of the name and color I want to get the number of likes. Now I know I can get likes if all models with certain model and year by writing: def get_total_likes(self): Car.likes.through.objects.filter(car__model=self.model, car__year=self.year).count() Now imagine a scenario where a user likes a car with model=A, year=1, color=r, name=something and then they decide to like a car with model=A, year=1, color=b, name=somethingelse. How can I NOT count duplicate users when getting the total … -
'xml.etree.ElementTree.Element' object has no attribute 'META'
I want to show pandas dataframe from xml file to HTML with django Views.py def dataframe(request): import pandas as pd import xml.etree.ElementTree as et parse_data = et.parse("dataset.xml") data = parse_data.getroot() content = main.data_view(data) return render(request, 'apps/dataframe.html', content) main.py def data_view(data): df_cols = ["DOCNO", "SONG", "ARTIST", "LYRICS"] rows = [] for node in data: s_docno = node.find("DOCNO").text if node is not None else None s_song = node.find("SONG").text if node is not None else None s_artist = node.find("ARTIST").text if node is not None else None s_lyrics = node.find("LYRICS").text if node is not None else None rows.append({"DOCNO": s_docno, "SONG": s_song, "ARTIST": s_artist, "LYRICS": s_lyrics}) DataFrame = pd.DataFrame(rows, columns = df_cols) return render(data, 'apps/dataframe.html', {'DataFrame': DataFrame}) dataframe.html <table> <tr> {% for data in DataFrame %} <th>{{ data }}</th> {% endfor %} {% for i, row in DataFrame.iterrows %} <tr> {% for value in data %} <td>{{ value }}</td> {% endfor %} </tr> {% endfor %} </tr> But the result is error message 'xml.etree.ElementTree.Element' object has no attribute 'META' How to solve this? -
Inter dependent filter api in django rest framework
I want to expose the sample dataset through a single generic HTTP API endpoint, which is capable of filtering, grouping and sorting. In this I want API to be interdependent. For eg. If I have to show the number of impressions and clicks that occurred before the 1st of June 2017, broken down by channel and country, sorted by clicks in descending order. I know how to perform singular operation in django filter by using django ORM and django rest_framework_filters but I'm completely unaware of this problem statement. Any sort of help will be appreciated. -
Django celery referencing obsolete tables
So I have this interesting issue with celery and will appreciate another set of eyes. So I have model Ark. class Ark(models.Model): name = models.CharField(max_length) title = models.CharField(max_length) So I ran migrations and ran a couple of periodic tasks using the model After sometime I made a change to the model class Ark(models.Model): name = models.CharField(max_length) # title field was removed ran migrations again, restarted celery + beat. The issue is my current tasks are failing because they I get this error that says something like column ark.title does not exist now, I didn't have any migration issues when I removed title and have also been able to create new ark objects. It is also important to note that I have DELETED all previous instances of ark objects just to be sure no old data persists. What am I missing here? -
Django allauth redirect_url_mistmatch
Hello i have A problem with django allauth. I have A site and i wanna connect Google and github login via django allauth. If i want login via google/github have error: redirect_url_mistmatch. Sorry for my bad English.