Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Ensure that urlpatterns is a list of path() and/or re_path() instances. to use path instead of tuple
from django.conf.urls import url, include from facts import views urlpatterns = [ url('upload/(?P<fact_object_type>\w+)', views.upload, name ='upload'), url('create/types/(?P<fact_object_type>\w+)', views.getForm, name ='form'), url('create/types/', views.getList, name ='list'), url('create/filetag', views.fileTag, name='filetag'), url('update/(?P<fact_id>\d+)', views.updateOptions, name ='update'), url('update/filetag/(?P<fact_id>\d+)', views.updateFileTag, name ='update_filetag'), url('update/save/(?P<fact_id>\d+)', views.update, {'submit':False}, name ='update_save'), url('update/submit/(?P<fact_id>\d+)', views.update, {'submit':True}, name ='update_submit'), url('create/', views.createFact, name ='create'), url('search/?$', views.search, {'facts':False}, name='search_view'), url('search/facts/view/(?P<fact_id>\d+)', views.getData, {'facts':True}, name ='view_user_data'), url('search/facts/view/(?P<path>.*)$', views.send_file), url('search/facts/edit/(?P<fact_id>\d+)', views.getUpdateForm, name ='edit_user_data'), url('search/facts/edit/(?P<path>.*)$', views.send_file), url('search/facts/?$', views.search, {'facts':True}, name='user_search_view'), url('search/(?P<fact_id>\d+)/likes', views.getLikes, name ='likes'), url('search/(?P<fact_id>\d+)', views.getData, {'facts':False}, name ='data'), url('search/(?P<path>.*)$', views.send_file), url('api/get_facts/(?P<term>.*)', views.get_facts), url('suggest/search/(?P<fact_id>\d+)/likes', views.getLikes, {'model_name': 'factsuggestion'}, name ='suggestion_likes'), url('suggest/search/', views.searchSuggestions, name ='search_suggestions'), url('suggest/', views.suggestFact, name ='suggest'), url('count/', views.factCount, name ='count'), ] ('(?P\d+)/add/filetag/$', self.admin_site.admin_view(self.filetag), {'newFact':True}) I have that, and get this error when running my python/django project.Am assuming its from the code I copied above.I dont know how to fix it.I tried some solutions posted, search stackoverflow and github issues posted.None helped me.Stuck on this for 3 hours now ERRORS: ?: (urls.E004) Your URL pattern ('(?P<fact_id>\\d+)/add/filetag/$', <function FactAdmin.filetag at 0x7ff178ae26a8>, {'newfact': True}) is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. HINT: Try using path() instead of a tuple. ?: (urls.E004) Your URL pattern ('(?P<fact_id>\\d+)/filetag/$', <function FactAdmin.filetag at 0x7ff178ae2510>) is invalid. Ensure that urlpatterns is a … -
Django-Admin and Django-Summernote create a file field in my forms
I am customizing django-admin with summernote and so far so good, but for some reason it creates a file field in my forms which is never allowed to be empty and I can't update records without uploading dummy fields. Please see attachment. My admin.py code is: rom django.contrib import admin from django_summernote.admin import SummernoteModelAdmin from .models import Post, Category, Tag # Register your models here. # admin.site.register(Post) # POST @admin.register(Post) class PostAdmin(SummernoteModelAdmin): """ Registers the model Post in the Admin Site """ list_display = ('title','publish','status') # Columns to display list_filter = ('status','created','publish','author') # Filter by on right column search_fields = ('title','body') # Search in these fields prepopulated_fields = {'slug': ('title',)} # Prepopulate filter_horizontal = ('tag',) raw_id_fields = ('author',) date_hierarchy = 'publish' ordering = ('status', 'publish') summernote_fields = ('body',) How can I remove the "file" field from there? Please help. Many thanks. -
Get token from URL in Django. TDAmeritrade API Call
Ok, I'm developing a website where I'm using Django. The website is for creating and keep track of stock portfolios. I have the database and the basics of the website set up but I would like to use the TDAmeritrade API in order to get the stock information. How it works is the user is redirected to TD where they enter there Login and Password they accept the terms and get transferred to a redirect page of the local host (until it goes live). Which looks a little like this "https://127.0.0.1:8000/?code=" with a huge code after the equals sign. Finally, how would one create the URL destination in Django url.py file and store the code for AUTH Token (current home - https://127.0.0.1:8000/) Thanks in advance! -
How to force django model save method to lookup queryset in custom manager method?
I have a model named Run with a manager named RunManager and with a custom save() method as follows. class RunManager(models.Manager): use_for_related_fields = True def get_queryset(self): queryset = super(RunManager, self).get_queryset() queryset = queryset.filter(archived=False) return queryset def unfiltered_runs(self): queryset = super(RunManager, self).get_queryset() return queryset class Run(models.Model): name = models.CharField(max_length=256) archived = models.BooleanField(default=False) objects = RunManager() def save(self, *args, **kwargs): # some business logic super(Run, self).save(*args, **kwargs) def archive(self): # Some business logic self.archived = True self.save() def recover_archived(self): # Some business logic self.archived = False self.save() This was an old code where the run.objects were used at several location, so to hide the archived runs I am using the RunManager. Everything was working fine, but now we want to unarchive the runs. So I added the unfiltred_runs() method which shows the list of all the runs along with the archived runs. But when I run recove_archived() method i get following error IntegrityError: UNIQUE constraint failed: run.id I know the error is because the db is treating it as a new entry with same id. I know I can completely override the save method but I want to avoid that. So is there any way to make save method lookup in the … -
Django: How to implement request.session in a class based view
I have a hard time understanding class based views in Django. At this time I try to implement a request.session in a ListView. I try to implement the following function based code from the MdM Django Tutorial in to a ListView. def index(request): ... # Number of visits to this view, as counted in the session variable. num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 context = { 'num_visits': num_visits, } return render(request, 'index.html', context=context) I tried the following (and a lot of other things) but to no avail: class ListPageView(FormMixin, ListView): template_name = 'property_list.html' model = Property form_class = PropertyForm def get(self, request, *args, **kwargs): num_visits = request.session.get('num_visits', 0) request.session['num_visits'] = num_visits + 1 return super().get(request, *args, **kwargs) # ... some more code here In my template I have: <p>You have visited this page {{ num_visits }}{% if num_visits == 1 %} time{% else %} times{% endif %}.</p> But the template variable renders always empty. Every help is appreciated. Thanks a lot in advance. -
404 on STATIC_URL and whitenoise does not call get on my view
I have a view class MyView(View): def get(request): return XXX and I add it to my urls urlpatterns += [url(r'^/static/', MyView.as_view())] When I go to a garbage link like localhost/static/garbage it shows me the Django 404 error page but it claims that it was raised by MyView. What's extremely frustrating is I have two apps with the same static files handling. One of the apps trigger my view, the other does not. I cannot tell what's different that's causing the issue. Both are on whitenoise==4.1.x -
How to use docker with Django and Rest Framework on windows
Disclaimer: I am new to django, rest framework, and docker. I am trying to run python manage.py runserver from my pipenv session and I get the following error: .... File "C:\Users\Tomer\.virtualenvs\policyEngine-bcFnXBzo\lib\site-packages\rest_framework\settings.py", line 27, in <module> from django.utils import six ImportError: cannot import name ' I've tried gunicorn but it doesn't work because I'm using windows. I've tried waitress but I also get an error. Frankly, I'm desperate, I can't manage to start my server in any way... how can you use django (and rest framework) with docker properly? thank you -
Django: endpoint to reverse status not working
I'm learning and experimenting with DRF. I'm learning actions to create routes (endpoints) to make custom modifications to my models. I succesfully have constructed: deactivate, deactivate_all, activate_all. But not reverse_status, which is meant to change the current status of a customer to the opposite. If customer.active = True, this would change it to False and viceversa. my action: @action(detail=False, methods=['PUT']) #when true only applies to 1 object / else to a list of objects def reverse_status(self, request, **kwargs): customers = Customer.objects.all() import pdb; pdb.set_trace() customers = [customer.update(active=False) for customer in customers if customer.active] serializer = CustomerSerializer(customers, many=True) return Response(serializer.data) As you notice, I've set a breakpoint to see what customers holds after the list comprenhension, but it gets converted to an empty list: Original: <QuerySet [<Customer: Gregory>, <Customer: Julia>, <Customer: Naty>]> After List Comprehension: [] Why? -
Should I upload my email-address and password written in 'settings.py' to Github?
I have made an email authentication app in django. This app required entering my email address and password in the 'settings.py' file in order to send an email for user verification. While uploading this project on Github, it would be very dangerous to upload the 'settings.py' file with my email and password written in it. How should I proceed so that on cloning the repository, the user has to enter his own email and password for the code to run ? Thanks for any help! -
how to pass data from multi model in django to html file?
i want to ask how i can get data from multi models to home page (html page) i mean i have multi models and i want to show everything i will add it from admin panel to my home page (html) directly and sort it by last added apps how to do that please i have tried to show my data by this way but it's doesn't work ,, for example home html page : {% for home_page in appnum %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{ home_page.get_image }}" alt="no image found !" height="160" width="165" > {{ home_page.name }} <br><br> <p id="p_size_first_page"> {{ home_page.app_contect}} <br> <br> <a href=" {{ home_page.page_url }} " type="button" class="btn btn-dark"><big> See More & Download </big> </a> </p> </label> {% endfor %} also this in home html page {% for android_app in AndroidApk %} <label id="label_main_app"> <img style="margin-top:.3%;margin-left:.3%" id="img_main_app_first_screen" src="{{ android_app.get_image }}" alt="no image found !" height="160" width="165" > {{ android_app.name }} <br><br> <p id="p_size_first_page"> {{ android_app.app_contect}} <br> <br> <a href=" {{ android_app.page_url }} " type="button" class="btn btn-dark"><big> See More & Download </big> </a> </p> </label> {% endfor %} etc .. and this my views.py def home_page(request): app = Homepage.objects.all() page = request.GET.get('home-page', 1) # the_home_page … -
Problem with Django generic.DetailView and Thread Process
I'm working with django and I have a problem with a background process that run inside a generic.DetailView. This background process is a threading.Treat that complete a specific work. The problem is that the return of the context to build the html page is waiting for the Thread finish, and this is slow, for that this is a background process. What can I do to fix this, and return the context with the template before that the tread background process finish? This is my code # View.py def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) ... cache_key = 'planned.course_{0}.year_{1}.semester_{2}'.format(self.course.pk, self.year, self.semester) cached = cache.get(cache_key) if not cached: from utils.thread_pop import POPThreadCartaGantt POPThreadCartaGantt(self.course.pk, self.year, self.semester, self.user.pk, cache_key).start() return context # Thread class POPThreadCartaGantt(threading.Thread): def __init__(self, course_pk, year, semester, user_pk, cache_key): self.course_pk = course_pk self.year = year self.semester = semester self.user_pk = user_pk self.cache_key = cache_key threading.Thread.__init__(self) def run(self): gantt = creating_gantt(self.cache_key, self.course_pk, self.year, self.semester, self.user_pk) -
Django select query with where clause
result = Sheet.objects.filter(id=id).all() list = [] for i in result: list.append(sheet.data) print(data) first am getting all the objects from sheet model then am iterating through each obj and getting all the data, is there any way in django through which i can get data list directly from sheet model. -
Is a Django PostgreSQL Backend Possible Without Using psycopg2? cPanel and Shared Hosting Deployment Constraints
I'm deploying a Django project in a cPanel hosting environment (NameCheap). NameCheap currently only supports PostgreSQL: 8.4.20. I want to use PostgreSQL as my Django database backend but (see bold requirement): The current psycopg2 implementation supports: Python version 2.7 Python 3 versions from 3.4 to 3.8 PostgreSQL server versions from 7.4 to 12 PostgreSQL client library version from 9.1 Upgrading from 8.4.20 to >= 9.1 is not an option in NameCheap (shared hosting plan). So my problem is, if I attempt to do a pip install psycopg2, I receive an error: ./psycopg/psycopg.h:30:2: error: #error "Psycopg requires PostgreSQL client library (libpq) >= 9.1 BECAUSE PostgreSQL 8.4.20 < PostgreSQL: 9.1. My Question Is: Is psycopg2 the only "approved"(?) / "official" / "supported" module for Django and PostgreSQL? If not, what psycopg2 alternative package could I use and how to implement in general? -
django, authenticate only for user not super user
Im using django >= 3.0, how to create an authentication that allowed only for non-super user. I' am currently working on login part where a normal user can login but strict for those user that labled as is_superuser = True def request(request): if len(request.POST) > 0 : # print(request.__class__.__name__); constraint = helpers.constraint(request); data = constraint.strict(["username", "password"], True); username = data['username']; password = data['password']; user = auth.authenticate( username = username, password = password ); if user : print(user); breakpoint(); auth.login(request,user) return HttpResponse("jkjhhj"); messages.info(request, "Invalid credentials"); return login(request); Same like this.... user = auth.authenticate( username = username, password = password, is_superuser = False ); -
How to make this search query in django?
my search query works fine when i fill the book and chapter in my searchfield. but when i only fill in the book i get an error. Can somebody help me? def get_queryset(self): query = self.request.GET.get('q') book, chapter = query.split() object_list = Verse.objects.filter( Q(book__icontains=book) & Q( chapter__exact=chapter)) return object_list -
Why many django internal functions returning string values are not working now?
I am having a hard time with some django errors that have appeared in my code. These errors have raised (I think) when I upgraded from python 2.7 to python 3.6. The errors are caused because some functions return a string instead of his primitive value. For example in a template in which I have html that should only be shown to superusers I have been using: {% if user.is_superuser %} This call should return an 0 (false) or 1, (true) whether the user is superuser or not. But now this is not working as expected, because it returns '0' or '1'. I must then parse to int the call to get the proper result: {% if int.user.is_superuser %} I find this very unsettling solution. This shouldn't behave like this and there are more internal functions I had to fix because behave in the same fashion. I am currently using Django 2.2.3 and python 3.6. Any help for a clean solution is much appreciated. -
Set up subdomains for tenants in a Django web app?
I have installed django-tenant-schemas for a multitenancy SaaS app I'm trying to build. So far I have managed to create schemas in postgres so each tenant has isolated tables. If a user goes to my website, e.g www.mydomain.com, and registers by providing a username, password and company (e.g "Joeys Company") - how would I dynamically create a new subdomain for that user, in this case joeyscompany.mydomain.com? People have mentioned wildcard domains, but not sure how to practically set that up -
Django LOGIN_REDIRECT_URL and ReactJS Router
I am running into a problem when using react-router and Django (3.0). I am setting up login authentication and I created a superuser just to test out the logging in. Here is what I have done: backend/settings.py ... LOGIN_REDIRECT_URL = '/' index.js ReactDOM.render( <Router> <ThemeProvider theme = {theme}> <Route exact path = {paths.home}> <PreLogHome/> </Route> <Route exact path = {paths.login}> <PreLogLogin/> </Route> </ThemeProvider> </Router>); Then I make the POST call in axios (the qs is used because I already saw: failed to configure axios with django rest auth to login and get auth token) axios.post(paths.login, qs.stringify({ username, password })) .then(function(response) { console.log(response); }) .catch(function(error) { console.log(error); }); I am trying to redirect to the home page upon successful login. When I type in a random username and password, I just get "POST /login/ HTTP/1.1" 200 2294, which makes sense because the credentials are not valid. However, if I type in the superuser credentials, I get "POST /login/ HTTP/1.1" 200 2294 \n "GET / HTTP/1.1" 200 2294, which means that the server is trying to redirect to '/'. However, on the actual page, I am getting no such redirection. What might the problem be? Is it with react-router? Any help would … -
What is the correct way to do a redirection from www. to the naked domain (Server or App or Domain Provider)?
I currently have an app that works with both www.domain.com and domain.com. Considering that this seems to be bad for SEO, I want it to always redirect to the naked domain. My app works in this way: Server: Google Cloud Platform (App engine) App: Django Domain provider: Godaddy As I have researched the redirection can be done from any of these 3 options. So I want to ask: What is the best option and why? -
Django Registration Using Custome User
I created a custome user using django AbstractUser. I really don't know how to reflect the added fields for user registration, login and update. Below is what i have tried: models.py class CustomUser(AbstractUser): state = models.CharField(choices=States, default ='abia', max_length=50 ) city = models.CharField(max_length=50) local_government = models.CharField(max_length=50) phone_number = models.CharField(max_length=50, blank= True) picture = models.ImageField(upload_to='user/photos', blank=False, null=False, validators= [clean_image]) forms.py class CustomUserCreationForm(UserCreationForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number', 'picture',) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserCreationForm.Meta.fields + ('state', 'city', 'local_government', 'phone_number', 'picture',) admin.py class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser list_display = ['id', 'first_name', 'last_name', 'email','subscription_plan', 'state', 'city', 'local_government', 'phone_number', 'picture'] views.py (for registration) def register (request): if request.method == 'POST': firstname= request.POST['firstname'] lastname= request.POST['lastname'] state= request.POST['state'] city= request.POST['city'] email= request.POST['email'] username= request.POST['username'] password= request.POST['password'] password2= request.POST['password2'] if password == password2: if User.objects.filter(username=username).exists(): messages.error (request, 'That username is taken') return redirect('register') else: if User.objects.filter(email=email).exists(): messages.error (request, 'That email is being used') return redirect('register') else: user= User.objects.create(username=username, first_name=firstname, last_name=lastname, email=email, password = make_password(password), state=state, city=city) user.save() messages.success (request, 'You are now registered and can login') return redirect('login') else: messages.error (request, 'passwords do not match') return redirect('register') else: return … -
Django blog engine
How can I implement similar functionality with django? I mean to mark something in a special way, let's say a text so that it is in a block like in the pictures below, something to mark as a link. I don't even have an idea how to google it 😅. Django stackoverflow -
Django/Python - Update more than one field simultaneously
supposed that i have in my db something like this: how can i update all 3 languages of user a in just one view??? I was trying something like this: def MyModelUpdate(request, item): index = get_object_or_404(MyModel, pk=item) temp = MyModel.objects.filter(usuario=request.user).values() if request.method == 'GET': form_update = MyModelForm(request.GET or None, user=request.user) elif request.method == 'POST': form_update = MyModelForm(request.POST or None, user=request.user, instance=index) try: MyModel.objects.get(usuario=request.user, id=item) MyModel.objects.get(usuario=request.user, id=item).delete() form_update.save() except MyModel.DoesNotExist: return redirect('../back') return render(request, 'somepage.html', { 'form_update': form_update, 'temp': temp, }) -
Python virtualenv - Could not open requirements file
I'm new to python and trying to setup python2, virtualenv and postgres database. I successfully set up the python2 and created virtualenv. Upon running the command - pip2 install -r requirements.txt --extra-index-url url in the python2 virtualenv, I'm getting an error that "ERROR: Could not open requirements file: [Errno 2] No such file or directory". Even though the file is present in the directory with full permission. But somehow it is not able to find the file requirements.txt. Can someone explains to me how to run this command without an issue? If I'm using the absolute path for the requirements.txt it works fine. But I can't do the same for my other python commands who are using the files present in the same directory. -
Azure certification for django
I'm currently working as a django developer and I was thinking of doing a certification on azure. Which azure course should I prefer for the same? -
view must be a callable or a list/tuple in the case of include()
File "/home/bsd/PycharmProjects/BSD/BSD_2_7/BSD_2_7/urls.py", line 10, in <module> url('$', 'base.views.index'), File "/usr/local/lib/python3.6/dist-packages/django/conf/urls/__init__.py", line 13, in url return re_path(regex, view, kwargs, name) File "/usr/local/lib/python3.6/dist-packages/django/urls/conf.py", line 73, in _path raise TypeError('view must be a callable or a list/tuple in the case of include().') TypeError: view must be a callable or a list/tuple in the case of include(). urlpatterns = [ url('$', 'myapp.views.index')] I am using django 2.2, pythong 3.6. The app previously written in django 1.7, I dont know how to fix that error into django 2.2 . When I try to do from myapp.views import index and url('$', index, name="index")] it doesnt see from myapp.views