Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
type object 'User' has no attribute 'objects' (AbstractUser) python
My user object is returning error : users = User.objects.filter(fb_userid=fb_user_id) AttributeError: type object 'User' has no attribute 'objects' models.py ** from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): fb_userid = models.CharField(max_length=256) avatar = models.ImageField(upload_to='avatars/', blank=True, null=True) views.py def fb_login(request): # permission_classes = (permissions.AllowAny,) if request.method == 'POST': if 'fb_user_id' not in request.data: return Response({'error':'missing fb_user_id'}, status=status.HTTP_404_NOT_FOUND) fb_user_id = str(request.data['fb_user_id']) users = User.objects.filter(fb_userid=fb_user_id) if users.count() == 0: user, created = User.objects.get_or_create(username=fb_user_id, email='fb@fb.net') if created: user.save() else: user = users[0] token = Token.objects.get_or_create(user=user)[0] # Likes likeIds = [] likes = ImageLike.objects.filter(user_id=user.id) for like in likes: likeIds.append(like.image.id) # Saved Places savedIds = [] saved = SavedRestaurants.objects.filter(user_id=user.id) for save in saved: savedIds.append(save.restaurant.id) jsonData = { 'token': token.key, 'saved': savedIds, 'likes': likeIds } return Response(jsonData) ** error : My user object is returning error : users = User.objects.filter(fb_userid=fb_user_id) AttributeError: type object 'User' has no attribute 'objects' -
main.js url different from chunks url on deployment while code splitting with create-react-app
I'm using React as my frontend, Django as my backend, hosting my site on Heroku and my staticfiles on AWS S3. I've followed the CRA Code Splitting docs and while it works in development, when I deployed my site, my main.js was referenced correctly through https://mywebsite.s3.amazonaws.com/static/js/main.js while my chunks are being referenced through http://mywebsite.com/static/js/2.chunk.js. I prefer not to run eject so the things I've tried included setting homepage to my s3 bucket link but this did not work. Any help would be much appreciated! -
Restrict users to read exclusively one's own articles
I have the following article_detail view which restrict that only users logged in could read the details. @login_required(login_url="/user/login/") def article_detail(request, pk): article = get_object_or_404(Article, pk=pk) total_views = r.incr("article:{}:views".format(article.id)) page_number = request.GET.get('page_number', 1) #mimic SO's 100 per-page per_page = request.GET.get("per_page", 30) .... How could I set that each user can exclusively read contents posted by oneself? -
Template Render is not passing pymongo aggregate variable to template
I am trying to pass a variable from pymongo on my views.py to a template. I am not getting any errors but neither is my code being rendered to my template. views.py: def gettheAudit(request): for x in mycol.aggregate([{"$unwind":"$tags"},{'$match': {'tags.tag.name':'A A',}},{'$project': {'url': 1, 'AR': 1, 'tags.tag.name': 1, 'tags.variables': 1, '_id': 0}},]): theURLs = x['url'] theNames = json.dumps(x['tags']['tag']['name']) theVs = json.dumps(x['tags']['variables']) template = loader.get_template('/folder/a.html') context = { 'theURLs' : theURLs, 'theNames' : theNames, 'theVs' : theVs, } return HttpResponse(template.render(context, request)) My HTML code is pretty simple. I am just trying to print a list of the urls: <ul> <li><h1>URLSSSS</h1></li> {% for theURL in theURLs %} <li>{ theURL.theURLs } {% endfor %} </ul> My result: URLSSSS {% for theURL in theURLs %} { theURL.theURLs } {% endfor %} I am new to Django and MongoDb and can't seem to figure out where I went wrong. -
Using Django Python I am stuck on " 'WSGIRequest' object has no attribute 'address' "error when trying to create an address form for my users
The error 'WSGIRequest' object has no attribute 'address' is not an issue on my CRM, but rather on my actual webserver. I cannot seem to figure out how to add address to users and is not allowing me to display the form on my 'information/' page. My end goal is for users to create their username, email, password on the registration page, then be directed to this page, information, where they can add their address and when I add the code, their billing information. Then it takes them to the home page. views.py from django.shortcuts import render, redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from .forms import AddressForm, UserRegisterForm, UserUpdateForm, ProfileUpdateForm from django.views import generic from . import forms from django.views.generic import ListView, CreateView, UpdateView def address(request): if request.method == 'POST': a_form = AddressForm((request.POST)) if a_form.is_valid(): a_form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been created! Please enter your additional information below') return redirect('') else: a_form = AddressForm(instance=request.address) return render(request, 'users/information.html', {'a_form': a_form}) urls.py from django.contrib import admin from django.contrib.auth import views as auth_views from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from users import views as user_views # from django.contrib.auth.decorators import login_required … -
How to change backgroud color in Django Admin
I have a simple model that I list in the admin, there is a field: etapa which takes a couple of values: {1, 3, 4, 5, 50, 77}. I want to mark all etapa=50 rows in RED. models.py class Registro(models.Model): ensayo = models.ForeignKey(Ensayo) fecha = models.DateTimeField(blank=False) fecha.date_fileter = True presion = models.FloatField(blank=False, help_text="Presion", verbose_name="PRESION (Bar)", null=False) etapa = models.IntegerField(blank=False, help_text="Etapa", null=False) tempin = models.FloatField(blank=False, help_text="Temp IN", verbose_name="TEMP. IN (C)", null=False) libre1 = models.FloatField(blank=False, help_text="Libre 1", null=False) libre2 = models.FloatField(blank=False, help_text="libre 2", null=False) libre3 = models.FloatField(blank=False, help_text="libre 3", null=False) def __unicode__(self): return "%s" % self.fecha class Meta: verbose_name_plural = "Registros" enter code here change_list.html Any idea? -
MultiValueDictKeyError Django
I'm trying to make simple form run but I have cost, I'm not using the forms.forms of django, I'm doing the forms from HTML directly. Well, my form simply has 1 file field and a post button, in the field I want to add an .xlsx and get data from that file and register it in a specific model but it gives me the following error: django.utils.datastructures.MultiValueDictKeyError: "'ar'" acontinuacion I want to show you how I have structured my code and I do not understand why I get an error, I would also like to give me an idea of how to obtain the excel data that I select in the input file and register it in bd: View: from django.views.generic import View from django.shortcuts import render,redirect from condominio.models import * class TestExcel(View): def post (self, request, *args, **kwargs): print (request.FILES) file = request.FILES['ar'] return HttpResponse('this is post') def get(self, request, *args, **kwargs): return render(request ,'testing.html' ,{}) template : {% extends 'base.html' %} {% load staticfiles %} {% load static %} {% block content %} <div class="container"> <div class="row"> <form action="#" method="POST"> {% csrf_token %} <div class="file-field input-field"> <div class="btn"> <span>File</span> <input name="ar" id = "ar" type="file" > </div> <div … -
django-distance - ImportError: No module named 'django.db.models.sql.aggregates'
I am using Django 2.1.1 and was trying to use django-distance. However after installing django-distane and running my app. I am getting the error ImportError: No module named 'django.db.models.sql.aggregates' Is there anything that I need to install extra to get aggregates ? -
Authentication in Django during GET request
I need to do a GET request to my Django server through an android application. The problem is that this GET function is written in Django with a @login_required. What kind of request should i do to login and perform the GET request? -
Django: populate user selectable databse fields in result
I have a big Django database table which has more than 50 columns. I take input from the user (in array) which columns he wants to see in the search results. I am unable to map the user selected columns to the database. ticker_details = ticker_quotes.objects.filter(mkt_cap__lte = float(20))[:100] if(len(ticker_details) > 0): # print("length: ",len(data)) for item in ticker_details: try: history[(item.symbol_id)] = {"title" : item.symbol_id, "change" : item.change} # How to select the database column using variable except: pass self.context["detail"] = history in the above code, I want to select the columns based on the user input but I get error when I try to access the column name using string variable. -
NameError: name 'name' is not defined [on hold]
I am using sublime text 3 for web development following a youtube video for Django. I am following exactly what the video says to but i keep getting an error. path('', views.home, name@'home'), NameError: name 'name' is not defined In the video when the guy types 'name' it changes colour however when i type it stays plain. -
Before runserver command executes render a page ask for password
Have a requirement to display a page when typed in manage.py runserver. This will display a page first which would only have a password input. Based on the password correctness it will execute manage.py runserver or whatever the command is. -
Using different databases depending on a parameter in the URL
Is there a way I can tell Django2 to use a different database (and cache/session store) depending on a parameter in the URL? Note that I have read the docs related to multiple databases en Django (https://docs.djangoproject.com/en/2.1/topics/db/multi-db/#automatic-database-routing), and that is not what I'm asking. The docs are showing an example about how to use DATABASE_ROUTERS, which is a way of choosing which database should be used programatically when using a model. What I'm asking is how can I make Django2 use different databases automatically depending on a parameter in the URL. Example: http://foo.bar/usa <-- use USA database http://foo.bar/europe <-- use Europe database -
How can I create a plugin to insert templated html within a text plugin in Django CMS
I'm fairly new to Django CMS so please forgive me if my terminology isn't right. I have a page with a placeholder within which I have added some html using the Text plugin. Within that, I would like to be able to add one or many pre-templated pieces of html. I have looked into building my own plugin but the documentation that I've been reading here only allows the plugin to be added from outside the actual text plugin page and renders the result beneath my text plugin content. What I'm looking for is to be able to build something so that it places block-level html elements within the content like the Link or Image plugins (in my case, it would be some block-level html content). How can I do this, or where can I find some more information on how this can be done? -
NoReverseMatch at / Reverse for 'post_detail' not found
I'm developing a simple blog with Python and Django. On my home page, I display the 3 latest posts and then all the posts. At this point my blog is working. But I added a link "Show more" or "Show article" to display the post alone in a new page but I get the following error when I load the page: NoReverseMatch at / Reverse for 'post_detail' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['post/(?P[0-9]+)/$'] PS: I'm following this tutorial in french (this one is in English but it is a bit different in english here. And please note that I'm juste starting Python and Django :) So here is my code: post_list.html (template) {% extends 'blog/base.html' %} {% block latestsnews %} {% for latest in latests %} <article class="lastnews"> <h4>{{ latest.title }}</h4> <h5 class="lastestcategory">{{ latest.category }}</h5> <p class="bodysmall">{{ latest.text|truncatewords:10 }}</p> <div> <p class="date">{{ latest.published_date }}</p> <p class="showmore"><a href="{% url 'post_detail' pk=post.pk %}">Show more</a></p> </div> </article> {% endfor %} {% endblock %} {% block posts %} {% for post in posts %} <article class="post"> <header class="postheader"> <h4>{{ post.title }}</h4> <p class="info">{{ post.category }}, {{ post.published_date }}</p> </header> <p class="bodyregular">{{ post.text|linebreaksbr }}</p> <footer class="postfooter"> <p class="author">Author: {{ post.author … -
How to get an instance in django middleware?
I want to write a visit saver. My logic: I get request to specific view in middleware and set the data up in the redis. How can I get the instance of view? My models.py class HitPoint(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) ip = models.GenericIPAddressField('ip', protocol='both', unpack_ipv4=True) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return str(self.post) And my custom middleware: class MultipleProxyMiddleware(MiddlewareMixin): def process_view(self, request, view_func, view_args, view_kwargs): # PostDetail is CBV with slug. if view_func.__name__ == PostDetail.__name__: ip, is_routable = get_client_ip(request) cache_name = f'post_{uuid.uuid4()}' cache.set(cache_name, { 'ip': ip, # HOW CAN I GET THE INSTANCE OF POST? 'post_id': ???, 'created': now(), }, timeout=None) -
upload csv file as users and send reset email django
I am facing problem in creating a custom user without username, I have a .csv file which has to be uploaded and on uploading the system has to create the user and send the reset password email to the user, so that they can create there own password. In my csv file, I don't have a username, I have email, firstname, lastname, age, and Address. I tried to follow the answer given[here][1] but I see a lot of errors. Could anyone please help me with this issue. NOTE - I am using Django 2.0 -
Django: multiple different fields -> one model
I want to show different fields (a html-option-field who gets Mymodel.object.all and a textfield). How can I build this? MultiValueField (https://docs.djangoproject.com/en/2.1/ref/forms/fields/) doesn't help with different fields? Has someone an example? How can I define which kind of field it is? -
Django Rest Framework multiples databases
i'm new in Django and i'm tring understand how django can use 2 dattabases for my apllication. Database 1 - i want to use to Django system Database 2 is an existing database with datas, and i want to avilable this datas in my api django, like the image below: Arquitetura da API Thanks all -
Serving static files with Ngnix, Django and Docker
I am fairly new to Nginx and Docker and am currently facing an issue regarding a docker container setup. The setup consists of three containers: Nginx, Django and Postgres. It works as expected for the most part, however, I am not able to access static files through Nginx. Here is the nginx.conf: user nginx; worker_processes 1; error_log /var/log/nginx/error.log warn; pid /var/run/nginx.pid; events { worker_connections 1024; } http { include /etc/nginx/mime.types; default_type application/octet-stream; log_format main '$remote_addr - $remote_user [$time_local]' '"$request" $status $body_bytes_sent' '"$http_referer" "$http_user_agent"' '"$http_x_forwarded_for"'; access_log /var/log/nginx/access.log main; upstream server { server server:8000; } server { listen 80 default_server; listen [::]:80 default_server; server_name localhost; charset utf-8; root /usr/share/nginx/html; index index.html; location / { try_files $uri $uri/ @rewrites; } location @rewrites { rewrite ^(.+)$ /index.html last; } location ^~ /static/ { autoindex on; alias /usr/share/nginx/html/static/; } location ~ ^/api { proxy_pass http://server; } location ~ ^/admin { proxy_pass http://server; } } } I would expect Nginx to serve /usr/share/nginx/html/static/ when I access the address localhost:8000/static. I did check the container fs at /usr/share/nginx/html/static/, and the static files are present. Here is the docker-compose.yml: version: "3" services: nginx: container_name: nginx build: context: . dockerfile: ./nginx/Dockerfile image: nginx restart: always volumes: - ./server/static:/usr/share/nginx/html/static ports: … -
Running Inner Join Using Django for two tables
I have two tables QUEUE and MESSAGE. The relationship is One Queue to Many Messages. The Queue table has SEQ field which directly links to Field QUEUE in Message table. So QUEUE field is a foreign key in QUEUE table, which links to Primary key SEQ field which resides in QUEUE table. I want to get Messages in a queue with a certain status and have certain age in minutes(calculated from date_create and current time), and the result set must contain a message with the queue name So views are as follows: Queue Table Fields: SEQ, NAME Message Table Fields: MSG_NO, QUEUE, STATUS1, DATE_CREATED I need two select Messages in the Message table for last 12 hours and turn INNER JOIN Queue name to the results: I want to produce similar result using Django ORM, raw query below: SELECT m.msg_no, q.seq, To_Char(m.date_created,'yyyy/mm/dd hh24:mi:ss'), To_Char(SYSDATE-30/1440,'yyyy/mm/dd hh24:mi:ss'), q.name, Round((round(SYSDATE - m.date_created,5)*1440),1) AS msg_age FROM message m INNER JOIN queue q ON m.queue = q.seq WHERE m.date_created > To_Date(To_Char(SYSDATE,'yyyymmdd')||'050000', 'yyyymmddhh24miss') And m.date_created < (SYSDATE - 30/1440) AND m.status1 = 0 AND m.direction = 0 -
Django: How to save form fields after failing validation?
I have a form with two filefields. What I am trying to do is, if the user inputs wrong files (or incompatible files), then it will throw an error and still keep the user's uploaded file there. However, it currently clears the uploaded files. I don't think I quite understand how forms work. return render(request, 'home.html', {'form':form, 'error_msg':error_msg,} When I print field values right before render, I see all the values there, but once it renders to home.html, the form is cleared. Is it that the data is not bounded to the form somehow? -
Form action forwarded to unknown page
question from newbie pls. Im modifying a bootstrap templates. The form tag didn't mentioned 'action' so I put a url to process the form but seems like the JS override this. I have gone through all the codes in JS file but can't find the 'contact/thanks' where the form directed to once submit button is clicked. <!-- Bootstrap core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom fonts for this template --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css? family=Lato:400,700,400italic,700italic" rel="stylesheet" type="text/css"> <!-- Plugin CSS --> <link href="vendor/magnific-popup/magnific-popup.css" rel="stylesheet" type="text/css"> <!-- Custom styles for this template --> <link href="css/freelancer.min.css" rel="stylesheet"> <!-- Bootstrap core JavaScript --> <script src="vendor/jquery/jquery.min.js"></script> <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- Plugin JavaScript --> <script src="vendor/jquery-easing/jquery.easing.min.js"></script> <script src="vendor/magnific-popup/jquery.magnific-popup.min.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Custom scripts for this template --> <script src="js/freelancer.min.js"></script> Where can I find where the form is redirected to? I supposed in one of the file above? but what should I look for? I tried looking for 'contact' in all files above(except the 'css' file) but found nothing. The form is handled with PHP but I want to use Django(i'm learning it at the moment). Thanks in advance. -
how to config supervisor with django channels and server daphne
I have a problem with my configuration supervisor, my file is in etc/supervisor/conf.d/realtimecolonybit.conf, when I try command supervisorctl reread, show me the "No config updates to processes" and when I try the other command like this supervisorctl status realtimecolonybit show me this error realtimecolonybit FATAL can't find command '/home/ubuntu/realtimecolonybit/bin/start.sh;' and when try the supervisorctl start realtimecolonybit show me this error realtimecolonybit: ERROR (no such file) my configuration in my file realtimecolonybit.conf is below [program:realtimecolonybit] command = /home/ubuntu/realtimecolonybit/bin/start.sh; user = root stdout_logfile = /home/ubuntu/realtimecolonybit/logs/realtimecolonybit.log; redirect_strderr = true; my configuration from my file start.sh is below #!/bin/bash NAME="realtimecolonybit" DJANGODIR=/home/ubuntu/realtimecolonybit/colonybit SOCKFILE=/home/ubuntu/realtimecolonybit/run/gunicorn.sock USER=root GROUP=root NUM_WORKERS=3 DJANGO_SETTINGS_MODULE=colonybit.settings echo "Starting $NAME as `whoami`" cd $DJANGODIR source /home/ubuntu/realtimecolonybit/bin/activate # workon realtimecolonybit export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPAHT=$DJANGODIR:$PYTHONPATH RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec daphne -b 0.0.0.0 -p 8001 colonybit.asgi:application when I run without supervisor like this (realtimecolonybit)realtimecolonybit/#/ ./bin/start.sh it's run ok and working well, but sometimes down the server I try to run a django 1.11 and django_channel with supervisor my app is in aws but I don't know why to happen that, please help me tanks for your attention. -
functional test for image in django
How do you write functional tests for an image field with selenium. I have started creating the functional test but i don't know how to test the image part. Model class Post(models.Model): title = models.CharField(max_length=255) content = models.TextField() image = models.ImageField(blank=True, null=True) publication_date = models.DateField(default=datetime.date.today) expiring_date = models.DateField() Test: class RegisterAPostTest(FunctionalTest): def test_can_register_a_post(self): # Nato goes to check the home page of the new blog app # he has heard about self.browser.get(self.live_server_url) # He notices the page title and the header mentions posts self.assertIn('Blog', self.browser.title) # He sees an invitation to create a new post and he clicks it create_post_page = CreatePostPage(self).go_to_create_post_page() # He is taken to a new page were he encounters different fields # he needs to fill. # He starts to filling the title of the post create_post_page.write_in_title_input_box('Awesome blog post') # Then he fills the content of the post create_post_page.write_in_content_input_box('Content of the post') ## TODO: PUT THE REST OF THE FIELDS # He after finish saves the blog post self.find_element_by_link_text('Create post').click() # The page shows him a success message telling him the blog has been # created navbar = self.find_element_by_css_selector('.navbar') self.assertIn('The blog post has been created', navbar) I know i have to click the link but how …