Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error after adding Django channels to installed_apps in settings file
I am just trying out django channels so I created a virtual environment and installed django, drf and channels. It threw error asking for visual c++ build tools which got resolved after installing it. Then I created a channels project and an app. Then just for testing I added a sample model as below and registered it with the admin. It compiled well and also I was able to see the model in the admin page. My Model Calss from django.db import models # Create your models here. class College(models.Model): name = models.CharField(max_length=50) address = models.CharField(max_length=150) objects = models.Manager() def __str__(self): return self.name My admin.py from django.contrib import admin from .models import College # Register your models here. admin.site.register(College) Now the Problem I added channels to the INSTALLED_APPS list in the settings.py file like below, INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'channelApp', 'channels', ] Now when I try to run the server using the runserver command I get the following error LookupError: No installed app with label 'admin'. I have been searching but failed to find any suitable answer. Kindly help me out. Thanks in advance. -
Assigning identifiable unique IDs to rows when importing data from XML
I'm designing a database in which I'll be importing a large amount of data from XML daily to create or update existing rows. Item data spans dozens of tables all related to the item_id in the main item table For every item in the XML file, I need to check if it already exists in the database and update or create if it's not there. Every XML belongs to a source_id and every item in the XML contains a unique alphanumeric ID up to 50 chars (but those IDs are not unique across all XMLs), so source_id:xml_item_id would be unique here What I need is a way of finding if the item already exists in the database. Ideally, I will search by pk and use the same pk to join other tables Attempt 1 I've tried encoding source_id:xml_item_id into a bigint for the pk as well as decode the bigint back to the original source_id:xml_item_id, but most of the times this is overflowing So this is not going to work Attempt 2 Use a UUID for the pk and source_id:xml_item_id as unique_id (string) for wich to search by, but join related tables to UUID While I don't see anything wrong … -
how to create a group of users
I want to create a link "create group" clicking on which it will display the total users that are registered till now and then we can select some users to create a group of them and can save that group in database for further use. -
Python is randomly multiplying the values of an imported nested list
I am creating a web app with Django. I use a file called simulateur_data.py which contains a Class called SimulateurData which stores all the key parameters I need to use in scripts and templates. The goal is that it will be easier to change the parameters when relevant. I use python 3.7.2 and django 2.1.7 It works fine when I import all parameters from SimulateurData, except one, which is a nested list. When I import it from another script, sometimes it import the right values, sometimes I get the nested list with a multiplicator of 137.74632546929436 applied to some values. I first thought it was because the nested list contains a mix of integer and float, but then I converted all the values to float and still get the same problem. Here is my app structure (I display only files and folders I think are relevant): - app/ - data/ - simulateur_data.py - scripts/ - calculs.py In simulateur_data.py, here is the code of the nested list that I have problem with (table_bareme_ir is the one I import: it converts t_i_r into float): class SimulateurData(models.Model): t_i_r = [ [0, 9964, 0, 0], [9964, 27519, 0.14, 2457.7], [27519, 73779, 0.3, 13878], [73779, … -
Django raise forms.ValidationError not working
I am trying to add a validator to django model form such that if specific value is selected then other field in the form should be entered if not entered it should give a validation error in the below form if the user selects "Project Support Activities" from the activity_name drop down then the project id field should be mandatory Django Form class ActivityTrackerModelForm(forms.ModelForm): date = forms.DateField(label='', widget=forms.DateInput(attrs={ "placeholder": "Select Date", 'id': 'datepicker', 'class': 'form-control w-100', 'autocomplete': 'off'})) activity_name = forms.ModelChoiceField(queryset=activity.objects.all().order_by( 'activity_name'), label='', empty_label="Select Activity", widget=forms.Select(attrs={'class': 'form-control w-100'})) system_name = forms.ModelChoiceField(queryset=system.objects.all().order_by('system_name'), label='', empty_label="Select System", widget=forms.Select(attrs={ 'class': 'form-control w-100'})) client_name = forms.ModelChoiceField(queryset=client.objects.all().order_by( 'client_name'), label='', empty_label="Select Client", widget=forms.Select(attrs={ 'class': 'form-control w-100'})) hour_choice = [('', 'Choose Hours'), (0, 0), (1, 1), (2, 2),(3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8)] hours = forms.ChoiceField(label='', choices=hour_choice, widget=forms.Select( attrs={'class': 'form-control w-100'})) min_choice = [('', 'Choose Mins'), (0, 0), (15, 15), (30, 30), (45, 45)] mins = forms.ChoiceField(label='', choices=min_choice, widget=forms.Select(attrs={'class': 'form-control w-100'})) no_of_records = forms.IntegerField(label='', required=False, widget=forms.NumberInput( attrs={"placeholder": "Enter no. of Records", 'class': 'form-control w-100', 'autocomplete': 'off'})) project_id = forms.CharField(label='', required=False, widget=forms.TextInput( attrs={"placeholder": "Project ID", 'class': 'form-control w-100'})) user_comments = forms.CharField( label='', required=False, widget=forms.Textarea( attrs={ "placeholder": "Enter Your Comments Here...", 'rows': 6, 'class': … -
Tinymce works fine in my app but not in admin - Django
I have a form in my app that has content attribute and uses tinymce like so: from tinymce.models import HTMLField class SomeModel(models.Model): content = HTMLField('Content', null=True) I also set up my tinymce in the installed apps and have the registered its url. In my app it works fine and the user can edit and enter his\her content using tinymce. but when I register this model to the admin, all fields appear fine except the content which does not appear to have any way to input (and because its a required field, this means that I cant enter new items through the admin). this looks like this in the admin: how can I make tinymce also available in the admin screen? bonus question: is there a safe way to use tinymce while letting the users use tinymce (currently im using form | safe which im guessing isn't really safe. -
Celery: Specific Exception in Task causes WorkerLostError
I have a simple task in a Django celery app like @shared_task def task(some_arg): # Do some stuff if some_error: raise Exception("Something went wrong") everything works as is should and the task fails as expected: [...:ERROR/ForkPoolWorker-2] Task task[some-id] raised unexpected: Exception('Something went wrong',) But when a library raises a custom Exception I get the following output: [...: WARNING/ForkPoolWorker-2] --- Logging error --- [...: ERROR/MainProcess] Task handler raised error: WorkerLostError('Worker exited prematurely: exitcode 0.',) Traceback (most recent call last): File ".../lib/python3.6/site-packages/billiard/pool.py", line 1226, in mark_as_worker_lost human_status(exitcode)), billiard.exceptions.WorkerLostError: Worker exited prematurely: exitcode 0. How to debug this? The custom Error class looks like this: class faultType(structType, Error): def __init__(self, faultcode = "", faultstring = "", detail = None): self.faultcode = faultcode self.faultstring = faultstring if detail != None: self.detail = detail structType.__init__(self, None, 0) ... -
Celery Daemonize Worker Using Python
I am running Celery Worker when initiating Django- python manage.py runserver My Celery Worker code is- from celery import current_app from celery.bin import worker class Worker: def start(): app = current_app._get_current_object() worker = worker.worker(app=app) options = { 'broker': 'amqp://guest:guest@localhost:5672//', 'loglevel': 'INFO', 'traceback': True, } worker.run(**options) Now I am initiating in init.py in Django, so it is starting the worker but as it is not in daemon or some child process I am unable to go to my main django jobs. I want this class to remain as I am making a generic library so that multiple microservices could use it just by importing this library -
Data product with Django
I'm creating a web application for a text mining algorithm. If I already have the html code for the interface, and I want the webapp to display the results from the python functions, could I just embed the html codes in Django? Would that be the correct way of doing it? If so, do you have any examples or tutorials on how to do it? (I'm new in Django) -
FactoryBoy / Django - handling constants
I am creating a factory for the following Django model: class Book(models.Model): tenant = models.ForeignKey('elearning.Tenant') book_id = models.IntegerField() ean = models.CharField(max_length=13, null=False) title = models.CharField(verbose_name="titel", max_length=200) author_name = models.CharField(max_length=200) description = models.TextField() price_id = models.IntegerField() buy_option_text = models.CharField(max_length=50) loan_days = models.IntegerField(null=True) type = 'Yindoboek' Which I turned into this factory: class BookFactory(factory.django.DjangoModelFactory): class Meta: model = Book tenant = factory.SubFactory(TenantFactory) book_id = factory.LazyFunction(lambda: random.randint(1, 1000)) ean = factory.LazyFunction( lambda: ''.join( random.choice(string.ascii_uppercase) for _ in range(6) ) + ''.join(random.choice(string.digits) for _ in range(6)) ) title = factory.Faker('company') author_name = factory.Faker('name_male') description = factory.Faker('text') price_id = factory.LazyFunction(lambda: random.randint(1, 1000)) buy_option_text = factory.Faker('sentence') loan_days = factory.LazyFunction(lambda: random.randint(1, 150)) type = 'Yindoboek' However, when I try to run the following test: def test_factory_matches_model(self): """ Verify that the factory generates a valid Book instance """ self.assertTrue(self.book) self.assertTrue(self.book.tenant) It crashes with the following error: TypeError: 'type' is an invalid keyword argument for this function FactoryBoy seems to be tripping of the type 'field' within the Book model, which is not a Django field instance but a constant. If I exclude this field from the factory the test will pass - but I'd rather not remove fields (the whole point is to test all fields / combinations) … -
How to check object status before showing in django CBVs
I want to check the objects' status in views. If it is True nothing changes but if the status not True I want to redirect users to another page. Here is my views: class ProductDetailView(LoginRequiredMixin, MultiSlugMixin, DetailView): model = Product def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) product_name = self.object.title category_commission = self.object.category.commission data = Stocks.objects.filter(product__title__icontains=product_name).order_by('price') context['category_commission'] = category_commission context['stocks'] = data return context And I have a status field at Product model like this: status = models.BooleanField(default=False) I want to achieve something like this: if self.object.status=True: do sth else: redirect('productlistpage') -
How to implement Django SSO with custom user model and object permission (EX/django-guardian) in multiple projects
I tried to search and study some information on the google, but I couldn't find the good solution. I have several Django projects and want to create "A" project store user information which implement Single-Sign-On(SSO) feature (ex/"django-simple-sso"). Then I need to classify user permission, I study the package "django-guardian" which maybe can help me do object permission. I found that I can't get user permission other project which "django-guardian" assign on "A" project. Does anyone have similar experience about this? If you have another recommendation package to implement the feature, welcome to share your experience. Thanks for your response. -
How to change sqlite db to postgres
I'm completely new to Django so sorry if I forgot to add something. So, I'm trying to change my SQLite db to Postgres. I changed settings.py to include postgres instead of sqlite ( https://i.imgur.com/BQkWtmG.png ), but python manage.py migrate is still doing sqlite db (and show me OperationalError at / no such table: articles_article https://i.imgur.com/IpgT5Wc.png ). Datadump > json didn't work because of same problem. Secret key and db pass added as environement variable with setx command. I don't really get why, but I have two settings.py files, but when I'm trying to change that deeper one everything is going wild and I can't even runserver as I'm getting NameError: name 'get_env_variable' is not defined. When I'm changing only db settings it's still no good https://i.imgur.com/TU6bpKf.png Little background: I made app with Django youtube tutorial by Netninja. It didn't have anything about deploying app online, hiding secret things or changing db so it's possible that I did more mistakes while searching for that. Site is currently online at https://fierce-brook-69212.herokuapp.com/ (without working db) and here is it's code https://github.com/grokoko/Django -
models clash with (META) inheritance
in a django project i' ve multiple apps, and the common contains the following models: class CLDate(models.Model): class Meta: abstract = True active = models.BooleanField(default=True) last_modified = models.DateTimeField(auto_now=True) created = models.DateTimeField(auto_now_add=True) class Switch(CLDate): name = models.CharField(max_length=64) code = models.CharField(max_length=64, blank=True, null=True) description = models.TextField(blank=True, null=True) sorted = models.IntegerField(default=0) class Currency(Switch): pass In another application i import the Switch, and try to add a ForeignKey to a model which inherits also from Switch class Country(Switch): ... currency = models.ForeignKey(Currency, on_delete=models.CASCADE) ... . Running makemigration or anything with manage.py i get the following error: SystemCheckError: System check identified some issues: ERRORS: ads.Country.currency: (models.E006) The field 'currency' clashes with the field 'currency' from model 'common.switch'. Why do i get this error, and how could i resolve it? I mean, at the database level it should be only a "pointer" to the currency Model / object, and should be irrelevant to its type. Of course if i change the inheritance type of the Currency to something else, it works fine. Django: 2.2 python: 3.5.3 . -
a way to migrate from sqlite to postgreeSQL in Django
I want to change DB in my project from SQLite to PostreeSQL. There are different approaches to do it. I found at least 10. Tried 2 of them: 1)Django : Transfer data from Sqlite to another database python manage.py dumpdata > db.json. Change the database settings to new database such as of MySQL / PostgreSQL. python manage.py migrate. python manage.py shell. Enter the following in the shell. from django.contrib.contenttypes.models import ContentType. ContentType.objects.all().delete() python manage.py loaddata db.json. 2) Use FullConvert software to do it. Both method failed. Do you know any "default/standard" way lets say to migrate? -
Post method in drf
I am sending a file name using axios from frontend using react js to my DRF api class now, i need to send that file name to my another api class using drf and search for file and return response. I know how to return from backend,but i am unable to post that filename using post methods. I am usng Django and drf and my front end as react js My frontend code looks something like this fetchFile = (value) => { const url = ${API}/dashboard/log_file/; const data = { info :value } axios.post(url,{data} ) }; -
Renaming Model in branch cause all other branch to fail
I got a Model called Cars. Master branch: Cars Branch feature/search: Cars Branch feature/showcar: Cars I renamed the Cars model to Car in branch, in order to make it work, I makemigrates and migrate it on feature/search branch now it becomes Master branch: Cars Branch feature/search: **Car** Branch feature/showcar: Cars It cause master and feature/showcar branch error, they couldn't find a model Cars in the database. And I cause my team a lot of problem. What could prevent this from happening? I hope this is clear. -
cant submit my form Error(Select a valid choice. That choice is not one of the available choices)
I can't submit my form seam everything is fine until I try to save some data in the database this is the code of the ###models.py### class City(models.Model): """Model definition for City.""" # TODO: Define fields here city_name = models.CharField(max_length=120) class Meta: """Meta definition for City.""" verbose_name = 'City' verbose_name_plural = 'Citys' def __str__(self): """Unicode representation of City.""" return self.city_name class Visa(models.Model): """Model definition for Visa.""" visa_type = models.CharField(max_length=50,choices=type) arrival_time = models.DateField() departure_time = models.DateField() number_of_vistor = models.CharField(max_length=50,choices=num) referance_number = models.CharField(max_length=50) purpose_trip = models.CharField(max_length=50) city = models.ForeignKey(City,on_delete=models.CASCADE) class Meta: """Meta definition for Visa.""" verbose_name = 'Visa' verbose_name_plural = 'Visas' def __str__(self): """Unicode representation of Visa.""" return str(self.id) i have connect this to models with ForeignKey this is the ###forms.py### code class VisaForm(forms.ModelForm): class Meta: model = Visa fields = ['visa_type','arrival_time','departure_time','number_of_vistor','purpose_trip','city'] labels = { 'visa_type':'Visa Type', 'arrival_time':'Arrival Time', 'departure_time':'Departure Time', 'number_of_vistor':'Number Of Visitor', 'purpose_trip':'Purpose of Trip', 'city':'City' } the form and the models seams fine to me but i dont know why its show up that validation error. -
How to render data in the texfield?
I'm new to Django, using Django 2.7.1 and python 3.7.2, trying to make a thing, which will take data from field forms on my site, then handle this data, and finally render the result in another field form on the same page. I've tried to make it by the model's methods, but didn't understood how. Now i'm trying to do it by views. So i understood what i should do, but still don't recognize how to render the result. this is my models.py from django.db import models # Create your models here. class CombinatorCols(models.Model): first_column = models.TextField("Column 1", null=True, blank=True) second_column = models.TextField("Column 2", null=True, blank=True) third_column = models.TextField("Column 3", null=True, blank=True) fourth_column = models.TextField("Column 4", null=True, blank=True) result = models.TextField("Result", help_text='Halo', blank=True,) def __str__(self): return self.first_column this is my forms.py from django import forms from .models import CombinatorCols class CombinatorForm(forms.ModelForm): class Meta: model = CombinatorCols fields = ('first_column', 'second_column', 'third_column','fourth_column', 'result',) this is my views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.template import loader from .models import Combinate,CombinatorCols from .forms import CombinatorForm,ResultForm # Create your views here. def get_col(request): #column = get_object_or_404(CombinatorCols) if request.method == "POST": form = CombinatorForm(request.POST) if form.is_valid(): column = form.save() column.sender … -
How to display django model data on the django cms page template
I would like to be able to use my external app data on django cms page. I am able to use custom plugin data but not data from normal django app I tried creating views to handle my data but how do I call this view from django cms pages? here is exactly what I am asking for but his explanation is shallow and the link provided in the answer is no longer in use. Here is my model: class ExternalArticle(models.Model): url = models.URLField() source = models.CharField( max_length=100, help_text="Please supply the source of the article", verbose_name="source of the article", ) title = models.CharField( max_length=250, help_text="Please supply the title of the article", verbose_name="title of the article", ) class Meta: ordering = ["-original_publication_date"] def __str__(self): return u"%s:%s" % (self.source[0:60], self.title[0:60]) My template has placeholders, but I dont mind displaying this data anywhere on the template if not possible inside a place holder I have a custom page that I am using in Django cms. I would like to display the above data is a section in the Django cms page If this model was inheriting from CMSPlugin then that would be easy because I could use a custom plugin in my placeholder … -
Adding reverse OneToOne related models to django admin panel
I have two related models class Profile(models.model): user = models.OneToOneField(User, related_name = 'profile', null=True) class User(AbstractUser): #fields For Profile admin.py looks like class ProfileAdmin(admin.ModelAdmin): #prepopulated_fields = {"slug": ("profile.last_name",)} list_display = ('id', 'get_trainer_name', 'add_date', 'city', 'is_active', 'pause') inlines = [PortfolioImageInline, OrderInline, ] list_display_links = ['id', 'get_trainer_name'] save_on_top = True list_filter = ['is_active'] def get_trainer_name(self, obj): return obj.user.get_full_name() admin.site.register(Profile, ProfileAdmin) I know that only one side of the OneToOneField can be set as the inline model. This means that I can add without any problems Profile to User admin view. But I need reverse view - like Orderinline or PortfolioInline at ProfileAdmin inlines. Is there any way to avoid this limitation so that I would not have to change the database schema? -
FactoryBoy/ Django - OneToOneField duplicate key error
I am writing tests for a large Django application with multiple apps. As part of this process I am gradually creating factories for all models of the different apps within the Django project. However, I've run into some confusing behavior with FactoryBoy Our app uses Profiles which are linked to the default auth.models.User model with a OneToOneField class Profile(models.Model): user = models.OneToOneField(User) birth_date = models.DateField( verbose_name=_("Date of Birth"), null=True, blank=True) ( ... ) I created the following factories for both models: @factory.django.mute_signals(post_save) class ProfileFactory(factory.django.DjangoModelFactory): class Meta: model = profile_models.Profile user = factory.SubFactory('yuza.factories.UserFactory') birth_date = factory.Faker('date_of_birth') street = factory.Faker('street_name') house_number = factory.Faker('building_number') city = factory.Faker('city') country = factory.Faker('country') avatar_file = factory.django.ImageField(color='blue') tenant = factory.SubFactory(TenantFactory) @factory.django.mute_signals(post_save) class UserFactory(factory.django.DjangoModelFactory): class Meta: model = auth_models.User username = factory.Faker('user_name') first_name = factory.Faker('first_name') last_name = factory.Faker('last_name') email = factory.Faker('email') is_staff = False is_superuser = False is_active = True last_login = factory.LazyFunction(timezone.now) profile = factory.RelatedFactory(ProfileFactory, 'user') Which I then run the followings tests for: class TestUser(TestCase): def test_init(self): """ Verify that the factory is able to initialize """ user = UserFactory() self.assertTrue(user) self.assertTrue(user.profile) self.assertTrue(user.profile.tenant) class TestProfile(TestCase): def test_init(self): """ Verify that the factory is able to initialize """ profile = ProfileFactory() self.assertTrue(profile) All tests in TestUser pass, … -
Django Rest return 0 bytes zip file in response
I have simple method that return zip archive with .pdf file in it. Here is part of code that generate zip archive and return it: pdf_file = HTML(string=rendered_html, base_url=request.build_absolute_uri()).write_pdf() temp = tempfile.TemporaryFile() archive = zipfile.ZipFile(temp, 'w', zipfile.ZIP_DEFLATED) with archive: archive.writestr('report.pdf', pdf_file) wrapper = FileWrapper(temp) http_response = HttpResponse(wrapper, content_type='application/zip') http_response['Content-Disposition'] = 'attachment; filename=report.zip' return http_response The problem is that I get in response 0 byte zip archive. What I am doing wrong? -
Django templates and modal Bootstrap
I am using Django with HTML and Bootstrap 3 to display a modal dialog for data input. I am trying to keep a "generic" modal dialog to use with all other model dialogs: <!-- generic/modal.html --> {% block modal_wrapper %} <div class="modal fade" id="{{ modal_id }}" role="dialog"> <div class="modal-body"> {% block modal_content %}{{ modal_content }}{% endblock %} </div> </div> {% endblock %} <!-- modal-add.html --> {% extends 'generic/modal.html' %} {% block modal_wrapper %} {% with modal_id='ssModal' %} {{ block.super }} {% block modal_content %} <form><div class="form-group"> <label>Recipient:</label> <input type="text" id="recipient-name"> </div></form> {% endblock %} {% endwith %} {% endblock %} <!-- main.html --> <div class="container"> {% include 'modal-add.html' %} </div> It looks like Django duplicates the contents of the "modal_contents" block, and inserts them both in the modal dialog (as intended) and within "main.html" (not intended behavior) - see attached screenshot. Is this a supported use case of the templates in Django or not? -
Use CRUD methods on JSONField in Django
I have a case where I need to read and write values stored inside model field of type JSONField. Below I'll reference this field as config Simplified version of model looks like this: class SampleModel(models.Model): config = JSONField(default=dict()) some_other_field = ... Access to this field is done by a separate URI with it's own serializer that represents the structure of data I'd like to store in config field. class ConfigSerizlizer(serializers.Serializer): config_value = serializers.IntegerField(required=False) another_config_value = ... In order to make serializer writable it has to implement create and update methods, although in my case it's only update that I'm interested in, because I intend to pre-populate config with default data if it's empty by the moment of request. The problem is that I can't figure out how to retrieve data from body of config field to serialize it (assuming it contains some data) for a get request and more importantly how to perform a put for a config's body.