Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Could not import QUERY_TERMS
I am running a website through Python and Django . Django-filters=2.1 installed Django=2.1 installed when i run, i get the error, importError: Could not import 'django_filters.rest_framework.DjangoFilterBackend' for API setting 'DEFAULT_FILTER_BACKENDS'. ImportError: cannot import name 'QUERY_TERMS' from 'django.db.models.sql.constants' (C:\Users\Android V\AppData\Loc al\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\constants. py). -
Unable to install gettext
I work in Django and want to implement internationalization I have admnistration right I need to install gettext but even following doc (https://www.drupal.org/docs/8/modules/potion/how-to-install-setup-gettext) it does not works My prompt display that gettext is not recognize... I have downloaded the 2 gettext files required (runtime and tools - V0.17) I get thoses folders for gettextruntime: bin lib manifest I get thoses folders for gettexttools: bin include lib manifest share Then I extract bin content of each files in a new folder: C:\Programmes\gettext (I also try to extract in a bin folder: C:\Programmes\gettext\bin) I have set my Path with C:\Programmes\gettext\bin don't know what is the problem? why other folders not mandatory? -
How do i implement a new feature in my Django framework website [closed]
I want to add a "add to wishlist" and some other ones. I have already tried to -
In Django, how to create .svg file of QR code and store models.py fields in QR code?
I am facing some issues regarding QR code generation in SVG format. When I feed 4 fields of data in qrform.html to generate QR code, the data is stored in the database but it was not showing any SVG file in project folder that is QR code data is submitted in the database but not creating SVG file. In views.py file, how to store all models field in QR code. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class qrcod(models.Model): Type_Of_Wallet = models.CharField(max_length=120) BLE_MAC_ID = models.CharField(max_length=17) Bar_code = models.CharField(max_length=100) Version = models.FloatField(blank=False) def __str__(self): return self.Type_Of_Wallet forms.py from django import forms from .models import qrcod class QRForm(forms.ModelForm): class Meta: model = qrcod exclude = [] urls.py from django.conf.urls import url from . import views app_name = 'qrcodes' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^topics', views.topics, name='topics'), url(r'^qr_topic/$', views.qr_topic, name='qr_topic'), url(r'^output/$',views.output, name='output'), ] views.py from django.shortcuts import render from .models import qrcod import requests from django.http import HttpResponseRedirect, Http404 from django.urls import reverse from .forms import QRForm import pyqrcode from pyqrcode import QRCode # Create your views here. def index(request): return render(request,'index.html') def topics(request): topics = qrcod.objects.all() context = {'topics':topics} return render(request, 'qrcode.html', context) def … -
Error while connecting Django with sql server database
Im using mssql as the backend for the database.In the setting.py file,I need to use the host name with backslash. Due to this, I got the timed out error. DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'xxxxx', 'USER': 'xxx', 'PASSWORD': 'xxxx', 'PORT': '1433', 'HOST': 'aaa\bbb', 'OPTIONS': { 'driver': 'SQL Server Native Client 11.0', }, } } Is there any way i could use the backslash in the host name. Thanks in advance.Please help me sort out. -
Does Django get() performs query to database on values()?
I have values queryset, if I get some date from it, does this perform a call to the database? instances_values = Model.objects.filter(**kwargs).values(*args) instance_with_id_one = instances_values.get(id=1) # does this perform a call to the databse? -
Send an array with ajax to my python function in django
I'm trying to send an array to my python function inside views.py but I can't. It always crash with a keyError because is not recognising the data from js. Code: Python function in views.py: def cargar_datos_csv(request): if request.method == 'POST': filtros = request.POST['node'] print(filtros) ctx = {'A':filtros} return JsonResponse(ctx) JS var csrftoken = $("[name=csrfmiddlewaretoken]").val(); var frutas = ['Manzana', 'Banana']; $.ajax({ url: '/../../data_bbdd/', type: 'POST', headers:{"X-CSRFToken": csrftoken}, data: { 'node': frutas, }, dataType: "json", cache: true, success: function(response) { coords = JSON.stringify(response.A); alert(coords); } }); How can I send an array to my python function? Thank you very much. -
While-True loop results in RecursionError because of django.setup()
I try to build a function that runs 24/7 (while True). The function is supposed to fetch data, convert the received string and populate the PostgreSQL DB. However, when I run the below shown script/function, I get an RecursionError: maximum recursion depth exceeded while calling a Python object which implies that something is wrong with the looping logic I guess. Why is that? feeder.py import django from django.conf import settings import zmq import time from time import sleep import uuid settings.configure(settings) django.setup() from Dashboard_app.models import AccountInformation # create zeroMQ Pull Socket to fetch data out of the wire context = zmq.Context() zmq_socket = context.socket(zmq.PULL) zmq_socket.bind("tcp://*:32225") time.sleep(1) while True: # check 24/7 for available data in the pull socket try: msg = zmq_socket.recv_string() data = msg.split("|") print(data) # if data is available, convert received string to required datatypes and assign variables version = data[1] DID = uuid.UUID(data[2]) accountNumber = int(data[3]) broker = data[4] leverage = data[5] account_balance = float(data[6]) account_profit = float(data[7]) account_equity = float(data[8]) account_margin = float(data[9]) account_margin_free = float(data[10]) account_margin_level = float(data[11]) account_currency = data[12] # push the manipulated data to the PostgreSQL DB using `AccountInformation` model feed = AccountInformation( version=version, DID=DID, accountNumber=accountNumber, broker=broker, leverage=leverage, account_balance=account_balance, account_profit=account_profit, account_equity=account_equity, account_margin=account_margin, … -
Django checkbox update
hey guys i need some help with a checkbox of mine here is my model: class Legend(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) title = models.CharField(max_length=100) description = models.CharField(max_length=1000) creator = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) date_created = models.DateTimeField('date created', auto_now_add=True) date_edited = models.DateTimeField('last edited', auto_now=True) date_pub = models.DateTimeField('date pubished', blank=True, null=True) is_pub = models.BooleanField(default=False) image = models.ImageField(upload_to='gallery/legends', blank=True, null=True) here is my view: def legend_update(request, id): template_name = 'legends/update.html' if request.method == 'POST': form = LegendUpdateForm(request.POST, request.FILES) if form.is_valid(): legend = get_object_or_404(Legend, pk=id) legend.title = form.cleaned_data.get('title') legend.description = form.cleaned_data.get('description') legend.image = form.cleaned_data.get('image') legend.is_pub = form.cleaned_data.get('is_pub') print('is published: ', legend.is_pub) legend.save() return HttpResponseRedirect(reverse('pages:owned')) and the part in my template: <div class="row s12"> <label> <input id="id_is_pub" name="is_pub" type="checkbox" {% if form.is_pub.value %}checked{% endif %}> <span>Veröffentlichen <small>(macht deinen Champion auf der Seite sichtbar für andere)</small></span> </label> </div> the reason im manually creating the form are the file input and the checkbox, since django doesnt create the proper layout which the mateializecss needs it ot be How do i update the value properly in the view since there seems to be a problem getting the value from the input box if it is checked or not Django version: 2.27 python version: 3.8 -
django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading
I installed spatialite for Django project but when I try to migrate it show me this error File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/contrib/gis/db/backends/spatialite/base.py", line 44, in get_new_connection raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: SpatiaLite requires SQLite to be configured to allow extension loading. I don't know how to figure out I tried this -
Getting token from local storage slowly in django rest framework & react development
AuthAction.js -> export const authLogin = (username, password) => { return dispatch => { dispatch(authStart()); axios.post('http://127.0.0.1:8000/rest-auth/login/', { username: username, password: password }) .then(res => { const token = res.data.key; const expirationDate = new Date(new Date().getTime() + 3600 * 1000); localStorage.setItem('token', token); localStorage.setItem('expirationDate', expirationDate); dispatch(authSuccess(token)); dispatch(checkAuthTimeout(3600)); axios.defaults.headers.common['Authorization'] = localStorage.getItem('token'); }) .catch(err => { dispatch(authFail(err)) console.log("ERROR") }) } } I want to make accessible the dashboard page when it gets the token. but First time it doesnt get the token so return the unauthorized message then after 2/3 seconds it redirects to dashboard automatically. Dashboard.js-> const {auth} = useSelector(state => ({ auth : state.authenticated })) const dispatch = useDispatch(); React.useEffect(()=>{ dispatch(actions.authCheckState()) },[]) if(!auth){ return( <p>Unauthorized</p> ) } -
Can't use variable in django template tag in AJAX function
Let say that my AJAX success: function(data) looks like this: success: function(data){ var li, trans_pk; for (i=0; i<data['income_transactions'].length; i++){ li = document.createElement('li'); trans_pk = 1; li.innerHTML = `<a href="{% url 'update_expense' ${trans_pk} %}">edit</a>`; document.querySelectorAll('.list_of_transactions')[0].appendChild(li); } } And it throws me an error: Could not parse the remainder: '${trans_pk}' from '${trans_pk}' But it works fine when I simply hard-code it: li.innerHTML = `<a href="{% url 'update_expense' 1 %}">edit</a>`; I can't figure it out how to do it with variable though. What am I missing here? -
How to allow superuser to edit or delete all data in django rest framework?
How to allow superuser to edit or delete all data in django rest framework but i want to do user only can see his data not others. I made that user only can see his data but admin cant see or cant edit. -
How to load/not load pagination depending if objects exists? Django
I am trying to make it so that my pagination only shows up if there are posts on the page and there can be only posts, if the admin has approved them. If there are no posts, there should be "No posts to show" shown on the template,if there are approved posts, then the posts should be shown and also the pagination options. What am I doing wrong here? models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) approved = models.BooleanField(default=False) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) views.py from django.shortcuts import render, get_object_or_404 from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from .models import Post def market(request): context = { 'posts': Post.objects.all() } return render(request, 'userMarket/market.html', context) class PostListView(ListView): model = Post template_name = 'userMarket/market.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 class UserPostListView(ListView): model = Post template_name = 'userMarket/user_posts.html' context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(author=user).order_by('-date_posted') class PostDetailView(DetailView): model = Post class … -
Django - Generic FormView - Passing inputs, into template
Using, Django==2.1.7, and python3.7 - I am really struggling using FormView - see below script. How can I pass variable search_string submitted via the form and the value within context["new_context_entry"] added via get_context_data - to the success_url, so those values can be rendered in my template on form submission? class ConfigSearchTest(FormView): template_name = 'archiver_app/config_view.html' form_class = forms.DeviceSearchForm success_url = 'archiver/search_results/' def form_valid(self,form): search_string = form.cleaned_data['search_string'] return super(ConfigSearchTest,self).form_valid(form) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) new_context_entry = "adding additional" context["new_context_entry"] = new_context_entry return context -
Django: No Module named 'foo' issue in context with model import
Background information: I would like to run a script using atoms script plug-in. I first encountered a ImproperlyConfigured error which was solved as suggested here: First fix Then I run into RuntimeError: Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. error which was solved by using an absolute path for the model import as shown below. Current issue: Using the mentioned absolute import, I receive this error: ModuleNotFoundError: No module named 'Dashboard_app' I can even render the template for that app etc. so I am confused why he tells me that the module doesn't exist. When I remove the model import, everything works just fine. Is it maybe that the script instance doesn't recognize it properly? What I've tried: deleted + re-created __init__.py checked settings for app to be included in INSTALLED-APPS dic changed import path to DASHEX.Dashboard_app.models resulting in no module named DASHEX error changed import path to models resulting in Model class models.AccountInformation doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS error feeder.py script: import django from django.conf import settings import zmq import time from time import sleep import uuid settings.configure() django.setup() import sys print(sys.path) from Dashboard_app.models … -
How to don't print django error in html file ir Frontend
I Want to print error with my html file but my script is printing text that in variable For Example! I Had This Form: if reg.is_valid(): if cap == True: user = reg.save(commit=False) user.set_password(User) user.save() reg = True else: reg = False If There is a error for example user already exist it need to set variable as false so we can add if statment in html and give alert there was a error But it's Also Set That False And Also Write in html False Here is the Screenshot! You Can See It's Also write False below sign in There I Don't need That i need to set that variable as False Not Also Write in html file You Can Take As I don't Want To Print Error in website! Here is my views if result['success']: cap = True if reg.is_valid(): if cap == True: user = reg.save(commit=False) user.set_password(User) user.save() reg = True else: reg = False else: cap = False else: reg = register() return render(requests,'signup.html',{'reg':reg,'cap':cap,}) You can see in my code: the variable set to be false but in the html it's also writing false -
How can i access images stored in my s3 bucket with url in html
i want to show uploaded images on my html page with returned/made url. but i am getting access denied on that url. I am new to aws s3 how can i fix it. I want ot access it in both(App and web with that url) -
Django multiple users store in a model by multiplechoicefield
i'am createing an application for different managing-services and run into a problem. I want to show the current logged user in an area-model, where other users of the company can work in this area. Areas: What i did is to get the users into a form, so i can choose them and there will be saved: And now comes the tricky-part: Not every user in the Database should be shown in the multiple-choice-filed, so i've added a query-set and a user-parameter in my view, to generate the choices dynamically: Result in my template: You can see, its not correct. Here are the problems: How can i show first_name and last_name in the choices field and still use the custom-form_valid-Functionaility of the model? If i try to add a user to my form, i can't valid the form by the model. How can i change the multipleinputfield to a Text-Field with available Choices and DropDown? I've tried different things (autocomplete, select2 etc.) but the documentation is not good. I ran into multiple errors. One of the biggest Problem is, that all tutorials use static choices or functions which creates the choices when the server is starting. The target is, that the … -
How to use order_by in Django queryset?
I apply order_by to a queryset and the results are mixed up. Is there any difference if I apply it to a queryset? The table has three columns: Name Age Description Here is the code: Query = table1.objects.filter(Name__iexact='Nico').order_by('Age').distinct() ages = Query.values_list('Age') descr= Query.values_list('Description') Here only Age is sorted correctly. The match between these Age and Description is distorted. What is wrong here? -
Django url embed link from youtube
i am building a movie review website application in Django. i want to create a video URL link section in Django administrator console that, when i enter copy the embedded link from YouTube and saving it at the correct movie, it shows the movies trailer. what do i need to write in the model.py to do so? much appreciate. -
django reference User model - You are trying to add a non-nullable field 'author' to question without a default [duplicate]
This question already has an answer here: You are trying to add a non-nullable field 'new_field' to userprofile without a default 14 answers Iam new to django and having an issue with integrating the Django auth model directly in apps' models by referring to it as question_text = models.CharField(max_length=200, blank=False) pup_date = models.DateField('date_published',auto_now=True) author = models.ForeignKey(User, on_delete=models.CASCADE) but when trying to run python manage.py makemigrations it gives the following error Please select a fix: 1) Provide a one-off default now (will be set on all existing rows with a null value for this column) 2) Quit, and let me add a default in models.py so would you please help me in this, I don't need to create a custom User model. regards -
Django database query spanning across multiple relationships
Given the models below: class Assets(models.Model): assettag = models.CharField() ... pass class Employees(models.Model): loginname = models.CharField() pass class Item(models.Model): descr = models.CharField() asset = models.OneToOneField('Assets') ... class Assignments(models.Model): employeeid = models.ForeignKey('Employees') assetid = models.ForeignKey('Assets') ... I can make a query that returns all Item models which contain a certain descr or a certain assettag, using Q objects. Item.objects.filter(Q(asset__assettag__icontains = query) | Q(descr__icontains = query) #| ).order_by('asset__assettag') Would it be possible to also include employeeid__loginname somehow? I couldn't figure out a way to do so. I want to retrieve the Assets that are refereneced in the Item table and which belong to a certain Employee. -
Custom Django 1.4.5 management command not found
I am working on a legacy python application developed with Django 1.4.5 and trying to create a custom management command. My app is called george and here's the folder structure (I've omitted out other irrelevant files & folder): manage.py /george __init__.py /management __init__.py /commands __init__.py what_time_is_it.py And this is the content of what_time_is_it.py: from django.core.management.base import BaseCommand from django.utils import timezone class Command(BaseCommand): help = 'Displays current time' def handle(self, *args, **kwargs): time = timezone.now().strftime('%X') self.stdout.write("It's now %s" % time) and I made sure george is included in my settings.py under INSTALLED_APPS: INSTALLED_APPS = ( ... 'george', ... ) The app is running in a docker container, so after building and running the container, i shelled into it and ran this command: root@e1973c07ba61:/code# python manage.py what_time_is_it and I get this error: Unknown command: 'what_time_is_it' Type 'manage.py help' for usage. Any ideas what I might be doing wrong here? When I run python manage.py help I don't see my custom command listed there, as if it's not registering. -
Django URL start with special character "?"
I'm trying to acceed to this url: https://www.topmoonitor.com/?a=details&lid=19 The problem is django don't care of the "?" before a=details&lid=19 and redirect me to the home page on this URL: path('', views.index, name='index'), If i remove the "?" it's work properly. My current code : path('?a=details&lid=<slug:lid>/', views.button_img, name="button_img"), I tried this but still not working :/ re_path(r'?a=details&lid=(?P<lid>\d+)', views.button_img, name="button_img"), Do you have some idea please ?