Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Reflection of HTML elements - django
I am trying to give an administrator of the webservice an ability to name buttons of the main menu using whathever text he or she wants. Moreover, I want to allow him to play with styles that particular button will be described with. Each of written above action should be available from the administrator's menu ( in this case it is a default django admin framework ). I've came up with an idea of using completely new model: class MainSiteButton(models.Model): button_title = models.CharField( max_length=100, null=True, blank=False, default="Click to edit", verbose_name="Text of the button" ) button_style = models.CharField( max_length=10000, null=True, blank=False, default="font-size: 10px; font-color: green;", verbose_name="Style of the button" ) button_default_name = models.CharField( choices=button_default_name_choices, max_length=500, null=True, blank=False, default=next(iter(button_default_name_choices))[0], verbose_name="Button back-end identifier" ) Using given model, I am going to define each button, that is defined in the webpage's menu. These will have such a form: queried_home_button = MainSiteButton.objects.create( button_title="Home", button_default_name='home_button' ) queried_logout_button = MainSiteButton.objects.create( button_title="Logout", button_default_name='logout_button' ) queried_login_button = MainSiteButton.objects.create( button_title="Login", button_default_name='login_button' ) Operation of defining new buttons will occur only once, at a start of the server Another step is to define a lazy context processor: @memoize def texts_of_buttons(request): context_data = dict() try: queried_home_button = MainSiteButton.objects.filter( button_default_name='home_button' )[0] queried_logout_button = … -
No 'Access-Control-Allow-Origin' header is present on the requested resource Django and ReactJS
Currently I have Django 1.98 as Backend and React as Front End. I'm getting this error: Access to XMLHttpRequest at 'https://mywebsite:8000/uploads/vtt/' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. I installed django-cors-headers==2.4.0 on my virtualenviroment This is my settings.py file: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'uploads.core', 'corsheaders', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CSRF_TRUSTED_ORIGINS = ['http://127.0.0.1:3000','http://localhost:3000','http://localhost:8000','https://mywebsite:8000','https://myapp.firebaseapp.com','https://mywebsite:8088'] CSRF_COOKIE_NAME = "csrftoken" CSRF_HEADER_NAME = [ 'HTTP_X_CSRFTOKEN' ] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') SECURE_SSL_REDIRECT = True SESSION_COOKIE_SECURE = True CSRF_COOKIE_SECURE = True CORS_ORIGIN_WHITELIST = ['http://localhost:3000','https://mywebsite:8088'] CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) Any idea how to solve it? Thanks. -
NoneType' object has no attribute 'objects' in Django after some time runing
I have recently migrated a Django 1.8 to Django 1.11, everything seems to work correctly, but in production, after some time running correctly, Django starts to return messages like: AttributeError: 'NoneType' object has no attribute 'objects' AttributeError: 'NoneType' object is not callable The user cannot continue using the application, each action returns an "Internal server error" (all related to 'NoneType' object ...). Even the 500 error template for Django, which I have customized, is not shown. Django runs on Apache/WSGI. It seems like classes and objects, in general, are suddenly 'NoneType' objects. After a reload of Apache server, everything starts to work fine again during some time and the error comes back (after a few hours). I have not found specific log errors that point to the cause of the error. What is the best way to debug this kind of sporadic change of behavior? Anyone knows how to solve these kind of errors? The same code is running in other instances on Django 1.8 and working correctly. -
Unit testing CRUD functions in Django
I am trying to create a basic unit test for my code. Here is what I'm running... from django.test import TestCase from django.contrib.auth.models import User from feed.models import Post class PostTests(TestCase): def setUp(self): user = User.objects.first() Post.objects.create(title='test', content='more testing', author=user) def test_content(self): post = Post.objects.get(id=1) expected_object_name = f'{post.content}' self.assertEquals(expected_object_name, 'more testing') The error I'm getting is "django.db.utils.IntegrityError: (1048, "Column 'author_id' cannot be null")" I believe the error is finding the user but when I run it in the shell it updates with no problems. -
Multiple file uploading in django admin
I have File model for uploading file. class File(models.Model): files = models.FileField(upload_to='sampleorder/%y/%m/%d', null=True, blank=True) order_detail = models.ForeignKey(OrderDetail, on_delete=models.SET_NULL, null=True) and for multiple file upload i have form.py class FileForm(forms.ModelForm): class Meta: model = File fields = ['files'] widgets = { 'files': forms.ClearableFileInput(attrs={'multiple': True}), } and in admin.py @admin.register(File) class FileAdmin(admin.ModelAdmin): form = FileForm list_display = ['id'] def save_model(self, request, obj, form, change): files = request.FILES.getlist('file') for f in files: File.create(files=f) return super(FileAdmin, self).save_model(request, obj, form, change) but its only save latest file. how to save multiple file at time? i also see this Upload multiple files using Files Field in Django Admin question but can configure where i am wrong. -
django migration error after adding new field
Previously i had models like this: class Company(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class PostJob(models.Model): title = models.CharField(max_length=256) company = models.ForeignKey('Company',on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return self.title later i added "desc" in PostJob model like this: class Company(models.Model): name = models.CharField(max_length=256) def __str__(self): return self.name class PostJob(models.Model): title = models.CharField(max_length=256) desc = models.TextField(default=None) company = models.ForeignKey('Company',on_delete=models.CASCADE,null=True,blank=True) def __str__(self): return self.title Then i ran below command : python manage.py makemigrations python manage.py migrate when i am opening the "PostJob" in my django-admin panel it is showing below error. MigrationError at /admin/api/postjob/ desc Request Method: GET Request URL: http://127.0.0.1:8000/admin/api/postjob/ Django Version: 2.1.3 Exception Type: MigrationError Exception Value: desc Exception Location: /usr/local/lib/python3.6/site-packages/djongo/sql2mongo/query.py in _align_results, line 290 Python Executable: /usr/local/bin/python Python Version: 3.6.7 Python Path: ['/usr/src/rango_api', '/usr/local/lib/python36.zip', '/usr/local/lib/python3.6', '/usr/local/lib/python3.6/lib-dynload', '/usr/local/lib/python3.6/site-packages'] Server time: Tue, 18 Dec 2018 18:14:24 +0000 I thing the migrations are not affecting to my database. Please have A look into my code -
Routing error: trying to route a defined route in urls.py
I encountered a strange behavior of Django urls. Although forecast/upload url is defined in the urls.py, Django is saying Page not found (404) Request Method: POST Request URL: http://localhost:8000/forecast/upload/ Using the URLconf defined in myproject.urls, Django tried these URL patterns, in this order: polls/ admin/ forecast/ [name='index'] forecast/ **forecast/upload/** [name='upload'] forecast/ help.html [name='help'] The current path, **forecast/upload/**, didn't match any of these. Project url.py: from django.contrib import admin from django.urls import include, path from django.conf.urls import url urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), path('forecast/', include('forecast.urls')), ] Application urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), #url(r'^$', views.home, name="home"), path('forecast/upload/', views.upload, name="upload"), path('help.html', views.help, name="help"), ] -
Establish templatetag as django variable
I am attempting to filter a django queryset in a template tag, like this: @register.simple_tag def splice(query, person_id): query2 = query.filter(personid=person_id) return query2 Then, in my template, I would like to pass the newly filtered queryset into an includes html file. Here is my attempt: {% with splice df person_id as x %} {% include 'includes/file.html' with df=x %} {% endwith %} How can I execute this properly? Or does anyone have ideas how to go about this a more efficient way? -
Can I use Ajax to Update a Django ModelForm?
I am looking for a clean, DRY way to update an object using a ModelForm and AJAX. Here is what I have: def update_entry(request): if not request.is_ajax() or not request.method == "POST": pass form_data = dict(request.POST) instance = form_data.pop('id') form_data['date'] = datetime.datetime(year=int(form_data.pop('year')[0]), month=int(form_data.pop('month')[0]), day=int(form_data.pop('date')[0])) form = EntryForm(form_data, instance=instance) if form.is_valid(): form.save() return JsonResponse({'message': "success"}) The problem I am having is that the request.POST object is immutable, so I cant actually use .pop() without changing the form into a dict object or something else. If I do this, it ends up changing all of the string values into lists containing the string values. I also need to create the date value as well. Am I on the right track here, or is there a more "Django" way to approach it? -
Is there a way to modify the HTTP_REFERRER before redirecting in Django?
Let's say someone is on www.yahoo.com, and then hits my URL www.mysite.com. Now, in Django, I want to do: return HttpResponseRedirect('https://www.google.com') However, when Google receives this request, they will see the HTTP_REFERER was Yahoo, but I want to modify the referer so it shows ‘www.mysite.com’. Can this be done? -
Bidirectional communication between two django applications
This might be a basic question about microservices. I searched for a few articles but not able to find anything apt. I am developing two different django rest applications (say A and B) which has to use the same authentication service. I've built the authentication service using django-rest-framework-simplejwt. My current plan is when a token is sent to A, I use TokenVerifyView from authentication service to validate the token. In certain cases where user information is required I have created a view in authentication service to return username. I'm intending to achieve this by sending a request to the authentication service for each view in A using a decorator. I understand this will be very slow and is a sub-optimal solution. What is a better way to achieve this? Thanks. -
Does Django Rest Framework ever modify UUIDs after sending the Response object?
I have a simple APIView that generates a UUID and stores it as a string against a model using str(uuid.uuid4()). I then immediately json serialize this and return it in the data attribute of the DRF Response object. I can see during debugging that the same UUID that is generated, is stored at in the database and passed to the response object. However, by the time the UUID makes it to the client it has changed to a brand new UUID. Is there some serialization/security feature coming in to play here that I am not aware of? Thanks in advance! -
ModuleNotFoundError: importlib when pushing to Heroku despite local changes
I get this error when I try to push to Heroku, the traceback is: "/app/.heroku/python/lib/pytho n3.7/site-packages/appconf/utils.py", line 5, in import_attribute 2018-12-18T16:39:08.833497+00:00 app[web.1]: from django.utils.importlib import import_module That path doesn't exist on my computer so I assume it's Heroku's own file, but I do have that same file and almost same path in my computer (it's in the directory that's linked to the remote repo. So I went to utils.py and commented out the line django.utils.importlib import import_module and replaced it from from importlib import import_module which I've learned is compatible with Python 3. However I still receive the same error when pushing, because that file isn't updated on Heroku. How would I go about fixing that library? -
How to save the users last logout time
I am looking to save the users last logout time.My idea was to add it to the users profile model. I am using Django 1.11.15 Example: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ... last_logout = models.DateTimeField(blank=True, null=True) below is how I created my profile model just for reference def signup(request): if request.method == 'POST': form = UserCreateForm(request.POST or None) if form.is_valid(): new_user = form.save() Profile.objects.create(user=new_user) return redirect('accounts:edit_profile') else: form = UserCreateForm() context = {'form': form} return render(request, 'accounts/signup.html', context) Below is what I intend to do. Is this the correct way. I want to add to django's default signout/logout method I am not sure if its called signout or logout class LoggedOut(TemplateView): template_name = 'logged_out.html' def signout(self): """logout user """ self.request.user.profile.last_logout = datetime.now() self.request.user.profile.save() My URL's url(r'^loggedout/$', views.LoggedOut.as_view(), name='loggedout'), -
Redirecting in Django with a specific status code
If a user tries to access a page, I want him to be redirected to the login page, but with a status code 401 (unauthorized). Like this: if not 'logged_user' in request.session: return redirect('mqr_admin:login', status=401) But the redirect() function doesn't have the status param as the function render() has. What should I do? -
why My django app is not runing on heroku?
i am trying to deploy my heroku app but it keeps showing following errors. remote: File "/app/.heroku/python/lib/python3.7/site-packages/django/contrib/staticfiles/storage.py", line 43, in path remote: raise ImproperlyConfigured("You're using the staticfiles app " remote: django.core.exceptions.ImproperlyConfigured: You're using the staticfiles app without having set the STATIC_ROOT setting to a filesystem path. remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you can disable collectstatic for this application: remote: remote: $ heroku config:set DISABLE_COLLECTSTATIC=1 remote: remote: https://devcenter.heroku.com/articles/django-assets remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to murmuring-shelf-23422. remote: To https://git.heroku.com/murmuring-shelf-23422.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/murmuring-shelf-23422.git' i guess it is due to absence of static root but i already specified it as:- """ Django settings for Diary project. Generated by 'django-admin startproject' using Django 2.1.3. For more information on this file, see https://docs.djangoproject.com/en/2.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.1/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR … -
Filter within includes in django template
I am utilizing an includes within my template, but would only like to send a splice of the django queryset through the template. I don't want to splice in my view, because this is apart of a larger for loop that will be continually calling the include with different subsections. Here was my wishful thinking: {% for g in gl %} {% include 'includes/file.html' with ps=ps|id:g.id %} {% endfor %} -
How to identify or remember user's browser in Django
I am trying to implement an alert when a user logs in from a new browser. Is there any method to identify a browser like UDID for mobile devices? request.META.get('HTTP_USER_AGENT', '') will provide the browser type. But I am looking to distinguish between browser a user logs in. Whether it be from same computer or different one. -
Django Url and Views cant pass parameters
I am using Django 2.1.4 I Want to Pass a parameter like question_id in the url but i just get 404 . This is My Code : urls.py : urlpatterns = [ path('index',views.index , name='index'), path('index/(?P<question_id>[0-9])',views.detail , name='detail'), ] and this is my : view.py def index(request,): return HttpResponse("Welcome To My Page") def detail(request, question_id): return HttpResponse("new Page" + str(question_id)) When I Enter http://127.0.0.1:8000/polls/index/12 in the url , i just get 404 . -
Is there a way to get the time of login before request.user.last_login in django
Intro: I have a 3 models user, post, group. User is able to make posts however each post has to belong to a group. Users have to choose from the existing groups for their posts. Users cannot add, delete, update group's. Furthermore: Users can become a member of groups and when they click on a certain group. They see all the posts in that group. What I want When Users come on the home page they see posts that were added since the last time they logged in My Models class Post(models.Model): user = models.ForeignKey(User, related_name='posts') group = models.ForeignKey(Group, related_name='posts') title = models.CharField(max_length=250, unique=True) message = models.TextField() created_at = models.DateTimeField(auto_now=True) My Views class Homepage(TemplateView): template_name = 'home.html' def get_context_data(self, **kwargs): context = super(Homepage, self).get_context_data(**kwargs) if self.request.user.is_authenticated(): context['object_list'] = Group.objects.filter(members=self.request.user) #The last login actually shows the users current login time as the last login. Which makes the below line of code useless new_posts = Post.objects.filter(created_at__gt=self.request.user.last_login).count() context['new_posts'] = new_posts else: context['object_list'] = Group.objects.all() return context In my templates I have <div class="list-group"> {% for group in object_list %} {% if not new_posts %} {{group.post.count}} {% else %} {{new_posts}} {% endif %} {% endfor %} </div> The Issue: The last login actually shows … -
Django custom ordering in url queries
Currently, in Django API rest framework, if a user wants to see a list of something in ascending or descending order, they have to do the following: 'Datastream&order_by=-name' shows names in descending order 'Datastream&order_by=name' shows names in ascending order. I want to make a custom query where typing in 'Datastream&order_by=asc name' will order the names by ascending order, and 'desc name' will do so in descending order. I've looked at some of the source code for the REST framework, but I may be looking in the wrong area. Getting stumped on what I should do. Any ideas? -
Django Efficient One-to-Many Chain Lookup
I have the below data structure: pk Project fk-> Mission fk-> Dataset fk-> File I'd like to efficiently decide if a Project contains any files. In SQL I join the 4 tables. How do I chain Project.mission_set to data_set to file_set in the django ORM? -
view static content after authentication
I have an old ( 500 html page witch includes many javascript and css files) I want to view them after the user has authenticate him self. I have tried to use read() in my views.py loadpage = open("files/Hydra_CAN_HTML5/TN-HY-RX101.htm", "rb").read() return HttpResponse(loadpage) But this is not the best practice, do you have any advice ? -
Sending GET multiple times
I want to send to server post filtered by category: /?category=IT But then when I load this page I want to sent by GET method next parameter for instance: /?category=IT&nav=next but how to do this? How to send once again category without clicking on it? Currently my code looks like this: def post_list(request): categories = Category.objects.order_by('name') if request.method == 'GET': if 'category' in request.GET.keys(): posts = Post.objects.order_by('-created').\ filter(category=Category.objects.filter(name=request.GET['category']).first()) else: posts = Post.objects.order_by('-created') if 'nav' in request.GET.keys(): if request.GET['nav'] == 'older': pass elif request.GET['nav'] == 'newer': pass return render(request, 'blog/post_list.html', {'newest': posts[0], 'posts': posts[1:], 'categories': categories}) -
Get data from an API and saving into a Postgresql database
I'm starting in Python and I'm currently coding a script that gets the data from an API, processes it and save in a Postgresql database. I'm using Django and Postgresql, both of them are dockerized. The code is getting the data from the API and showing for me, so that part is ok. The problem now is how I save it in the database. I used to do that in PHP with Symfony and it was something along the lines of this: PHP/Symfony /*Movie*/ $movie_imdb_id = 'NULL'; $movie_status = $value->isPlaying; $movie = new Movie(); $movie->setImdbId($movie_imdb_id); $movie->setStatus($movie_status); $entityManager->persist($movie); $entityManager->flush(); I want to make the exact same thing, but in Python. Here it is my script so far. Python/Django #RestfulClient.py import requests from requests.auth import HTTPDigestAuth import json import psycopg2 conn = conn = psycopg2.connect(database="database", user="user", password="password", host="host", port="port") url = "url_api" myResponse = requests.get(url, verify = True) if(myResponse.ok): jData = json.loads(myResponse.content) for f in jData: #print(json.dumps(jData, indent = 4, sort_keys = True)) cur = conn.cursor() cur.execute("INSERT INTO table VALUES ('value', 'value')") conn.commit() else: myResponse.raise_for_status() My main problem is how to INSERT the data that I got in the Postgres tables, since they're object. Thanks for any help!