Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Variable can be not defined
I have this piece of code from django.db import transaction with transaction.atomic(): try: variable = 1 except Exception: raise Exception() print(variable) And pycharm (2018.1.2) tells me that variable in print function can be not defined. In which case it can be happen? Or is it a pycharm bug? -
DRF with DDD few fundamental questions
I am getting into Domain Driven Design, learning the core concepts of it, and trying to figure out how I might implement them with Django Rest Framework- how can concepts from both be related to each other. I am going to pose multiple questions and not one, but they are related to each other. Questions are roughly based on https://www.mirkosertic.de/blog/2013/04/domain-driven-design-example/ that describes implementing DDD Question 1: In Djnago we start a new app with python manage.py startapp XYZ. Each such app in our project e.g. Authentication, Cart etc. represents a subdomain with bounded context? And the entire project our main domain? Question 2: There seem to be main 4 layers: Domain, Application, Infrastructure and Client. Client layer could be completely isolated like Angular app. Does view.pyin our apps represent application layer as it is responsible for taking commands from client layer and invoking appropriate functions? Does ORM and our choice of database represent Infrastructure layer? Models.py domain layer (however, I am not sure where to place serializers.py and perhaps role of service.py in this picture)? Question 3: There are two ways of writing views in DRF: More elaborate way: @api_view(['GET', 'POST']) def task_list(request): """ List all tasks, or create a … -
Django Group By Model Field
For this particular model and I want to run a query and group the response by category. class Catalog(models.Model): id = models.AutoField(primary_key=True) item = models.CharField(max_length=512) text = models.TextField() category = models.CharField(max_length=512) book = models.ForeignKey('Book', on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) I tried stuff on stackoverflow but that didn’t help me to achieve what I wanted to, can someone help point me in the right direction. Catalog.objects.values('category').annotate(category_name=Count('category')).filter(book=123) -
TyeError when connecting to MariaDB with django
TypeError when connecting to MariaDB from django using mysql.connector i have tried to install mysql client but there is an error building the wheel file on centos 7. Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7faffd2d7268> Traceback (most recent call last): File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception raise _exception[1] File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/core/management/__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/utils/autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/apps/registry.py", line 112, in populate app_config.import_models() File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/apps/config.py", line 198, in import_models self.models_module = import_module(models_module_name) File "/home/admin/django-apps/env/lib64/python3.6/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/db/models/base.py", line 114, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/db/models/base.py", line 315, in add_to_class value.contribute_to_class(cls, name) File "/home/admin/django-apps/env/lib/python3.6/site-packages/django/db/models/options.py", line 205, in contribute_to_class self.db_table = … -
Filter with OR in neomodel
Recently I start to useing neo4j and neomodel and now I need to filter 2 parameters with OR in neomodel. I searched in document and codes but couldn't find anything about it. In django model there is a Q object to handle OR in queries. How can handle OR query in neomodel? I have to get query params from http request and response to it. Neomodel handle AND but I have no idea for handling queries with OR. Is there any way to handle it with out using cypher mannualy? -
Not able to run a Django console after installing a new version of Python in digitalocean Ubuntu 16.04
After uploading to a droplet a Django project I realized that I was using new functionality like f' strings that aren't supported on the 3.5 I proceed to install Python 3.6.3 using this guide: https://www.rosehosting.com/blog/how-to-install-python-3-6-on-ubuntu-16-04/ It looks like the installation is successful. When I write "python3 -V" on the console it answers back Python 3.6.3. When typing "pip freeze" it appears Django==2.0.4 . The problem comes when typing "python3 manage.py makemigrations" I got this error: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
Serializer remove parent field django
{ "episode": { "id": 6, "channel_id": 2, "channel": { "id": 2, "tags": [ "new" ] }, { "episode": { "id": 7, "channel_id": 3, "channel": { "id": 2, "tags": [ "new" ] } }, Hey I am new to Django. I am wondering how to remove episode parent written in the serializer response and directly go into the id, channel. Episode is not useful for me here. I have a model that sets the priority of these episodes. Have excluded the priority and id field but don't know how to remove episode parent. -
how to implement multiple level of admin in django?
I need a superadmin_A for the whole project and that superadmin_A can create superadmin_A and admin_A for the project. Superadmin_A can create a company Q and can create superadmin_B for the company Q. Superadmin_B can create admin_B and superadmin_B level for the company Q Now admin_B and Super Admin_B can login only for the company assigned to him and can create/edit Articles, Member etc of the company. I am doing this in django 2. Superadmin_A - can cerate admin_A and superadmin_A for the site Admin_A - can create only company Superadmin_A - can create a company Q superadmin_B for company Q Superadmin_B - can create Admin_B and other company details -eg Articles, Members etc. Admin_B - can create deatils of comapny Q eg. Article, Member etc. Levels of admin - A - admin for site/project B - admin for a comapny Hierarchy Superadmin_A Admin_A SuperAdmin_B admin_B Can anyone please guide me on how I go about implementing this. Any help would be greatly appreciated. Thanks in advance. -
Using a Raw Queryset inside a Custom Model Queryset
I want to use a raw queryset inside a custom model queryset. The issues is that I need to use/declare the queryset based model, before the model class is declared. Can I declare a substitute of the model, that will be interpreted at the execution time ? So, the code is like this: class EntityModelQuerySet(models.query.QuerySet): def search_by_item(self, id__list): qs = Entity.objects.raw( ............. class Entity -
Link static file in home.html
I have a problem running a js file from home.html For example, let's suppose I have the following files: home.html {% load static %} <head> <script src="{% static 'js/assets/jquery.js' %}"></script> <script src="{% static 'js/chatterbot/chatbot.js' %}"></script> </head> chatbot.js $(function () { console.log('running'); } I am supposed to get the running message in the console when loading the home page but I don't. settings.py has the static urls defined BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' # Extra places for collectstatic to find static files. STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) urls.py urlpatterns = [ url(r'^admin/', admin.site.urls), url('accounts/', include('allauth.urls')), url(r'^$', Home.as_view(), name='home'), url(r'^api/chatterbot/', include(chatterbot_urls, namespace='chatterbot')), ] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) and the project structure Any idea what I might be doing wrong? -
How to change text
In my Django admin I have a TabularInLine class. How can I change the text circled by red color on picture? -
Django Rest Framework, database queries optimization
I'm new at using an ORM to perform my databases calls and I have troubles finding a good way to optimize my code/queries. I have Productss that can be in ProductGroups. Products can have 0 to n Prices. A Price is defined by its ActorLocation and its value. I would like to display the min and max of the Prices of all the Products that are in a ProductGroup. The code I wrote is working but is extremely slow due to the amount of db access. Any help to go to the good direction will be appreciated :) Models : class ProductGroup(OwnedClass): name = models.CharField(max_length=200, blank=False) class Product(models.Model): name = models.CharField(max_length=200, blank=True) internal_code = models.CharField(max_length=200, blank=True) description = models.CharField(max_length=1000, blank=True) product_group = models.ForeignKey( ProductGroup, blank=True, null=True, on_delete=models.CASCADE) class Price(models.Model): price_without_taxes = models.FloatField(default=None, null=True) location = models.ForeignKey( ActorLocation, blank=True, null=True, on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) class ActorLocation(models.Model): name = models.CharField(max_length=200, blank=False, null=False) Here is my function to generate the context I send to my ProductGroupSerializer : def get_context(product_groups): locations = company.actor_locations.all() for product_group in product_groups: price_list = [] products = product_group.product_set.all() for product in products: for location in locations: price = Price.objects.filter(product=product, location=location).last() if price: price_list.append(price.price_without_taxes) if price_list: context = {'lowest_product_price': … -
LINKS NOT VISIBLE IN SIDE NAV AFTER CLICKING ON ONE LINK
The side nav data is pulled from the db, on clicking on one link in side nav it loads the data on the same page but all the rest of the links are then not visible. url changes to :127.0.0.1:8000/main/1 where 1 is the id. and side nav becomes empty. **views.py** def index(request): all_client = Clients.objects.all() return render(request,'update/index.html',{'all_client' : all_client}) def detail(request,album_id): client = get_object_or_404(Clients,pk=album_id) return render(request,'update/detail.html',{'client' : client}) **urls.py** urlpatterns = [ # /music/ url(r'^$',views.index, name='index'), # /music/71/ url(r'^(?P<album_id>[0-9]+)/$',views.detail, name='detail'), ] **index.html** <div id="sidebar-wrapper"> <h2 style="color: #e1dcd9; font-family:'Lobster';font-size:20px" align="center" >Clients</h2> <ul class="sidebar-nav"> {% for client in all_client %} <li><a href="{% url 'update:detail' client.id %}"> {{client.client_name}}</a></li> {% endfor %} </ul> </div> -
python3 comment went wrong in url file
I am new in python3, and I used django to create a web. However, when I wrote url file, I used '''comment here''' as comment instead of #. And it went wrong, with this error. path('photo/',views.indexPhoto, name="indexPhoto"), ^ SyntaxError: invalid syntax Here is the code with comment from django.urls import path from . import views urlpatterns = [ path('',views.index, name="index"), '''comment here''' path('photo/',views.indexPhoto, name="indexPhoto"), path('photo/add/',views.addPhoto, name="addPhoto"), path('photo/insert',views.insertPhoto, name="insertPhoto"), ] When I delete the '''comment here''', then the project works, and I can view the web page. I am not sure why it happens, anyone help? -
ValueError: The field admin.LogEntry.user was declared with a lazy reference
I'm developing a new django project and stuck with migration. I would like to make a UserModel, and in order to do that, I did two things so far. 1. I made AuthUser model and set a Meta class in the class below. In models.py class AuthUser(AbstractUser): user_type_id = models.PositiveIntegerField(choices=UserTypes.choices()) user_id = models.PositiveIntegerField() class Meta(AbstractUser.Meta): swappable = 'AUTH_USER_MODEL' @property def user_type(self): return UserTypes(self.user_type_id) def original_orm(self): if self.user_type.value == UserTypes.raijosha.value: return RaijoshaUsers.objects.filter(id=self.user_id).first() elif self.user_type.value == UserTypes.shuttennsha.value: return Users.objects.filter(id=self.user_id).first() In settings.py, I set AUTH_USER_MODEL. AUTH_USER_MODEL = 'recommend.AuthUser' Here's the error codes. Operations to perform: Apply all migrations: admin, auth, contenttypes, recommend, recommend_raijousha, sessions Traceback (most recent call last): File "manage.py", line 25, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.6/dist-packages/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.6/dist-packages/django/core/management/commands/migrate.py", line 164, in handle pre_migrate_apps = pre_migrate_state.apps File "/usr/local/lib/python3.6/dist-packages/django/utils/functional.py", line 35, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/state.py", line 218, in apps return StateApps(self.real_apps, self.models) File "/usr/local/lib/python3.6/dist-packages/django/db/migrations/state.py", line 295, in __init__ raise ValueError("\n".join(error.msg for error in errors)) ValueError: The field admin.LogEntry.user was declared with a lazy reference to 'recommend.authuser', but app … -
django queryset select_related . values() rename key
Using python3.4 django 2.0.2 models.py class Userinfo(models.Model): useruid = models.BigAutoField(db_column='UserUID', primary_key=True) useremail = models.CharField( db_column='UserEmail', unique=True, max_length=100) userpassword = models.CharField(db_column='UserPassword', max_length=128) passwordsalt = models.CharField(db_column='PasswordSalt', max_length=128) userstatus = models.IntegerField(db_column='UserStatus', default=0) username = models.CharField( db_column='UserName', max_length=100, default=0) class Meta: managed = False db_table = 'userinfo' class Postinfo(models.model): postuid = models.BigAutoField(db_column='PostUID', primary_key=True) content = content = models.TextField(db_column='Content') useruid = models.ForeignKey( Userinfo, db_column='UserUID', on_delete=models.CASCADE) class Meta: managed = False db_table = 'worryreply' queryset postquery = models.Postinfo.objects.all().select_related("useruid").order_by( '-postuid') postquery is <QuerySet [{'content': 'test','postuid': 1, 'useruid_id': 1},OtherPosts...> and userinfoquery = postquery.values("useruid_id__username","useruid_id__userstatus","useruid_id") userinfoquery is <QuerySet [{'useruid_id__username': 'firstuser','useruid_id__userstatus': 0, 'useruid_id': 1},OtherUsers...> i want useruid_id__username - > username useruid_id__userstatus -> userstatus useruid_id - > useruid i tried this userinfoquery = postquery.values( useruid="useruid_id", username="useruid_id__username", userstatus="useruid_id__userstatus") this code raise exception QuerySet.annotate() received non-expression(s): useruid_id, useruid_id__uesrname, useruid_id__userstatus. how can remove useruid_id__ -
Trying to enrol Student into Class - django
So I am trying to register student to a class. When User is logged in they see enrollment page which is populated with classes (from MusicClass model) User clicks on the submit button which enrols the student into class. In StudentProfile Model I have foreign key to MusicClass i.e student_class = models.ForeignKey(to=MusicClass, related_name="student_class", null=True, blank=True) ISSUE: Trying to pass the class_name when a submit button is clicked to the view.studentEnrol. Not sure how to submit it to the StudentProfile models student_class field enrol.html {% for class in classes %} <tr> <td>{{ class.class_name }}</td> <td>{{ class.instrument_taught }}</td> <td>{{ class.class_level }}</td> <td>{{ class.class_time }}</td> <td>{{ class.teacher }}</td> <td>{{ class.class_room }}</td> <td><form method="post"> {% csrf_token %} <input type="hidden" name="enrolBtn" value="{{ class.class_name }}"> <input type="submit" name="enrolBtn" value="Enrol"> </form></td> </tr> {% endfor %} Models.py class StudentProfile(models.Model): class Meta: verbose_name="Student Profile" verbose_name_plural="Student Profiles" def __str__(self): return self.first_name + " " + self.last_name user = models.OneToOneField('Accounts', related_name='student_profile') first_name = models.CharField(max_length=250, blank=True) last_name = models.CharField(max_length=250, blank=True) # additional fields for students AMEB_Ratings = models.PositiveIntegerField(default=0) birth_date = models.DateField(null=True, blank=True) student_class = models.ForeignKey(to=MusicClass, related_name="student_class", null=True, blank=True) is_student = models.BooleanField('student status', default=False) Views.py enrolls student def studentEnrol(request): if request.method == "POST": ## TRYING TO REGISTER STUDENT TO CLASS????? student = StudentProfile.objects.get(username=username, … -
Null byte injection in Python
Is there no need to consider the null byte injection vulnerability when writing code in Python? I know how to write (and it means how to avoid) vulnerable code for null byte injection in some languages: http://projects.webappsec.org/w/page/13246949/Null%20Byte%20Injection but I don't know in Python. Does anyone know how to write vulnerable code? -
Nginx doesn't serve static files
I've just deployed my django website on an Ubunto server. But it doesn't load any static file. settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"),] STATIC_ROOT = 'staticfiles' nginx/sites-available configuration: server { server_name 138.197.172.33; access_log off; location /staticfiles/ { root staticfiles; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } Errors: ... [14/May/2018 05:28:28] "GET /static/vendors/underscore/underscore.js HTTP/1.1" 404 113 [2018-05-14 05:28:29,252] base: WARNING - Not Found: /static/vendors/bootstrap-notify-simple-wrapper/bootstrap-notify- simple-wrapper.min.js [14/May/2018 05:28:29] "GET /static/vendors/bootstrap-notify-simple- wrapper/bootstrap-notify-simple-wrapper.min.js HTTP/1.1" 404 159 [2018-05-14 05:28:29,690] base: WARNING - Not Found: /static/js/custom.js [14/May/2018 05:28:29] "GET /static/js/custom.js HTTP/1.1" 404 93 [2018-05-14 05:28:30,236] base: WARNING - Not Found: /static/js/converter.js [14/May/2018 05:28:30] "GET /static/js/converter.js HTTP/1.1" 404 96 ... -
Django execute a custom function from Admin
I am new to Django and have gone through the first Django App tutorial.I understand the separate bits but am not able to form a complete solution. My requirement is to add a custom button to a Model's Change List Page in Admin, redirect it to a confirmation page, execute a function on confirmation and then redirect to the change list page with execution status. I have added the custom button but am lost after that. Can anybody please guide me through the steps required? -
'AnonymousUser' object has no attribute '_meta'
views.py code from django.shortcuts import render,redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from tutorial import views from accounts.form import Registrationform,EditProfileForm from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm from django.contrib.auth.models import User from django.contrib.auth import update_session_auth_hash # Create your views here. def home(request): numbers=[1,2,3,4,5] name="jay" args={'myName':name} return render(request,'accounts/home.html',args) def register(request): if request.method == "POST": form = Registrationform(request.POST) if form.is_valid(): form.save() return redirect('/account') else: return HttpResponse('please fill all the fields and make sure new password must be match') else: form = Registrationform() args={'form' : form} return render(request,'accounts/reg_form.html',args) def view_profile(request): args = {'user' : request.user} return render(request,'accounts/profile.html',args) def edit_profile(request): if request.method=="POST": form = EditProfileForm(request.POST,instance=request.user) if form.is_valid(): form.save() return redirect('/account/profile') else: form = EditProfileForm(instance=request.user) args = {'form' : form} return render(request,'accounts/edit_profile.html',args) def change_password(request): if request.method == "POST": form = PasswordChangeForm(data=request.POST,user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect('/account/profile') else: return HttpResponse("password doest not match,go back and try again") else: form = PasswordChangeForm(user=request.user) args = {'form' : form} return render(request,'accounts/change_password.html',args) and form.py is from django import forms from django.contrib.auth.forms import UserCreationForm,UserChangeForm from django.contrib.auth.models import User #from django.forms import RegistrationForm,EditProfileForm class Registrationform(UserCreationForm): email = forms.EmailField(required=True) class Meta: model = User fields = ( 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ) def save(self,commit=True): user=super(Registrationform,self).save(commit=False) user.first_name= self.cleaned_data['first_name'] user.last_name=self.cleaned_data['last_name'] user.email=self.cleaned_data['email'] if … -
Hosting a Django Website
I've recently Been working on a Bug Tracking Software and my client wants the website up and running as soon as possible. I'm using the built in Sqlite for the database. What i cant figure out is, how do i host it for as cheap as possible and can i use Sqlite as a database for production. Its a really small website running on the admin part of django and based on what the client told me, there will be very minimal number of users. I've read that if the database is going to be huge, i should go for mySql or MongoDB or any of the other database systems, but as i mentioned earlier, there aren't got to be a lot of users. Is Aws a good option? If it is, how much would it cost me to get it up and running. Need help As soon as possible! Thank you in advance! -
Django Models and normalization
Can you please explain me the best practice of DB normalization via Django Models? Am I right considering that Django works with DB using simple SELECT, exclude JOIN or so and then work with it using Python? The problem I met is that it's hard to make a good Admin Panel using 3NF+ normalized DB and even simple methods in Models become complex. So the question is - do we need to get a high level of normalization using Django Models or it is redundantly? -
Changing Django development Database from the default SQLite to PostgreSQL
What are the steps I need to take to migrate from the default SQLite database to Postgres database? I'm doing this to get my local development environment as close to my live server (which uses postrgres). Or is there a reason why local development uses SQLite? Is it not recommended to use Postgres for local development? -
Django Python uploading a file to a specific folder
I am working on a Django app and I want the users to be able to upload a csv file to a folder in the server. Appreciate if you could point me to the right direction.