Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access django development server onVM virtual box from actual computer?
I have my actual laptop which has virtual box installed. I am running ubuntu 18.04 as a virtual machine and I installed django on the virtual machine and am testing my app so I did python manage.py runserver and I can access the app by visiting 127.0.0.1:8000 from my VM, however, If I go to 127.0.0.1:8000 from the actual computer (not the VM), it says 'chrome could not connect to 127.0.0.1:8000'. If I did manage.py runserver 192.0.2.15:8000 on vm where 192.0.2.15 is ip address of vm, it gives error :that ip address can't be assigned to. Any idea how to fix it? Please help me. -
use if condition inside html tag using jinja tag
i made a header for my site project and it has some sections... i want to change the section color name on header using jinja but i can't the template already rendered without error but section name doesn't change and in pycharm this message shows up :Tag start is not closed <ul class='menu'> <li {% if section == "dashboard" %}class="selected"{% endif %}> <a href="{% url 'dashboard' %}">My dashboard</a> </li> <li {% if section == "images" %}class="selected"{% endif %}> <a href="#">Images</a> </li> <li {% if section == "people" %}class="selected"{% endif %}> <a href="#">People</a> </li> </ul> -
Using Two Databases in Django (one read-only)
I am using two databases, one to read data from and then write data to another. Below is my Router class and my changes to settings but am very new to this concept, can someone with more experience in this area confirm that it should work or help make edits? The application is named "myapp", the read-only database I have named "readonly_db" and the database I want to write to is the "default" database. class MyappRouter: def db_for_read(self, model, **hints): if model._meta.app_label == 'myapp': return 'readonly_db' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'myapp' return 'default' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == obj2._meta.app_label: return True else: return False return None def allow_migrate(self, db, **hints): if db == 'default': return True elif db == 'readonly_db': return False return None DATABASE_ROUTERS = ['<path to>.myapprouter.py'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'myapp' , 'USER': 'USER', 'PASSWORD': 'PASSWORD', 'HOST': 'LOCALHOST', 'PORT': '5432' } 'readonly_db': { 'ENGINE': 'django_postgres_readonly' 'NAME': 'READONLY' 'USER': 'USER' 'PASSWORD': 'PASSWORD' 'HOST': 'LOCALHOST' 'PORT': '5432' } -
How to transfer one mongodb database from one computer to another
I am using django 2.2 and mongodb as database for backend. i have inserted all data in my application.I am also using Robo3T for seeing collections of mongodb database.My database name is CIS_FYP_db. In my computer everything is going perfect but i want to transfer that project into another computer while i am transferring the project which also contains data\db file with many collections.wt files but when i am running that project in other computer it is showing me that database is blank.No data were present there and mongodb is making new database with the same name CIS_FYP_db with no collections.Please help me to solve this problem that how can i transfer my mongodb database into other computer so i can use it into my application which is already made for that database.Thanks in advance setting.py DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': 'CIS_FYP_db', } } -
Why django doesnt upload files which contain specific characters to s3?
I have a Django App, which allows users to upload csv files on an AWS S3 Bucket. Lets assume that I want to upload a file called myfile.csv to an s3 bucket, then I am able to upload it on my bucket with no problems. Despite that, if I rename the exact same file to myfile(1).csv, then for some reason the file does not get uploaded to the bucket anymore. Does anyone have an idea as to why this happens? Here is my code: forms.py class CsvForm(forms.ModelForm): csv_file = forms.FileField(widget=forms.FileInput( attrs= { 'class': 'form-group', } )) class Meta: model = CSVUpload fields = ('csv_file', ) def save(self): csvfile = super(CsvForm, self).save() return csvfile def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file'] if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith('.csv'): return uploaded_csv_file else: raise forms.ValidationError("File must be csv") else: return uploaded_csv_file models.py from converter.storage_backends import CsvStorage from django.db import models from django.utils import timezone import time class CSVUpload(models.Model): csv_file = models.FileField(storage=CsvStorage()) def __str__(self): return self.csv_file storage_backends.py from storages.backends.s3boto3 import S3Boto3Storage from django.conf import settings import boto3 import time class CsvStorage(S3Boto3Storage): location = settings.AWS_CSV_LOCATION file_overwrite = False views.py def csvtojson(request): if request.method == 'POST': form = CsvForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(about) else: form = … -
lookup was already seen with a different queryset
I sort the list of credits by ajax request. The first time everything goes well, I get sorted list of credits and update the cache. But when I try to sort again, I get an error. 'creditpayments' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. If the cache is not to update, then there will be no error. But I need to update it... models class Credit(models.Model): pass class CreditPayment(models.Model): credit = models.ForeignKey(Credit, on_delete=models.CASCADE, related_name='creditpayments') rate = models.DecimalField(_('rate'), max_digits=7, decimal_places=2) views class SortedCreditsList(ListView): def get(self, *args, **kwargs): if self.request.is_ajax(): credits = cache.get('credits') prefetch = Prefetch('creditpayments', CreditPayment.objects.all()) credits = credits.prefetch_related(prefetch).annotate(min_rate=Min('creditpayments__rate')) credits = credits.order_by('min_rate') cache.set('credits', credits) credits = credits.filter(best=False, hot=False) template_ajax = render_to_string( template_name='credits/includes/credits_filter_result.html', context={ 'credits': credits, }) return JsonResponse({'success': True, 'template': template_ajax}) Traceback ValueError at /sorted_kredit/ 'creditpayments' lookup was already seen with a different queryset. You may need to adjust the ordering of your lookups. Traceback: File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 149. response = self.process_exception_by_middleware(e, request) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response 147. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/views/generic/base.py" in view 68. return self.dispatch(request, *args, **kwargs) File "/home/m0nte-cr1st0/.virtualenvs/finbee/local/lib/python2.7/site-packages/django/views/generic/base.py" in dispatch 88. return handler(request, *args, **kwargs) File "/home/m0nte-cr1st0/work_projects/startup/finbee/credits/views.py" in get 555. cache.set('credits', credits) File … -
Raspberry Pi django server ImportError cannot import name 'etree'
I'm trying to setup Django project on Raspberry Pi to serve a framework on a local network. I have succesfuly installed Django, it is starting with apache2 and all computers on network can see default Django "It worked" page. After I load my app, I'm getting the web page with error: ImportError cannot import name 'etree' at location /home/pi/Django/Ponude/lib/python3.6/site-packages/docx/opc/oxml.py in <module>, line 12 I have installed with pip all necessery modules, here is all from pip freeze: Django==2.2.3 lxml==3.6.0 Pillow==6.1.0 python-docx==0.8.10 pytz==2019.1 sqlparse==0.3.0 When I try to import modules manually in shell, there is no problem importing, only when starting django. I have tried uninstalling and installing all modules, but no help. I also searched Stack Overflow, but found nothing similar or nothing that helped. Can somebody please help me? Is it maybe about permissions or apache2 config? I'n case it helps, here is my apache2 config: <VirtualHost *:80> ServerName www.example.com ServerAdmin webmaster@localhost Alias /static /home/pi/Django/Ponude/Ponude/static <Directory /home/pi/Django/Ponude/Ponude/static> Require all granted </Directory> <Directory /home/pi/Django/Ponude/Ponude/Ponude> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess Ponude python-path=/home/pi/Django/Ponude/Ponude:/home/pi/Django/Ponude/lib/python3.6/site-packages WSGIProcessGroup Ponude WSGIScriptAlias / /home/pi/Django/Ponude/Ponude/Ponude/wsgi.py </VirtualHost> Thank you -
AttributeError: 'function' object has no attribute 'as_view'
I've got this error but I don't understand with it occurs. I've another Django project and it works fine (url was with id, now it is pk, might have an error here?). error: path('/delete/', views.item_deleteView.as_view(), name='delete_item'), AttributeError: 'function' object has no attribute 'as_view' views.py: from django.views.generic import DeleteView Delete a product tree item class item_deleteView(DeleteView): template_name = 'product_tree/pt_delete_item.html' def get_object(self): pk_ = self.kwargs.get("pk") return get_object_or_404(ProductItem, pk=pk_) def get_success_url(self): return reverse('db_books:db_list') urls.py: from . import views app_name = 'product_tree' urlpatterns = [ ... path('/delete/', views.item_deleteView.as_view(), name='delete_item'), ... ] -
Django 2.2.3 How list all pages of project and associated its in choicefield models
I have faced in difficulty is that i have a model now in my models i have choicefield. I want that user create slider and associate this slider to existed page url. That's my utils.py (Url of source code) contains: from django.conf import settings from django.urls import get_resolver, URLPattern, URLResolver urlconf = __import__(settings.ROOT_URLCONF, {}, {}, ['']) def list_urls(lis, acc=None): if acc is None: acc = [] if not lis: return l = lis[0] if isinstance(l, URLPattern): yield acc + [str(l.pattern)] elif isinstance(l, URLResolver): yield from list_urls(l.url_patterns, acc + [str(l.pattern)]) yield from list_urls(lis[1:], acc) def get_list_urls(): RESOLVERS_LIST = list() i = 0 for u in list_urls(urlconf.urlpatterns): value = ''.join(u), str(''.join(u)).upper() RESOLVERS_LIST.append(value) return RESOLVERS_LIST My models: @python_2_unicode_compatible class Slider(models.Model): LIST_PAGES_URLS = get_list_urls() master_start = models.IntegerField(default=1000, blank=True) master_end = models.IntegerField(default=5000, blank=False, null=True) view_to_add = models.CharField(_("Assoc page url ?"), max_length=100, choices=LIST_PAGES_URLS) def __str__(self): return self.get_view_to_add_display() class Meta: verbose_name = _("Slider") My main problem is that when i try to import my model class in admin.py. *Server return me ImportError: cannot import name 'Slider'* I use Python 3.7 and Django 2.2.3... Please help ! -
how to prevent input type file from accepting some inputs on change function
I'm working on a project and I need the user to upload only pdf files. I'm trying to do this in the front-end so whenever the input detects a file type that is not a pdf should reject it. Everything seems correct. However, when I hover over the input it shows me that the wrong file is uploaded. So what should I do? function changeName(elem) { $("input[type='file']"). elem.on("change", function() { var fileName = elem.val().split("\\").pop(); var fileExtension = elem.val().split(".").pop(); if (fileExtension === "pdf") { elem.siblings(".Syllabus").text(fileName); } else { elem.siblings(".Syllabus").val(''); elem.siblings(".Syllabus").text('...'); alert('Only PDF files are accepted'); } }); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label class="Syllabus fileReset">...</label> <input type="file" accept="application/pdf" name="file1" onClick="changeName($(this));" required class="upload-button removable" /> -
Looking for a model example in Django
i just finished an online Django course and i am working on my first project. I want to make a sub model under AbstractUser model which the user could edit manually. I don’t know where to start to look for it (I tried to do that in github and didn't found one), i would be happy if somebody could share some example or video or something like that sub model. When i mean edit manually is that he could choose fields and fields type and name them , so i as the web admin could manipulate them. Thanks! -
2 Slug in url path
I want the url like this example.com/lol/tournament/tournament-slug/match/match-slug i did it However, is it the right approach to use it like this? Is there a better way? code: leagueoflegendsgame=game[0] views.py def lolmatch_detail(request, tournamentslug, lolslug): lolmatch=get_object_or_404(LeagueOfLegendsGame, lol_slug=lolslug) game=LeagueOfLegendsGame.objects.filter(lol_slug=lolslug) tournamentslug = get_object_or_404(Tournament, tournament_slug=tournamentslug, leagueoflegendsgame=game[0]) urls.py path('lol/tournament/<str:tournamentslug>/match/<str:lolslug>', lolmatch_detail, name='lol_match_detail'), models.py class LeagueOfLegendsGame(Game): name=models.CharField(max_length=255,blank=True,null=True) lol_slug=models.SlugField(unique=True,max_length=255) tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, null=True, blank=True) match=models.ManyToManyField(Match)... class Tournament(models.Model): name=models.CharField(max_length=255) tournament_slug=models.SlugField(unique=True,max_length=255) -
How to count queryset from ManyToManyField in django?
In models: class Match(models.Model): user = models.ManyToManyField(User, blank=True) hot_league = models.ManyToManyField('HotLeague', blank=True) class HotLeague(models.Model): user = models.ManyToManyField(User, blank=True) price_pool = models.IntegerField() winner = models.IntegerField() In views: match = Match.objects.filter(user=request.user) hot_league = match.hot_league.filter(user=request.user).count() Here in views count() is not working. How can I count the hot_league which situated in match ?? -
Django Mysql: MigrationSchemaMissing Error Windows
SO has a lot of questions on this error, but I am unabble to get rid of it. I am trying to connect my Django app to a MySQL database, but keep getting this error: raise MigrationSchemaMissing("Unable to create the django_migrations table (%s)" % exc) django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table ((1064, "pa rse sql 'CREATE TABLE `django_migrations` (`id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `app` varchar(255) NOT NULL, `name` varchar(255) NOT NULL, `applied` datetime(6) NOT NULL)' error: syntax error at position 8 near create")) I have initialised a new project and just changed settings.py to this: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'enigma', 'HOST': '10.5.245.137', 'PORT': '3306', # 'USER': '', # 'PASSWORD': '', 'OPTIONS': { # 'sql_mode': 'traditional', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'", }, } } I have removed Options, but it does not work. I have used different Django versions and mySqlClient versions, but still can't get it to work. My current Django and mysqlclient are the latest versions, i.e. mysqlclient-1.4.2.post1 and django-2.2.3. -
How Can i Create a UI using nested database table fields in Python Using REST API?
I want to Create a tree structure for categories and subcategories in UI. Data should be retrieve from database entries. I have to Use REST API to get the data from backend & authentication for REST API as well UI 1. Create a tree structure for categories and subcategories view. 2. Subcategories can be up to N level Database: 1. Create database and required tables for managing tree structure 2.Use test entries to display on UI Backend: 1. Write Python code to fetch and display data 2. Use Authenticated REST API as a middleware -
Is there a way of accessing other table using foreign key
I am making a job-portal and I needed to access user field of Vacancy model using VacancyApply model. model.py class Vacancy(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) jobcategory=models.IntegerField(choices=( (1,'IT/Telecomunication'), (2,'Engineering'), (3,'Medical'), )) title=models.CharField(max_length=50) date_added=models.DateTimeField(auto_now_add=True) updated_on=models.DateTimeField(auto_now=True) deadline=models.DateField(default=datetime.now() + timedelta(days=15)) description=RichTextField() def __str__(self): return(self.title) class VacancyApply(models.Model): user=models.ForeignKey(User,on_delete=models.CASCADE) vacancy=models.ForeignKey(Vacancy,on_delete=models.CASCADE) applieddate=models.DateField(auto_now=True) status=models.IntegerField(choices=status_choices,default=1) -
Direct assignment to the forward side of a many-to-many set is prohibited
I'm trying to write a script that will fill database from json file. It looks like this: class Command(BaseCommand): def handle(self, *args, **options): categories = load_from_json('categories') ProductCategory.objects.all().delete() for category in categories: new_category = ProductCategory(**category) new_category.save() restaurants = load_from_json('restaurants') Restaurant.objects.all().delete() for restaurant in restaurants: category_name = restaurant['category'] _category = ProductCategory.objects.get(name=category_name) restaurant['category'] = _category new_restaurant = Restaurant(**restaurant) new_restaurant.save() When i run it, django throws an error: Direct assignment to the forward side of a many-to-many set is prohibited. Use category.set() instead. My models looks like this: class ProductCategory(models.Model): name = models.CharField(verbose_name='наименование категории', max_length=64, unique=True) image = models.ImageField(upload_to='category_images', blank=True) description = models.TextField(verbose_name='описание категории', blank=True) def __str__(self): return self.name class Restaurant(models.Model): name = models.CharField(verbose_name='наименование ресторана', max_length=64, unique=True) description = models.TextField(verbose_name='описание категории', blank=True) image = models.ImageField(upload_to='restaurant_images', blank=True) category = models.ManyToManyField(ProductCategory) def __str__(self): return self.name Looks like many people have encountered with this problem, but i struggle with finding a solution to this. -
save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'
I'm trying to create a logic in Django to check if all the TabularInline items are saved before saving the model itself. here is the code am using: def save_formset(self, request, form, formset, change): instances = formset.save(commit=False) for instance in instances: item_count_in_origin = instance.prc_item.quantity print(item_count_in_origin) if instance.quantity > item_count_in_origin: messages.error(request, 'Quantity is higher than origin branch.') return else: for item in instances: if item.id is not None: item.close() else: formset.save() def save_model(self, request, obj, form, change): if obj.transfer_items.all().count() != 0: user = request.user if self.save_formset: if not change: obj.solicitor = user obj.date_solicited = datetime.now() created_status = Status.objects.get(name=StatusEnum.CREATED) obj.status = created_status return super(TransferenceAdmin, self).save_model(request, obj, form, change) else: messages.error(request, 'Quantity is higher than origin branch.') return when the condition if instance.quantity > item_count_in_origin: it works right and bring back an error, but when it is false and we go the part of for item in instances: if item.id is not None: item.close() else: formset.save() it fails with the error save() prohibited to prevent data loss due to unsaved related object 'xxxxxxxx'. -
Django Channels 2 implementing Multiplexer/Demultiplexer like Channels 1
Unless I am missing something it seems there is not out-of-the-box solution for multiplexing a single channel in Channels 2 like we had with Channels 1. My understanding is I effectively have 3 consumers in Channels 1 served by a single multiplexer/channel there is nothing analogous to this in Channels 2. First option is that I'd rather not touch the client code and mimic a multiplexer unless this seems wrong-headed. Other option (I think from my initial readings in Channels 2) is I'd just have 3 endpoints as websocket URL routes and change the client code to use multiple websockets using those routes. Are those both viable options? Which makes the most sense? -
How to apply __str__ method to subclass of abstract superclass class
I have 3 models, one of which is an Abstract superclass and two of which are subclasses if that superclass. I am trying to implement a simple str method on the model, but no matter the implementation it throws me this error: TypeError: __str__ returned non-string (type NoneType) Here are my models: class DemandBase(models.Model): demand = models.FloatField(blank=True, null=True) building = models.ForeignKey(Building, on_delete=models.CASCADE) class Meta: abstract = True class DemandHeat(DemandBase): def __str__(self): return str(self.id) class DemandCool(DemandBase): def __str__(self): return str(self.id) Ok so I tried casting it as in the example above, but I tried also the following without success: return "This is an example {}".format(self.demand) and this return f"This is an example {self.demand}" and this: return "this is a string" All these alternatives work on normal models, but here it doesn't, so I assume it has to do with the inheritance or the abstraction of the class..... Any help or hints are very much appreciated. Thanks in advance! -
How can I use 3D in Django 2.0
I want to use 3D in my Django project. For object presentations, animations and web design. I heard about WebGL, Blender4web, WebGL2 and many other. But which one more good if I want to use it in django. And I don't want to learn js more hard, c++ and other for that. If you need to know, I use blender and unreal engine 4 for create 3d, but i think it's not important... -
Dynamically counting objects in an aggregate Django
I have a relatively complex query to handle and I'm bashing my head against it. Allow me to explain the scenario. I want to return a queryset annotated with the number of cases a user has completed where they are certified. Imagine my user has three roles. a_delegate, b_certified and c_accredited. a_delegate tells us that the user is in training for course a, we don't want to count any completed cases for course a. b_certified tells us that the user has completed training for course b and is certified. We need to count these completed cases c_accredited tells us that the user has advanced past their training for course b. We need to count these completed cases I am using the built-in User model that Django supplies, nothing special there. Roles are just the name of the built-in Group model that Django supplies again. Now, I know this is likely to get "just write raw sql" comments, and that's fine. I'm not dismissing the possibility of using raw sql here. I just want to know if there is a way of doing this with the ORM first. I have this function, which maps input to relevant roles. def convert_filter_str(str: str) … -
How to properly fork an app in Django Oscar 2.0
I am attempting to make a minor modification to the mixin.py file in the checkout app (specifically, attempting to comment out the line within OrderPlacementMixin that automatically sends an email after a successful order as described in this stackoverflow post). However, I can't seem to get oscar to recognize my fork. I have already followed the steps as enumerated here, with no luck. Here are the steps I've done 1) Create a custom_apps directory in the project root, and an empty __init__.py file inside it 2) Run manage.py oscar_fork_app checkout custom_apps - this command generates the checkout directory as well as multiple files. Here's the terminal output. I've also attached a photo of the directory structure (venv) work@pc:~/MyProjects/oscar2_project/frobshop$ ./manage.py oscar_fork_app checkout custom_apps Creating package custom_apps/checkout Creating app config Creating models.py Replace the entry 'oscar.apps.checkout.apps.CheckoutConfig' with 'custom_apps.checkout.apps.CheckoutConfig' in INSTALLED_APPS 3) I commented out 'oscar.apps.checkout' in my INSTALLED_APPS in my settings.py, and I inserted 'custom_apps.checkout' at the end of the INSTALLED_APPS` list 4) I run python manage.py runserver, to which I get the exception oscar.core.exceptions.AppNotFoundError: Couldn't find an Oscar app to import checkout.calculators from. At this point, I haven't even tried to modify any code yet, however, my fork already refuses to … -
How to update a field of another model in a pre_save function?
I have a model called SPL, which gets new objects in a fixed interval. Everytime it gets a new object, the function "process_data" gets called by the pre_save signal. In this function, I am trying to update the field "leq_start" in another model "Index" based on the field "time" of the SPL model object. The Code seems to work because I don't get any error, but the field does not get updated. What's wrong? I have some other functions based on a post_save signal where it works fine... I've already tried the update alternative, but that didn't work either. Index.objects.filter(device_id=id_).update(leq_start=instance.time) def process_data(sender, instance, **kwargs): id_ = instance.device_id num = instance.number # new code prevNum = Index.objects.get(device_id=id_).previous_nbr dP = num - prevNum if dP > 0: if prevNum == 0: dT = 60 b = Index.objects.get(device_id=id_) b.leq_start = instance.time b.save() instance.leq_60=instance.leq return else: ... pre_save.connect(process_data, sender=SPL) -
How to realize the hard delete function in Python Django?
I have a User realization class, in there I want to have two type delete function: class User(AbstractUser): nickname = models.CharField(max_length=16, blank=True, null=True) # nickname real_name = models.CharField(max_length=12, null=True, blank=True) phone = models.CharField(max_length=18) # telephone ... status = models.CharField(max_length=1, null=True, default=1) def soft_del(self): self.status = 4 return True def hard_delete_user(self): # what should I do there? return True you see, one is soft delete a user, the other is hard delete a user. I mean the soft delete, a user still in the database, but I will not query it by my code, the hard delete is delete it from the database table. How to realize the hard_delete_user function?