Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to filter multiple similar data in python/django?
access I can get all the emails with access_membership but what if I only want to save unique emails(i.e the scenario is I have added an email to access = "tester4@testing.inc" and I can still add "tester4@testing.inc" ) I would like to prevent saving an email that was already added in the database. Is this the right code for that? "Access_Membership.objects.filter(member_email=request.user.email).exists()" how do I use this and where should I put it? views.py def give_access(request, user_pk, arb_pk): arbitration = Arbitration.objects.get(pk=arb_pk) form_kw = {'user':request.user, 'arb_pk':arb_pk} AccessInvitationFormset=inlineformset_factory(Arbitration, Access_Membership, form = AccessMembershipForm, extra=1, can_delete=False) ctx = {'form_url' : reverse("giveaccess", args=[user_pk, arb_pk])} dict = {'mytype': 'access', } snip_tpl = 'app/snippets/new_access_section.html' if request.method == "POST": formset = AccessInvitationFormset(request.POST, form_kwargs=form_kw, prefix="A", instance=arbitration) else: formset = AccessInvitationFormset(queryset = Access_Membership.objects.none(), form_kwargs=form_kw, prefix="A", instance=arbitration) return save_new_members(request, user_pk, arb_pk, formset, ctx, dict, snip_tpl) new_access_section.html {%for tm in arbitration.access_membership_set.all%} <tr> {%if tm.member%} β¦ -
Reuse django form for insert and delete
I'm making a form to add and delete some items form an items Model. The thing is i would like to know if i can use the same form for this. I want to use the form once to add to the database and then, coming from a different url, to be able to choose from a dropdown which items to delete from the database. forms.py for idea: class CategoryForm(forms.ModelForm): def __init__(self, *args, **kwargs): self.current_url = kwargs.pop('current_url') super(CategoryForm,self).__init__(*args,**kwargs) self.helper = FormHelper() self.helper.form_method = 'POST' self.helper.add_input(Submit('submit', 'Submit', css_class='btn-success')) if 'delete' in self.current_url: self.fields['section'].widget = forms.HiddenInput() here i would like to pass the Category objects so they can be shown in the dropdown. something like: self.fields['name'].widget = forms.Select(Category.objects.all()) class Meta: model = Categories fields = '__all__' I don't know what is the best practice for this or how it's usually done. -
Alternate key lookup with Django Rest Framework
I have the following viewset: class ProductViewSet( mixins.RetrieveModelMixin, viewsets.GenericViewSet): ... This provides me with endpoint for fetching a product by ID: /products/{id} I'm trying to add another endpoint for fetching a product with secondary unique key: /products/uuid/{product_uuid} How can I achieve this with DRF? I'm using DRF 3.8.2 and Django 1.11. Is it somehow possible to make @action() decorator provide this? Its basic behaviour does not solve the problem as it only provides urls of pattern /products/{id}/detail or /products/detail. -
Installing Django behind corporate firewall
is there a way to install Django even behind a corporate firewall? I keep getting the following error using pip install: `Could not fetch URL https://pypi.python.org/simple/django/: There as a problem confirming the ssl cerificate: [SSL: CERTIFICATE_VERIFY_FAILED] certificate very failed (_ssl.c:465) - skipping Could not find a version that satisfies the requirement Django==2.0.5 (from versions: ) No matching distributions found for Django==2.0.5` I was able to install this version on my personal computer easily. The machine with the problem is using Pythong 3.52.:: Anaconda 4.2.0 (and no I can't upgrade both of those). -
Django syntaxError when starting django project in virtualenv with python 3
A question very similar to this one already exists, but it is regarding python2. In another related question the user did not activate their virtual environment. I did. After I encountered this problem in a larger project, I tried and succeeded in replicating it on a brand new project. In empty folder test-django, I ran the following: virtualenv env env/scripts/activate pip install django to make sure python had successfully installed django, I tried: python import django No import error was raised, and the version of Python running was Python 3.6.3 (v3.6.3:2c5fed8, Oct 3 2017, 18:11:49) so then I started the project... django-admin startproject test cd test ./manage.py and got File "test-django\test\manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax The contents of manage.py are: #!/usr/bin/env python import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "phoenix2.settings") try: from django.core.management import execute_from_command_line except ImportError as exc: raise 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?" ) from exc execute_from_command_line(sys.argv) when I remove "from exc", the ImportError is raised successfully-- but I shouldn't be getting an ImportError, running from within a virtual environment β¦ -
Display total number of comments related to each object in a list view
I have a view which displays all my posts. Post has foreignkey relation with comment.I want to be able to display the total number of comments related to each post in a listview . Like on facebook feedback one can see the total number of comments on each post display on user activity feed . Model. py class Post(models.Model): name=models.CharField(max_length=230,null=True) text=models.TextArea(null=True) class Comments(models.Model): comment=models.TextArea(null=True) post=models.ForeignKey(Post,related_name="post",null=True,on_delete=model.CASCADE) View.py def PostListView(request): #getting all post objects allpost=Post.objects.all() #getting all comments allcomments=Comments.objects.all() template_name="post.html" context={'allpost':allpost,'allcomments':allcomments} return render(request,template_name,context) def PostDetail(request,slug): postinstance=get_object_or_404(Post,slug) #getting comments for this post comments_for_post=Comments.objects.all().filter(post=postinstance) #get the total count for comments for post commentcount=comments_for_post.count() In Listview i want to be able to display the total number of comments related for each post . In list view template i want something like this {% for post in allpost %} {{post.name}} #get total number of comments for each post {{commentcount}} {% endfor %} Note I have no problem displaying the total number of comments for a post in DetailView . Please i need help in handling this query -
django href url with parameter throwing error
I have the following setup for a simple href download page: urls.py url(r'^fileformaterror/download/(?P<s3_key>.*)$', FileFormatErrorDownloadView.as_view(), name='file-format-error-download') template.html: <a href="{% url 'file-format-error-download' s3_key=file.s3_key %}" target="_blank">Download</a> views.py: class FileFormatErrorDownloadView(View): def get(self, request, s3_key): pass But when executing I get the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'file-format-error-download' not found. 'file-format-error-download' is not a valid view function or pattern name. -
Enable markdown to render text submitted from a form
When employ the bootstrap in Django to format the form, it display nicely. {% for entry in entries %} <div class="panel panel-default"> <div class="panel-heading"> <h3> {{ entry.date_added|date:"M d, Y H:i"}} <small> <a href="{% url 'learning_logs:edit_entry' entry.id %}"> edit entry</a> </small> </h3> </div> <div class="panel-body"> {{ entry.text|linebreaks}} </div> </div> <!-- panel --> However, it can only render my submitted data in plain text like: How to enable markdown to render the text in Django? -
Update Nested Serializers Correctly in Django Rest Framework
I am using django rest framework I am trying to implement an update method to a nested serializer. How do I implement an update method to nested serializer correctly? I'm trying to update an existing employee but I get the following response: { "user": { "username": [ "A user with that username already exists." ] } } I have implemented an update method on the serializers just to update the user fields. class EmployeeUpdateSerializer(serializers.ModelSerializer): user = UserSerializer() contract_type = ContractSerializer(read_only=True) company = CompanySerializer(read_only=True) job_title = JobSerializer(read_only=True) department = DepartmentSerializer(read_only=True) skill = SkillSerializer(read_only=True) unit = UnitSerializer(read_only=True) class Meta: model = Employee fields = ['id', 'user', 'hr_number', 'nssf_no', 'nhif_no', 'induction_date', 'induction_date', 'contract_type', 'company', 'tax_id_number', 'joining_date', 'job_title', 'skill', 'unit', 'department', 'identification_number', 'is_manager', 'active'] def update(self, instance, validated_data): user = validated_data.get('user') instance.user.first_name = user.get('first_name') instance.user.save() return instance Then in the views I have implemented the following: class EmployeeDetailView(APIView): permission_classes = [AllowAny] # queryset = Employee.objects.all() serializer_class = EmployeeUpdateSerializer """ Retrieve, update or delete a employee instance. """ def get(self, request, pk, format=None): try: employee = Employee.objects.get(pk=pk) except Employee.DoesNotExist: raise Http404 serializer = EmployeeUpdateSerializer(employee) return Response(serializer.data, status=status.HTTP_200_OK) def put(self, request, pk, format=None): try: employee = Employee.objects.get(pk=pk) serializer = EmployeeUpdateSerializer( employee, data=request.data) except Employee.DoesNotExist: raise Http404 β¦ -
Longclaw Client JS Missing
When I tried adding the variants via {% add_to_basket_btn variant.id btn_text="Add To Basket" btn_class="btn btn-default" %}, the console logs Loading failed for the <script> with source βhttp://localhost:8000/static/longclawcore/js/vendors.bundle.jsβ. example-product2:189 Loading failed for the <script> with source βhttp://localhost:8000/static/longclawcore/js/longclawclient.bundle.jsβ. example-product2:192 Loading failed for the <script> with source βhttp://localhost:8000/static/longclawcore/js/longclawclient.bundle.jsβ. What should I do to fix this error? -
radio buttons and filter in Django
Django==1.11 I want to create a filter in a task app it will a radio button - my task or me task and displayed will be all tasks. tasks_list = Task.objects.all().filter( Q(executive_man=request.user) | Q(author=request.user)).order_by( '-created_date') The code show all task. executive_man=request.user - if first button, author=request.user - the second button. And I do not understand how it to do. I now read http://django-filter.readthedocs.io/en/master/index.html but if I right to understand the library use our models, right? But me not need the models. I know ORM and know how to show the data in HTML. form = WhoTask(request.POST or None) if form.is_valid(): who = form.cleaned_data['tasks'] if who == 'me': tasks_who = tasks_list.filter(executive_man=request.user) return render(request, 'task/task_list.html', {'filter_category': tasks_filter, 'form': form, 'task_who': tasks_who}) elif who == 'my': tasks_who = tasks_list.filter(author=request.user) return render(request, 'task/task_list.html', {'filter_category': tasks_filter, 'form': form, 'task_who': tasks_who}) else: pass return render(request, 'task/task_list.html', {'filter_category': tasks_filter, 'form': form}) This views without django-filter library but I don't see data in HTML, I think the error in return because if I print who I see a selection in the terminal. I hope you will help me to understand how to implement the filter. Thank you very much. -
Attribute Error object has no attribute 'cleaned_data'
I am trying to implement taking multiple values from multiple range sliders from my HTML. I will be passing for seven values from sliders and I would like to use them for my own purpose although I am receiving no attribute cleaned_data I have done the same with three values it is working fine. Am I doing something wrong here? Thanks in advance. Forms.py class p_d_q_s(forms.Form): p = forms.IntegerField() d = forms.IntegerField() q = forms.IntegerField() P = forms.IntegerField() D = forms.IntegerField() Q = forms.IntegerField() s = forms.IntegerField() Views.py def sarimax_manual(request): template_name = 'polls/SARIMAX_man.html' if request.method == "POST": p = p_d_q(request.POST) d = p_d_q(request.POST) q = p_d_q(request.POST) P = p_d_q_s(request.POST) D = p_d_q_s(request.POST) Q = p_d_q_s(request.POST) s = p_d_q_s(request.POST) if p.is_valid() and d.is_valid() and q.is_valid() and a.is_valid() and b.is_valid and c.is_valid() and s.is_valid(): p = p.cleaned_data['p'] d = d.cleaned_data['d'] q = q.cleaned_data['q'] P = P.cleaned_data['P'] D = D.cleaned_data['D'] Q = Q.cleaned_data['Q'] s = s.cleaned_data['s'] output = {'P': P, 'Q':Q, 'D':D, 's':s} return render(request, template_name , output) return render(request, template_name , ) My html code is something like: <form method = "POST"> <p style="width: 400px"> p value <input type="range" name="p" id="pInputId" value="0" min="0" max="10" oninput="pOutputId.value = pInputId.value"> <output name="pOutputName" id="pOutputId">0</output> <br> d β¦ -
Mysql Install, django
I've downloaded the 2nd file (x86, 64 bit) from this link (Linux - Generic (glibc 2.12) (x86, 64-bit), Compressed TAR Archive) How do i install it on Kali linux? I found out how to install it on windows but not on Linux. For Linux, I've found outdated explanations. But when i looked through the website, i couldn't find any details for the newer versions This is the first time I'm using mysql on kali linux.. Could someone also tell me how to integrate it with my project on Django? I've been using sqlite to make my project.. How do i migrate to MysSQL keeping all the data as is? Also how do i upload my Django Program onto a server (Client already has their own server. so i dont need to use any services to upload. I've read that its a lengthier process but I'll still have to do it because i dont have any option) Thanks in Advance! -
Django: How to tell Django where it should look for apps?
After reading Two Scoops of Django 1.11, I changed my project's structure like this: myname_project βββ config/ β βββ settings/ β β βββ base.py β β βββ local.py β β βββ staging.py β β βββ prod.py β βββ __init__.py β βββ urls.py β βββ wsgi.py βββ docs/ βββ myname/ β βββ accounts/ # App β βββ blog/ # App β βββ core/ # App β βββ media/ # Development only! β βββ static/ β βββ templates/ βββ .gitignore βββ Makefile βββ README.md βββ manage.py βββ requirements/ My problem is now, that Django doesn't find the app anymore. Here is a gist of how my settings files look: import os from pathlib import Path from django.core.exceptions import ImproperlyConfigured def get_env_variable(var_name): """Get the environment variable or return exception.""" try: return os.environ[var_name] except KeyError: error_msg = 'Set the {} environment variable'.format(var_name) raise ImproperlyConfigured(error_msg) # Build paths inside the project like this: BASE_DIR / 'media' BASE_DIR = Path(__file__).resolve().parent.parent PROJECT_ROOT = BASE_DIR.parent / 'myname' INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... 'accounts', 'blog', 'core', ] ... ROOT_URLCONF = 'config.urls' ... The problem is now, when I run python manage.py makemigrations --settings=config.settings.local I get the error: ModuleNotFoundError: No module named 'accounts'. So Django β¦ -
{{ form }} in html file is not being renderd
views.py from django.http import HttpResponse from django.shortcuts import render,redirect from django.contrib.auth.forms import UserCreationForm from tutorial import views from accounts.form import Registrationform,EditProfileForm from django.contrib.auth.forms import UserChangeForm,PasswordChangeForm from django.contrib.auth.models import User from django.contrib.auth import update_session_auth_hash from django.contrib.auth.decorators import login_required from django.views.generic import TemplateView from .forms import HomeForm class HomeView(TemplateView): def get(self,request): form = HomeForm(request.get) return render(request, 'accounts/home.html', {'form': form}) @login_required def home(request): numbers=[1,2,3,4,5] name="jay" args={'myName':name} return render(request,'accounts/home.html',args) def register(request): if request.method == "POST": form = Registrationform(request.POST) if form.is_valid(): form.save() return redirect('/accounts') else: return HttpResponse('please fill all the fields and make sure new password must be match') else: form = Registrationform() args={'form' : form} return render(request,'accounts/reg_form.html',args) @login_required def view_profile(request): args = {'user' : request.user} return render(request,'accounts/profile.html',args) @login_required def edit_profile(request): if request.user.is_authenticated(): #<p>Welcome, {{ user.username }}. Thanks for logging in.</p> if request.method=="POST": form = EditProfileForm(request.POST,instance=request.user) if form.is_valid(): form.save() return redirect('/accounts/profile') else: return HttpResponse("please go back and write correct vaues") else: form = EditProfileForm(instance=request.user) args = {'form' : form} return render(request,'accounts/edit_profile.html',args) else: HttpResponse("hllo") return redirect('/accounts/login') @login_required def change_password(request): if request.user.is_authenticated(): if request.method == "POST": form = PasswordChangeForm(data=request.POST,user=request.user) if form.is_valid(): form.save() update_session_auth_hash(request, form.user) return redirect('/accounts/profile') else: return HttpResponse("password does not match,go back and try again") else: form = PasswordChangeForm(user=request.user) args = {'form' : form} return render(request,'accounts/change_password.html',args) β¦ -
Run command only once after Django app startup
I have a django-based function that needs to be run only once in Django, when the app boots up. The tricky part is that: The code in question heavily uses django ORM, so apps have to be ready at that point, The code should run only once - e.g. not once per every worker, but exactly once per "website" (regardless of whether it's deployed via gunicorn with a dozen of workers, or run locally via the built-in development web-server), The code should only run once the app boots, but NOT by running other management commands. The code can take a while to complete, and I don't want it to trigger each time I run makemigrations or shell. I could, theoretically, just introduce a locking mechanism and let it run somewhere in AppConfig.ready() method, but that would still run in all management commands as well. Since the app is packaged in Docker, I've been also thinking about simply wrapping the code in a separate management command and running it in the entrypoint, just before the app is being started. That seems to do the trick, but it will be done automatically only in that particular container - if somebody runs a β¦ -
Django swagger special character escape documentation
I use django and swagger. I write doc string in my django function like this : /?first_name__icontains=saeed&age__gte=20. But swagger show them like this how can i escape characters like & in django and swagger? -
products.FuelType.none is returned cascaded dependent dropdown when fetching model object in template - Django
models.py class Car(models.Model): Car_Name = models.CharField(max_length=40) Car_Details = models.TextField() Car_Price = models.PositiveIntegerField() Car_Brand = models.ForeignKey('Brand', on_delete=models.CASCADE) Fuel_type = models.ManyToManyField('FuelType') def __str__(self): return self.Car_Name def get_absolute_url(self): return reverse('car_detail', args=[str(self.pk)]) class FuelType(models.Model): Fuel_Choices = ( ('Petrol','petrol'), ('Diesel','diesel'), ('CNG','cng') ) Fuel_Variant = models.CharField(max_length=10, choices=Fuel_Choices, default='1') def __str__(self): return self.Fuel_Variant forms.py class AjaxModelChoiceField(forms.ModelChoiceField): def __init__(self, model_class, *args, **kwargs): queryset = model_class.objects.none() super(AjaxModelChoiceField, self).__init__(queryset, *args, **kwargs) self.model_class = model_class def to_python(self, value): if value in self.empty_values: return None try: key = self.to_field_name or 'pk' value = self.model_class.objects.get(**{key: value}) except (ValueError, self.queryset.model.DoesNotExist): raise ValidationError(self.error_messages['invalid_choice'], code='invalid_choice') return value # a Custom Choicefield to populate Dropdown on Selection (let's ajax works) class SearchCarForm(forms.ModelForm): Car_Brand = forms.ModelChoiceField(queryset=Brand.objects.all(), widget=forms.Select(attrs={'class':'form-control'}), empty_label="Select Brand") Car_Name = AjaxModelChoiceField(model_class=Car, widget=forms.Select(attrs={'class':'form-control'}), empty_label="Car Models", required=False) Fuel_type = AjaxModelChoiceField(model_class=FuelType, widget=forms.Select(attrs={'class':'form-control'}), empty_label="Fuel Options", required=False) class Meta: model = Car fields = ('Car_Brand', 'Car_Name', 'Fuel_type') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['Car_Name'].queryset = Car.objects.all() if 'Brand' in self.data: try: brand_id = int(self.data.get('Car_Brand')) self.fields['Car_Name'].queryset = Car.objects.filter(Car_Brand_id=brand_id).order_by('Car_Name') except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty Car queryset elif self.instance.pk: self.fields['Car_Name'].queryset = self.instance.Brand.Car_set.order_by('Car_Name') self.fields['Fuel_type'].queryset = FuelType.objects.all() if 'Car' in self.data: try: Car_id = int(self.data.get('Car_Name')) self.fields['Fuel_type'].queryset = FuelType.objects.filter(id=car_id).order_by('Fuel_type') except (ValueError, TypeError): pass # invalid input from the β¦ -
Heroku exit when running gunicorn locally
I get the message to add "0.0.0.0" to ALLOWHOST when issue heroku command $ heroku local [WARN] No ENV file found 14:32:50 web.1 | [2018-05-16 14:32:50 +0800] [21796] [INFO] Starting gunicorn 19.8.1 14:32:50 web.1 | [2018-05-16 14:32:50 +0800] [21796] [INFO] Listening at: http://0.0.0.0:5000 (21796) 14:32:50 web.1 | [2018-05-16 14:32:50 +0800] [21796] [INFO] Using worker: sync 14:32:50 web.1 | [2018-05-16 14:32:50 +0800] [21799] [INFO] Booting worker with pid: 21799 14:34:39 web.1 | Invalid HTTP_HOST header: '0.0.0.0:5000'. You may need to add '0.0.0.0' to ALLOWED_HOSTS. Follows the instruction to configure the setting: ALLOWED_HOSTS = ["0.0.0.0"] When run `heroku local' again $ heroku local [WARN] No ENV file found 14:50:11 web.1 | [2018-05-16 14:50:11 +0800] [23319] [INFO] Starting gunicorn 19.8.1 ... Can't connect to ('0.0.0.0', 5000) 14:50:16 web.1 Exited with exit code 1 It constantly exit. $ heroku local Procfile [WARN] No ENV file found [WARN] Required Key 'Procfile' Does Not Exist in Procfile Definition How to solve the problem? -
504 error when the view loading takes more than 5 s
I've got an installation with django-nginx-gunicorn-supervisor-postgresql. In the django admin I've got a 504 if the loading of the view takes more than around 5 seconds. For instance, if I filter a changelist view with many records and takes more than that time the 504 appears. The same view with less records works, as long as it takes less time. I've noticed also that some views are still running in background, even after the 504, cause I can see the modifications they make in database after they finish. I've tried to increase all timeouts I've found (nginx, gunicorn), but none of them were configured to 5 seconds. Any guess of what could be misconfigured? Or where could be the timeout that raises the 504? Thanks -
Django tests have started failing after adding Wagtail objects
I'm using regular Django tests for my Django models, using ./manage.py test non_wagtail_app_name but all of sudden (and after adding some Wagtail models), I can't run them: Creating test database for alias 'default'... Traceback (most recent call last): File "./manage.py", line 12, in <module> execute_from_command_line(sys.argv) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/commands/test.py", line 29, in run_from_argv super(Command, self).run_from_argv(argv) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/commands/test.py", line 62, in handle failures = test_runner.run_tests(test_labels) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/test/runner.py", line 601, in run_tests old_config = self.setup_databases() File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/test/runner.py", line 546, in setup_databases self.parallel, **kwargs File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/test/utils.py", line 187, in setup_databases serialize=connection.settings_dict.get('TEST', {}).get('SERIALIZE', True), File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/backends/base/creation.py", line 69, in create_test_db run_syncdb=True, File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/__init__.py", line 131, in call_command return command.execute(*args, **defaults) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle fake_initial=fake_initial, File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/home/fleon/development/virmyasb/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", β¦ -
How to monitor django urls using prometheus plateform
How can we Configure Prometheus in Django project, so that we can monitor metrics from prometheus_client. -
Django Send variable from model in an email
I Have a django function that bans users and adds them to a Banned_User table, which has a profile and reason_reported column to mark them as banned. I'm looking to send an email to the user,once banned with a list of reasons from the report_reasons field as to why they have been banned. def banning_users(self, request, queryset): for obj in queryset: if hasattr(obj, 'user'): # This object is a Profile, so lookup the user profile = obj user = obj.user user.is_active = False user.save() banned_reasons = [] banned_user = profile.banned_profile.create(profile=profile) reports = banned_user.profile.user_reported_report.all() banned_user.save() for report in reports: banned_user.report_reason.add(report) # Send the email subject = 'Ban' message = 'You have been banned for the following reasons: []' email_from = settings.EMAIL_HOST_USER recipient_list = [user.email] send_mail( subject, message,email_from, recipient_list) self.message_user(request, "User is banned and Email has been sent") -
Django : How to upload csv file in unit test case using APIClient
I would like to write a unit test for a view on a Django REST Framework application. The test should upload a CSV file using the POST. @staticmethod def _file_upload(client, string, args, file_name): base_path = os.path.dirname(os.path.realpath(__file__)) with open(base_path + file_name, 'rb') as data: data = { 'file': data } response = client.post(reverse(string, args=[args]), data, format = "multipart") return response.status_code, response.data The above code I used which obviously doesn't work it shows the following error Missing filename. Request should include a Content-Disposition header with a filename parameter. The following code is the one that I want to test via unit testing. class ChartOfAccounts(views.APIView): parser_classes = (JSONParser, FileUploadParser) def post(self, request, pk, *args, **kwargs): request.FILES['file'].seek(0) csv_data = CSVUtils.format_request_csv(request.FILES['file']) try: coa_data = CSVUtils.process_chart_of_accounts_csv(company, csv_data) serializer = CoASerializer(coa_data, many=True) if len(serializer.data) > 0: return Utils.dispatch_success(request, serializer.data) except Exception as e: error = ["%s" % e] return Utils.dispatch_failure(request, 'DATA_PARSING_ISSUE', error) Any help regarding this is welcome. Thanks in advance -
Import Error in armbian
It was working fine at first but when reinstalled to verify my process I get this error, all the requirements have been confirmed, and I have not changed the path of any file, kindly guide. Traceback (most recent call last): File "src/gevent/greenlet.py", line 705, in gevent._greenlet.Greenlet.run File "/home/tinker/a/BEMOSS/volttron/platform/auth.py", line 147, in zap_loop time = gevent.core.time AttributeError: 'module' object has no attribute 'core' 2018-05-16T05:19:17Z <Greenlet "Greenlet-0" at 0xb436e360L: <bound method AuthService.zap_loop of <volttron.platform.auth.AuthService object at 0xb4371b30>>(<volttron.platform.vip.agent.core.Core object at 0)> failed with AttributeError 2018-05-16 05:19:17,340 () volttron.platform.main DEBUG: In-process VIP router bound to inproc://vip 2018-05-16 05:19:17,341 () volttron.platform.main DEBUG: Local VIP router bound to ipc://@/home/tinker/.volttron/run/vip.socket?domain=vip#bdc8ff59-e99b-4629-b6b7-df00ffc8cc44 2018-05-16 05:19:17,441 () volttron.platform.main DEBUG: protected topics file /home/tinker/.volttron/protected_topics.json 2018-05-16 05:19:17,497 () volttron.platform.main INFO: loading protected-topics file /home/tinker/.volttron/protected_topics.json 2018-05-16 05:19:17,498 () volttron.platform.main INFO: protected-topics file /home/tinker/.volttron/protected_topics.json loaded 2018-05-16 05:19:17,503 () volttron.platform.web INFO: Web server not started. 2018-05-16 05:19:17,505 () volttron.platform.vip.agent.core ERROR: unhandled exception in periodic callback Traceback (most recent call last): File "/home/tinker/a/BEMOSS/volttron/platform/vip/agent/core.py", line 124, in _loop method(*self.args, **self.kwargs) File "/home/tinker/a/BEMOSS/volttron/platform/vip/agent/subsystems/heartbeat.py", line 160, in publish self.pubsub().publish('pubsub', topic, headers, message) File "/home/tinker/a/BEMOSS/volttron/platform/vip/agent/subsystems/pubsub.py", line 396, in publish message=message, bus=bus) File "/home/tinker/a/BMEOSS/volttron/platform/vip/agent/subsystems/rpc.py", line 303, in call request, result = self._dispatcher.call(method, args, kwargs) File "/home/tinker/a/BEMOSS/volttron/platform/vip/agent/subsystems/rpc.py", line 115, in call result = β¦