Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to properly run Django dev server locally for testing form another device in the network
I'm trying to run a local dev server on Django using the command python manage.py runserver 0.0.0.0:5000 but it takes very long time loading whenever I try to open it, and in the cmd, it shows this error An established connection was aborted by the software in your host machine Note Using Postgresql as a database. Traceback Exception happened during processing of request from ('127.0.0.1', 53334) Traceback (most recent call last): File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socketserver.py", line 720, in __init__ self.handle() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Administrator\AppData\Local\Programs\Python\Python37\lib\socket.py", line 589, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
Django get data from second model filtered by values from the first
I have this little model: 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) class Reservation(models.Model): # The Category table name that inherits models.Model event_id = models.ForeignKey(Event, on_delete=models.CASCADE) quantity = models.IntegerField(default=0) When I list all my events, I wan to calculate the rest of possible participant. So I tried it at my view: def events_list(request): events = Event.objects.all().order_by('date') #I started here for event in events: obj = Reservation.objects.filter(event_id=event) return render(request, 'events_list.html', {'events': events, 'obj': obj}) But the obj is empty. Or is there a better way to calculate the participant (participant - quantity)? Thanks -
Want to ask about web hosting
I'm currently working on a project. It's a website built with Python Django and Firebase. Expecting 2000+ registered users and around 400/500 concurrent users access to the site at once. What options do I have? I currently has a GCP account with 275USD Trial Credits left. The site will be hosted for around 2-3weeks. and should I use App Engine or Compute Engine to host the site? -
What is the different user type in django
I have a task in django to create a 1.superuser 2. admin user 3.user . The task is to create test for users , superuser will give authority to admin users to check the answer given to user. How can i implement in django? -
Django, is it possible to have a formset factory with two ForeingKey?
How can I set two ForeignKey in a inline formset factory? I have created an inline formset factory utilizing two models: Lavorazione and Costi_materiale. class Lavorazione(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali, ) numero_lavorazione=models.IntegerField() class Costi_materiale(models.Model): codice_commessa=models.ForeignKey(Informazioni_Generali) numero_lavorazione=models.ForeignKey(Lavorazione) prezzo=models.DecimalField() After I have created the inline formset facotry as the following: CostiMaterialeFormSet = inlineformset_factory( Lavorazione, Costi_materiale, form=CostiMaterialeForm, fields="__all__", exclude=('codice_commessa',), can_delete=True, extra=1 ) But I have in Costi_materiale two ForeignKey, instead in the form the formset recognise only numero_lavorazione and not also codice_commesse. I want that the formset set in the first model the codice commesse and lavorazione fields and subsequently in the inline formset the other fields. -
Not Understood an Aspect of Django
So you see I'm learning the basics of Django from a course on YouTube by Rafeh Qazi. In that course we were making a polls application following the Django at a glace documentation. So on the third video we talked about something called Namespacing URL names. And I didn't quit understand it. Can anyone please tell me about it You See here is how the tree view of my project look like: ## Django Crash Course ## -> ### mysite ### > folder: _pycache_ > __init__.py > asgi.py > settings.py > urls.py > wsgi.py -> ### polls ### > folder: _pycache_ > folder: migrations > folder: templates > folder: polls > index.html > detail.html > __init__.py > admin.py > apps.py > models.py > test.py > urls.py > views.py > .gitignore > db.sqlite > manage.py I may not be able to show you the images of my code I can take you there: follow this link: My Github project -
How to add nested json
class activitySerializere(serializers.ModelSerializer): class Meta: model=ActivityPeriods fields = ['members_id','start_time','end_time'] class membersSerializere(serializers.ModelSerializer): activity = activitySerializere(many=True,read_only=True) class Meta: model=Members fields = ['id','real_name','tz','activity'] depth = 1 -
How to validate local running Json data in javascript?
Firstly, I am doing the quiz app using the Django. And I have retrieved the questions, options from the DB using views.py. Next I need to validate the user given answer and correct answer which is already stored in the DB. On click it need to change the red or green based on the answer. So here I have stucked : Using Django rest framework I have created the API . (127.0.0.1:8000/api/) Actually in every JavaScript quizzes there are taking the temparory variable and storing the questions and validating them . But here I have taken the questions in the DB and already so How to validate the answers my taking that json into the JS file and how to display the file. Can anyone please right the js file for the Model which I will share the code here. Models.py:- from django.db import models # Create your models here. class Quiz(models.Model): slug = models.SlugField(max_length =200) question = models.CharField(max_length=200) option1 = models.CharField(max_length=200) option2 = models.CharField(max_length=200) option3 = models.CharField(max_length=200) option4 = models.CharField(max_length=200) correct_answer = models.CharField(max_length = 200) views.py:- from django.shortcuts import render, redirect, get_object_or_404 from django.http import JsonResponse from django.utils import timezone from .models import Quiz from rest_framework import generics from … -
how can I reduce database hints in Django ORM?
I have some Models: F ---> D ---> C <--- B ---> A class A: - class B: a = ForeignKey c = ForeignKey class C: - class D: c = ForeignKey class F: d = ForeignKey and I'm using this query: querset = B.objects.select_related('c').filter(a=a_instance) to show result in template: {% for b in querset %} {% for d in b.c.d_set.all %} {% for f in d.f_set.all %} {% endfor %} {% endfor %} {% endfor %} how can I reduce database hints? is it ok to use Prefetch like this or am I wrong? querset = B.objects.select_related( 'c' ).prefetch_related( Prefetch('c__d_set__f_set') ).filter( a=a_instance ) django = 2.2 thanks -
Django throws custom error page when going home page without language code
Today, I added custom handler404 and it works properly, but there is one problem. I am using localization. Before adding custom 404 page, when I was going to mysite.com it was redirecting me mysite.com/en but now it throws 404 error. PS. It works properly when I am going to mysite.com/en my project/urls.py file urlpatterns += i18n_patterns( path("", include("geotravel_app.urls")), path("tours/", include("tours.urls")), path("guides/", include("guides.urls")), path('transport/', include('transport.urls')), ) urlpatterns += [ path('geotranslate/', include('rosetta.urls')), ] handler404 = 'geotravel_app.views.error_404' Thanks beforehand, sorry for my bad English. -
Django Queryset on Cassandra User Defined Type throws Type Error
I am using a combination of the DataStax Python Driver and the Django Cassandra Engine to communicate with Cassandra through a Django app. Here is how I define a model with User Defined Type columns (example only): from cassandra.cqlengine import columns from cassandra.cqlengine.usertype import UserType from django_cassandra_engine.models import DjangoCassandraModel class UserAddress(UserType) street = columns.Text() number = columns.Integer() class User(DjangoCassandraModel): __table_name__ = 'users' user_id = columns.UUID(primary_key=True) name = columns.Text() address = columns.UserDefinedType(UserAddress) class Meta: managed = False get_pk_field = 'user_id' I'm attempting to query this model with the following call: User.objects.filter(user_id=user_id) which throws this error: File "/usr/local/lib/python3.8/site-packages/cassandra/cqlengine/columns.py", line 1043, in to_python if copied_value[name] is not None or isinstance(field, BaseContainerColumn): TypeError: tuple indices must be integers or slices, not str This error originates from the UserDefinedType class declaration, specifically this function: def to_python(self, value): if value is None: return copied_value = deepcopy(value) for name, field in self.user_type._fields.items(): if copied_value[name] is not None or isinstance(field, BaseContainerColumn): copied_value[name] = field.to_python(copied_value[name]) return copied_value It would seem to me that the Django Cassandra Engine, which includes the DjangoCassandraQuerySet class, is not playing well with the UserDefinedType class, though I'm not sure why. I've not had any problems with these libraries up until now and I find … -
stopping refresh after liking a post : Django
Is there any way to stop refreshing a page after liking it or commenting on with in django platform without using ajax. I don't know about ajax i know little about Javascript only and i'm working on django. If there is any way please tell or just give me a link from where i can learn it -
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