Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create a database (model) table in django when an url is called
How to create a table in django database when a specific URL is called? eg: When user goes to http://localhost:8000/create/ a table with two fields (say: x and y) and current timestamp as table name should create dynamically. Thank you in advance. -
Run single task upto n times in django celery
Suppose I have task called lazy_post_task. code somethings like this @app.task(bind=True) def lazy_post_task(self, post_url): self.update_state(state='PROGRESS', meta={}) ............. Now i want to run this task upto n times and n depends on user input and also i want to wait until previous task complete. i mean, suppose user input=2 then i want to run task upto 2 times but one at a time. -
Wrapping block tag in cache tag
If I have a template extending another, how can I cache its content? Or most of it, rather. {% extends 'base_template.html' %} {% block header %}{% endblock %} {% block content %}{% endblock %} {% block footer %}{% endblock %} {% block js %}{% endblock %} How about when there's nested blocks? {% block header %} {% block brand_img %}{% endblock %} {% endblock %} Can I just wrap all those blocks at once? {% cache 3600 cache-name %} {% block header %}{% endblock %} {% block content %}{% endblock %} {% block footer %}{% endblock %} {% block js %}{% endblock %} {% endcache %} Or do I need to do it within every single block I have? -
Django - Urls are appending to one another
I'm making a web app in django and currently I'm facing this problem. I have a dashboard page and an upload page. There's a button in dashboard page which links to the upload page. but whenever I click the button then the upload page url appends the dashboard page. below is the code: views.py from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from .models import Registration from .forms import UploadForm from django.urls import reverse # Create your views here. def homepage(request): return render(request, 'index.html', {}) def dashboard(request): posts = Registration.objects.all() return render(request, "dashboard.html", {'posts': posts}) def upload(request): form = UploadForm() return render(request, "upload.html", {'form': form}) def uploadimage(request): if request.method == 'POST': form=UploadForm(request.FILES['image'], request.POST) if form.is_valid(): pic = request.FILES['image'] desc = request.POST post = Registration(pic='pic', desc='desc') post.save() urls.py from django.urls import path from django.conf import settings from django.conf.urls.static import static from . import views urlpatterns = [ path('', views.homepage, name='homepage'), path('dashboard/', views.dashboard, name='dashboard'), path('upload/', views.upload, name='upload'), path('create/', views.uploadimage, name='uploadimage'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) dashboard.html <div class="profile"> <div class="left-s col s12 m3 l3"> <div class="profile-overview"> <img src="{%static 'images/group.jpg' %}" alt="profile-pic" class="circle responsive-img"> <p>Daljit Singh</p> <p>Lorem ipsum dolor sit amet.</p> </div> <hr> <div class="container"> <ul> <li><a href="#">About</a></li> <li><a href="#">Friends</a></li> <li><a href="#">Photos</a></li> … -
I have a list of dictionaries from Salesforce database and I need to replace the '__c' with a space
AM creating a Django app to store user dictionaries from the salesforce query. I have this loop printing key Value pairs, but the keys have "__c" which I need to remove before saving the dictionaries as users to Postgress for employee_data in data: for key, value in employee_data.items(): print('{}: {}'.format(key, value)) sample_data_from_sandbox = [{'attributes': {'type': 'Employee__c', 'url': '/services/data/v38.0/sobjects/Employee__c/aAs7E0000004FkISAU'}, 'Id': 'aAs7E0000004FkISAU', 'Line_Manager__c': 'aAsD000000001S7KAI', 'HR_Employee_ID__c': None, 'Employee_Active__c': True, 'Employee_First_Name__c': 'Martin', 'Name': 'Martin Luther', 'Work_Email__c': None, 'IsDeleted': False}, {'attributes': {'type': 'Employee__c', 'url': '/services/data/v38.0/sobjects/Employee__c/aAs7E0000004FjKSAU'}, 'Id': 'aAs7E0000004FjKSAU', 'Line_Manager__c': 'aAsD0000000GmgMKAS', 'HR_Employee_ID__c': None, 'Employee_Active__c': True, 'Employee_First_Name__c': 'Khole', 'Name': 'Khole Kardashian', 'Work_Email__c': None, 'IsDeleted': False}] -
django is it possible to aggregate all the fields of a queryset at once
Data comes from another database so i cant edit the model. each user plays several matches and each match's stats are saved on its own table line for example if i need to count the amount of kills a player made i can count it by kills = Get5StatsPlayers.objects.filter(steamid64=reuest.user.SocialAuth.uid).aggregate( sum=Sum('kills')) my question is can i do it to all of the fields at once? class Get5StatsPlayers(models.Model): matchid = models.PositiveIntegerField(primary_key=True) mapnumber = models.PositiveSmallIntegerField() steamid64 = models.CharField(max_length=32) team = models.CharField(max_length=16) rounds_played = models.PositiveSmallIntegerField() name = models.CharField(max_length=64) kills = models.PositiveSmallIntegerField() deaths = models.PositiveSmallIntegerField() assists = models.PositiveSmallIntegerField() flashbang_assists = models.PositiveSmallIntegerField() teamkills = models.PositiveSmallIntegerField() headshot_kills = models.PositiveSmallIntegerField() damage = models.PositiveIntegerField() bomb_plants = models.PositiveSmallIntegerField() bomb_defuses = models.PositiveSmallIntegerField() v1 = models.PositiveSmallIntegerField() v2 = models.PositiveSmallIntegerField() v3 = models.PositiveSmallIntegerField() v4 = models.PositiveSmallIntegerField() v5 = models.PositiveSmallIntegerField() number_2k = models.PositiveSmallIntegerField(db_column='2k') # Field renamed because it wasn't a valid Python identifier. number_3k = models.PositiveSmallIntegerField(db_column='3k') # Field renamed because it wasn't a valid Python identifier. number_4k = models.PositiveSmallIntegerField(db_column='4k') # Field renamed because it wasn't a valid Python identifier. number_5k = models.PositiveSmallIntegerField(db_column='5k') # Field renamed because it wasn't a valid Python identifier. firstkill_t = models.PositiveSmallIntegerField() firstkill_ct = models.PositiveSmallIntegerField() firstdeath_t = models.PositiveSmallIntegerField() firstdeath_ct = models.PositiveSmallIntegerField() -
How to implement custom login function and auth in django?
I have created a new model named AppUser in the sqllite db through Django and i dont want use the default django administration user model for my app login system. I ve implemented a login view function (below code) and the point where i am stuck is that i want to store the matched username as a local storage variable in the form of session,cookie,etc and later i want to access them to check whether the user is logged in or not by getting the session value in all my rest views/templates. I need help that what will be the best way to do so. below is my current login view function LOGIN.PY from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import render, redirect from .models import AppUser from .forms import AppUserForm from django.utils.timezone import now as timezone_now def login_submit(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') curtime = timezone_now() form = AppUserForm(request.POST) if AppUser.objects.filter(username=username, password=password).exists(): AppUser.objects.filter(username=username, password=password).update(checklogin=1, lastlogin=curtime) request.session['username'] = username //HERE I WANT TO SAVE THE VALUE LOCALLY return HttpResponseRedirect('/') else: return login(request) -
Open and Close browser using selenium(python
I have a test where I need to do a login, close browser and open it again login again user username and password How can I do this with (python and selenium) here I'm using django celery to run task in the background. Test is something like this: Open browser Login Close browser Open browser again and login again -
Add to my logger field with ManyToMany relation in Django
A custom logger is written, it is used when editing or modifying objects. A field with a many-to-many relationship has appeared and its change is not displayed. How can this be fixed? Handler's code: class BaseLog(metaclass=ABCMeta): def __init__(self, instance, created): self.diff = {} self.created = created self.new_instance = instance self.old_instance = self._get_object(instance.id) self.fields = self._get_fields() def update_diff(self, field, new, old=None): print(old) if old is None: self.diff[field] = new else: if old != new: self.diff[field] = (old, new) def get_diff(self): for field in self.fields: if self.old_instance is not None: self.update_diff( field[0], getattr(self.new_instance, field[1]), getattr(self.old_instance, field[1]), ) else: self.update_diff(field[0], getattr(self.new_instance, field[1])) return self.diff @abstractmethod def _get_object(self, obj_id): pass @abstractmethod def _get_fields(self): pass Code for my model: class ServiceLog(BaseLog): def _get_object(self, obj_id): if self.created: return None try: return Service.objects.get(id=obj_id) except Service.DoesNotExist: return None def _get_fields(self): return [ ('flow', 'flow_name'), ('currency', 'currency_iso_name'), ('contractor', 'contractor_name'), ('amount', 'amount'), ('callback_url', 'callback_url'), ('definition', 'definition'), ('description', 'description'), ('charge_strategy', 'charge_strategy'), ('routine', 'routine'), ('service_keys', 'service_keys') ] Save the record: @receiver([pre_save_with_user, post_save_with_user]) def logger_update_callback(sender, **kwargs): is_created = kwargs['created'] if sender == Service: obj_log = ServiceLog(kwargs['instance'], is_created) elif sender == Deal: obj_log = DealLog(kwargs['instance'], is_created) else: raise NotImplementedError( 'Logs for the model {} are not implemented'.format(sender) ) log_record = {'who': str(kwargs.get('user', None)), 'what_model': … -
dynamicly change part of form in django admin
I have a model with jsonField type like below class Product(models.Model): name=models.CharField(max_length=255,null=False,blank=False) description=models.TextField(max_length=500,null=True,blank=True) category=models.ForeignKey(Category,null=False,on_delete=models.CASCADE) values = JSONField() and category model which include JsonSchema needed for this json field as below: class Category(models.Model): category_name=models.CharField(max_length=255,unique=True) type = models.ForeignKey(Type, on_delete=models.CASCADE) attributes_Schema_name = models.CharField(max_length=255) def __str__(self): return self.category_name and i made admin form like below : def Make_ProductJSONModelAdminForm(cat_id): class ProductJSONModelAdminForm(forms.ModelForm): class Meta: model = Product fields = "__all__" DATA_SCHEMA_name=Category.objects.values_list('attributes_Schema_name',flat=True).get(id=int(cat_id)) with open("attSchemas/{0}".format(DATA_SCHEMA_name)) as jfile: DATA_SCHEMA=json.load(jfile) widgets = { 'values': JSONEditorWidget(DATA_SCHEMA, collapsed=False), } return ProductJSONModelAdminForm @admin.register(Product) class ProductModelAdmin(admin.ModelAdmin): form = Make_ProductJSONModelAdminForm(cat_id=2) inlines = [productUnitInline, productImageInline] the problem is : i need to pass cat_id=2 dynamicly when category is selected in admin. actually i need to get cat_id in below code dynamicly on category select in admin. form = Make_ProductJSONModelAdminForm(cat_id=2) i am wondering is it possible or not ? -
IntegrityError: insert or update on table "carts_cart_items" violates foreign key constraint
DETAIL: Key (cartitem_id)=(11) is not present in table "carts_cartitem"."carts_cart_items_cartitem_id_197166f7_fk_carts_cartitem_id" DETAIL: Key (cartitem_id)=(11) is not present in table "carts_cartitem". guys what I missing in this error: models: class CartItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.IntegerField(default=1) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) def __unicode__(self): return item.title class Cart(models.Model): items = models.ManyToManyField(CartItem, null=True, blank=True) products = models.ManyToManyField(Item, null=True, blank=True) total = models.DecimalField(max_digits=100, decimal_places=2, default=0.00) created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) active = models.BooleanField(default=True) class Meta: get_latest_by = "updated" def __unicode__(self): return "Card Id: %s" %(self.id) -
Django: Set an alias to the group by (annotate) field of Model.objects.filter
When group by is used on a Django Model filtering, how can we set an alias/label to the order by field in the response? now = datetime.now() Attendance.objects.filter(member_id=user_id, date__gte=now.date()).values('attdate__week_day').annotate( attendance_amount=Count('attdate__week_day')) This returns the following. { "attdate__week_day": 2, "attendance_amount": 2 } In above result set I need to change the "date__week_day" to "day". Is this possible? -
Loop over multiple values in Jinja
I have a dict of lists which look like this: context = {"x":["col1", "col2", "col3"], "a":["val1","val2","val3"], "b":["val4","val5","val6"]} ** I have particular reasons for this structure. I'm passing this data from views.py to file.html like return render(request, "main/file.html", context) And I'm looping like this to get a data to table in html to look like a csv file (horizontaly) <table id = "table_one", style="font-size:12px;"> <tr> {% if x %} # Creating column names {% for y in x %} <th>{{ y }}</th> {% endfor %} </tr> <tr> <td>{{ a.0 }}</td> # First data(first row) for the first column name <td>{{ b.0 }}</td> # First data(first row) for the second column name etc.... </tr> <tr> <td>{{ a.1 }}</td> <td>{{ b.1 }}</td> </tr> <tr> <td>{{ a.2 }}</td> <td>{{ b.2 }}</td> </tr> It makes something like this: col1 col2 col3 val1 val2 val3 val4 val5 val6 Which works (col1 contains val1 and val4 which have a relationship). But I have to make a lot of tags, when I want to render more than two rows of values. I would like to make this for all data in a and b, which are thousands of rows.... Why I'm creating a and b in my views.py … -
return queryset for specific fields to autocomplete formfields
I'm not a django expert so I'm not sure if I'm just searching for the wrong thing but I'm trying to use django-autocomplete-light to autocomplete some fields on a modelform. I have a model, Animal. Animal has several fields. My goal is to have a modelform that has autocomplete for several of these fields. forms.py class AnimalForm(ModelForm): class Meta: model = Animal fields = [ 'myfield' ] widgets = { 'myfield': autocomplete.ListSelect2( url='myfield-autocomplete') } views.py: class MyfieldAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return Animal.objects.none() qs = Animal.objects.filter().values('myfield') if self.q: qs = qs.filter(name__istartswith=self.q) return qs I get: AttributeError: 'dict' object has no attribute 'pk' I think because the Animal.objects.filter().values('myfield') returns the actual values, rather than a queryset. If I change my queryset to: class MyfieldAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): # Don't forget to filter out results depending on the visitor ! if not self.request.user.is_authenticated: return Animal.objects.none() qs = Animal.objects.all() if self.q: qs = qs.filter(name__istartswith=self.q) return qs This loads and my autocomplete field is populated with the name field of the Animal objects. Instead of name I want to be able to specify an arbitrary field. -
Sessions not storing while using them in view function django
I want to store the username value in my browser sessions when i call the login function from view . I have tried the request.session syntax but it is not working and not storing the username in my sessions. I have confirmed that by going to the developer tools console. VIEW FUNCTION def login_submit(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') form = AppUserForm(request.POST) # form['my_field'].value() if AppUser.objects.filter(username=username, password=password).exists(): request.session['username'] = username //I WANT TO SET THE SESSION HERE return HttpResponseRedirect('/') else: return login(request) -
Multiple-Table inheritance Django
When would you ever need to use Multiple_table inheritance? Its essentially just a combined step for instantiation a Child Model, Parent Model and a one to one associated relation Has anyone used multiple_table inheritance? -
query to get the 10 question ids for the input tag ids
I have 2 models class Tag(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) def __str__(self): return self.name class Question(models.Model): ques_id = models.IntegerField(default=0) name = models.CharField(max_length=255) Tag_name = models.ManyToManyField(Tag) class Meta: ordering = ['ques_id'] def __str__(self): return self.name I want the response like { "id": 1, "name": "QUES 1", "tags": [{ "id": 1, "name": "Abcd" }] } what will be query to get the 10 question ids for the input tag ids ? -
Signup page upon submission leads to error Django
I have built a site, where the user upon successful signup should be redirected to the login page. However it is not occurring so. Attached below are the relevant files: Signup page html: {% extends "base.html" %} {% load bootstrap4 %} {% block content %} <div class="container"> <h1>Sign Up</h1> <form method="POST" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button type="submit" class="btn btn-primary">Sign Up</button> {% endbuttons %} </form> </div> {% endblock %} Urls.py from django.urls import path from django.contrib.auth import views as auth_views from . import views app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name="accounts/login.html"),name='login'), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('signup/', views.SignUp.as_view(), name="signup"), ] views.py: class SignUp(CreateView): form_class = forms.UserCreateForm success_url = reverse_lazy("login") template_name = "accounts/signup.html" Any help is appreciated. Thank you. -
How can change fields name with list of labels when I am registring my model in django admin site
I registered my model in admin.py, I want to change some model fields name with list of labels. I know how to do it in forms but mentioning labels in Admin model class are not reflecting it on Admin site. I need help how to use list of labels in Admin.py class eAdmin(admin.ModelAdmin): list_display = ('name', 'phone_number', 'email_id', 'country', 'state') list_filter = ('funnel', 'country', 'state') search_fields = ['email_id'] exclude = ('city',) class Meta: labels = labels_list admin.site.register(EApplications, eAdmin) -
How to send message from django view to consumer (django-channels)?
I want to send some message from Django view to django channels consumer. I have consumer like: from channels.generic.websocket import AsyncWebsocketConsumer import json class KafkaConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'kafka' # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] # Send message to room group await self.channel_layer.group_send( self.room_group_name, { 'type': 'kafka_message', 'message': message } ) # Receive message from room group async def kafka_message(self, event): message = event['message'] # Send message to WebSocket await self.send(text_data=json.dumps({ 'message': message })) And, my Django view is like: from django.views.generic import TemplateView from django.http import HttpResponse from channels.layers import get_channel_layer from asgiref.sync import async_to_sync class LogView(TemplateView): template_name = "kafka/index.html" def testview(request): channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send( 'kafka', { 'type': 'kafka.message', 'message': 'Test message Krish' } )) return HttpResponse('<p>Done</p>') URL url is like: from django.urls import path from .views import LogView, testview urlpatterns = [ path(r'', LogView.as_view()), path(r'test/', testview), ] So, when I do http://mydevhost/test, consumer do not receive message. However, I can send message from/within consumer i.e. KafkaConsumer.receive in channels consumer. -
retrieve data or record from DB in JSON format Django
I have this model class Pharmacy(models.Model): name = models.CharField(max_length = 256) contact = models.CharField(max_length = 15) city = models.CharField(max_length = 20) address = models.TextField() lat = models.FloatField() long = models.FloatField() def __str__(self): return self.name it is views.py def PharmacyJsonList(request): data = serializers.serialize('json',Pharmacy.objects.all()) return JsonResponse({'data':data}) result is in this format I want just fields in json format without these slushes could I do it in Class Base View? -
Implementing countdown in django in template
I have a bootstrap template where the countdown is already implemented. And the time is hardcoded like below. <div data-countdown="2020/03/01"></div> here, if I change the number like 2020 it shows the calculated time. But I didn't want this hardcoded time or number. I want to put my actual time from my DateTime fields. So how can I use my DateTime variable as a template variable and put it as the parameter of the data-countdown attribute above? Like we do with {{}} . -
How to create nodes dynamically in neo4j database by using angularjs(fornt end) and django, python?
Using AngularJs we are creating labels in a tree structure (i.e main-node, sub-nodes). When ever we create a new label or sub-label(main-node or sub-node) from front end then dynamically the front end label name should be create as a node(with label name) in neo4j database.For back-end we are using Python with Django framework. For above requirement how can I implement,please share any reference. -
How to connect with multiple database in Django?
I want to connect with multiple databases in Django and to show the selected records from each table in view. -
What are the steps to create a socket using Django Rest Framework
How to implement socket programming using django rest framework. And how to create Api for send message,recive message etc..