Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django static files inconsistent
This is driving me crazy. I have the following file structure: django_project/ - manage.py -- django_project/ --- static/ ---- admin/ ---- cms/ ---- djangocms_admin_style/ So, nothing special here. However, files from e.g. /static/djangocms_admin_style/js/dist/bundle.adminstyle.min.js get served while files like /static/admin/css/base.css result in an 404 error (yes, they do exist). Additionally, these are the settings in question (from settings.py): STATIC_ROOT = os.path.join(PROJECT_ROOT, "static") STATIC_URL = '/static/' How on earth can they be treated differently? It only occurs with /static/admin/ files. Are some files more equal than others? -
Is ON DELETE CASCADE in database considered a bad practice these days?
Django documentation says: When an object referenced by a ForeignKey is deleted, Django will emulate the behavior of the SQL constraint specified by the on_delete argument. And Django seems to not deem it necessary. Or maybe even discourages it. Question about setting up cascade deleting in Rails has answer that suggests using database for that, alongside framework-level setting, takes 4th place right now. And actually, I'm not sure if it makes sense or is a good idea to use both. So, which is it? Should I use both? Should I stick to app-level? Which is better and under which conditions? -
Django Rest Framework JWT - "Error Decoding Signature" on first try only
As you may be able to tell from the title, I'm having an issue with rest_framework_jwt. Strangely, right after authenticating and receiving my token, if make a follow up request using that token, and I receive a 401 Permission Denied: "Error decoding signature". I've tracked it down to an exception thrown by jwt.decode() in the jwt python library, and no variation in JWT settings resolves the issue. The next time I make the request (same url, I just hit refresh in my app), I am verified properly and I receive a proper response. Even more bizarre, using https://jwt.io/ and my settings.SECRET_KEY, I can verify my signature! So I know it's valid. Any thoughts? -
django many to many deny selecting existing objects in admin
Default widget for many-to-many relationships in django admin lets create new or select existing objects. Is it possible to not show existing and allow admin only create new objects ? -
Connect refused in response to Django runserver
Working my way through a Django tutorial, I have run django-admin startproject mysite. Now I cannot get the next step to work: I do not get the the "'Welcome to Django' page, in pleasant, light-blue pastel" as described in the tutorial. $ python manage.py runserver This produces no output. It can be terminated by control-C. Most importantly, I get a connection refused error when connecting to http://127.0.0.1:8000. For other commands python manage.py works correctly. For example: $ python manage.py check System check identified no issues (0 silenced). $ python manage.py shell --command 'import sys; print(sys.version)' 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:27:37) [MSC v.1900 64 bit (AMD64)] $/ python manage.py shell --command 'import django; print(django.__version__)' 1.11.2 I am at loss for how explore further. I have tried: Using multiple browsers Varying the IP and port Turning off the proxy Consulting other Stack Overflow, such as here and here Rebooting my computer I am at loss for other steps to debug this problem. -
Postgres Sequences as Default Value for Django Model Field
I have a PostgreSQL database that is being used by a front-end application built with Django, but being populated by a scraping tool in Node.js. I have made a sequence that I want to use across two different tables/entities, which can be accessed by a function (nexval(serial)) and is called on every insert. This is not the primary key for these tables, but simply a way to maintain order through some metadata. Using it in Node.js during the insertion of the data into the tables is trivial, as I am using raw SQL queries. However, I am struggling with how to represent this using Django models. There does not seem to be any way to associate this Postgres function with a model's field. Question: Is there a way to use a Postgres function as the default value of a Django model field? -
Django--- Allowing Users to only edit their profile
I want to allow User to only edit their profile. This is my URL: url(r'^profile/(?P<pk>[0-9]+)/$', views.UserUpdate.as_view(), name='profile') Now when the user click on 'my profile' they will get their own profile which they can edit but if they manually edit the urlpath in browser and enter other user's id like below, they can view and edit other User's profile http://127.0.0.1:8000/profile/1/ this is my view class UserUpdate(UpdateView): model = Profile fields = ['personal_info','job_title','department', 'location','expertise', 'user_photo','phone_number','contact_facebook','contact_linkedin','contact_skype'] template_name = 'user_form.html' success_url = reverse_lazy('index') Now in user_form.html I have checked if the user is authenticated so that only logged in user can view the profile page but still logged in User can view other user's profile. {% if user.is_authenticated %} <h3> {{ user.first_name }}'s Profile</h3> <form class="form-horizontal" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'form-template.html' %} <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <button type = "submit" class="btn btn-success">Submit</button> <a href={% url 'index' %}><input type="button" class = " col-sm-offset-2 btn btn-warning " name="cancel" value="Cancel" /></a> </div> </div> </form> This is my model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) personal_info = models.TextField(blank=True) job_title = models.CharField(max_length=100, blank=True) department = models.CharField(max_length=100, blank=True) location = models.CharField(max_length=100, blank=True) expertise = models.TextField(blank=True) phone_regex = RegexValidator(regex=r'^\+?1?\d{5,15}$', message="Phone number must be entered in … -
Populating a FormView with custom queryset
I'd like to set the logged in user's data to a profile form. Why isn't the below view populating the model form? class UpdateProfile(FormView): model = User form_class = ProfileForm def get_queryset(self): return self.model.objects.get(pk=self.request.user.id) class ProfileForm(forms.ModelForm): class Meta: model = User fields = ['email', 'name', 'company', 'title'] All my fields end up empty. -
django UUIDfield renders without hyphens in form
I have a model with an UUIDField: class TrafficReceiverCampaign(NamedModel): uuid = models.UUIDField(default=uuid4) which is displayed in admin this way @admin.register(TrafficReceiverCampaign) class TrafficReceiverCampaignOpts(admin.ModelAdmin): fields = ('uuid',) and while it can be saved correctly not throwing any errors, it is rendered in the form without hyphens: how do I make hyphens visible? -
django help needed. Have a frondend webpage with a form in it. Need to connect it to db using django [on hold]
I have a html file, its basically a form to submit data developed using bootstrap, javaScript and jQuery. Now I plan to develop the backend code such that I can take this data into database and store it. I am using django framework to achieve this, I have already created a model and created a table for the form in sqlite db. Now I need help to connect my frontend form with the db. Can someone let me know how to achieve this -
emacs as python IDE with elpy and django
I have my emcas configured withe elpy adn it works very fine: Sytaxis correction, autocomplete, see documentation, go to definition etc Unfortunately, It doesn't work with django classes. Is there any way to enable the use of django in my emacs? -
can not import models/views/urls from my django app in project/urls.py
i am unable to import anything from my models/views/urls/admin of my django app, all of which fails with something like this: Environment: Request Method: GET Request URL: http://52.74.49.108:8081/ Django Version: 1.10.3 Python Version: 2.7.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'djcelery', 'mailer'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/core/handlers/exception.py" in inner 39. response = get_response(request) File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/core/handlers/base.py" in _get_response 172. resolver_match = resolver.resolve(request.path_info) File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/urls/resolvers.py" in resolve 270. for pattern in self.url_patterns: File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/urls/resolvers.py" in url_patterns 313. patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/utils/functional.py" in __get__ 35. res = instance.__dict__[self.name] = self.func(instance) File "/home/ubuntu/rmailer/lib/python2.7/site-packages/django/urls/resolvers.py" in urlconf_module 306. return import_module(self.urlconf_name) File "/usr/lib/python2.7/importlib/__init__.py" in import_module 37. __import__(name) File "/home/ubuntu/ReportMailer/ReportMailer/urls.py" in <module> 21. from mailer.models import Mailer Exception Type: ImportError at / Exception Value: No module named models Though i have models/views/urls in mailer, if i write import mailer it will pass without errors (and i have __init__.py in mailer folder, have it in installed apps too), but i dont see any models from my app showing in django admin which means django did not found any admin.py. my admin.py is: from django.contrib import admin from … -
Why does Django think my query string is empty?
I've been having trouble with a query string in one of my views in Django. I've successfully handled query strings in other views, so I'm not sure what I did wrong here. I stripped things down to a really basic view, and I'm still not getting anything. My URL: localhost/view/?foo=foo My template: <html> <head> <title>Title</title> </head> <body> <p>{{ query_string }}</p> </body> </html> My view: def query_view(request): query_string = request.META['QUERY_STRING'] return render(request, 'query_view.html', {'query_string': query_string}) I should expect foo=foo to be displayed on the page, right? Currently, I'm getting nothing. -
Best way to implement Video Chat with Django Backend?
So i'm trying to build a React Native with basic video chat functionality. So far I have a Django backend and users can signin/signup/signout. Other than that, what's the best way to tackle this video chat? Thanks! -
Unable to retrieve logged in user specific content on html page in django
I have successfully created a login page and i am able to login the user after signing them up. But i fail to retrieve the user data and display it in user's home page apart from user's username and email(which come up with inbuilt User model since i have inherited it.). Here i want to show the profile picture of the user on its home page after logging in.Thanks in advance. models.py class Profile(models.Model): user = models.OneToOneField(User) first_Name=models.CharField(max_length=26,default=" ") last_Name=models.CharField(max_length=26,default=" ") gender=models.CharField(max_length=10) father_name=models.CharField(max_length=56) profile_pic=models.ImageField(max_length=100,upload_to='profile_pics') @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: profile=Profile.objects.create(user=instance) instance.profile.save() def __str__(self): return self.user.username forms.py class UserForm(forms.ModelForm): password=forms.CharField(widget=forms.PasswordInput()) class Meta(): model = User fields=('username','password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model=Profile fields=('first_Name','last_Name','gender','father_name','profile_pic') views.py @login_required def IndexView(request,user_id): user = User.objects.get(pk=user_id) profile_pict=user.profile.profile_pic return render(request,"studenthome.html",{ 'username': user.username, 'address':user.profile.address, 'profile_pict':profile_pict, }) class LoginView(View): form_class = UserForm template_name="login.html" def get(self,request): form=self.form_class(None) return render(request,self.template_name,{'form':form}) def post(self, request): password = request.POST['password'] username = request.POST['username'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: if user.is_staff: login(request, user) return render(request,'teacher.html',{'username':user.username}) else: login(request,user) return render(request,'studenthome.html',{'username':user.username}) # return redirect('IITMApp:index') else: return HttpResponse("Inactive user.") else: # return redirect("IITApp:login") return render(request, 'login.html',{ 'login_message' : 'Enter the username and password correctly',}) return render(request, "studenthome.html") -
Cannot access Django webpage when using Docker to run a virtualized Django project on Linux server
I set up a docker for a Django project on a Linux server. However, when I run the Django project, it cannot be accessed through the Internet. The project is set up using Docker automatic build and pulled using docker-compose. The docker-compose ps command gives the following output, indicating the project is running. ~/otree-docker$ docker-compose ps Name Command State Ports ------------------------------------------------------------------------------------ otreedocker_database_1 docker-entrypoint.sh postgres Up 5432/tcp otreedocker_otree_1 /bin/sh -c /opt/otree/entr ... Up 0.0.0.0:80->80/tcp otreedocker_redis_1 docker-entrypoint.sh redis ... Up 6379/tcp When I use nginx to set up a test webpage, however, it can be accessed without any issue. Most importantly, I used the same Docker automatic build on another server, it ran without any issue, so the issue must be the setup of the server, not the Django project or the Docker automatic build. Anyone can suggest where to identify the issue? I have been struggling with this issue for several days, and have no idea where to check. BTW, when I check the usage of the ports when running the Django project, I get the following: ~$ netstat -ntl Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State tcp 0 0 0.0.0.0:49471 0.0.0.0:* LISTEN tcp 0 … -
Django messages formatting
does anyone understand this code and how it would be changed to show "sender wrote : message" on the same line instead of having it split on different lines. As you see in the image below. I really dont understand why they've gone for this formatting. Code in utils.py def format_quote(sender, body): """ Wraps text at 55 chars and prepends each line with `> `. Used for quoting messages in replies. """ lines = wrap(body, 55).split('\n') for i, line in enumerate(lines): lines[i] = "> %s" % line quote = '\n'.join(lines) return ugettext(u"%(sender)s wrote:\n%(body)s") % { 'sender': sender, 'body': quote } this is the messaging app im using: https://github.com/arneb/django-messages It just look horrendous as it is and i can figure out how to make it look nicer, any help would be hugely appreciated! -
django server not running on host with vagrant
Vagrantfile: config.vm.network "forwarded_port", guest: 8080, host: 8080 On my virtual machine I am running this command: python manage.py runserver 0.0.0.0:8080 But when I try to curl on host machine, response is curl: (52) Empty reply from server and on browser it says 127.0.0.1 didn’t send any data. I looked on stackoverflow for this problem, most of them were able to resolve it by adding 0.0.0.0 to the runserver command. But, I have already added it. I tried: Disabling the firewall and allowing all connections to the virtual machine by accepting all input and output in iptables. I changed the 127.0.0.1 localhost in /etc/hosts to 0.0.0.0 localhost but still the same response. I ensured that my host machine is not preventing it by disabling the firewall on my host machine too. Note: I am using ubuntu machine on virtual box and mac OS on host. -
Django base template (using bootstrap3) overwrites index.html completely
I've created a base.html file where I want my bootstrap3 navbar and footer to live. These will be used on every page of my site. However, the base.html & corresponding css file that goes with it seems to overwrite all of the index.html file and specific css for that view. I've read the django documentation and closely-related questions like this one on overriding the base template. Other website have tutorials but still aren't making sense. I believe I am misunderstanding something fundamental. Here is the code: base.html: <!DOCTYPE html> {% load staticfiles %} <html> <head> <link rel="stylesheet" href="/static/css/main.css" /> <!-- jquery --> <script src="//code.jquery.com/jquery-1.12.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <!-- [/] jquery --> </head> <body> {# Load the tag library #} {% load bootstrap3 %} {# Load CSS and JavaScript #} {% bootstrap_css %} {% bootstrap_javascript %} {# Display django.contrib.messages as Bootstrap alerts #} {% bootstrap_messages %} {# Navigation Menu #} <header> <nav class="navbar navbar-default"> ----->Navbar code here<----- </nav> </header> <footer> <div class="container"> <p>Good stuff is here in the footer</p> </div> </footer> </body> </html> index.html: <!DOCTYPE html> <html lang="en"> <head> <meta name="description" content="Online community"> <meta name="author" content="My name"> <title>Planet</title> <link href="/static/css/homepage.css" rel="stylesheet"> </head> <body> {% extends 'base.html' %} {% block content %} <p>WORDS … -
how to make USERNAME field unique for multiple type of users in User Model
I have followed these [1,2,3] links to create a custom user model by extending AbstractBaseUser class. I am storing login information of three type of users lets say teacher, Admin and students in this table. USERNAME field is emailId. I want to make emailId unique among one type of users. In other words, in my system student can register as teacher as well with same emailId. But since emailId is USERNAME field and hence unique, I am unable to achieve this. Please suggest how can I do this in Django application. UserModel : class UserModel(AbstractBaseUser): user_type_choices = ( (constants.USER_TYPE_ADMIN, 'Admin'), (constants.USER_TYPE_INSTITUTE, 'Institute'), (constants.USER_TYPE_STUDENT, 'Student') ) sys_id = models.AutoField(primary_key=True, blank=True) name = models.CharField(max_length=127, null=False, blank=False) email = models.EmailField(max_length=127, unique=True, null=False, blank=False) mobile = models.CharField(max_length=10, unique=True, null=False, blank=False) user_type = models.PositiveSmallIntegerField(choices=user_type_choices, null=False, blank=True) is_staff = models.BooleanField() is_active = models.BooleanField(default=True) objects = MyUserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ['name', 'mobile', 'user_type','is_staff'] I am using other models like StudentsDetails, TeacherDetails with foreign key to UserModel to store extra information. -
How to deploy django project and postgreSQL from localhost to AWS or Digital ocean
I have developed django project on my computer. I used virtuelenv and installed all libraries and packages there. I also have postgreSQL database on my computer. How could I deploy my existing server with all files and libraries, my postgreSQL database with all tables and all rows to either digitalocean or AWS. I only found tutorials on how to create new django projects on these platforms. -
Pre-order traversal of django CMS plugins
I need an iterable of all the CMSPlugins in a placeholder, ordered the same way as they appear in the Structure Board. Logically, this is a pre-order traversal, but I have not yet found an efficient way to implement this with django CMS. Things I've tried: order_by('path') / CMSPlugin.get_tree(): Works initially but is not fully updated when plugins are moved get_position_in_placeholder(): Is incorrectly named as it just returns the position with respect to the immediate parent Does anyone have an efficient solution? -
Docker continuum/miniconda3 container not showing "conda"
I have a Docker container running the continuum/miniconda3 image with a Django project that is successfully serving to localhost:8000, and I can see my project running in the browser. The container is built with the following Dockerfile FROM continuumio/miniconda3 ENV PYTHONUNBUFFERED 1 RUN mkdir /pft WORKDIR /pft RUN rm /bin/sh && ln -s /bin/bash /bin/sh RUN apt-get update && apt-get install -y && \ apt-get install build-essential libssl-dev -y && \ rm -rf /var/lib/apt/lists/* RUN conda create --name pft python=3 RUN source activate pft RUN pip install 'django==1.10.5' However, when I try and run the "conda" command in the running terminal with the following: docker exec -it my_running_container /bin/bash I am getting this error message: root@ad9621c5e9bd:/pft# conda bash: conda: command not found What else is confusing is that in the Dockerfile the official image uses which can be found here https://hub.docker.com/r/continuumio/miniconda3/~/dockerfile/ An image is built with the following command, and I am not seeing the either /etc/profile.d/conda.sh or /opt/conda. RUN echo 'export PATH=/opt/conda/bin:$PATH' > /etc/profile.d/conda.sh && \ wget --quiet https://repo.continuum.io/miniconda/Miniconda3-4.3.14-Linux-x86_64.sh -O ~/miniconda.sh && \ /bin/bash ~/miniconda.sh -b -p /opt/conda && \ rm ~/miniconda.sh I am sure that I am attaching to the correct container for one because I can see … -
Join model based on similar fields in joining model
I know very little about django so I'm not really sure where to start in solving this. I have 3 models, customer/order/ordercustomer used for a rest API When a customer is created, both the customer and the order number are added to the OrderCustomer model. What I am trying to do is create a relation between Order and OrderCustomer so that the Order model will contain the Customer ID based off of what was entered when creating the Customer. This is an example of what I have so far in my models.py class OrderCustomer(models.Model): order_number = models.CharField(max_length=100) customer = models.ForeignKey(Customer) class Customer(models.Model): def _get_order_number(self): order_number = None try: order_customer = OrderCustomer.objects.get( customer_id=self.id ) order_number = order_customer.order_number except: pass return order_number order_number = property(_get_order_number) class Order() order_number = models.CharField(max_length=100) customer_number = ????? def __str__(self): return self.order_number -
Add up all the values in a queryset in Django
I am writing a django app that has two classes: A review, and a reply to the said review. The reply is stored in a ManyToMany Field in the review. This is my Class for the review: class Review(models.Model): title = models.CharField(max_length = 30) replies = models.ManyToManyField(Reply) def __str__(self): return self.title And here is my reply class: class Reply(models.Model): rating = models.DecimalField(decimal_places=1, max_digits = 2, validators = [MaxValueValidator(5), MinValueValidator(0)], default = 0 ) text_reply = models.TextField(max_length = 200) One of the things I wish to do, is to take all the ratings for a certain Review, and calculate the average of these numbers. I have tried to do this by doing this: def calculate_average(): objects = Review.objects.all() average = 0 length = 0 for reply in objects: average += reply.replies.rating length += 1 return average/length This returns a AtrributedError in my console.