Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Passing a date to a queryset based on a button click in Django
I have Manifest View that querys date_scheduled and returns distinct values. I pass that queryset to a template and loop over the values and present them as buttons on the HTML file. I am able to click any button and pass the corresponding date into the URL,((localhost/schedule/2019-06-20) when I click on the June, 20 2019 button) thus redirecting me to my RoastManifestDetailView. Now I want to be able to filter my RoastManifestDetailView based only on the date passed to the URL (or which date button was clicked). I have tried RoastManifest.obejects.filter(date_scheduled__date=date.today())just to see if I could return anything schedule for today but I keep getting Fielderrors (Unsupported lookup 'date' for DateField or join on the field not permitted.). Please note I know that is not the exact queryset for me. I wish to pass in a variable into the queryset. This is the model: (NOTE: roast_order is in there only to allow for use of adminsortable2 library) def batch_number_incrementer(): current_max = RoastManifest.objects.order_by('-batch_number').first() if current_max: return current_max.batch_number + 1 else: return 8000000 batch_number = models.IntegerField(unique=True, default=batch_number_incrementer, ) product = models.ForeignKey(Product, related_name="products", on_delete=models.PROTECT) date_scheduled = models.DateField() roaster_profile = models.ForeignKey(RoasterProfile, on_delete=models.PROTECT) roast_order = models.PositiveSmallIntegerField(default=0, blank=False, null=False) class Meta: ordering = ('roast_order',) This is … -
SSL error in Django MySQL Connection (2026 SSL_CTX_set_tmp_dh failed)
Attempting to connect to RDS MySQL instance through databases dict in settings.py file yields django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed'). Setup (Similar to SSL connection error when connecting to RDS MySQL from Django) Standard Django application MySQL RDS instance with security group allowing connections from all IP addresses MySQL user is setup to allow connections from any host Amazon's pem has been downloaded and is specified in Django settings Connection through cli works, as does connecting in interpreter through PyMySql. I've tried verifying that the path to the ca is absolute, which it is, and making sure that I'm not using python to attempt to build it, as in SSL connection error when connecting to RDS MySQL from Django. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dev', 'USER': os.environ['DEV_DATABASE_USERNAME'], 'HOST': os.environ['DEV_DATABASE_HOST'], 'PASSWORD': os.environ['DEV_MYSQL_PASSWORD'], 'OPTIONS': { 'ssl': { 'ca': <PATH TO CA CERT> }, } } } -
django-filter filter on annotated field
class EventViewSet(viewsets.ModelViewSet): queryset = Event.objects.all() serializer_class = EventSerializer def get_queryset(self): return super().get_queryset().annotate( is_active=ExpressionWrapper( Q(start_date__lt=timezone.now()) & Q(end_date__gt=timezone.now()), output_field=BooleanField() ), ) search_fields = [ 'name', 'short_desc', 'desc', ] filterset_fields = [ 'is_active', ] I have this ViewSet that I want to filter on an annotated field, normally you can simply just filter on the annotation in django querysets, however the above combined with this serializer: class EventSerializer(serializers.ModelSerializer): is_active = serializers.SerializerMethodField() @staticmethod def get_is_active(obj): return obj.is_active class Meta: model = Event fields = [ 'timestamp', 'id', 'name', 'short_desc', 'desc', 'start_date', 'end_date', 'is_active', ] I haven't looked deep into the source code but I'd assume it would do a simple qs.filter for the fields in filterset_fields but I'm getting this beautiful error that fails to explain much(at least to me): 'Meta.fields' contains fields that are not defined on this FilterSet: is_active -
Django is not sending me an email when there is an error 500
After deploying my website, I would like to get an email with the errors when there is an error 500. I am able to send normal emails with send_mail. I alsp have DEBUG= False, ADMINS=[('name'),('email')] andSERVER_EMAIL = "domain email", however I and not getting any emails. I believe it is because I created a custom template for handler500 urls.py handler500 = myapp.error_500 views.py def error_500(request): data = {} return render(request,'.../error_500.html', data) How do I send the email with an error? -
Is it possible cache the whole page in Django?
I'm currently working this website. The problem is that the pages takes 3-4 seconds to get the first bye, and I think it's because query to load data in the pages is very slow. In the store page, it basically uses an object of a store to show the store's basic information and uses ForeignKey relation to access the store's images. In addition, it uses ManyToManyField to access the store's similar stores which are a store object as well. For this solved, I used prefetch_related and select_related so minimized many of duplicated queries. But still it shows a low performance. After that I thought, I could improve it with caching, so I did the below. To be honest, what I expected with caching was like super fast loading as it is supposed to store all the processed queries and just show the data from the requested cache. But, to be honest, it still shows 3-4 seconds loading performance. Am I using the cache in a wrong way? settings.py ... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'django_cache', } } ... views.py class StoreDetailView(View): def get(self, request, *args, **kwargs): store_domainKey = self.kwargs['store_domainKey'] cache_store = 'store-{0}'.format(store_domainKey) store = cache.get(cache_store, None) if … -
Add extra value before save serializer
My form sends data to django-rest-framework, but the form contains two fields, and I want to save 5 fields in the database, other fields I calculate on my own (they are not sent by the form). How can I add additional values before saving? so, form send 'user' and 'comment' values, I want add 'article', 'ip_address' before save to DB models.py class Comments(models.Model): article = models.ForeignKey(Articles, on_delete=models.CASCADE) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) comment = models.TextField(verbose_name=_('Comment')) submit_date = models.DateTimeField(_('Created'), auto_now_add=True) ip_address = models.CharField(_('IP address'), max_length=50) is_public = models.BooleanField(verbose_name=_('Publish'), default=False) serializers.py class CommentsSerializer(serializers.ModelSerializer): user = serializers.ReadOnlyField(source='user.first_name') class Meta: model = Comments fields = ('user', 'comment') views.py class AddCommentViewSet(viewsets.ModelViewSet): queryset = Comments.objects.all() serializer_class = CommentsSerializer -
Django ORM: filter for tuples of foreign key attributes
I'm writing a matching service that will match you with profiles based on overlapping expertise. E.g. if you are REQUESTING python expertise, it will match you with folks OFFERING python expertise. I'm having trouble determining how to structure that query with the Django ORM. Setup I have models: class Profile(models.Model): pass class Expertise(models.Model): profile = db.ForeignKey('profile', on_delete=models.CASCADE) name = db.CharField(choices=[(1, 'python'), (2, 'javascript'), (3, 'golang')], max_length =255) direction = db.CharField(choices=[('offered', 'offered'), ('requested', 'requested')], max_length = 255) Data I've got data that essentially looks like the following: # setup some fields profile = Profile() profile.save() Expertise(profile=profile, name=1, direction='requested').save() Expertise(profile=profile, name=2, direction='offered').save() Obviously Wrong Attempt Profile.objects.filter( expertise__name__in = [e.name for e in profile.expertise_set()] expertise__direction__in = [e.direction for e in profile.expertise_set()] ) I'm essentially looking for the ability to combine boolean AND and boolean OR in the query. In a different technology, I'd... In SQL I'd do something along the lines of: SELECT * FROM app_profiles JOIN app_expertise on app_profiles.id = app_expertise.app_profiles_id WHERE (app_expertise.direction = 'offered' AND app_expertise.name = 1) OR (app_expertise.direction = 'requested' AND app_expertise.name = 2) -
strange data display in select at Django
Already a dead hour I puzzle over a problem with. Why in the first case is SECURITY_WITHOUT displayed, and in the second - display? After all, everything is identical ... In general, in both cases, the translated phrase with django.po should be displayed. But how to achieve this? ... models.py SECURITY_WITHOUT = 'Without display' CONFIRMATION_WITHOUT = 'display' #this displayed SECURITY_CHOICES = ( (SECURITY_WITHOUT, _('Without display')) #SECURITY_WITHOUT displayed ) CONFIRMATION_CHOICES = ( (CONFIRMATION_WITHOUT, _('Display')), ) income_proof = models.CharField(_('proof'), max_length=255, choices=CONFIRMATION_CHOICES, default=CONFIRMATION_WITHOUT) security = models.CharField(_('security'), max_length=255, choices=SECURITY_CHOICES, default=SECURITY_WITHOUT) forms.py security = forms.ModelChoiceField(queryset=CreditPayment.objects.values_list('security', flat=True).distinct(), widget=forms.Select(attrs={'class': "selectpicker form-control", 'title':_("Security")})) income_proof = forms.ModelChoiceField(queryset=CreditPayment.objects.values_list('income_proof', flat=True).distinct(), widget=forms.Select(attrs={'class': 'selectpicker form-control', 'title':_("Income proof")})) template {{ big_form.security }} {{ big_form.income_proof }} html <div class="form-group"> <div class="dropdown bootstrap-select form-control show"> <select class="selectpicker form-control" id="id_big-security" name="big-security" tabindex="-98"> <option value="" selected="selected">---------</option> <option value="SECURITY_WITHOUT">SECURITY_WITHOUT</option> </select> <button type="button" class="btn dropdown-toggle bs-placeholder btn-light" data-toggle="dropdown" role="button" data-id="id_big-security" title="---------" aria-expanded="true"><div class="filter-option"><div class="filter-option-inner"><div class="filter-option-inner-inner">---------</div></div> </div></button> <div class="dropdown-menu show" role="combobox" style="max-height: 394px; overflow: hidden; min-height: 0px; position: absolute; transform: translate3d(0px, 61px, 0px); top: 0px; left: 0px; will-change: transform;" x-placement="bottom-start"><div class="inner show" role="listbox" aria-expanded="true" tabindex="-1" style="max-height: 376px; overflow-y: auto; min-height: 0px;"><ul class="dropdown-menu inner show"><li class="selected active"><a role="option" class="dropdown-item selected active" aria-disabled="false" tabindex="0" aria-selected="true"><span class=" bs-ok-default check-mark"></span><span class="text">---------</span></a></li><li><a role="option" class="dropdown-item" aria-disabled="false" tabindex="0" … -
How does one save Django objects to models dynamically using functions?
I have several models that inherited an abstract model. With Django Rest Framework, I'm creating a custom action. I'm trying to save models based off an argument provided when utilizing the function: def mover_func(blobs, noteModel, commentModel): myself = blobs.get_object() U1(author=myself.author, title=myself.title, summary=myself.summary).save() class P1ViewSet(viewsets.ModelViewSet): queryset = PNote1.objects.all() serializer_class = PNote1Serializer @action(detail=True, methods=['get']) def pnote_move_to_unote(self, request, pk): mover_func(self, blah1, blah2) return Response({'status', 'Done'}) U1 is one of the models inheriting the abstract model. Later on, other viewsets such as P2ViewSets, P3, etc. are included, I need to save them to the models U2, U3, etc. There's more unrelated stuff than that, but I just wanted to minimize it for readability. I was thinking of adding an argument to mover_func like mover_func(self, blah1, blah2, U1) U1 being the model that should be creating and saving the object, but my recollection of previous experiences in Django 2.2 tells me that won't work... Again, something helpful is that the attributes author, title, and summary are the same across U1-->UInfinite (if you forgot that these models inherited from the same abstract model). -
Problem sending information between Django template and views using AJAX call
I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page. With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix. This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert. $.post({ headers: { "X-CSRFToken": '{{csrf_token}}' }, url: `http://www.joedelistraty.com/user/applications/1/normalize`, data: {arr}, dataType: "json", contentType : "application/json", success: function(norm_data) { var norm_data = norm_data.toString(); alert( norm_data ); } }); This is my Django URLs code to receive the request: path('applications/1/normalize', views.normalize, name="normalize") This is the python view to retrieve the code and send it back to the javascript file: from django.http import JsonResponse def normalize(request,*argv,**kwargs): norm_data = request.POST.get(*argv, 'true') return JsonResponse(norm_data, safe = … -
"No module named 'settings' error when trying to use Django OAUTH toolkit models
I want to access the models that are used by Django OAUTH Toolkit so I can periodically delete old tokens from the database. I thought I'd just import them: # this module will periodically delete rows from the table from oauth2_provider.models import AbstractAccessToken old_access_tokens = AbstractAccessToken.objects.all() print(old_access_tokens) I tried testing this but I receive the error: Traceback (most recent call last): File ".\db_cleanup.py", line 3, in <module> from oauth2_provider.models import AbstractAccessToken File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\models.py", line 12, in <module> from .generators import generate_client_id, generate_client_secret File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\generators.py", line 4, in <module> from .settings import oauth2_settings File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\settings.py", line 24, in <module> USER_SETTINGS = getattr(settings, "OAUTH2_PROVIDER", None) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__ self._setup(name) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\User\.virtualenvs\gsm-django\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'settings' Do I need to be referencing the settings file somewhere where I'm currently not? -
KeyError at /admin/login/ 'request'
What could be the cause of this issue? I have looked at similar questions and most of the answers recommended are things I have already configured in my settings file. When I try login to the admin section. This error shows up KeyError at /admin/login/ 'request' the request context processor here is already part of the configuration here is my TEMPLATE configuration { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(APPS_DIR.path('templates')), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTH BACKENDS AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] Django 1.11 PS: I am using djangorestframework as well, any ideas if it's somehow affecting this? -
How to correctly query Tags from the database and display the result in templates in DJANGO
I am trying to query Tags (Django taggit) associated to objects IDs and display the result to the templates. For some reason it returns NONE when I try to debug it with PDB. So far I have tried multiple way to debug it still the console return NONE when I try to query the ```tag`` from the page. models.py from taggit.managers import TaggableManager class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete='models.CASCADE', related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag/>', views.post_list, name='post_list_by_tag'),path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share') ] views.py from taggit.models import Tag def post_list(request, tag_slug=None): """ List of Posts and Tags. """ page_posts = Post.published.all() # Tags tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) page_posts = page_posts.filter(tags__in=[tag]) paginator = Paginator(page_posts, 2) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: … -
How to properly config html code to replace confirm button in Sweet Alert 2?
I'm currently on a crucial step on my Sweet Alert program. I need to replace the default submit and cancel buttons by some inside-html buttons (the form is being rendered through ajax), but I cannot find any reference on how to properly get the submited information or close the alert. My form html code: <div class="card"> <div class="card-header card-header-icon" data-background-color="orange"> <i class="large material-icons">cloud_upload</i> </div> <br> <div class="card-content"> <form {% if modal_title_id %} id="{{ modal_title_id }}"{% endif %} class="form-{{ style|default:'stacked' }} {{ class }} create-form" method="{{ method|default:'post' }}" {% if action %} action="{{ action }}"{% endif %} enctype="multipart/form-data"> {% if not method == "get" %}{% csrf_token %}{% endif %} {% if title %}<h5><i class="icon-sitemap icon-large"></i>{{ title }}</h5>{% endif %} {% include 'dashboard/partials/form_fields.html' %} </form> <div class="row"> <button type="button" class="btn btn-secondary" id="closeSwal">{% trans 'Close' %}</button> <button type="submit" class="btn btn-primary" id="PostSwal">{% trans 'Upload File' %}</button> </div> </div> </div> My button html code: <p> <button type="button" class="btn btn-primary upload-file-js" data-url="{% url 'crm:customer:lead_upload' %}"> <span class="glyphicon glyphicon-plus"></span> Importar Leads </button> <button type="button" class="btn btn-primary js-import-client"> <span class="glyphicon glyphicon-plus"></span> Importar Clientes </button> </p> and my js code is: $('.upload-file-js').click(function() { var uploadUrl = $(this).attr('data-url') $.ajax({ url: uploadUrl, type: 'get', dataType: 'json', success: function (data) { Swal.fire({ … -
How To Load Fonts In Django
I have a project I am working on in django and i am trying to load locally installed fonts with the .tff extensions but they dont seem to be working. My css code is @font-face { font-family: 'JandaAppleCobbler'; src: url('../fonts/JandaAppleCobbler.tff') format("truetype"), local('JandaAppleCobbler'); } My directory structure is --static |--css | |--main.css | |--fonts |--JandaAppleCobbler.tff -
Why don't see data from multiple select in admin page?
I wrote a multi-select form for the admin page. The data saved, but for some reason it is don't show in field as selected. What could be the problem? Django 1.9 class ConditionAdminForm(forms.ModelForm): """docstring for ConditionAdminForm.""" REGISTRATION_CHOICES= ( ('Any', _('Any')), ('Constant', _('Constant')), ('Temporary', _('Temporary')), ) registration = forms.MultipleChoiceField(choices = REGISTRATION_CHOICES, label=_("registration form")) def clean_registration(self): registration = self.cleaned_data['registration'] if not registration: raise forms.ValidationError("...") registration = ', '.join(registration) return registration class Meta: model = Condition fields = '__all__' class ConditionInlineAdmin(admin.StackedInline): model = Condition form = ConditionAdminForm field "регистрация" -
No matching object on query during save() override on model - DoesNotExist error thrown
I'm overriding my Model save() to check and see if there is a Consumer (related object) that already exists with the email entered. When a Consumer does exist with a matching Email, the code executes as expected and associates the Case to the correct Consumer. However, if there is not an existing Consumer that exists with a matching Email, I'm receiving the error: "DoesNotExist: Consumer matching query does not exist." I've tried adjusting the save() method, however to me it looks correct (obviously, could be wrong here). Models.py class Case(models.Model): ... def save(self,*args,**kwargs): if Consumer.objects.get(email__iexact=self.email): self.consumer = Consumer.objects.get(email__iexact=self.email) else: consumer = Consumer(first_name=self.first_name,last_name=self.last_name,email=self.email) consumer.save() return super().save(*args,**kwargs) The expected results is to create a new Consumer object in the case that the Email entered on the Case does not match an already existing Consumer's email. Instead, it throws this error. -
How to highlight and get informations from elasticsearch-dsl search in django?
I'm using django-elasticsearch-dsl. I have already index datas and set up some queries on them. Here is an example of query in my views : q = HemisticheDocument.search().query(operation, field="value") Then after I have : listHem = [hit for hit in q[:q.count()] I have results. When operation is "match", I have no problem because it is an exact term that I am looking for. However, when I use "fuzzy" as my operation, I would like to know if it possible for any hit : To highlight or extract the term (which may not be the exact one) that has been found in the hit. To get the score of it. I would put them in a dictionary for other uses. Thank you in advance. Hope the question is clear enough. -
How to take into consideration objects with null foreign keys?
Image I have two models: class Category(models.Model): name = models.CharField(max_length=1024) def __str__(self): return self.name class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) now i want to get number of cards in categories: cards_by_categories = Card.objects.filter( user_id=request.user.id).values('categories__name').annotate( num_per_cat=Count('categories__name') ) And I get (please consider that i have many Cards without categories): [ { "categories__name": null, "num_per_cat": 0 <-- do not want 0 here, why 0? }, { "categories__name": "alol", "num_per_cat": 2 }, { "categories__name": "category_name1", "num_per_cat": 3 } ] However, I want the amount of cards with null categories to be not null, but actual number of cards without categories. I know I can query like Cards.objects.filter(categories=None), but how to combine that? -
ERROR: Failed building wheel for mysqlclient
I'm unable to 'pip install mysqlclient', and every attempt returns the error: 'ERROR: Failed building wheel for mysqlclient'. For context, I'm running on macOS Mojave 10.14.5. The rest of this post assumes that both 'python==3.6' and 'virtualenv' are already downloaded. In addition, x-code command line tools are already installed (not that I think that matters). The steps to this are (from command line): 'virtualenv ~/venv' Output: Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/usr1/venv/bin/python3.6 Also creating executable in /Users/usr1/venv/bin/python Installing setuptools, pip, wheel...done." 'source ~/venv/bin/activate' 'pip install mysqlclient' So far, I've viewed and attempted everything on: Failed building wheel for mysqlclient "Failed building wheel for psycopg2" - MacOSX using virtualenv and pip Failed building wheel for mysql-python Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command /Users/usr1/venv/bin/python3.6 -u -c 'import setuptools, tokenize;file='"'"'/private/var/folders/2j/1qt0_7q96lxbxl2w5kx8r1zr0000gn/T/pip-install-4uobjq_4/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/2j/1qt0_7q96lxbxl2w5kx8r1zr0000gn/T/pip-wheel-ehvuw9uv --python-tag cp36: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.13-x86_64-3.6 creating build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/times.py … -
How to use purchased UI Theme with Django
I'm working with Django framework and I've recently purchased a dashboard Theme in order to give to my application a nice front end. My idea is to use styles, components, fonts and everything else provided in the Theme through in Django's templates. The product that I bought is called architectui-html-pro-theme. According to documentation provided the template is powered by jQuery, Bootstrap4 & Webpack The installation process of the Theme consist of: 1) Download files 2) Run npm install 3) and then start the application thought npm run start After all that, what i got is a nice Demo of the Theme running on http://localhost:8081 Great... But none further informations is provided regarding how to make the Theme works in My Django application. It's looks like the Theme installed a lot of dependencies (node_modules directory ) so I think to make it work in my Django project it is not just a matter of copy and paste the full directory in some "static" folder and just make reference some main.css style file in my "base.html" file. I have already asked the provider but no answer so far. This is the file structure of the Theme: .babelrc .gitignore architectui-html-pro <dir> node_modules <dir> … -
How do I properly set up Django-Rest-Tracking, so I can log usage
I am not sure how to use drt. I've read through the documentation multiple times and I am not understanding it. So far what I have is from rest_framework_tracking.mixins import LoggingMixin in my polls\views.py app and then from rest_framework import generics from rest_framework.response import Response from rest_framework_tracking.mixins import LoggingMixin class LoggingView(LoggingMixin, generics.GenericAPIView): def get(self, request): return Response('with logging') In my api\views.py app, nothing is changing on the logs page on the admin site, and I am not sure what is wrong, or where to go from here. -
django theader for consume rabbitmq queue error
i new in microservices pattern and i have a django app that contains a view sending a message and a consumption in node js calling a message processes and returns to a django application. This entire communication process is done by rabbitmq. when an http request arrives at a certain endpoint the application django sends a message in a queue this process is working to consume the answer I thought about launching a theader that consumes the answer queue. I can launch theader but the client (django) closes the connection with rabbitmq my app ready from django.apps import AppConfig from rpc.rpc_queues import RcpOrder class SaleConfig(AppConfig): name = 'sale' def ready(self): r = RcpOrder() r.daemon = True r.start() my rpc interface class RpcInterface(Thread): host = None queue = None def __init__(self): #cria conexao TCP self.connection = pika.BlockingConnection( pika.URLParameters(self.host) ) #cria um canal virtual que server para o envio e consumo de mensagens self.channel = self.connection.channel() #declara a queue criando se for necessario result = self.channel.queue_declare(queue='', exclusive=True) self.callback_queue = result.method.queue super().__init__() def on_response(self, ch, method, props, body): #verifica se a mensagem foi para este consumer if self.corr_id == props.correlation_id: self.response = body def call(self, body): self.response = None #cria um id unico … -
returning related field in template
I have the following classes, I can get the related objects through this {{plantpart.fraction_id.fraction}} going up the models, but I want to go the other way. I know I need a related_name to avoid the _set ending and it needs to be in a nested for loop. So how do I correct the following: {% for f in fractions %} {% for pp in plantparts%} {{pp.plantparts.fraction}} {% endfor %} {% endfor %} class Fraction(models.Model): fraction_id = models.AutoField(primary_key=True) composition_id = models.ForeignKey(Composition, db_column='composition_id', on_delete = models.PROTECT) fraction = models.CharField(max_length=20, choices = FRACTIONS) class PlantPart(models.Model): plantpart_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', on_delete = models.PROTECT, related_name='plantparts') taxon_id = models.ForeignKey(Taxon, db_column='taxon_id', on_delete = models.PROTECT, related_name='plant_taxon', blank=True, null=True) part = models.CharField(max_length=100) weight = models.DecimalField(max_digits=10, decimal_places=3) quantity = models.DecimalField(max_digits=10, decimal_places=3) p.s. I know I don't need to use an id, but this connects to an existing database. -
Are Django models tightly coupled with databases?
Are Django Models tightly coupled with databases? I want to create a web application using Django framework, but I don't want to use any database. By this, I mean that my data is stored in the network file system and I have already written python functions to read/write data from/to the file system. How can I go about creating such an application using Django?