Posts

Showing posts with the label django

How to convert csv into mock when csv file is specified as argument in unit test of Django command

How to convert csv into mock when csv file is specified as argument in unit test of Django command There is a django command that gives the path of the csv file as an argument as follows. class Command(NoticeCommand): def add_arguments(self, parser): parser.add_argument( '--file', dest="file", type=str, required=True ) def handle(self, *args, **options): with open(options['file'], 'r') as f: reader = csv.reader(f) next(reader) for row in reader: ... I am thinking to make this csv file mock when doing unit test. However, I do not know which part and how to make mock. Also, the argument is required = True . How can I call UnitTest when csv is mocked? required = True from mock import patch from django.core.management import call_command class ImportCsvTest(TestCase): @patch("common.management.commands.import_csv.????") def test_import_csv(self...

Django model “doesn't declare an explicit app_label”

Django model “doesn't declare an explicit app_label” I'm at wit's end. After a dozen hours of troubleshooting, probably more, I thought I was finally in business, but then I got: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label There is SO LITTLE info on this on the web, and no solution out there has resolved my issue. Any advice would be tremendously appreciated. I'm using Python 3.4 and Django 1.10. From my settings.py: INSTALLED_APPS = [ 'DeleteNote.apps.DeletenoteConfig', 'LibrarySync.apps.LibrarysyncConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] And my apps.py files look like this: from django.apps import AppConfig class DeletenoteConfig(AppConfig): name = 'DeleteNote' and from django...

angularjs 6 python django rest framework crossdomain api call issue

angularjs 6 python django rest framework crossdomain api call issue I have configured django rest framework with python 3. And the API is working fine in postman. But am facing a cross domain issue, when I call this api through my angualar 6 project. OS: Mac OS I have included oauth2 for authentication. It works well with postman API Url: http://127.0.0.1:7777/api/v1/token/ Angular 6 website url: http://localhost:5000/#/login When I called this with angualrjs it shows the following error. Mozilla: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://127.0.0.1:7777/api/v1/token/. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Safari: Failed to load resource: Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin. XMLHttpRequest cannot load http://127.0.0.1:7777/api/v1/token/. Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin. Chrome: Failed to load http://127.0.0.1:7777/ap...

is django compressor default on django install?

is django compressor default on django install? Is django compressor default on django install? I have been having an issue with whitenoise and django. I keep getting this error: ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' ValueError: Missing staticfiles manifest entry for 'inline.bundle.js' now all the research I have done points that it may be a whitenoise (im using heroku) and a issue with django compressor. But I do not remember installing such a tech. Is it by default? One of the work arounds suggested is to replace django compressor with another. But how? whitenoise Actively researching this, if anyone has had this issue before would appreciate a work around. That looks like an Angular issue. And no, django-compressor is not installed by default unless it is installed by a third party library. – Selcuk Jul 2 at 3:38 ...

How can I add files to GitLab with `python-gitlab`?

How can I add files to GitLab with `python-gitlab`? Using Django, I’d like to sync the files in the database with git repositories on my GitLab instance via python-gitlab . python-gitlab Here you can find my Python code: import gitlab import base64 import os from .models import Meme from django.conf import settings class Sync: def sync () : gl = gitlab.Gitlab('<GitLab URL>', private_token='xxxxxxxxxxxxxx') for meme in Meme.objects.all(): meme_title = meme.meme_title meme_file = str(meme.meme_file) root = settings.MEDIA_ROOT place = os.path.join(root, meme_file) # Create a new project on GitLab. project = gl.projects.create({'name': meme_title }) data = { 'branch': 'master', 'commit_message': 'Automatic commit via sync.py.', 'actions': [ { ...

Django print models constant array in template

Django print models constant array in template I have a constant array in my model: DELIVERY_TYPES = ( ('self', u'one'), ('paid', u'two'), ('free', u'3') ) in my django template I'am trying to render it: <span style="font-size: 20px;">{{ DELIVERY_TYPES[shop.delivery_type] }}</span> I get an error, how to print these values right? Can you post your model where you have defined DELIVERY_TYPES and views from where you have sent the Model object to template? – Sijan Bhandari Jul 2 at 10:05 DELIVERY_TYPES 2 Answers 2 You can use: {{ shop.get_delivery_type_display }} See the docs on get_FOO_display for more info. get_FOO_display You could use instance of the model to acces...

Django and Mysql 8: 2012, 'Error in server handshake'

Django and Mysql 8: 2012, 'Error in server handshake' I am trying to install Django on new developer machine running MacOS High Sierra with latest version of Mysql (Ver 8.0.11). When I try to: python manage.py runserver i get this error message: django.db.utils.OperationalError: (2012, 'Error in server handshake') Does anyone has any experience with this? I have installed and I am running virtual environment that I have created with python3.6. I have installed mysqlclient too but I can't find anyone with this issue.. If you have both MySQLdb and mysqlclient installed in the virtualenv, remove both, then install just the newest mysqlclient . – AKX Jul 2 at 6:48 MySQLdb mysqlclient mysqlclient Also, based on this Percona article, it seems MySQL 8 has changed authentication plugin defaults. per...

Associate classes with django-filters

Associate classes with django-filters Bonjour, I have a question regarding django-filters. My problem is: I have two classes defined in my models.py that are: class Volcano(models.Model): vd_id = models.AutoField("ID, Volcano Identifier (Index)", primary_key=True) [...] class VolcanoInformation(models.Model): # Primary key vd_inf_id = models.AutoField("ID, volcano information identifier (index)", primary_key=True) # Other attributes vd_inf_numcal = models.IntegerField("Number of calderas") [...] # Foreign key(s) vd_id = models.ForeignKey(Volcano, null=True, related_name='vd_inf_vd_id', on_delete=models.CASCADE) The two of them are linked throught the vd_id attribute. I want to develop a search tool that allows the user to search a volcano by its number of calderas (vd_inf_numcal). I am using django-filters and for now here's my fi...

How to paginate more than two object lists in one page - Django get_context_data()

How to paginate more than two object lists in one page - Django get_context_data() Suppose I have two or more than two object lists objects_a and objects_b in Views.py with get_context_data() of Django , and I would like to paginated for objects_a and objects_b, I pasted my objects_list.html as below too, which can only paginated one of objects, objects_a or objects_b, how to paginated both of objects? objects_a objects_b get_context_data() of Django I have more than two object lists, four or five lists, how to paginate more than two object lists in one page? Thank you so much for any advice. class ObjectListView(PaginationMixin, ListView): model = Object ordering = ('name', 'department') context_object_name = 'objects' template_name = '' paginate_by = 20 def get_queryset(self, **kwargs): queryset = Permit.objects.all() return queryset def get_context_data(self, **kwargs): ................. ob...

Django: mulitselect options not prepopulating in html

Django: mulitselect options not prepopulating in html I'm using django-multiselect . On the html, all of the items are showing, but the ones that are already checked are not showing that they are checked. I was looking at the documentation, but it's coming prechecked. In particular this line of code isn't working: {% if value in myroles %}checked="checked"{% endif %} Can someone see what I did wrong? django-multiselect {% if value in myroles %}checked="checked"{% endif %} html {% for value, text in form.role.field.choices %} <div class="ui slider checkbox"> {{ value }}{{ text }} <input id="id_role_{{ forloop.counter0 }}" name="{{ form.role.name }}" type="checkbox" value="{{ value }}" {% if value in myroles %}checked="checked"{% endif %}> <label>{{ text }}</label> </div> {% endfor %} models.py aaa= 1 bbb= 2 ccc= 3 ddd= 4 eee= 5 ROLE_CHOICES = ( ...

How to use redis to cache the list of relevant articles as values mapped with the articles' id as key in django?

How to use redis to cache the list of relevant articles as values mapped with the articles' id as key in django? models.py from django.db import models from django_pandas.managers import DataFrameManager # Create your models here. class BcContent(models.Model): asset_id = models.PositiveIntegerField() title = models.CharField(max_length=255) alias = models.CharField(max_length=255) title_alias = models.CharField(max_length=255) introtext = models.TextField() state = models.IntegerField() sponsored = models.IntegerField() sectionid = models.PositiveIntegerField() mask = models.PositiveIntegerField() catid = models.PositiveIntegerField() created = models.DateTimeField() created_by = models.PositiveIntegerField() created_by_alias = models.CharField(max_length=255) modified = models.DateTimeField() modified_by = models.PositiveIntegerField() checked_out = models.PositiveIntegerField() checked_out_time = models.DateTime...

Django media url including app url

Django media url including app url My media URL is showing good in HTML like href="/media/Properties/1/scaled_3714427_10513837_VyyZzt3.jpg" but it is not displaying images because when I'm clicking on the image it is being redirected with new URL http://domain/dashboard/media/Properties/1/scaled_3714427_10513837_VyyZzt3.jpg dashboard should not be in URL href="/media/Properties/1/scaled_3714427_10513837_VyyZzt3.jpg" setting.py MEDIA_ROOT = os.path.join(BASE_DIR, '/media/') MEDIA_URL = '/media/' url.py urlpatterns = [ path('admin/', admin.site.urls), url(r'', include('search.urls')), # url(r'^siteadmin/', admin.site.urls), url(r'^dashboard/', include('search.urls')), url(r'^owner/',include('owner.urls')), # url(r'^scrap/',include('scrap.urls')), url(r'^favicon.ico$', Redi...

JSON Models Django

JSON Models Django I have the following models: class Estado(models.Model): nome = models.CharField('Estado', max_length=30) uf = models.CharField('UF', max_length=2) class Cidade(models.Model): municipio= models.CharField('Municipio', max_length=50) estado = models.ForeignKey(Estado, on_delete=models.DO_NOTHING) How can i create a .json fixture for them? To add the states, I did the following: [{ "model": "comum.estado", "pk": 1, "fields": { "uf": "AC", "nome": "Acre" } }, ...etc... ] To add cities, I tried doing the following, but it did not work: [{ "model": "comum.cidade", "pk": 1, "fields": { "municipio": "Afonso Cláudio", "estado": 8 } }, ...etc... ] What should I do to fix it? 1 Answer ...

How can I write my own decorator in Django?

How can I write my own decorator in Django? My models.py file is as follow: models.py from django.contrib.auth.models import User class Shopkeeper(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... class Customer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) # ... And I have some views which only Customers can access after login, but Shopkeepers cannot. And vice versa. How can I write decorator for such task? 1 Answer 1 There is nothing magical about a decorator, it is a function that takes as input the function (or class) to decorate, and makes some changes to it. If we look at the login_required decorator [GitHub], we see: login_required def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks tha...

How to order by a django property, or alternative solutions

How to order by a django property, or alternative solutions Ok, so I'm new to django and not sure if I'm approaching this correctly, but here goes: I have a class of incidents, and source of incidents, where you can have multiple sources for a single incident. class Incident(models.Model): iid = models.IntegerField(primary_key=True) person = models.ForeignKey('Person', on_delete=models.SET_NULL, null=True) @property def first_reporteddate(self): return self.source_set.aggregate(first=Min('datereported'))['first'] class Source(models.Model): sid = models.IntegerField(primary_key=True) incident = models.ForeignKey('Incident', on_delete=models.SET_NULL, null=True) url = models.TextField(validators=[URLValidator()]) datereported= models.DateTimeField(null=True, blank=True) When a new incident is created, I want to require that a source is also created. I want to give users the option to sort the Incident model ...

Django 2.0 Access Models (CREATE/REMOVE/FILTER) Standalone [without manage.py shell]

Django 2.0 Access Models (CREATE/REMOVE/FILTER) Standalone [without manage.py shell] I have a Django project and I wanted to generate some objects (from the models) What I'm trying to get at : Standalone Python Script to create bunch of objects and/or filter,delete. after importing the model with from apps.base.models import MyModel and setting up the configuration as the previous StackOverflow Questions suggested I was not able to run the script. from apps.base.models import MyModel import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myProject.settings") import django django.setup() from apps.base.models import MyModel Please note that this is on Django version 2.0.6 [Django 2.0+] . Correct settings have been used, ( i.e. myProject.settings ) myProject.settings After properly configuring everything else I get the following error: RuntimeError: Model class apps.base.models.MyModel doesn't declare an explicit app_label and isn't in an applicat...