Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
djangocms custom apphook with multilanguage
I am using djangoCMS with some custom App hook with models. Everything is working fine for English. Now I need the app in Arabic. But when I change the content for Arabic, the same is getting reflected in English page also. How to deal with the same. I am very new to django cms. Please help. App hook Model from django.db import models from filer.fields.image import FilerImageField from django.urls import reverse from cms.models.fields import PlaceholderField from cms.models import CMSPlugin from djangocms_text_ckeditor.fields import HTMLField # Create your models here. class Services(models.Model): class Meta: app_label= 'voxservices' service_name = models.CharField( blank=False, unique=True, help_text="Please enter the Service you are providing", max_length=100 ) slug = models.SlugField( blank=False, default='', help_text='Provide a unique slug for this service', max_length=100, ) photo = FilerImageField( blank=True, null=True, on_delete=models.SET_NULL, help_text='Add the photo for the service' ) font_awesome_class = models.CharField( max_length=100, null=True, blank=True ) service_intro = models.TextField() service_description = HTMLField(blank=True) is_featured = models.BooleanField() def get_absolute_url(self): return reverse("voxservices:services_detail", kwargs={"slug": self.slug}) def __str__(self): return self.service_name # For plugin class FeaturedServicesPluginModel(CMSPlugin): featured_services = Services.objects.all().filter(is_featured=True) def __str__(self): return "{selected} Selected articles".format(selected=self.featured_services.all()) def copy_relations(self, oldinstance): self.featured_services = oldinstance.featured_services.all() views from django.shortcuts import render from django.views.generic import DetailView,ListView from .models import Services # Create your views here. class … -
Netbox Management IP Address
I have installed netbox on an Ubuntu Server. I have tested the netbox out using this command python3 manage.py runserver 0.0.0.0:8000 --insecure This works and I have left it running as a task in the background for now. It's not a permanent solution. I was able to get the service running, as I am able to access it using wget 127.0.0.1:8000 This is a local loopback address and I wanted to know how I can change this to the ip address of the server. I have tried to change the Server Address in the config but no luck This is what the systemctl status looks like: Nov 02 12:05:29 l systemd[1]: Started NetBox WSGI Service. Nov 02 12:05:29 l gunicorn[2330166]: !!! Nov 02 12:05:29 l gunicorn[2330166]: !!! WARNING: configuration file should have a valid Python extension. Nov 02 12:05:29 l gunicorn[2330166]: !!! Nov 02 12:05:29 l gunicorn[2330166]: [2020-11-02 12:05:29 +0000] [2330166] [INFO] Starting gunicorn 20.0.4 Nov 02 12:05:29 l gunicorn[2330166]: [2020-11-02 12:05:29 +0000] [2330166] [INFO] Listening at: http://127.0.0.1:8000 (2330166) Nov 02 12:05:29 l gunicorn[2330166]: [2020-11-02 12:05:29 +0000] [2330166] [INFO] Using worker: sync Nov 02 12:05:29 l gunicorn[2330195]: [2020-11-02 12:05:29 +0000] [2330195] [INFO] Booting worker with pid: 2330195 If someone could … -
The virtual environment is made in my user s folder
No matter what folder am I'm, command 'pipenv shell' creat virtualenvironment named by my username, doesn't create virtualenvironment named by my project(folder's name). Could you please help me with that? -
How to write submit method for shopping in django models?
In the code below, i want to write submit method for the shopping, i don't know what i have written is correct or not, and i don't know how to stop customer from adding new items after the order is submitted.( when we submit an order, shopping is done.) please help me or give me some points to write cancel and send methods of Order class too. Thanks. class OrderRow(models.Model): product = models.ForeignKey('Product') order = models.ForeignKey('Order', on_delete=models.CASCADE) amount = models.IntegerField() class Order(models.Model): # Status values. DO NOT EDIT STATUS_SHOPPING = 1 STATUS_SUBMITTED = 2 STATUS_CANCELED = 3 STATUS_SENT = 4 status_choices = ( STATUS_SHOPPING, STATUS_SUBMITTED, STATUS_CANCELED, STATUS_SENT, ) customer = models.ForeignKey('Customer') order_time = models.TimeField(auto_now_add=True) total_price = sum(F('OrderRow.product__price') * F('OrderRow.amount')) status = models.IntegerField(choices=status_choices) @staticmethod def initiate(self, customer): self.customer = customer self.status = 1 def add_product(self, product, amount): self.status = 1 if self.orderrow_set.filter(product=product).exists(): preexisting_order_row = OrderRow.objects.get(product=product, order=self) preexisting_order_row.amount += amount preexisting_order_row.save() else: # new_order_row = OrderRow(product=product, order=self) # new_order_row.amount += amount # new_order_row.save() new_order_row = OrderRow.objects.create( order=self, product=product, amount=amount ) # create saves already def remove_product(self, product, amount=None): pass def submit(self): if self.customer.balance >= self.total_price: order_products = OrderRow.objects.filter(order=self) for p in order_products: if p.amount <= p.product.inventory: self.status=2 def cancel(self): self.status = 3 … -
How can I make Django Query Return Nothing When Subquery Is Empty
I have Django query with sub-query like this cust_order = TOrder.objects \ .select_related('user') \ .annotate(category_name=Subquery(TOrderDetail.objects .filter(t_order=OuterRef('id'), deleted_at__isnull=True, deleted_by__isnull=True) .values_list('product__product_category__name', flat=True)[:1]) cust_feedback=Subquery(TOrderFeedback.objects .filter(t_order=OuterRef('id'), deleted_at__isnull=True, deleted_by__isnull=True, .values_list('message', flat=True)[:1]), The problem is, some times the sub-query of cust_feedback will empty, and how can I do filter if the cust_feedback is empty then the parent query should return nothing ? Thanks -
Using Django without ORM and be able to create users
I am a beginner when it comes to django. I have a database project in which we design a database (MySQL) with a frontend without using an ORM (it will be car rental project), so without using the model classes that are available in django, because the tutor assumes that we should learn making queries. I know that it's possible to use django without orm by yourself creating queries, but I don't know how it looks when it comes to create a user account. Is it possible to create a user (through user registration page) and simultaneously have access to him in the admin panel and be able to create relationships with him in the database without using model classes? -
Best practice for passing data to JavaScript in Django
When writing a view in Django, there are several ways to pass a list of data to javascript. Some of the methods I found are: Passing the data in the response text by serializing into JSON and assigning into a JavaScript variable, Passing the data via an AJAX request after the page is loaded. There are also two ways for this: Sending a POST request to the same URL, Sending a request to another URL Which method is the most reliable one? -
-vps- better than webhostting to deploy?
i have django app and there is a lot of site who provide hostserver i see a lot of them give the same hardwear -ram-cpu-hdd-..etc for VPS and Share hosting web but big different on the price what vps give me more to spend more money for !?? -
ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_po
I had finished deploying my django app on heroku. But, when I went there to see it, I saw this error: ProgrammingError at /blog/ relation "blog_post" does not exist LINE 1: SELECT COUNT(*) AS "__count" FROM "blog_post" WHERE "blog_po... If you want to see the full error message, go here: https://fathomless-lowlands-24834.herokuapp.com/blog/ I could not include the entire message as it was really long, and exceeded the limit of words I was allowed to have in my question. I can't even understand where the error is. I tried searching for this online, but did not find any response that helped me. -
How to set such an object to Django memcached
How can I set such object: {'request': <rest_framework.request.Request object at 0x7fd5df07c6a0>, 'format': None, 'view': <jobs.api.views.JobDetailAPIView object at 0x7fd5df065790>, 'coordinates': None} to Django Memcached? I get a pickle error when I try: cache.set(key, context, time..) context variable is the dictionary: {'request': <rest_framework.request.Request object at 0x7fd5df07c6a0>, 'format': None, 'view': <jobs.api.views.JobDetailAPIView object at 0x7fd5df065790>, 'coordinates': None} -
group base on dates and create arrays of dates in django
hello I have a problem in achieving this I have Model class TimeLine(models.Model): lead = models.ForeignKey(Lead, on_delete=models.CASCADE, related_name='lead') user = models.ForeignKey(User, on_delete=models.SET_NULL, related_name='user',null=True) created_at = models.DateTimeField(auto_now_add=True) action = models.CharField(max_length=60) action_type = models.CharField(max_length=60) action_id = models.IntegerField() **Note: created_at is time stamp so it will be "2020-10-31 14:15:21.474851+05:30" ** Problem: I want to group by base on creation date (date only not time) of creatde_at field and order by those group in descending of that date with every data inside each group will be also ordered by created_at descending Ex: [ 2020-11-02 : { {name:'abc', created_at: '2020-11-02 14:17:05.638698+05:30'}, {name:'xyz', created_at: '2020-11-02 14:16:50.703442+05:30'}, }, 2020-11-01: { {name:'sss', created_at: '2020-11-01 12:16:28.262846+05:30'}, {name:'aaa', created_at: '2020-11-01 13:18:09.262846+05:30'}, {name:'rrr', created_at: '2020-11-01 16:16:27.262846+05:30'}, } ] Summary: I want every record of database bundle in dates then order by those bundle in descending and every row in the bundle should be in descending order of there created_at field. Thanks in advance by <3. -
Django forms.ModelChoiceField does not dynamically update html select options on page refresh
Django 2.2.16. I have a django form with an owner field. End-users of my django app need to select an owner between logged-in users. Django renders this field with a <select><option>...</option></select> html tag. I want the options contained in the tag to be updated on page refresh (when end-user hits F5). Since the owner field must contain a list of logged-in users, the option list has to be reasonably up-to-date. As far as I understood, forms.ModelChoiceField should have this behavior, since "(the queryset passed to forms.ModelChoiceField) is evaluated when the form is rendered", cfr. https://docs.djangoproject.com/en/2.2/ref/forms/fields/#modelchoicefield My assumption here is that the form gets re-rendered upon page refresh, but this is not happening. The queryset passed to forms.ModelChoiceField works fine, i.e. when users log-in/out from my django app, a call to _get_logged_in_users() returns a queryset containing the correct list of logged-in users. Finally, I noticed the option list of logged-in users gets correctly updated only upon django restart. forms.py from django import forms from django.contrib.auth.models import User from django.contrib.sessions.models import Session from django.utils import timezone from .models import Event def _get_logged_in_users(): # private helper to return a queryset of logged-in users, by querying # all non-expired sessions sessions = Session.objects.filter(expire_date__gte=timezone.now()) uid_list … -
Django view definition with subfolder not rendering correctly in second time
I have a Django app accounts and in my Login link, when I click for the first time, it loads correctly: When I click for the second time it loads incorrectly. It basically trying to add the account/login at the end of the previous URL. I want to load http://127.0.0.1:8000/accounts/login when I click on the Login link, no matter I many times I have clicked on it. I am a newbie on Django and Python. I have tried to redirect, render, if-else statement and still no luck. Here are the details, I have an app name accounts in my project. The project urls.py: urlpatterns = [path("accounts/", include("accounts.urls")) ]. The account app urls.py urlpatterns=[ path("register", views.register, name="register"), path("login", views.login, name="login"), ]. The accounts app has two view function register and login: def register(request): return render(request, "register.html") def login(request): return render(request, "login.html") I am using two links, <li><a href="accounts/login">Login</a><i></i></li> <li><a href="accounts/register">Register</a></li> -
How can i add to a list in python without creating it
I have the following django view @login_required def statistics(request, slug=False): qn = get_object_or_404(Questionnaire, slug=slug) questions = Question.objects.filter(questionnaire=qn).count() qs = Question.objects.filter(questionnaire=qn) responses = Response.objects.filter(question__in=qs, user=request.user).count() if questions == 0 or responses == 0 or not questions <= responses: return render(request, "questionnaire/stats.html") out = {} for q in qs: response = Response.objects.filter(question=q, user=request.user).order_by("session_datetime").first() out[q.category] = {} time = response.session_datetime time_string = time.strftime("%d/%m/%Y") out[q.category][time_string] = [] responses_in_time = Response.objects.filter(question=q, user=request.user, session_datetime__gte=time, session_datetime__lt=time + datetime.timedelta(hours=24)) for res in responses_in_time: out[q.category][time_string] += [res.value] print(out) for category in out.keys(): print("outcat"+ str(out[category])) for time in out[category].keys(): out[category][time] = sum(out[category][time])/len(out[category][time]) print(out) return render(request, "questionnaire/stats.html", context={"questionnaire": qn, "stats_json": json.dumps(out)}) and i am wondering if there is a way to put together the dictionary with a time from the model/record in the loop without reseting it each time, if i try += without creating it first it complains but i do not know the initial time inside the loop. -
TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role'
I get this error when trying to create superuser: TypeError: create_user() missing 3 required positional arguments: 'first_name', 'last_name', and 'role' Is this the proper way to create it? I want to create superusers without username, just with email, and user can login only with their email addresses, and now when I create superuser it wants email, how I wanted, but gives me the error too. class MyAccountManager(BaseUserManager): def create_user(self, email, first_name, last_name, role, password=None, **extra_fields): if not email: raise ValueError("Users must have an email address") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, role=role, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): user = self.create_user( email=self.normalize_email(email), password=password ) user.is_admin = True user.is_employee = True user.is_headofdepartment = True user.is_reception = True user.is_patient = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class CustomUser(AbstractUser): ADMIN = 1 RECEPTION = 2 HEADOFDEPARTMENT = 3 EMPLOYEE = 4 PATIENT = 5 NOTACTIVE = 6 ROLE_CHOICES = ( (ADMIN, 'Admin'), (RECEPTION, 'Reception'), (HEADOFDEPARTMENT, 'HeadOfDepartment'), (EMPLOYEE, 'Employee'), (PATIENT, 'Patient'), (NOTACTIVE, 'NotActive'), ) role = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, blank=True, default=True, null=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) is_superuser = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) is_headofdepartment = models.BooleanField(default=False) is_reception = models.BooleanField(default=False) is_patient … -
Time Data Format Non Accepting On PostgreSQL
I have a script that goes into my outlook calendar to change a date on a event that is already posted. Basically what happens is it does a query on the date you enter and searches for the name of the event. If it exists, it will delete the old event and post new. My current code im posting works on my dev server that is a SQL-Lite backend, my production server is on Heroku with PostgreSQL. It fails on my production. Here is my code. print('Authenticated W/ O365') # Checkes if event exists in K8 Calendar calendar = schedule.get_calendar(calendar_name ="K-8") calendar.name = 'K-8' print('Checking if Event Exits in K8 Calendar') print("Event Name:", obj.event_name) print("Event Start:", obj.start_date) print("Event End:", obj.end_date) q = calendar.new_query('start').equals(datetime.strptime(str(obj.start_date) ,'%Y-%m-%d %H:%M:%S%z')) <-- These are the lines that fail q.chain('and').on_attribute('end').equals(datetime.strptime(str(obj.end_date) ,'%Y-%m-%d %H:%M:%S%z')) <-- These are the lines that fail k8 = calendar.get_events(query=q, include_recurring = True) Traceback ValueError at /eventscalendar/event_request_non_approval_view/49 time data '2020-10-31 14:00:18-04:00' does not match format '%Y-%m-%d %H:%M:%S%z' -
Converting serialized data to dictionary in django
I tried to serialize user data in Django but then I wanted to print it in the console as a dictionary, it was giving me an empty dictionary, how would I go about this. serializer.py from rest_framework import routers, serializers, viewsets from accounts.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = 'username', 'email', 'first_name', 'last_name', 'date_joined' views.py from django.shortcuts import render from rest_framework.generics import ListAPIView from rest_framework.response import Response from .serialize import UserSerializer import json class userApi(ListAPIView): def get(self, request): queryset = User.objects.all() serializer_class = UserSerializer(queryset, many=True) return Response(serializer_class.data) apiuser=userApi() point = json.dumps(apiuser.__dict__) print(point) console Watching for file changes with StatReloader [2020-11-02 15:45:50,086] autoreload: INFO - Watching for file changes with StatReloader Performing system checks... **{}**#This is what it is printing Any help guys -
host django project on windows laptop can be access through internet [duplicate]
I want to host my Django project on a local machine with docker. I have configured the docker and create an image of it. i configured in dockerfile: EXPOSE 8000 cmd python manage.py runserver 0.0.0.0:8000 but I can only access only on local machines and machines which are connected in LAN. I want to access through any other device which is out of my LAN. I don't want any external software for hosting. in short, I want to host my website with IP address and run on my machine with docker. and can be accessed through internet. -
Axios interceptor returns 400 as 200
I'm using interceptors in a react native app and it works well except for a single request. This is my axios instance import axios, { AxiosResponse, AxiosError } from 'axios'; import JwtDecode from 'jwt-decode'; import { baseURL } from './utils/variables'; import { store } from './redux/store'; import { navigate } from './services/navigation/NavigationService'; import { ActionType, RootState } from './redux/types'; const _axios = axios.create({ baseURL, headers: { Accept: 'application/json' } }); _axios.interceptors.response.use( (response) => { if (__DEV__) { console.log(response.config.url); const axiosResponse = response; console.log({ axiosResponse }); } return response; }, async (error) => { console.log('[INSIDE ERROR]'); if (__DEV__) { if (error.config) { console.log(error.config.url); console.log(error.response?.status); console.log(error.response); const axiosError = error; console.log({ axiosError }); } } const originalRequest = error.config; console.log('[BEFORE RESPONSE CHECK]'); if (!error.response) return Promise.reject(error); console.log('[BEFORE 401 CHECK AND FALSE RETRY]'); if (error.response.status === 401 && !originalRequest._retry) { console.log('[IS 401!!]'); originalRequest._retry = true; if (originalRequest.url === '/login/') return Promise.reject(error); if (error.response.status === 401 && originalRequest.url == '/token/refresh/') return Promise.reject(error); return _axios .post('/token/refresh/', { refresh: (store.getState() as RootState).auth.authenticationRefreshToken, }) .then((res) => { store.dispatch({ type: ActionType.AUTHENTICATE, payload: { authenticationToken: res.data.access, }, }); store.dispatch({ type: ActionType.LOAD_TOKEN_INFO, payload: JwtDecode(res.data.access), }); originalRequest.headers.Authorization = `Bearer ${res.data.access}`; console.log('[BEFORE REQUEST RETRY]'); return _axios(originalRequest); }) .catch((err) => { if (err.response) … -
I am using django right now and i don't know how i could parse the data direct from the admin panel to the homepage template
I did this in my views.py file from django.shortcuts import render from . import models def home(request): context = { 'name': models.alldets, } return render(request, 'sites/home.html', context=context) on my home.html i did this <h1> {{ name }}</h1 and this is now my models.py from django.db import models class alldets(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name all files are in the same directory. I want to parse the data in my models.py to my homepage through the admin panel -
How to use GroupConcat on subquery in Django
I've got an app storing played music on different musicstations. My models looks like these: class PlaylistItem(models.Model): played_at = models.DateTimeField(_('played at')) station = models.ForeignKey(Station, on_delete=models.CASCADE) log_track = models.ForeignKey('LogTrack', on_delete=models.CASCADE) class LogTrack(UpdateInfo): track = models.ForeignKey(Track, on_delete=models.CASCADE, blank=True, null=True) class Track(UpdateInfo): artist = models.CharField(_('artist'), max_length=150) tracktitle = models.CharField(_('tracktitle'), max_length=150) The Track model is a model consisting standardised names of LogTrack songs. What I want is an overview of overlapping songs between different stations (matching a master station) in a period of time. And I want to know how many times this song has been played at the different stations. The idea is: I'm thinking of an output like this: Master Station | Station B | Station C ----------------------------------------- Track 1 (5 plays) | 8 plays | 3 plays Track 2 (2 plays) | No | 5 plays Track 3 (2 plays) | 2 plays | No In MySQL I've got this (maybe overcomplicated) query: select playlist_logtrack.track_id, count(playlist_logtrack.track_id) as playcount, json_group_played_per_station from playlist_playlistitem p1 left join playlist_logtrack on p1.log_track_id = playlist_logtrack.id left join ( select track_id, group_concat(json_played_per_station) as json_group_played_per_station, count(json_played_per_station) as station_count from (select track_id, concat('{"id":"', track_id, '", "station":"', station_id, '", "play_count":"', count(log_track_id), '"}') as json_played_per_station from playlist_playlistitem left join playlist_logtrack on playlist_playlistitem.log_track_id … -
How to create dropdown in django and pass the selected value to a method in django?
I am trying to create a combo box which should also allow me type the text using choicefield in django. This is Model. CATEGORY_CHOICES = Choices( ('KtCoffee', 'Karnataka Coffee'), ('Atea', 'Assam tea'), ('WBRice', 'West Bengal Rice'), ('GujCotton', 'Gujarat Cotton'), ('KerCocoa', 'Kerala Cocoa'), ) class maincategory(models.Model): category = models.CharField(choices=CATEGORY_CHOICES,max_length=25) def __str__(self): return self.category VIEW def update(request): if request.method == "GET": context = { 'choices': maincategory._meta.get_field('category').choices } return render(request, 'update.html', context) HTML <div> <input list="category-input"> <datalist id="category-input" style="width:100px"> {% for des,text in choices %} <option value={{text}}>text</option> {% endfor %} </datalist> </div> I am able to get dropdown list but only first word is shown in dropdownlist like for 'Karnataka Coffee' only 'Karnataka' comes in dropdown. -
Take the aggregate of an aggregate
I am trying to perform a number of calculations on a database table that requires me to aggregate (perform groupby's) at different levels. Let's say I have an existing queryset qs which looks something like <QuerySet [{'foo': foo_value, 'bar': bar_value, 'quantity': '10'}, {'foo': foo_value, 'bar': ... ]> where the vales in foo and bar are not unique. I can then groupby on fields foo and bar using qs = qs.values("foo", "bar").annotate(foobar_quantity=Sum("quantity")) to obtain the total quantity for each unique foo-bar combination. Then, a problem arises when I try to obtain the total for foo from the current query set. That is, if I try qs = qs.values("foo").annotate(foo_quantity=Sum("foobar_quantity")) I get the error django.core.exceptions.FieldError: Cannot compute Sum('foobar_quantity'): 'foobar_quantity' is an aggregate How would I go about aggregating on a field that itself is an aggregate? Keeping in mind that I need to groupby on certain fields and that I need to do some calculations in between the two groupby's. Is there some way around this or is this simply not possible in the Django ORM? -
Hello coders i have a problem with showing the image in django and i don't know how to fix it and i'm just a begginer
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/media/profile_pics/686319f4c9b83342a478a1a41561efbf.jpg Using the URLconf defined in basic_project.urls, Django tried these URL patterns, in this order: [name='index'] admin/ basic_app/ The current path, media/profile_pics/686319f4c9b83342a478a1a41561efbf.jpg, didn't match any of these. -
Django ValueError: Cannot query "user": Must be "Profile" instance
I am trying to add simple user to user messaging functionality to my blog app in Django. I have a view that allows a user to send a message but I am having difficulty in displaying the messages after. Here is my Message model: class Message(models.Model): user = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages') sender = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='messages_from') message = models.TextField(blank=True) timestamp = models.DateTimeField(default=timezone.now, editable=False) unread = models.BooleanField(default=True) Here is my MessagesView attempt: class MessagesView(ListView): model = Profile template_name = 'users/messages.html' context_object_name = 'msg' def get_queryset(self): return Profile.objects.filter(messages_from__isnull=False, messages__user_id=self.request.user) And here is the url: path('messages/<int:pk>/', MessagesView.as_view(), name='messages'), Upon trying to load this page I receive the error Cannot query "user": Must be "Profile" instance where "user" is the name of the logged in user who's messages I am attempting to load. I have spent a long time googling a solution to this but have found nothing that relates to my case. Please help