Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to understand the code behind ListView
I reviewed my trace back and saw this issue queryset = kwargs.pop('object_list', self.object_list) AttributeError: 'ProductListView' object has no attribute 'object_list' Here was my original code class ProductListView(ListView): model = Product template_name = "products/list.html" # added for pagination context_object_name='object_list' #Default: object_list # print(context_object_name) # paginate_by = 3 def get_context_data(self, *args, **kwargs): context = super(ProductListView, self).get_context_data(*args, **kwargs) cart_obj, new_obj = Cart.objects.new_or_get(self.request) print("get context data") # context = {} context['cart'] = cart_obj return context def get_queryset(self, *args, **kwargs): request = self.request return Product.objects.all() def get(self, request): paginate_by = request.GET.get('paginate_by',6) or 4 data = self.model.objects.all() paginator = Paginator(data, paginate_by) page = request.GET.get('page') try: paginated = paginator.page(page) except PageNotAnInteger: paginated = paginator.page(1) except EmptyPage: paginated = paginator.page(paginator.num_pages) context = self.get_context_data() context['DataPaginated'] = paginated context['paginate_by'] = paginate_by return render(request, self.template_name, context) To fix the issue I had to modify the get_context_data function in the class ProductListView(ListView): def get_context_data(self, *args, **kwargs): self.object_list = super().get_queryset() context = super(ProductListView, self).get_context_data(*args, **kwargs) I examined the code for ListView here https://www.kite.com/python/docs/django.views.generic.ListView. Method Flowchart dispatch() http_method_not_allowed() get_template_names() get_queryset() get_context_object_name() get_context_data() get() render_to_response() I am baffled why adding in super().get_queryset() helped though. My original problem was that the object had no attribute 'object_list'. The get method of BaseListView sets the object_list on the … -
My python datetime is not getting verified in my django application
I am trying to create a delete button in django app which sends the date whose entry has to be deleted to views.py when i click that button. Then I convert the date to correct format and try to fetch and delete the object from models.py whose date matches the date which is recieved from the delete button. The problem is that the date from delete button and date of objects stored in database isn't matching due to some reason. So the object isn't getting deleted. I am receiving this error when i click the delete button: Entry matching query does not exist. my views.py for handling the delete button: date = request.POST.get('date')#returns a date like Aug. 5, 2020, 12:58 a.m. date = date.replace('.', '')#here i replace the . from date otherwise it gives errors date = datetime.strptime(date, '%b %d, %Y, %I:%M %p')#converting the date to required format print(date)#prints: 2020-08-05 00:58:00 print(type(date))# prints: <class 'datetime.datetime'> req_entry = Entry.objects.filter(date=date).get() req_entry.delete() I tried to find in which format the date is stored through shell entry = Entry.objects.all().first() print(entry.date)#prints: datetime.datetime(2020, 8, 5, 0, 58, 50, 216525, tzinfo=<UTC>) I know that the date format in which data is stored and my date format aren't … -
Django: Get one-day activity of object of Queryset
Above is my feed model class Feed(models.Model): user = models.ForeignKey(UserModel, verbose_name=_("user"), on_delete=models.CASCADE) likes = models.IntegerField(_("Likes"),default=0) views = models.IntegerField(_("Views"),default=0) date_created = models.DateTimeField(auto_now_add=True) My question is the likes and views of this feed(model) will increase day by day, so if I want to know how likes or views got added today. How can I get that? For example, on first day feed gets 10 views, on second day it got 30 so the total of 40 views and on third day(present day) the total got to 70, the increase is 30, like this how can I get increase in views is 30 today in Django? -
Bokeh + Holoviews + Datashader on Django
We are trying to build a web app--Dashboard-- to show different interactive(including click callback, fetch new data etc) charts with Bokeh + Holoviews + Datashader on DJango. Since data is very large and could have 10+ million points we are using datashader. We can have a static html from backend from Bokeh + Holoviews + Datashader from Backend and pass it to front end using Django REST api as : views.py import numpy as np import holoviews as hv import datashader as ds from dask import dataframe as dd from bokeh.io import show, curdoc from bokeh.layouts import layout from bokeh.models import Slider, Button from holoviews.operation.datashader import datashade renderer = hv.renderer('bokeh').instance(mode='server') def home(request): def plot_info(y_col): from vaex import dataframe as datafm df_dask = dd.read_parquet(r"C:\Dropbox\1mln.parquet", engine='pyarrow', columns=['nest11', 'nest21', 'first_element', 'second_element', 'timestamp']) df_dask['timestamp'] = dd.to_datetime(df_dask.timestamp, unit='ns') return hv.Curve((df_dask['timestamp'], df_dask[y_col])) def bearer(): stream = hv.streams.Stream.define('y-axis', y_col="nest11")() dmap = hv.DynamicMap(plot_info, streams=[stream]) vmap = datashade(dmap).opts(width=1200, height=600, responsive=True) html = renderer.static_html(vmap) return html context = { 'seq_num': bearer(), } return render(request, 'home/welcome.html', context) Works fine. However Since we used Datashader, data is aggregated and converted in static html when we zoom in we would not get the data which we are looking for at from end side. … -
Implement search_fields functionality on Django admin webpage
In Django admin, I know there is "search_fields" which lets us decide which fields are searched for in python codes. I currently have that in my admin.py. Can I make this function built in the Django admin webpage so that users can decide the fields to search upon on the Django admin page? I guess checkbox would be a great choice. I know admin is not meant to be for general users but I need to know. For example, is it feasible/recommendable to change Django package codes? Thanks so much in advance. -
how to delete the previous objects which are not coming in the latest Api request made on basis of post_id from database in django
Here below is the function that is creating the objects with the model :All_Post:,where :all_post_request: is the function that has the json data from the api call to create the objects. Now when i trigger this below function what it does is just creates or updates the objects with post_id which are coming in the API request but few objects are like which were in previous request but now they are not coming in this new API request that i have made today i want it to delete those from db. def all_post_datarequest(): for i in all_post_request(): All_Post.objects.update_or_create(**i) I am trying below code in the above function after the objects are made. for j in All_Post.objects.all(): if j not in all_post_request(): j.delete() This function is deleting all the objects in this model :All_post: -
How to pass a string to html in django?
I'm supposed to pass a string to html from views.py but I can't print it out. I tried to make function that returns the desired string but it doesn't work. In calendarOfGroup.html: <body class="text-center mt-5"> <div class="cover-container d-flex w-100 h-100 p-3 mx-auto flex-column"> <main class="inner cove border" role="main" style="background-color: white;"> <h1 class="cover-heading mt-3">Lista Calendari di {{ nome }}</h1> <div class="mt-5"> <ul class="list-group"> {% for calendar in object_list %} <a href="{{ calendar.id }}"><li class="list-group-item list-group-item-action">{{ calendar.name }}</li></a> {% empty %} <li class="list-group-item">Non ci sono calendari disponibili per questo edificio</li> {% endfor %} </ul> </div> </main> </div> </body In views.py: class CalendarsOfGroupView(generic.ListView): model = Calendar template_name = 'cal/calendarOfGroup.html' #i = kwargs['group_id'] def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) group_id = self.kwargs['group_id'] object_list = Calendar.objects.filter(group=group_id) context.update({'object_list': object_list}) #print (context['object_list'][0].group.name) return context def nome(): return context['object_list'][0].group.name In urls.py: urlpatterns = [ url(r'^home/(?P<group_id>\d+)/$', views.CalendarsOfGroupView.as_view(), name='group_view'), ] In models.py: class CalendarGroups(models.Model): name = models.CharField(max_length = 155, blank=True, null=True) class Calendar(models.Model): name = models.CharField(max_length=200) #created_by group = models.ForeignKey(CalendarGroups, on_delete = models.CASCADE, default='') -
django test doesn't create a database for the test
i am trying to run tests with python manage.py test the output is this. System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s i have ran python manage.py test -v 2 an the output is this Skipping setup of unused database(s): default. System check identified no issues (0 silenced). ---------------------------------------------------------------------- Ran 0 tests in 0.000s OK It is not creating a database or even running the tests in my file, i do not know what is wrong. This is my first time running tests. settings.py """ Django settings for vuewe project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os import sys import environ env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file environ.Env.read_env() # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env('SECRET_KEY') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env('DEBUG') ALLOWED_HOSTS = [] LOGOUT_REDIRECT_URL … -
Restricting users that do not follow an account from viewing certain fields?
Currently I have an accounts endpoint /api/accounts/ and also more specific endpoints such as /api/accounts/1/followers The users who follow the account to be able to see all their fields (username, profile picture, posts, followers, ...) but users who do not should only see their username and profile picture. I have tried setting the queryset in the accounts viewset to only accounts the user folllows, but this raises a problem as it would prevent the user from discovering more accounts. I want it to be similar to instagram where discovering accounts is still possible but you cannot view their posts and etc. until you follow them or they are public. -
add django for loop in the template using javascript
can i add a {% for in %} loop and {{ variables }} in django template using javascript dom (insertAdjacentText, or textContent) and charge data from the views without refresh the page ? if yes guide me i searched and i did not function display3D(){ let label = document.getElementById('label'); let rem = document.getElementById('remove') let amg = document.getElementsByClassName('amg') let namep =document.getElementsByClassName('namep') let add =document.getElementById('add') add.insertAdjacentText('afterbegin','{% for plan in plan3 %}') add.insertAdjacentText('beforeend','{% endfor %}')*/ for(let i =0;i<x.length;i++){ x[i].textContent='{{ plan.IdPlans }}' amg[i].setAttribute('src','{{plan.Image.url}}') namep[i].textContent='{{ plan.NamePlan }} :' } } <figure id="label3" class="fig" onclick="displayMaquette()"> <figcaption class="caption" onmouseover="figCaptionHover(this)" onmouseout="figCaptionOut(this)">Cliquez pour afficher les maquettes</figcaption> <img class="figimg" src="" alt="Elephant at sunset" > </figure> </div> <article class="works none"> <p class="pNone" style="display: none;"></p> <div class="worksimg"> <img class="Img amg" Img src=""> </div> <div class="Description"> <h2 class="namep"></h2> <p></p> </div> </article> <div id="remove"></div> find? By onclick event i add the for loop and {{ variables }} but it display as text in the browser it doesn't charge datas from views what i wan't is charge data from database -
Why are my Django passwords not being encrypted?
I'm using Django, and I added the views to create, update, etc. my users. I'm using the users fromfrom django.contrib.auth.models import User, and I can successfully see the auth_user created when migrating. The only issue I see is that the passwords are not being hashed. I have another project, in which I can see the passwords being automatically hashed, and as far as I could investigate, that's the default behavior they should have when using the default Django users, correct? I'm relatively new to Django, so this is probably something quite simple. My create view looks like this: class UserCreateView(LoginRequiredMixin, CreateView): """ -----------------------Vista de crear usuarios-------------------------- """ template_name = 'users/users_form.html' model = User fields = ["username", "password", "is_superuser", "is_staff", "first_name", "last_name", "email", "is_active"] success_url = reverse_lazy("users:list_users") Another thing (that's less of an issue, but maybe it's relevant information) is that the password field is in the view not appearing as a password field per se, but as a regular text field. Any help would be grately appreciated. -
How to import data from file lets say .csv to djagno model?
I want to export data from django models from django admin panel, how can i quickly make it happen, i am new to django so don't have much idea, thanks in advance. -
Button not working as it was supposed to in a django website that I am working on
I am working on a website . There is a payment button on my website . Here is the HTML code for for the button: <button class="btnabc btnabc-secondary btnabc-lg d-none" id='payment-info'>Proceed</button> and here is the javascript code for it: document.getElementById('payment-info').addEventListener('click', function (e) { submitFormData() }) function submitFormData() { console.log('Payment Button Clicked') var userFormData = { 'name': null, } var shippingInfo = { 'address': null, } shippingInfo.address = form.address.value userFormData.name=form.name.value var url = "/process_order/" fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'form': userFormData, 'shipping': shippingInfo }), }) .then((response) => response.json()) .then((data) => { console.log('Success:', data); alert('Transaction Completed') window.location.href = "{% url 'index' %}" }) } After wring this code I integrated a payment gateway . Before integrating it was working fine and on clicking the payment button I was getting the alert Transaction completed and the data was being saved in my database. This is my views.py for the respective button: def processOrder(request): transaction_id = datetime.datetime.now().timestamp() data = json.loads(request.body) if request.user.is_authenticated: customer=request.user.customer order, created=Order.objects.get_or_create(customer=customer, complete=False) total=float(data['form']['total']) order.transaction_id=transaction_id if total == order.get_cart_total: order.complete = True order.save() ShippingAddress.objects.create( customer=customer, order=order, address=data['shipping']['address'], name=data['form']['name'], ) param_dict = { 'MID': 'Your-Merchant-Id-Here', 'ORDER_ID': '3', 'TXN_AMOUNT': '4', 'CUST_ID': 'j', 'INDUSTRY_TYPE_ID': 'Retail', 'WEBSITE': 'WEBSTAGING', 'CHANNEL_ID': … -
How to fix the ImproperlyConfigured exception?
I listen to a video that explains how to do login API to Facebook now I installed the allauth lib by pip3 and placed it into INSTALLED_APPS and I did create AUTHENTICATION_BACKENDS and all the initializations of allauth lib to handle it and when I do migrate to apps I was show error that defines that I should put django.setup() and I did fix it now I receive the next Trace: Traceback (most recent call last): File "manage.py", line 23, in <module> django.setup() File "/media/abdelhamedabdin/BE4C6BE74C6B98C3/Cources/Django/all git/ripo/website/venv/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/media/abdelhamedabdin/BE4C6BE74C6B98C3/Cources/Django/all git/ripo/website/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 76, in __getattr__ self._setup(name) File "/media/abdelhamedabdin/BE4C6BE74C6B98C3/Cources/Django/all git/ripo/website/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 57, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. so how can I fix this issue? -
bootstrap sticky-top class does work properly (used with django)
i have a bootstrap navbar with a sticky-top class it's works for about 200px scroll but when i pass that 200px limit it does not work , the thing is when a use the navbar with the bootstrap starter template ( no local server just html ) it works but when use it whit django and i run my sever it does not work base.html <!DOCTYPE html> <html> {% include 'head.html' %} <body> {% include 'header.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html> head.html: {% load static %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="robots" content="all,follow"> <!-- Bootstrap CSS--> <link rel="stylesheet" href="{% static 'vendor/bootstrap-4.5.0/css/bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'swiper-5.3.7/package/css/swiper.min.css' %}"> <script src="https://kit.fontawesome.com/f057e2fa03.js" crossorigin="anonymous"></script> <link rel="stylesheet" href="{% static 'vendor/jquery-ui-1.12.1/jquery-ui.min.css' %}"> <!-- Google fonts - Open Sans--> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <!-- theme stylesheet--> <!-- Custom stylesheet - for your changes--> <link rel="stylesheet" href="{% static 'css/custom.css' %}"> <!-- semantic UI --> <link rel="stylesheet" type='text/css' href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.2.14/semantic.min.css"> <!--Chart js--> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js" integrity="sha256-Uv9BNBucvCPipKQ2NS9wYpJmi8DTOEfTA/nH2aoJALw=" crossorigin="anonymous"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.css" integrity="sha256-aa0xaJgmK/X74WM224KMQeNQC2xYKwlAt08oZqjeF0E=" crossorigin="anonymous" /> <!--braintree--> <script src="https://js.braintreegateway.com/web/dropin/1.22.1/js/dropin.min.js"></script> </head> header.html {% url 'home' as home_url %} {% url 'products_list' as … -
i'm not able to create another database in postgres with django after creating the first one
i'm using django in all my projects and in my first project i changed the database from sql lite normally i created a server group then the server and the DB etc.. and changed the settings.py file of the project with the according configuration DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myDatabaseName', 'USER': 'postgres', 'PASSWORD': 'MyPassword', 'HOST': 'localhost', 'PORT': '5432', } and after about a month i started another project with django and ofc i needed a database and whenever i create another database it automatically associates it with the earlier one and it automatically have the same tables with earlier one so i need the steps to create another database with diffrent models and tables , thank you -
JSON data reading error for django weather website project - KeyError "main"
I am pulling data in JSON format from https://openweathermap.org/ to display on a django website. The JSON is shown below but I seem to be unable to read it and insert it into a dictionary. I call it using the proper API key that reads by city. When attempting to access the server, I get a KeyError with the exception value of "main" on the views.py code. Main is an attribute on the JSON which confuses me. JSON {"coord": { "lon": 139,"lat": 35}, "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" } ], "base": "stations", "main": { "temp": 281.52, "feels_like": 278.99, "temp_min": 280.15, "temp_max": 283.71, "pressure": 1016, "humidity": 93 }, "wind": { "speed": 0.47, "deg": 107.538 }, "clouds": { "all": 2 }, "dt": 1560350192, "sys": { "type": 3, "id": 2019346, "message": 0.0065, "country": "JP", "sunrise": 1560281377, "sunset": 1560333478 }, "timezone": 32400, "id": 1851632, "name": "Shuzenji", "cod": 200 } views.py from django.shortcuts import render import requests from .models import City from .forms import CityForm def index(request): cities = City.objects.all() url = 'http://api.openweathermap.org/data/2.5/weather?q={}&units=imperial&appid=a8e8641ead06969636aaca4a66e2f90e' if request.method == 'POST': # only true if form is submitted form = CityForm(request.POST) # add actual request data to form for processing form.save() # … -
Signal seems to be not connected
Django=3.0.8 apps.py from django.apps import AppConfig class AdminAuxConfig(AppConfig): name = 'admin_aux' def ready(self): import admin_aux.allauth_avatar # Breakpoint. Stopps here when the server is run. admin_aux/allauth_avatar.py @receiver(user_signed_up) # Breakpoint. Doesn't stop here when the server is run. def on_user_signed_up(sender, request, *args, **kwargs): sociallogin = kwargs.get('sociallogin') if sociallogin: copy_avatar(request, sociallogin.account.user, sociallogin.account) Problem: the receiver doesn't receive the signal. I marked breakpoints in the code. When I run debugging in PyCharm, I expect that the interpreter will stop at the breakpoint in allauth_avatar.py. But it doesn't. So, signal seems to be not connected. Could you help me here? -
Getting profile Linkedin Profile Picture django-allauth
I know that this should be a question, but after such a headache, I thought that I should help some one with this same problem. I'm using Allauth 0.42.0 and Django 3.0.8, following the allauth documentation, I could not, for the love of my life get the Profile Picture url from the user. -
display and charge data from databae in django template with onclick event
i am working on a one page web site using django, when the page is charging i have 3 pictures and i wan't add a differents onclick for each picture and each click will display a differents data(one table with the same foreign key for each picture) from the database now i made it but using the dom, i charge all data in the page and i play with the display(css) to display data for each onclick of the pictures what i wan't is that data charge when i click not from the begining with the page if i can adod a{% for in %}loop by javascript it will resolve the problem but when i add the for loop the for loop is displayed on the browser and data isn't charged from db pleeaaase heeeelp thank's pictures where the onclick is Liste to display from data base after the onclick -
Django - How to sett a variable on layout template and use it across all views
I would like to set a variable and display it on the top navigation. I would like to do a count of received email and display the number on the menu informing the user they have eg 3 messages. Just as you can access your user id or username I want to access the count of the email the user received. I was checking how to set global variables but there might be something else I can do. Please let me know if you need more info. -
Private chat feature using Django and Vue.js
Can someone help me out on how to implement a private(user to user) chat feature using Django and Vue.js? The frontend and backend communicate using APIs with the help of django rest framework. Looked up and found a way using polling, but does not seem to be an efficient method. A few tutorials on Django channel seem to be on chat rooms, but that is not what I'm looking for. -
ModelForm has no model class specified while accessing to html
I have a model form and shown the error: ModelForm has no model class specified while accessing to html. forms.py: class Add_Product(forms.ModelForm): product_name = forms.CharField() price = forms.DecimalField() img = forms.ImageField() img2 = forms.ImageField() img3 = forms.ImageField() storage_amount = forms.IntegerField() description = forms.CharField(widget=forms.Textarea(attrs={'cols': 80, 'rows': 20})) Hot = forms.BooleanField(widget=forms.CheckboxInput()) type = forms.ChoiceField(widget=forms.RadioSelect, choices=PRODUCT_CHOICES) status = forms.ChoiceField(choices=STATUS) slug = forms.CharField() class Meta: models = Product fields = ('product_name', 'price', 'img', 'img2', 'img3', 'storage_amount', 'description', 'Hot', 'type', 'status', 'slug') views.py: def add_product(request): if request.method == 'POST': form = Add_Product(request.POST) if form.is_valid: form.save() messages.success(request, 'Succeed') return redirect('/') else: form = Add_Product() context = {'form': form} return render(request, 'add_product.html', context) add_prodcut.html: <form method="POST" class="card-body" > {% csrf_token %} {{ form | crispy }} <button type="submit" value="submit">Submit</button> </form> -
How to get multiple line charts using plotly in Django framework?
I am trying to create two line charts at once. I was successful at creating one line chart path = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..\\..\\..\\database\\data.csv') predict_data = pd.read_csv(path) predict_data_x = pd.melt(predict_data,id_vars=['time'],value_vars=[last_recorded',ax_last_recorded']) fig = px.line(predict_data_x,x='time',y='value',color='variable') p = opy.plot(fig, auto_open =False, output_type='div' ) return render(request, 'pred_recom/trends.html', {'graph': p}) This successfully creates a line graph showing two lines. I want to create another one from the same predict_data dataframe but when I am rewriting the above code and only changing the value_vars I am getting an error saying opy is not defined. I am very new to this. Where am I going wrong? -
css file in static folder is not applied to the web page
I have given all the requirements to have static files all the files in static folder is loaded and accessable in webpage but the css file is not applied to the webpage.I once again gone through the documentation to setup static files but the style is applied and there is no error while run in local host