Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'django' while running manage.py
I have installed virtualenv and then installed django in my Windows 10. After activating virtualenv and running: python manage.py runserver, I am getting: File "manage.py", line 10, in main 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: 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? Also just found while running django-admin.exe I am getting: Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). -
Django Haystack: Loop over SearchQuerySet results is extremely slow
I'm using Django 2.1/Python 3.6 with Django Haystack/Whoosh as search engine for a database of around 25k objects. I would like to build a table (DataTable) with my search results. However, looping through the SearchQuerySet results is being around 7x slower than looping through the page.object_list given by the haystack default form/view. My search_index: class MyModelIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) def get_model(self): return MyModel def index_queryset(self, using=None): return self.get_model().objects.all() My Comparison is the following: Test A: I use the default Haystack form/view to search for kerword. It takes less than a second to return 81 results, all in the same page (HAYSTACK_SEARCH_RESULTS_PER_PAGE = 100). Test B: I make the query by my self in the code, and transform it in a list so that I can send this list to build my data table: from haystack.query import SearchQuerySet results = list(SearchQuerySet().models(MyModel).filter(text='keyword')) This takes 7 seconds to return the same 81 results. I've tried to find out how haystack builds its page.object_list, however I had no success. I would like to know what I'm doing wrong. Thanks in advance. -
Install failed with django-keyboard-shortcuts 0.0.7 by pip in django 2.0.6
I am trying to install django-keyboard-shortcut via pip pip install django-keyboard-shortcuts I am using python 3.6. My error: Collecting django-keyboard-shortcuts Using cached https://files.pythonhosted.org/packages/b9/00/743c60d56a50cab02ca 8c2a2177b63e5b4548f3ce4293604422ad6651f67/django-keyboard-shortcuts-0.0.7.tar.gz Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "C:\Users\BRACKE~1\AppData\Local\Temp\pip-install-mpf8o833\django-key board-shortcuts\setup.py", line 121, in <module> long_description=read('README.rst'), File "C:\Users\BRACKE~1\AppData\Local\Temp\pip-install-mpf8o833\django-key board-shortcuts\setup.py", line 12, in read return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read () File "c:\users\bracketline\bracketnew\lib\encodings\cp1252.py", line 23, i n decode return codecs.charmap_decode(input,self.errors,decoding_table)[0] UnicodeDecodeError: 'charmap' codec can't decode byte 0x9d in position 8439: character maps to <undefined> ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in C:\Users\BRACKE~1 \AppData\Local\Temp\pip-install-mpf8o833\django-keyboard-shortcuts\ -
Django - Charfield creates an item int my BD
I have a simple project here, with two models that contain an attribute called telefone in both. telefone is phone in portuguese. Code class Medico (models.Model): nome = models.CharField(max_length=50) endereco = models.CharField(max_length=60) cpf = models.CharField(unique=True, max_length=11) telefone = models.CharField(max_length=15) especialidade = models.ForeignKey(Especialidade, on_delete=models.CASCADE) def __str__(self): return self.nome class Paciente (models.Model): nome = models.CharField(max_length=50) endereco = models.CharField(max_length=60) cpf = models.CharField(unique=True, max_length=11) telefone = models.CharField(max_length=15) def __str__(self): return self.nome I did the makemigrations and migrate, everything worked as expected, I'm using MySQL as BD. But for some reason, the phone field is int int in my BD for both the patient table and the medical table, see the image: Now the other fields are correct, could anyone tell me why this is happening? -
Using a UUID(PK) from table and create table with pk name in it
I’m using Postgres and Django. Currently making a “factory” model which produces tables upon a trigger. There’s a main model that stores a uuidv4 as pk’s. When the user fires the trigger, a new record is inserted into the main model. The “factory” model creates a new table. Can the table name contain the UUID from the main model (including an appended “.post” at the end of it)? Will that weaken security? -
Django retrieve rows for the distinct column values
I want to query Model rows in Django, class Language(models.Model): language_id = models.CharField(max_length=100, default="") code = models.CharField(max_length=100,default="") name = models.CharField(max_length=500, default="") In this table, the language_id is not unique, for example, below is the sample data language_id | code | name 12345 en english 12345 te telugu 54321 en english 54321 te telugu I want to filter the rows(all columns) which should have distinct language_ids. What currently I am doing. language_list = Language.objects.all() list = [] idlist = [] for language in language_list: if language.language_id not in idlist: il = language list.append(il) idlist.append(language.language_id) then list will have all the distinct rows(model objects). Is there any better way to do this. I don't want to rotate through all the language models. -
Django Authentication register API
I am trying to register users in django auth module through an API call but the users are getting registered without the password being hashed which, I suspect, is making my authentication fail. Registering the users through the admin form is hashing the password and therefore working. I developed my own User model by extending AbstractBaseUser and also created a UserManager extending BaseUserManager and defining the create_user and create_superuser method. I developed a simple serializer for it. I read somewhere that the password can only be hashed if I developed the Admin form as well and so I did it. In this form, I followed django documentation and developed clean_password and save functions. I also registered these forms on the app admin.py. Lastly, I created the APIView to the POST requests where I send the registration json and use the serializer do validate and save. model class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): if not email: raise ValueError('The given email must be set') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): user = self.create_user(email, password=password, **extra_fields) user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField(max_length=40, unique=True) first_name = models.CharField(max_length=30, blank=True) last_name = … -
How to get instant notification from a service endpoint you previously requested to in django
I'm new with django rest framework and I'm exploring it, I have a service FirstService that have the following endpoints : "/instances" "/instances/{instanceID}" "/subscriptions" "/subscriptions/{subscriptionID}" It accept post request to /subscriptions to subscribe to an instance that have been created via a PUT on /instances/{instanceID}. I want my FirstService to return to another service (client) a notification data (right after the subscription) via a POST to the subscriptionUri the client posted when subscribing and I don't know if there is any mecanism in django for that or in general how to approch this kind of problem. -
Take two objects in detail views to different URLs : DJANGO
How would you structure two objects in a DetailView page that link to a different URL each when you click on it? I am having a hard time to find a solution. lets say that we have class Course(models.Model): name = models.CharField(max_length=20) user = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='typecourses') class Module(models.Model): name = models.CharField(max_length=20) courses = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='courses', null=True) Based on the above: Lets assume that we have 'Computer Science' as a Course. Computer science has 2 modules: 'Python' and 'Django'. Computer science is the ListView, when you click 'Computer Science', you access the DetailView, which contain 'Python' or 'Django'. Now is my problem. How can you create a distinction between when someone click on Python to access another page that has information about Python module and do the same when someone click on 'Django'. I am looking for the BEST PRACTICE. My thought right now is simply to create a URL for each objects that takes to a new URL, different for each one.(This will not include using any PK or ID - I wonder if this the good way to solve this problem) Any help on the logic implementation will be much appreciated. -
Django: save() method in a different database
I'm trying to save an object in a non-default database. I have already configured a second connection. I know that in order to get objects it is Class.objects.using('the_db').all But when I try object.using('the_db').save() it doesn't work. (Error: "object has no attribute 'using'". I also tried object.save('the_db') but it also does not work. How can I achieve this? I couldn't find the correct syntax. -
How to send data from running application to django admin?
I need to send true/false from external continuously running application (app.py) to django admin site. My application, when executed, have inside logic with True/False value. Application is large and can't provide all details. I'm new in API, HTTP and connections. I have tried to make requests, use socket, created mini server through http.server.HTTPServer(another file). Stack. I want to know how can I connect my application with django? I want to see in admin site True or False when in application logic changes. In other word: you have to create socket in application and with django requests.get make request to the endpoint. Or you should build server. I need links, tools, tips, anything... -
how to display users from database into a table and create a group
How to display users which are registered using the default user django-admin panel, no external db query is written. I want when when the user click show users list, it will show a table with all the registered user listed in it. -
authtoken.Token.user: (fields.E304) Reverse accessor for 'Token.user' clashes with reverse accessor for
I have read a lot of questions related to clashes reverse accessor but nothing seems to help me. I'm trying to customize the Token field in DRF to be able to add some fields to it (I would like to have a Token per Company and Companies can create FiscalEntities and each FiscalEntity will have its own Token) I have followed the following question: How to use custom token model in Django Rest Framework core/models from django.db import models from django.utils.translation import ugettext_lazy as _ from rest_framework import authentication from company.models import Company from fiscalentity.models import FiscalEntity class CustomAuthenticationToken(models.Model): """ The default authorization token model. """ key = models.CharField(_("Key"), max_length=40, primary_key=True) company = models.OneToOneField( Company, related_name='auth_token', on_delete=models.CASCADE, verbose_name=_("Company") ) created = models.DateTimeField(_("Created"), auto_now_add=True) # Fiscal entity can be null because if it is null this token belongs to the parent Company fiscal_entity = models.ForeignKey(FiscalEntity, null=True, on_delete=models.CASCADE) class Meta: verbose_name = _("Token") verbose_name_plural = _("Tokens") def save(self, *args, **kwargs): if not self.key: self.key = self.generate_key() return super(CustomAuthenticationToken, self).save(*args, **kwargs) @staticmethod def generate_key(): return binascii.hexlify(os.urandom(20)).decode() def __str__(self): return self.key class BearerAuthentication(authentication.TokenAuthentication): """ Simple token based authentication using utvsapitoken. Clients should authenticate by passing the token key in the 'Authorization' HTTP header, prepended … -
Can´t use multiple bootstrap modals in django template
Im writing a template view on which i need to open several different modals - always just one at a time. This template has tabs and the trigger buttons for the modals are between the tab navigations and the tab content. I used multiple modals like this before with exactly the same code in a different view except the tab navigation and it works like supposed. But in this template my modal divs get nested together so the data-toggle wont work. Im sure i missed something little but i cant figure out what I tried to put the modal at the end of the included html (noteTable.html)to separate the modals, but this breaks my tab navigation - all content from every tab is shown in each tab then <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#newKNAModal">Kosten-Nutzen-Analyse</button> <button type="button" class="btn btn-secondary" data-toggle="modal" data-target="#newNote"><i class="fas fa-plus"></i> Neue Notiz</button> <div class="tab-content"> <div class="tab-pane active" id="details" role="tabpanel"> {% include 'detailForm.html' %} </div> <div class="tab-pane" id="notes" role="tabpanel"> {% include 'noteTable.html' %} </div> <div class="tab-pane" id="dokumente" role="tabpanel"> {% include 'documentTable.html' %} </div> </div> <!-- New KNA Modal --> <div class="modal fade bs-example-modal-lg" id="newKNAModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLongTitle" aria-hidden="true"> <div class="modal-dialog modal-xl" role="document"> <div class="modal-content"> <div class="modal-body"> {% include 'newKNA.html' … -
How can I automatically add data to the database on a weekly basis?
I want to add a 'Weekstaat' to the database automatically every end of the week. model: class Weekstaat(models.Model): id = models.AutoField(primary_key=True, null=False, blank=False) #status = models.ForeignKey(Status, null=False, blank=False, default=1,on_delete=models.CASCADE) jaar = models.ForeignKey(Jaar, default=datetime.now().year, null=False, blank=False,on_delete=models.CASCADE) week = models.ForeignKey(Week, default=date.today().isocalendar()[1], null=False, blank=False,on_delete=models.CASCADE) werknemer = models.ForeignKey(User, related_name='weekstaat_werknemer', null=False, blank=False, default=1,on_delete=models.CASCADE) maandag = models.FloatField(null=True, blank=True) dinsdag = models.FloatField(null=True, blank=True) woensdag = models.FloatField(null=True, blank=True) donderdag = models.FloatField(null=True, blank=True) vrijdag = models.FloatField(null=True, blank=True) zaterdag = models.FloatField(null=True, blank=True) zondag = models.FloatField(null=True, blank=True) def __str__(self): return str(self.jaar) + ' week ' + str(self.week) + str(self.werknemer) view: class weekstaat(generic.ListView): model = Weekstaat context_object_name = 'Weekstaten' template_name = 'weekstaat/index.html' -
where to add "social_core.backends.yammer.YammerOAuth2" for social authentication in django
Hey guys I am new to django , I am learning to build some application using it , so I am following some example instructions of some blog. In that there is need of configuring an social authentication django package with my app. I am not getting where to add this line please point out. Add social_django to INSTALLED_APPS Add social_core.backends.yammer.YammerOAuth2 to AUTHENTICATION_BACKENDS Set LOGIN_REDIRECT_URL = ‘/badges/’ Set LOGIN_URL = ‘/login/yammer’ -
pick id of the user who is not logged in
In this my views I get users by their exact name example www.mysite.com/usuario1 and so far it's working, but I need it in the photos section to get only the photos of that user1 and that user1 is not logged into the system. how do I pull only the photos of the user1? models.py class Photo(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=255, blank=True) file = StdImageField( upload_to='photos/', blank=False, variations={ 'large': (600, 400), 'thumbnail': (100, 100, True), 'medium': (300, 200), }) uploaded_at = models.DateTimeField(auto_now_add=True) class Negocio(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py def profile_detail(request, username): if User.objects.get(username__iexact=username): user_details = User.objects.get(username__iexact=username) photos_list = Photo.objects.filter(user=request.username.pk) return render(request, "profile.html", { "user_details": user_details, 'photos': photos_list }) else: return render("User not found") profile.html {% for photo in photos %} <img src="{{ photo.file.medium.url}}"class="img-thumbnail" width="200" height="200"> {% endfor %} -
Problem in rendering Multiple Drilldown in fusioncharts
I am using Django. I want use the drilldown feature in fusioncharts. I am able to get the first drilldown correctly. But when I code for the second drilldown it is showing "No data to display". Also the following code renders all the charts in the same type. But I want to render the child charts in different types. I am sharing the snippet below. def chart(request): dataSource = {} dataSource['chart'] = { "caption": "Top 10 Most Populous Countries", "showValues": "0", "theme": "zune" } dataSource['data'] = [] dataSource['linkeddata'] = [] sbc = MTD.pdobjects.values('Vertical', 'Channel','Brand','Sales_Value') sbc_df = sbc.to_dataframe().reset_index(drop=True)#Trying to use filtered model for dataframe sbc_df['Sales_Value']=sbc_df['Sales_Value'].astype(float) chn_gb=sbc_df.groupby('Channel')['Sales_Value'].sum().reset_index() channel=list(chn_gb['Channel']) channel_val=list(chn_gb['Sales_Value']) sbc_gb=pandas.pivot_table(sbc_df,index=['Vertical','Channel'],values=['Sales_Value'],aggfunc='sum').reset_index() brd_gb=pandas.pivot_table(sbc_df,index=['Vertical','Channel','Brand'],values=['Sales_Value'],aggfunc='sum').reset_index() for i in range(len(channel)): data = {} data['label'] = channel[i] data['value'] = channel_val[i] data['link'] = 'newchart-json-'+ channel[i] dataSource['data'].append(data) linkData = {} linkData['id'] = channel[i] linkedchart = {} linkedchart['chart'] = { "caption" : "Top 10 Most Populous Cities - " + channel[i] , "showValues": "0", "theme": "fusion", } linkedchart['data'] = [] sbc_filtered=sbc_gb[sbc_gb.Channel == channel[i]] vertical_list=list(sbc_filtered['Vertical']) vertical_val=list(sbc_filtered['Sales_Value']) for k in range(len(sbc_filtered)): arrDara = {} arrDara['label'] = vertical_list[k] arrDara['value'] = vertical_val[k] arrDara['link'] = 'newchart-json-'+ vertical_list[k] linkedchart['data'].append(arrDara) linkData = {} # Inititate the linkData for cities drilldown linkData['id'] = vertical_list[k] linkedchart = {} linkedchart['chart'] = … -
Upload Multiple images in Django-admin
Estou tentando fazer o upload de diversas imagens ao mesmo tempo no admin do Django, vi alguns exemplos usando Forignkey, entretanto as imagens devem ser colocadas uma por vez, para minha aplicação fica inviável, gostaria de coloca-las todas de uma vez só, entretanto não encontrei soluções claras ainda. Estou usando Django 2.0.6. Alguma sugestão? -
Django IntegretyError, when try to change ManyToMany field's value
models.py class BaseMedia(AbstractObject): staff = models.ManyToManyField('main.Profession', blank=True) # etc class Profession(Id): profession = models.CharField(max_length=15) creator = models.ForeignKey('main.Creator', on_delete=models.CASCADE) character = models.ForeignKey('main.Character', on_delete=models.CASCADE, null=True, blank=True) forms.py for profession, staff in staff.items(): for person in staff: professions.append(Profession.objects.update_or_create( profession=profession, creator_id=person.get('creator_id'), character_id=person.get('character_id') )[0]) instance.staff.set(professions) instance.staff.set(professions) from forms.py raise: django.db.utils.IntegrityError: update or delete on table "main_profession" violates foreign key constraint "main_basemedia_staff_profession_id_075458d2_fk_main_prof" on table "main_basemedia_staff" DETAIL: Key (id)=(dd032d79-d458-4ead-b05b-da3b419b58a0) is still referenced from table "main_basemedia_staff". I absolutely have no idea that's the point of this trouble. -
setUp Django test with insert statements from a .sql files
I have a .sql file with insert statements for different tables. How can I run the file against test in-memory db in setUp() method of a TestCase? -
How to serve `Docs` folder in Django restricted to admins only?
I have following code structure in Django. ├── docs │ └── _build │ ├── doctrees │ └── html │ └── index.html │ ├── localcoinswap ├── scripts ├── _static ├── _templates ├── tests └── manage.py Here the docs folder contains static html files. i.e index.html Here are some questions regarding to problem: The docs folder's html should be served as url <domain>/docs/index.html in Django project. How to achieve this It should be restricted to User's who have is_staff attribute True. What urlpattern should I use and Which View is useful to serve those static files (Admin restricted)? Thank you in advance! -
Django annotate on boolean Field
class Forecast(Model): id = UUID() type = StringField() approved = BooleanField() I want to group on the field type by applying 'logical and' on approved field. Suppose the annotated field is all_approved. all_approved should be True if all the items with that type is True, and false if atleast one is False. So finally in my queryset i want to have two fields type, all_approved. How can i achieve this? I tried something based on this answer, but couldn't get anything. -
Django - unioning QuerySet for different sbubclasses of an abstract model
For example, I have an abstract model X, and the A, B, and C models inherited from X (with some fields redefined). I want to create a QuerySet which includes all the As, Bs and Cs. Since X is abstract and does not have its own QuerySet (because it's no table for generic X), I'm trying to do the following: # annotating with a `type` integer denoting the actual type # some_field is present in A and B, but absent in C, so we add a placeholder to allow `union` (A.objects.all().annotate(type=models.Value(1, models.IntegerField())) .union(B.objects.all().annotate(type=models.Value(2, models.IntegerField()))) .union(C.objects.all().annotate(some_field=models.Value(None, models.IntegerField()), type=models.Value(3, models.IntegerField())) ) ) However, this does not work because the column order in the formed SQL query is different for each part of the union (due to the redefined fields). Is there a way to explicitly specify the order? P.S. Here I cannot use values() or values_list() since I have to keep the model objects (not dictionaries/tuples) in the QuerySet. -
Change Django Boolean value from default value "False" to something like "No"
I have a Boolean value which is false, but I want it to say something like "No" rather than "False" when printed on the web page. The same goes for printing "Yes" instead of "True" if it were true. I'm assuming this is possible! Code: urgent = models.BooleanField() Now, to print this sounds weird: Urgent: False But this sounds more natural, better UX etc.: Urgent: No