Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Multithreading in Python with multiple for loops inside main function
Am checking if you can thread multiple for loops inside a main function as per below code. reason for this is because am trying to save this data inside a database. But while running the code new values are coming in which makes data inconsistent between the lists. I use zip function to pair all the list values together. So if I can run each for loop as a seperate thread, it will be fast enough to get acurate data. # Creating empty list to store the values ana_username = [] publicip = [] privateip = [] bytes_Tx = [] bytes_Rx = [] group_policy03 = [] duration03 = [] def ana(): # SSH Connection parameters remote_conn_pre = paramiko.SSHClient() remote_conn_pre.set_missing_host_key_policy(paramiko.AutoAddPolicy()) remote_conn_pre.connect(hostname='10.10.10.10', port=22, username='root', password='*******', look_for_keys=False, allow_agent=False) remote_conn = remote_conn_pre.invoke_shell() # Initiating list of commands remote_conn.send('\n') remote_conn.send('en\n') remote_conn.send(str(password)+ '\n') remote_conn.send('conf t\n') remote_conn.send('pager 0\n') remote_conn.send('end\n') time.sleep(1) remote_conn.send('sh vpn-sessiondb anyconnect | grep Username\n') time.sleep(1) policy_user = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Assigned\n') time.sleep(1) policy_ip = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Bytes\n') time.sleep(1) policy_bytes = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Group Policy\n') time.sleep(1) policy_group = remote_conn.recv(11111) remote_conn.send('sh vpn-sessiondb anyconnect | grep Duration\n') time.sleep(1) policy_duration = remote_conn.recv(11111) # End the SSH session remote_conn.send('pager … -
'NoneType' object is not iterable ERROR when editting profile in Django framework Python 3.7
I'm still junior developer in Django and webframe. Working on developing a coworkspace management system in django 3. In the profile page of user, when they click edit profile they get this error. Note: Editting the profile using the 'admin' works perfectly fine with no errors. but the users themselves get this error. if theres any details needed more i will post it. Heres the traceback: Traceback (most recent call last): File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/maha/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/maha/venv/lib/python3.7/site-packages/django/contrib/auth/decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "/home/maha/venv/nadine/member/views/profile.py", line 232, in edit_profile return render(request, 'member/profile/profile_edit.html', context) File "/home/maha/venv/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/home/maha/venv/lib/python3.7/site-packages/django/template/loader.py", line 62, in render_to_string return template.render(context, request) File "/home/maha/venv/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 171, in render return self._render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 936, in render bit = node.render_annotated(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/base.py", line 903, in render_annotated return self.render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/template/loader_tags.py", line 150, in render return compiled_parent._render(context) File "/home/maha/venv/lib/python3.7/site-packages/django/test/utils.py", line 95, in instrumented_test_render return self.nodelist.render(context) File … -
Django ModalForm unable to process requests correctly
I'm currently trying to implement modal forms in my Django application ( I installed this library: https://pypi.org/project/django-bootstrap-modal-forms/ My urls.py looks like this: from django.urls import path from cloudapp.server_users.views import * app_name = "server_users" urlpatterns = [ path("", ServerUsersManagement.as_view(), name="user_management"), path('add_user/', ServerUsersCreateView.as_view(), name='add_user') ] My views.py looks like this: ... from django.views import generic from bootstrap_modal_forms.generic import (BSModalCreateView, BSModalUpdateView, BSModalReadView, BSModalDeleteView) class ServerUsersManagement(LoginRequiredMixin, generic.ListView): model = ServerUsers context_object_name = 'server_users' template_name = "pages/user_management.html" queryset = ServerUsers.objects.all() def get_context_data(self, **kwargs): context = super(ServerUsersManagement, self).get_context_data(**kwargs) context['email_aliases'] = EmailAliases.objects.all() return context # Create User class ServerUsersCreateView(LoginRequiredMixin,BSModalCreateView): template_name = 'server_users/add_user.html' form_class = ServerUsersForm success_message = 'Success: User was created.' success_url = reverse_lazy('server_users:user_management') def form_valid(self, form, **kwargs): username = form.cleaned_data['username'] company_id = str(self.request.user.id) final_path = server_users_logic.create_path(settings.VPN_BUNDLE_PATH, company_id, username) form.instance.vpn_certificate = final_path #company_id FK in the company table form.instance.company_id = self.request.user.id return super().form_valid(form) My models.py: from django.db import models from cloudapp.users.models import Company class ServerUsers(models.Model): given_name = models.CharField(max_length=30) family_name = models.CharField(max_length=30) cloud_email = models.EmailField(max_length=254) date_of_registration = models.DateField(auto_now=False, auto_now_add=True) username = models.CharField(max_length=30) vpn_certificate = models.FileField(max_length=100, blank=True, default="OK") user_changed_password = models.BooleanField(blank=True, default=False) password = models.CharField(max_length=100, default="some_password") company = models.ForeignKey('users.Company', on_delete=models.CASCADE) My HTML part looks like this: user_management.html {% extends "pages/base.html" %} {% block title %}{% block head_title %}{% endblock … -
How to retrieve all data from foreign keys with Django ORM and return them as JsonResponse
I am trying to get all the data from a model and its foreign keys and I have a hard time using select_related() and values() or values_list(). I got an Order table who got two foreign keys. I need to query all the data and send it as a JsonResponse. This is the line: Order.objects.select_related('persoana_fizica__persoana_juridica').values() I saw I can write inside values what fields I need, I am looking for a method to select all of them without writing every single one, 'all' didn't worked. Any ideas? -
Django: how to update multiple records?
I need to update multiple records (rows) in a table. First, I get informations to select rows to be update: ran_st1 = 1 ran_st2 = 1 ran_bra = 'A' pay_ide = 'FR' bra_lib = 'Polyvitamines et oligo-éléments' Then, I select rows to be updated: rows= Randomisation.objects.filter(Q(ran_st1 = ran_st1) & Q(ran_st2 = ran_st2) & Q(ran_bra = ran_bra) & Q(pay_ide = pay_ide)) And then, I though to make a loop like that, but not sure: for row in rows: r = get_object_or_404(Randomisation, ran_ide = row.ran_ide) r.ran_act = 1 r.save() -
Filtering by CharField choices text property
How could you filter by the choices text instead of the choices key? Suppose you have the following CharField in a model: CHOICES = ( ('FI', 'First'), ('SE', 'Second'), ('TH', 'Third') ) choiceField = models.CharField(max_length=2, choices=CHOICES) Then you try to filter it in a view like so: query_in_choice_field = Model.objects.filter(choiceField__contains=query) This filter only checks 'FI', 'SE' and 'TH'. How would you filter by 'First', 'Second' and 'Third'? -
Django with Ajax with multiple values
I had a html page where on click of a button I open a modal window. Modal window will display some text from database. on button click below jquery executed $('.openbtn').click(function(){ var fname; var mname; var lname; fname="Rakesh"; mname="kumar"; lname="Sharma"; $.ajax( { type:"GET", url: "/myapp/member/search/", data:{ "fname":fname, "mname":mname, "lname":lname, }, success: function( data ) { $( '#divcontent' ).html(data); } }); }); Below is the view def displayModalView(request): return render(request, 'myapp/display_serch_member.html') and following is the url path('member/search/', views.displayModalView, name="display_modal"), No I need to pass fname,mname,lname to views. I have tried path('member/search/<fname>/<mname>/<lname>', views.displayModalView, name="display_modal"), def displayModalView(request,fname,mname,lname): return render(request, 'myapp/display_serch_member.html') but i dont get the desired result. What is wrong or what I need to change? -
NameError at / free variable 'y' referenced before assignment in enclosing scope
I need to make a small project for my university -create webapp that will solve Transportation Problem and well deadline is for tomorrow so I am making MVP version really. I am using Django for webapp and PuLP for transportation problem part. When launching my problem solving logic I receive an error: NameError at / free variable 'y' referenced before assignment in enclosing scope for line: prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of Products out of Warehouse %s"%x I was using PuLP example from their GitHub here My code for this part is as below: Warehouses = [0,1,2] supply = { 0: deliver1, 1: deliver2, 2: deliver3 } Distributors = [0, 1, 2] demand = { 0: receiver1, 1: receiver2, 2: receiver3 } costs = [ #dsitributors -static variables for debugging will change that later on #D E F [3, 5, 7],#A Warehouse [12, 10, 9],#B Warehouse [13, 3, 9],#C Warehouse ] prob = LpProblem("Transportation Problem",LpMinimize) Routes = [(x,y) for x in Warehouses for y in Distributors] route_vars = LpVariable.dicts("Route",(Warehouses,Distributors),0,None,LpInteger) prob += lpSum([route_vars[x][y]*costs[x][y] for (x,y) in Routes]), "Sum of Transporting Costs" for x in Warehouses: prob += lpSum([route_vars[x][y] for x in Distributors]) <= supply[x], "Sum of … -
Returning array of deleted objects in single GraphQL mutation (graphene-django)
While in the past I used a GraphQL mutation that deletes a single record, I came up with the idea that this is not ideal in the case I want to delete several records at once since it ended up by calling the mutation that delete 1 record several times (in a loop) which results in several API call over the network. So I decided to instead modify the mutation to accept has an argument a list of objects or IDs (whatever) on which I can loop in the backend. By doing this, it does only 1 call to the API with all the records to delete. I managed to do it and the only blocking point that I face is the return statement. I couldn't figure out how to write it. So if I have a model (in my schema) such as : class UserType(DjangoObjectType): class Meta: model = User fields = ( 'id', 'username', 'password', 'first_name', 'last_name', 'is_active', 'group_ids', ) full_name = graphene.String() full_identification = graphene.String() In the past I used : class DeleteUser(graphene.Mutation): username = graphene.String() class Arguments: id = graphene.ID() def mutate(self, info, **kwargs): user = get_object_or_404(User, id=kwargs['id']) user.delete() return user class Mutation(graphene.ObjectType): delete_user = DeleteUser.Field() … -
How to make search in Django with SearchVector on ArrayField?
I have a Company model with related tags. I need to configure search by name, content and tags, and if search works with name, content fields , it doesn't on ArrayField -> tags models.py class Company(models.Model): name = models.CharField(max_length=150) content = models.TextField(blank=True) **tags** = ArrayField(models.CharField(max_length=200), blank=True, null=True utils.py def get_rank_search_result(q, category=None): ... vector = SearchVector('name', config='russian', weight='A') + \ SearchVector('content', config='russian', weight='B') + \ SearchVector('tags', config='russian', weight='B') #SearchVector(Func(F('tags'), Value(' '), function='array_to_string'), config='russian', weight='B') #doesn't work either query = SearchQuery(q, config='russian', search_type=search_type) return list(qs.annotate(rank=SearchRank(vector, query)).filter(rank__gte=0.3).order_by('-rank')) ``` Actually, the search stops working after i add line with SearchVector('tags').... -
Edit a unique field used as foreignkey in Django
I have two models, one Price and Market: class Market(models.Model): market_name = models.CharField(max_length=3, unique=True) class Price(models.Model): market = models.ForeignKey(Market, on_delete=models.CASCADE, to_field="market_name") I want to be able to edit the market_name field on the Market model and have the subsequent Price objects updated without causing errors. update or delete on table "appname_market" violates foreign key constraint "appname_price_market_id_5f75a816_fk_appnames" on table "appname_price" DETAIL: Key (market_name)=(Cute Martket Name) is still referenced from table "appname_price". Pointing them on the pk is one the solution, but I want to stick to using market_name as foreignkey for a reason. How would you do that ? I imagined a method for pre_save : @receiver(pre_save, sender=Market) def update_market_field(sender, instance, *args, **kwargs): try: obj = sender.objects.get(pk=instance.pk) except sender.DoesNotExist: pass # Object is new, so field hasn't technically changed, \ # but you may want to do something else here. else: if not obj.market_name == instance.market_name: # Field has changed Price.objects.filter(market=obj.market_name).update_or_create(market=instance) But this still producing errors because actually the Market object hasn't been saved yet. A half solution also is to delete all Prices with that obj.martket_name in this pre_save method, and I have seen that it effectively update the unique field but ... -
If a user uploads an infected file but my Django server does not write it to disk, is my server still at risk?
In the Django docs, it mentions that image uploads below 2.5MB are not written to disk, just to memory. I just need my server to process these images. My concern though, is it possible for my server to still get infected despite not writing them to disk? -
i made an extra Template Tag and it bring a problem for me
Guys I already made an init.py for this to make this as a module so that's not the error from django import template from markdownx.utils import markdownify register = template.Library() @register.filter(name = 'markdown') def markdown(text): return markdownify(text) <p>{{ blog.| markdown |safe }}</p> This not giving any error to me but when I write a blog then on the webpage it is not showing anything, means for which I used markdown template tag, so please help me if you can. -
How do I resolve a 403 error upon accessing site with django?
The site is running on a vps with CentOS7. The server is using the latest version of httpd (apache2 for centos) and mod-wsgi. The website was made with django. Every time I try to access the site either through the ip I get a 403 forbidden error and when I try the site's domain I get a timed out error. sudo status httpd returns Loaded: loaded (/usr/lib/systemd/system/httpd.service; disabled; vendor preset: disabled) Active: active (running) since Wed 2020-04-29 01:44:44 MST; 1s ago Docs: man:httpd(8) man:apachectl(8) Process: 3698 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=0/SUCCESS) Process: 29778 ExecReload=/usr/sbin/httpd $OPTIONS -k graceful (code=exited, status=0/SUCCESS) Main PID: 3703 (httpd) Status: "Processing requests..." CGroup: /system.slice/httpd.service ├─3703 /usr/sbin/httpd -DFOREGROUND ├─3704 /usr/sbin/httpd -DFOREGROUND ├─3705 /usr/sbin/httpd -DFOREGROUND ├─3706 /usr/sbin/httpd -DFOREGROUND ├─3707 /usr/sbin/httpd -DFOREGROUND ├─3708 /usr/sbin/httpd -DFOREGROUND └─3709 /usr/sbin/httpd -DFOREGROUND This is my sites config file stored in /etc/httpd/conf.d/mysite.com.conf # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value … -
Error in models, TypeError: on_delete must be callable
When I run the following command: python manage.py makemigrations I have this error: File "/home/user/project/myvirt/forum/boards/models.py", line 9, in <module> class Topic(models.Model): File "/home/user/project/myvirt/forum/boards/models.py", line 12, in Topic board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') File "/usr/local/lib/python3.7/dist-packages/django/db/models/fields/related.py", line 801, in __init__ raise TypeError('on_delete must be callable.') TypeError: on_delete must be callable. My models.py content is: from django.db import models from django.contrib.auth.models import User # Create your models here. class Board(models.Model): name = models.CharField(max_length=30, unique=True) description = models.CharField(max_length=100) class Topic(models.Model): subject = models.CharField(max_length=255) last_updated = models.DateTimeField(auto_now_add=True) board = models.ForeignKey(Board, related_name='topics', on_delete='cascade') creator = models.ForeignKey(User, related_name='topics', on_delete='cascade') class Post(models.Model): message = models.TextField(max_length=4000) topic = models.CharField(Topic, related_name='posts', on_delete='cascade') created_by = models.CharField(User, related_name='posts', on_delete='cascade') created_at = models.DateTimeField(auto_now_add=True) updated_by = models.CharField(User, related_name='posts', on_delete='cascade') updated_at = models.DateTimeField(null=True) This is an exercise in sample forum and seems to be a problem with on_delete='cascade'. -
Django admin reset search box query on filter selection
I have the following class in Django admin of a model: class TopUpsAdmin(admin.ModelAdmin): search_fields = ('user__email', 'user__phone_number',) list_filter = ('status',) Currently the default behavior of the filter is if search box in the listing page is input with test_1 which is a user name and search up the result(url will have the following parameter /?q=test_1) , if select an option in the filter then the filter results also got affected by the search box query on the URL ?q=test_1&status__exact=1) I would like to not have the search results filter the list when i choose a filter. Reading Django docs only provide me how to override the filter with existed query in the parameter(which come from search box). Any help would be appreciate -
how to return several FileField from Queryset in Django?
I have a models with FileField for videos. When i upload only one video i can return it with this code in the view.py: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) But when i upload two or more videos whith formset, and i change get fuction by filter it doesn't work: def cours(request, id, slug): c = Cours.objects.get(id=id, slug=slug) p = Plan_simple.objects.filter(cours=c) return render(request, 'upload/cours.html', locals()) the models.py class Cours(models.Model): titre = models.CharField(max_length=100) slug = models.SlugField(max_length=100) auteur = models.CharField(max_length=42) comment = models.TextField(null=True) link = models.CharField(max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") categorie = models.ForeignKey('Categorie', on_delete=models.CASCADE) def save(self, *args, **kwargs): self.slug = slugify(self.titre) super(Cours, self).save(*args, **kwargs) class Meta: verbose_name = "cours" db_table = "cours" ordering = ['date'] class Plan_simple(models.Model): partie = models.CharField(blank=True, max_length=100) date = models.DateTimeField(default=timezone.now, verbose_name="Date de parution") vid = models.FileField(upload_to='file/', blank=True, null = True) cours = models.ForeignKey(Cours, related_name = "plan_simple", on_delete=models.CASCADE) def __str__(self): return self.partie class Meta: db_table = "plan_simple" Can you help me? Thanks -
Django JsonField Lookup Filtering with an unknown subkey
I want to filter a Django model by the value of a nested JSON field key when I don't know one of the key values. E.g. I want to do: Model.objects.filter(json_field__firstKey__{UNKNOWN_ID_KEY}__desiredKey__in=[OPTION1,OPTION2]) so that whenever this nested structure exists, and desiredKey exists, I can filter by the desiredValue being OPTION1 or OPTION2 i.e. {desiredKey: OPTION1} or {desiredKey: OPTION2}. I have not managed to find documentation supporting this. Is this possible? If not, does anybody have any alternavtive suggestions? -
Django combine two querysets
My model: class Renewal(models.Model): policy_number = models.integerField() invitation_date = models.DateTimeField() Snapshot of my table is as follows id policy_number invitation_date 86 4353 2020-04-21 16:37:39.071941 87 4354 2020-04-21 16:38:16.082238 97 4355 2020-04-21 17:18:03.997882 99 4377 2020-04-21 17:26:58.414530 162 4218 2020-04-22 18:42:23.066879 167 4218 2020-04-22 18:29:10.571033 171 4218 2020-04-22 18:39:17.546550 175 4238 2020-04-23 17:35:54.444945 176 4238 2020-04-23 17:36:01.482819 177 4239 2020-04-23 17:42:15.056850 178 4238 2020-04-24 13:00:06.886101 179 4243 2020-04-24 13:00:32.098504 180 4241 2020-04-24 13:21:31.215547 181 4360 2020-04-29 13:48:18.765400 in my views, I'm trying to get policy_number in a given date range, as follows def some_function(request): start_date = datetime.date.today() end_date = start_date - datetime.timedelta(days=5) renewals = Renewal.objects.filter(invitation_date__gte=star_date, invitation_date__lt=end_date) print(renewals) what i'm getting : [4238, 4243, 4241] expected answer : [4238, 4243, 4241, 4360] this should ideally give me all renewal records created in last 5 days. However, if today is 2020-04-29, the last policy record should have been 4360, but my last policy record is 4241 -
Django :Redirect to a url which having parameters in it through other template
I wanna to redirect to a url which having parameters in it through other webpage from database like I have homepage and a button on it when click on it then it render a page details with parameters through home page from database in it And on detailpage also have a button With name show and i want when i click on the show button then it again redirects me to the page detailpage but it shows me no reverse found and then parameter arguments id -
python list.append() problem when storing class objects
I have a problem when the some class objects are going to be added to the list in a loop process. let's say I have a database [ 'kid' , 'parent' , 'grandfather' ] with many records. i have a class: class Person: name children grandchildren I make a loop (I know it's a bad idea and that I can simply use queries) and look for every grandfather. an instance of class stores the data of every grandfather and at the end is appended to a list called Persons_List. Here is the Code: p = Person() Persons_List = list() pr = "" #parents gr = "" #grandfather for i in my_database.objects.all().order_by('grandfather'): if gr != i.grandfather: gr = i.grandfather pr = i.parent if p.name !="": Persons_List.append(p) # [:] raises Error and deepcopy not working p.name = "" p.parents.clear() p.grandchildren.clear() p.name = i.grandfather p.children.append(i.parent) p.grandchildren.append(i.kid) else: if pr != i.parent: pr = i.parent try: p.children.remove(pr) except: None p.children.append(pr) p.grandchildren.append(i.kid) Persons_List.append(p) #Adds The Last p To The List the problem is that in the end the Data Stored in list is wrong and messy. the name is the last p.name. and the children and grandchildren are wrong. -
user foreign key in Django
I have written a view that let me store some datas in a database: def save(request, product_id): product = Product.objects.get(pk=product_id) user = request.user p = SavedProduct(username= user, product_off_id=product.off_id) p.save() This is my models: class Product(models.Model): name = models.CharField(max_length=2000) off_id = models.BigIntegerField() class SavedProduct(models.Model): username = models.CharField(max_length=2000) product_off_id = models.BigIntegerField() It does the job but I am struggling to implement a OneToOneField to username and product_off_id. I know product_off_id = models.BigIntegerField() should be product_off_id =models.OneToOneField(Product) but what should I pass in p=SavedProduct() for the product_off_id field? -
Django NoReverseMatch error with no arguments not found. 1 pattern(s) tried
I have a model which has two foreign keys as below class BatPerformance(models.Model): country = models.ForeignKey('TeamStructure', on_delete=models.CASCADE, null=True, related_name='country') player = models.ForeignKey('PlayerStructure', on_delete=models.CASCADE, related_name = 'playerbatperf') # Batting Performance Fields batting_Matches = models.IntegerField(default=0) batting_innings = models.IntegerField(default=0) batting_notouts = models.IntegerField(default=0) batting_Runs = models.IntegerField(default=0) batting_HS = models.IntegerField(default=0) batting_avg = models.FloatField(default=0.0) batting_ballsfaced = models.IntegerField(default=0) batting_strikerate = models.FloatField(default=0) batting_hundreds = models.IntegerField(default=0) batting_fifty = models.IntegerField(default=0) batting_twohundreds = models.IntegerField(default=0) batting_fours = models.IntegerField(default=0) batting_sixes = models.IntegerField(default=0) def __str__(self): return str(self.player) + ': ' + str(self.match) I created a form for the same with all the fields. my views.py as Below. class BatStatistics(FormView): template_name = 'form.html' form_class = NewPlayerBatStatistics success_url = '.' def form_valid(self, form): # Form is Valid new_team = form.save(commit=True) return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): # Form is Invalid print(form.errors) return self.render_to_response(self.get_context_data(form=form)) urls.py urlpatterns = [ path('', test), path('homepage/', Index.as_view(), name = 'index'), path('teamdetails/', Teams.as_view(), name = 'teamlist'), path('fixtures/',Fixtures.as_view(), name='fixtures'), path('teamdetails/newteam', NewTeam.as_view(), name='newteam'), path('teamdetails/<int:pk>/', PlayerDetailView.as_view(), name='teamname'), path('teamdetails/newplayers/', NewPlayer.as_view(), name='newplayer'), path('teamdetails/<int:player_details_pk>/<int:pk>/', PlayerStatistics.as_view(), name= 'playerdetails'), path('teamdetails/<int:player_details_pk>/<int:pk>/batstatistics', BatStatistics.as_view(), name= 'batstatistics'), path('teamdetails/<int:player_details_pk>/<int:pk>/bowlstatistics', BowlStatistics.as_view(), name= 'bowlstatistics'), ] In the form fields, the first two fields are the country and player name.SO whenever I select the dropdown of the country I don't want to see all the country players in the player … -
What are the best technique for having a real-time notifications, messages or other stuffs that requires an async request on django?
I just want to know if there is a best technique for achieving a async tasks like real-time notifications, messages etc. in django? Are django-channels + redis server is ok? Django celery? -
Modify a django package that's deployed to heroku
I'm getting a import error ImportError: cannot import name python_2_unicode_compatible That error comes from /app/.heroku/python/lib/python3.6/site-packages/hitcount/models.py. In my local environ i've edited that file and replaced it with code that works. How can i do the same when when the app is deployed to heroku?