Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Flask socketServer error on request - python 3.8
I am setting up a python flask for API service. But getting an error on request. I am using python version 3.8 Here is my manager.py import unittest import time from app import app, manager @manager.command def run(): """Run the app.""" app.run(host='0.0.0.0') if __name__ == '__main__': manager.run() I run the command python manager.py run it's showing: $ python manage.py run * Serving Flask app "app" (lazy loading) * Environment: production WARNING: Do not use the development server in a production environment. Use a production WSGI server instead. * Debug mode: on But when I hit a request through route then its showing errors : ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 50776) ---------------------------------------- Exception happened during processing of request from ('127.0.0.1', 50778) Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/socketserver.py", line 720, in __init__ self.handle() File "/Users/selim.bongo/Sites/python/digital-agency-ms/venv/lib/python3.8/site-packages/werkzeug/serving.py", line 327, in handle rv = BaseHTTPRequestHandler.handle(self) File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/server.py", line 425, in handle self.handle_one_request() File "/Users/selim.bongo/Sites/python/digital-agency-ms/venv/lib/python3.8/site-packages/werkzeug/serving.py", line 361, in handle_one_request elif self.parse_request(): File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/server.py", line 351, in parse_request conntype = self.headers.get('Connection', "") AttributeError: module 'http.client' has no attribute 'get' ---------------------------------------- Suggest a way to fix β¦ -
Assign request.user when saving form clashes with admin panel?
I've got a formset that I'm trying to save, and I'd like for the newly created form to be automatically assigned to the user (request.user). In my models Meta class, I added this: forms.py class Meta: model = Timesheet # fields = "__all__" exclude = ("user", ) and then in views.py class TimesheetCreateView(View): object = None def post(self, request, *args, **kwargs): form = TimesheetModelForm(request.POST) if form.is_valid(): self.object = form.save(commit=False) self.object.user = request.user self.object.save() success_url = reverse("timesheets:current-week", args=(self.object.year, self.object.week)) else: # Warning: Silent form error print(form.errors) success_url = reverse("timesheets:default-current-week") return HttpResponseRedirect(success_url) This works fine, however - if I now go into the admin panel - the dropdown field for user (foreign key) is gone as well. Is there to show all fields in the admin panel, but automatically use the request.user in the template? I tried using fields = "__all" and using the same logic in my views.py file, but I'm getting a form error screaming about "user is required" - I don't want the user have a dropdown menu showing all available users. If I add this in forms.py def __init__(self, user, *args, **kwargs): super(TimesheetModelForm, self).__init__(*args, **kwargs) self.fields['user'].queryset = User.objects.filter(id=user.id) # show logged in user in dropdown The dropdown correctly β¦ -
Error while trying to run dsample project with django
I am getting the following error while trying to run a project in django. I have installed it in the virtual environment. (venv) D:\djEnv\t2>python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "c:\programdata\anaconda3\Lib\threading.py", line 926, in _bootstrap_inner self.run() File "c:\programdata\anaconda3\Lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "D:\djEnv\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\djEnv\venv\lib\site-packages\django\core\management\commands\runserver.py", line 109, in inner_run autoreload.raise_last_exception() File "D:\djEnv\venv\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "D:\djEnv\venv\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "D:\djEnv\venv\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "D:\djEnv\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "D:\djEnv\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "D:\djEnv\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "D:\djEnv\venv\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "D:\djEnv\venv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "D:\djEnv\venv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "D:\djEnv\venv\lib\site-packages\django\db\models\base.py", line 121, in __new__ new_class.add_to_class('_meta', Options(meta, app_label)) File "D:\djEnv\venv\lib\site-packages\django\db\models\base.py", line β¦ -
Saving image fails without error in django model form
I want to try to save an image to my model: def user_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/user_<id>/<filename> return 'user_{0}/{1}'.format(instance.user.id, filename) class Leverandor(models.Model): ID = models.AutoField(primary_key=True) UserID = models.ForeignKey('Stamdata', on_delete=models.CASCADE) Name = models.CharField('Name', max_length=200) URL = models.URLField('URL', max_length=200) ImageURL = models.ImageField('ImageURL',blank=True, null=True, upload_to=user_directory_path) To this Form.py: class EditLeverandorForm(forms.ModelForm): Name = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) URL = forms.URLField(widget=forms.TextInput(attrs={'class': 'form-control', 'autofocus': True})) ImageURL = forms.ImageField class Meta: model = Leverandor labels = { 'Name' : 'LeverandΓΈr', 'URL' : 'Webside', 'ImageURL' : 'Logo', } fields = ['UserID', 'Name', 'URL', 'ImageURL'] And rendererd to this view.py def add_leverandorer(request): user_id = request.user.id # if this is a POST request we need to process the form data if request.method == 'POST': print (user_id) form = EditLeverandorForm(request.POST, request.FILES, instance=request.user) if form.is_valid(): form.save() return HttpResponseRedirect('/backend/leverandorer') else: print ('somethin goes wrong') print (user_id) form = EditLeverandorForm() return render( request, 'backend/add_leverandorer.html', { 'title':'WestcoastShop - Backend', 'form': form, } ) The problem is that before I add the instance=request.user part its saves the entry correct but without image. Now I add the part from Django documentation like provided for save to an variable path but nothing happened after i click to save button. <form action="/backend/leverandorer/add" method="post" enctype="multipart/form-data"> {% β¦ -
Django REST Framework filter backend with multiple value?
I want to get query list with one key more values. For example, http://127.0.0.1:8000/management/device/model/list/?device_type=1&hardware_model_mother=master&hardware_model_mother=MasterModel1&hardware_model_child=SlaveModel1 Then i can get query list of device_type=1,hardware_model_child=SlaveModel1,hardware_model_mother=master and device_type=1,hardware_model_child=SlaveModel1,hardware_model_mother=MasterModel1γ I found some filters in django-filter's doc, here's the link: https://django-filter.readthedocs.io/en/latest/ref/filters.html I choose MultipleChoiceFilter, it will use OR, that's what i wanted. Here's my filter's code: from django_filters import FilterSet, MultipleChoiceFilter from Device_set.views.DeviceModelFilter import DeviceModelFilter from .head import * # one key for multiple values class DeviceModelFilter(FilterSet): MOTHER_CHOICES, CHILD_CHOICES = DeviceModelFilter().MyChoices() hardware_model_mother = MultipleChoiceFilter(choices=MOTHER_CHOICES) hardware_model_child = MultipleChoiceFilter(choices=CHILD_CHOICES) class Meta: model = device_model fields = ['hardware_model_mother', 'hardware_model_child'] and my ListAPIView: class DeviceModelListView(ListAPIView): permission_classes = [Developer | IOTWatch | IsAdminUser] serializer_class = DeviceModelListSerializer queryset = device_model.objects.all() filter_backends = (SearchFilter, DjangoFilterBackend,) filter_class = DeviceModelFilter search_fields = ('id', 'name') filterset_fields = ('hardware_model_mother', 'hardware_model_child') def list(self, request, *args, **kwargs): dtype = self.request.query_params.get('device_type') if dtype is not None: queryset = self.queryset.filter(device_type__icontains=dtype) else: queryset = self.queryset queryset = self.filter_queryset(queryset) page = self.paginate_queryset(queryset) if page is not None: serializer = self.get_serializer(page, many=True) return self.get_paginated_response(serializer.data) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) def get(self, request, *args, **kwargs): return Response(Return_msg(self.list(request))) when url is http://127.0.0.1:8000/management/device/model/list/?device_type=1&hardware_model_mother=master&hardware_model_mother=MasterModel1 The result is right: right response However, when url is http://127.0.0.1:8000/management/device/model/list/?device_type=1&hardware_model_child=SlaveModel1 It's wrong: false Traceback: Traceback It cost me about one day to β¦ -
Django rest framework post item to db
I'm working on my school project and I'm totally stuck. I'm newbie on django. Trying to create an nmap reporter api. I have an JSON data with nested object. I need to save this JSON data to my database. But I cant. My data is this: [ { "host": "192.168.1.8", "hostname": "", "hostname_type": "", "state": "open", "service": [ { "name": "http", "port": "80", "product": "Apache httpd", "version": "2.2.8", "extrainfo": "(Ubuntu) DAV/2", "vulnerabilities": [ {"name":"CVE Example","version":"2.42"}, {"name":"CVE Example","version":"2.42"}, {"name":"CVE Example","version":"2.42"}, ] } ] } ] But my saved data is: [ { "host": "192.168.1.8", "hostname": "", "hostname_type": "", "state": "open", "service": [ { "name": "http", "port": "80", "product": "Apache httpd", "version": "2.2.8", "extrainfo": "(Ubuntu) DAV/2", "vulnerabilities": [] } ] } ] Can anyone help me?Thanks. My models and serializers: I have 3 models for this. class Service(models.Model): class Meta: db_table = 'tblService' result = models.ForeignKey(Result, on_delete=models.CASCADE, related_name='service') name = models.CharField(max_length=50, blank=True) port = models.CharField(max_length=50, blank=True) product = models.CharField(max_length=50, blank=True) version = models.CharField(max_length=50, blank=True) extrainfo = models.CharField(max_length=50, blank=True) This is service model for service section on JSON. class Vulnerability(models.Model): class Meta: db_table = 'tblVulnerability' Service = models.ForeignKey(Service, on_delete=models.CASCADE) name = models.CharField(max_length=255) priority = models.CharField(max_length=255) version = models.CharField(max_length=255) url = models.TextField() This model β¦ -
Django - How to add multiple instances of the same model in a field
I have a class that looks like this. In the pack items I want to have the number of that instance of Item and how many of that as a number. class Item(models.Model): title = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=10) is_pack = models.BooleanField(default=False) pack_items = models.ManyToManyField(PackItem, blank=True) class PackItem(models.Model): packitem = models.ForeignKey('Item', on_delete=models.CASCADE) quantity = models.IntegerField(default=1) This seems to work but every time I create a new pack in the admin, I have to create first, one by one, each PackItem and then put them in the packitems field of Item. The goal is: I have bottles of drinks as Items and I want to have pre-made Packs of these drinks. Would my way of doing it cause problems later on? Is there a better practice? Or is this already wrong? -
How to remove ASCII values in Python Flask Template
How to avoid assertion error in render template in Python Flask? @app.route("/") def hello(): return render_template("index.html",ans="Hello World!!! I've run my first Flask application.") Although in index.html, I got the correct output, my test case is failing with the below error. I created templates folder and placed index.html in that. My only concern is how to remove ASCII-'I've' in Unit test execution Error Message: self.assertIn(b"Hello World!!! I've run my first Flask application.", response.data) AssertionError: b"Hello World!!! I've run my first Flask application." not found in b'Hello World!!! I&#39;ve run my first Flask application.' -
How to filter relationships based on their fields in response using Django REST Framework
I have three models: House, Resident, Car. Each House has many Residents (One to Many). Each Resident has 0 or 1 cars (One to One). For my frontend, I want to display all the residents of a house that have a car. Django Rest Framework suggests using Filtering, but this only works at the top level. For example, in my HouseDetailView(generics.RetrieveAPIView), I can only modify the queryset of the House model itself. I want to be able to modify the queryset of the Resident (resident_queryset.exclude(car=None)). class HouseDetailView(generics.RetrieveAPIView): queryset = House.objects.all() serializer_class = HouseSerializer Can/Should I do this all in one request? Are query parameters my only way of filtering? -
can not insert an embedded document into a model using django
I can't create an embedded document into a model using django, i'm using djongo as my database.It keeps telling me that my value must be an instance of Model:<class 'django.db.models.base.Model'> even though I have created all the fields in the model. I really need some help.... my model: class SMSHistory(models.Model): ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True) SoDienThoai = models.CharField(max_length=100,null=True,blank=True) SeriNo = models.CharField(max_length=100,null=True,blank=True) Count = models.IntegerField(default=0,null=True,blank=True) class WebHistory(models.Model): ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True) DiaChiIP = models.CharField(max_length=100,null=True,blank=True) SoDienThoai = models.CharField(max_length=100,null=True,blank=True) SeriNo = models.CharField(max_length=100,null=True,blank=True) Count = models.IntegerField(default=0,null=True,blank=True) class AppHistory(models.Model): ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True) DiaChiIP = models.CharField(max_length=100,null=True,blank=True) SoDienThoai = models.CharField(max_length=100,null=True,blank=True) SeriNo = models.CharField(max_length=100,null=True,blank=True) Count = models.IntegerField(default=0,null=True,blank=True) class CallHistory(models.Model): ThoiGian = models.DateField(default=datetime.date.today,null=True,blank=True) SoDienThoai = models.CharField(max_length=100,null=True,blank=True) SeriNo = models.CharField(max_length=100,null=True,blank=True) Count = models.IntegerField(default=0,null=True,blank=True) class History(models.Model): MaTem = models.CharField(max_length=100,null=True,blank=True) MaSP = models.CharField(max_length=100,null=True,blank=True) SMS = models.EmbeddedModelField( model_container = SMSHistory ) App = models.EmbeddedModelField( model_container = AppHistory ) Web = models.EmbeddedModelField( model_container = WebHistory ) Call = models.EmbeddedModelField( model_container = CallHistory ) my views class check(View): def get(self,request): return render(request,'website/main.html') def post(self,request): matem=request.POST.get('txtCheck') print(matem) temp=khotemact.objects.filter(MaTem=matem) print(temp[0]) tim=History.objects.filter(MaTem=temp[0].MaTem) if len(tim)==0: print('khong co') them=History.objects.create(MaTem=temp[0].MaTem,MaSP='123', SMS={'ThoiGian':'2010-1-1','SoDienThoai':'12324','SeriNo':'12343','Count':0}, App={'ThoiGian':'2010-1-1','DiaChiIP':'1','SoDienThoai':'12324','SeriNo':'1236','Count':0}, Web={'ThoiGian':'2010-1-1','DiaChiIP':'1','SoDienThoai':'12324','SeriNo':'1236','Count':0}, Call={'ThoiGian':'2010-1-1','SoDienThoai':'1233','SeriNo':'123','Count':0} ) them.save() else: print('co') # History.objects.filter(MaTem=temp[0].MaTem).update(Web={'Count':Count+1}) return HttpResponse('oke') i received an error like this ValueError at /website/check/ Value: {'ThoiGian': '2010-1-1', 'SoDienThoai': '12324', 'SeriNo': '12343', 'Count': 0} must be instance of β¦ -
How to count sub-categories in Django?
I have a Model called Topic and Problem: class Topic(models.Model): name = models.CharField(max_length = 250, unique = True) slug = models.CharField(max_length = 250, unique = True) class Meta: ordering = ('name',) verbose_name = 'Topic' verbose_name_plural = 'Topics' def get_url(self): return reverse('problemdirectory', args = [self.slug]) def __str__(self): return self.name class Problem(models.Model): slug = models.CharField(max_length = 250, unique = True) topic = models.ForeignKey(Topic, on_delete = models.CASCADE) questionToProblem = models.TextField() solutionToProblem = models.TextField() class Meta: ordering = ('questionToProblem',) def get_url(self): return reverse('solution_details', args = [self.topic.slug, self.slug]) def __str__(self): return self.questionToProblem Topic is like a "folder", or category to Problem. How would I count the number of problems a certain Topic has in views.py and reference it in the HTML template?: def topicList(request): topics = Topic.objects.all() #numberOfProblems = Problem.objects.count() Problem.objects.filter(topic__name= topic).count() topics.order_by('name') return render(request, 'topiclist.html', {'topics': topics}) I have tried importing Q and filter() with no success so far. -
Django negated Q model not generating expected query
I have a Django template that contains a set of buttons that pass parameters back to Django based on their activation state using some simple JS. The value passed back in the URL is just the string "Yes". Whenever this value is passed back I want to search for all objects within the model that have a non-null value for that particular field (since the id of the button is actually the string version of the corresponding column in the database and this is why I'm using dictionary unpacking to pass values to the Q model as seen below). The code for this is as follows: for query_obj in data_type_fieldnames+tax_fieldnames: if request.GET.get(query_obj, '') == "Yes": options[query_obj] = None queries = Q() query_list = [] for key in options: query_list.append((~Q(**{key: options[key]}))) queries &= (~Q(**{key: options[key]})) print(query_list) Now suppose I select 4 buttons on the page and submit this button-based form, this is the value of query_list I get back [<Q: (NOT (AND: ('dissimilarity_id', None)))>, <Q: (NOT (AND: ('cartesian_id', None)))>, <Q: (NOT (AND: ('multi_level_id', None)))>, <Q: (NOT (AND: ('stability_id', None)))>] I see the negation operator in there but there is also and AND statement first which I think is what is causing β¦ -
hello, i am trying to connect netmiko and django application but there is an error and does not know the code
as netmiko specifies there should be a device type, IP Address, username and a password so i made a model named devices and what i am trying to do is when i click on each device created in a table it should execute netmiko with the four credentials such as Device type, IP Address, Username and password for the specific device selected or clicked and it should allow me to type a command which can be executed by a press of button can you please help me with the code Model.py class Device(models.Model): CISCO1 = 1 CISCO2 = 2 CISCO3 = 3 CISCO4 = 4 DEVICE_TYPES = ( (CISCO1, 'cisco_ios'), (CISCO2, 'cisco_nxos_ssh'), (CISCO3, 'cisco_s300'), (CISCO4, 'cisco_tp_tcce'), ) device_name = models.CharField(max_length=50) publication_date = models.DateField(null=True) IP_address = models.CharField(max_length=50) username = models.CharField(max_length=30) password = models.CharField(max_length=30) device_type = models.PositiveSmallIntegerField(choices=DEVICE_TYPES) timestamp = models.DateField(auto_now_add=True, auto_now=False) def __str__(self): return self.device_name View.py This is the connection code but i dont know know to get data from the Model (Device) and pass it here or when i select a device from the view it should get the credential to this method def connection_manage(request): if request.method == "POST": form = CommandForm(request.POST) if form.is_valid(): from netmiko import ConnectHandler device = {} β¦ -
Python upgrade to 3.7.5 and django from 1.8 to 1.9...deprication warning on "collections"
The actual warning is: "C:\ProgramData\Anaconda2\envs\d19\lib\site-packages\django\db\models\sql\query.py:11: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3,and in 3.9 it will stop working" Saw some similar posting on github and apparently had been resolved and closed. But, could not figure out how. This is not seemingly in the application code. Any guidance please? Thanks. Apologies if duplicate question. -
how to get url parameter in modelform
I have one model name is cityform i want to get url parmeter in this CityFrom hwo can i do this? here is my url path('state/city/<int:id>/', City.as_view(), name="city") http://localhost:8000/country/state/city/3/ here is my form class CityFrom(forms.ModelForm): def __init__(self, *args, **kwargs): super(CityFrom,self).__init__(*args, **kwargs) print(args) print(kwargs) self.fields['state'] = forms.ModelChoiceField( empty_label = 'Select', queryset = State.objects.all() ) class Meta: model = City fields = ('stat e', 'name') in this form i want to access id = 3 -
first_name and last_name not showing in template when using AbstractUser
I've a custom view for the signup, where I want to show 2 forms: ClientSignUpForm and ProfileForm ClientSignUpForm uses an extended User model, that uses AbstractUser. I can show all fields from ProfileForm in template, but not all from ClientSignUpForm. I can only show: username and password1 and password2 and not: first_name, last_name, email. Why? models.py: from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_client = models.BooleanField(default=False) is_seller = models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=True) cedula_ruc = models.CharField(max_length=30, blank=True) telephone = models.CharField(max_length=30, blank=True) mobile = models.CharField(max_length=30, blank=True) address = models.CharField(max_length=100, blank=False) address_reference = models.CharField(max_length=100, blank=False) location = models.CharField(max_length=100, blank=False) shipping_address = models.CharField(max_length=100, blank=False) shipping_provincia = models.CharField(max_length=100, blank=False) shipping_canton = models.CharField(max_length=100, blank=False) shipping_parroquia = models.CharField(max_length=100, blank=False) views.py: @transaction.atomic def MyClientSignupView(request): provincias_list = ["Azuay", "BolΓvar", "CaΓ±ar", "Carchi", "Chimborazo"] cantones_list = ["Aguarico", "Baba", "Daule", "EcheandΓa", "Flavio Alfaro"] parroquias_list = ["Parroquia1", "Parroquia2", "Parroqui3", "Parroquia4", "Parroquia5"] if request.method == 'POST': client_form = ClientSignUpForm(request.POST) client_profile_form = ProfileForm(provincias_list, cantones_list, parroquias_list, request.POST, request.FILES) if client_form.is_valid() and client_profile_form.is_valid(): client = client_form.save(commit=False) client.is_active = True client.save() username = client_form.cleaned_data.get('username') signup_user = User.objects.get(username=username) customer_group = Group.objects.get(name='Clientes') customer_group.user_set.add(signup_user) raw_password = user_form.cleaned_data.get('password1') user.refresh_from_db() # This will load the Profile created by the Signal client_profile_form = ProfileForm(provincias_list, cantones_list, parroquias_list, request.POST, request.FILES, β¦ -
How to run tasks of Django Periodic Task Object [django-celery-beat]
Django Celery Beat has an option in the admin panel where you can run tasks directly by selecting each individual PeriodicTask model object. https://github.com/celery/django-celery-beat from django_celery_beat.models import PeriodicTask get_task = PeriodicTask.objects.get(id=1) different objects have different tasks registered to them. How to execute the celery task by taking the values from the PeriodicTask model object? -
How do I ensure that my Django singleton model exists on startup?
I'm using a django third party app called django-solo to give me a SingletonModel that I can use for some global project settings, since I don't need multiple objects to represent these settings. This works great, but on a fresh database, I need to go in and create an instance of this model, or it won't show up in Django Admin. How can I make django automatically make sure that when django is starting up, when it connects to the database, it creates this? I tried using the following code that I got here in my settings_app/apps.py, but it doesn't seem to fire at any point: from django.db.backends.signals import connection_created def init_my_app(sender, connection, **kwargs): from .models import MyGlobalSettings # This creates an instance of MyGlobalSettings if it doesn't exist MyGlobalSettings.get_solo() print("Instance of MyGlobalSettings created...") class SettingsAppConfig(AppConfig): ... def ready(self): connection_created.connect(init_my_app, sender=self) The instance isn't created, and I don't see my print statement in the logs. Am I doing something wrong? The sample code has something about using post_migrate as well, but I don't need any special code to run after a migration, so I'm not sure that I need that. -
permission using decorator django class based view
I am trying to set up based permission. my requirements are so basic. I want to use permission_required using class-based views I Have a separate app managed account everything related to user accounts (logins, passwords, etc), and website (landing page, and course content) views from django.contrib.auth.decorators import permission_required @permission_required('account.admin') class ProfileView(TemplateView): template_name = 'profile.html' {% if request.user.is_authenticated %} <a class="button is-info" href="{% url 'logout' %}">logout</a> <h2>Hi! {{ request.user.first_name }} {{ request.user.last_name }}</h2> <p>Your E-mail ID: {{ request.user.email }}</p> {% else %} <a class="button is-info" href="{% url 'login' %}">login</a> or <a class="button is-info" href="{% url 'signup' %}">signup</a> {% endif %} . βββ apps β βββ account β β βββ admin.py β β βββ apps.py β β βββ forms.py β β βββ helpers.py β β βββ __init__.py β β βββ migrations β β β βββ 0001_initial.py β β β βββ __init__.py β β β βββ __pycache__ β β β βββ 0001_initial.cpython-36.pyc β β β βββ __init__.cpython-36.pyc β β βββ models.py β β βββ __pycache__ β β β βββ admin.cpython-36.pyc β β β βββ forms.cpython-36.pyc β β β βββ helpers.cpython-36.pyc β β β βββ __init__.cpython-36.pyc β β β βββ models.cpython-36.pyc β β β βββ urls.cpython-36.pyc β β β βββ views.cpython-36.pyc β β βββ β¦ -
axios.delete not working in react.JS ERROR code 403 forbidden
i am developing a project using DRF and react js not delete using drf working fine but by axios.delete giving 403 error. actions/review.js export const deleteReview = (id) => dispatch => { axios .delete(`/api/review/${id}`) .then(res => { dispatch({ type: DELETE_REVIEW, payload: id }) }) .catch(err => console.log(err)) } reducers/review.js case DELETE_REVIEW: return { ...state, review: state.review.filter(review => review.id !== action.payload) } main review file <tbody> { this.props.review.map(review => ( <tr key={review.id}> <td>{review.id}</td> <td>{review.city_name}</td> <td>{review.traveller_name}</td> <td>{review.traveller_review}</td> <td>{review.review_img}</td> <td><button onClick = {this.props.deleteReview.bind(this, review.id)}className="btn btn-danger btn-sm">Delete</button></td> </tr> </tbody> -
Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['moneybooks/update/(?P<pk>[0-9]+)/$
I made a update function, but error occur like below: NoReverseMatch at /moneybooks/1/ Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['moneybooks/update/(?P[0-9]+)/$'] i try many things... but don't know what's problem. datail.html <a href="{% url "moneybooks:update" moneybooks.pk %}">Update Moneybook</a></br> views.py class moneybook_update(UpdateView): form_class = forms.UpdateMoneybookForm template_name = "moneybooks/update.html" def form_valid(self, form): moneybook = form.save() moneybook.owner = self.request.user moneybook.save() return redirect(reverse("cores:home")) url.py from django.urls import path from . import views app_name = "moneybooks" urlpatterns = [ path("create/", views.moneybook_create.as_view(), name="create"), path("update/<int:pk>/", views.moneybook_update.as_view(), name="update"), path("<int:pk>/", views.moneybook_detail, name="detail") ] form.py class UpdateMoneybookForm(forms.ModelForm): class Meta: model = models.Moneybook fields = ( "name", "companion", "country", "location", "start_date", "end_date", ) def save(self, *args, **kwargs): moneybook = super().save(commit=False) return moneybook -
Removing labels from chart.js with a media query (or change option value)
I am using Django and have a bar chart in a view like so: index.html <script> $(document).ready(function(){ var ctx = document.getElementById('pollingBarChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: [{% for c in categories %}"{{ c.name }}",{% endfor %}], datasets: [{ label: '# of Votes', data: [{% for a in active_votes %} {{ a }}, {% endfor %}], }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true, fontColor: 'white', callback: function(value) {if (value % 1 === 0) {return value;}} } }], xAxes: [{ ticks: { fontColor: 'white', fontSize: 12, } }], }, legend: { labels: { fontColor: 'white' }, }, } }); }); </script> I have figured out I can set the xAxes -> ticks -> fontSize to 0 to achieve what I'm looking for, however I haven't been able to figure out how to change this value to 0 with a media query. I'm still learning JavaScript so not sure the best way to approach this. One possibility I found was to use window.matchMedia("(max-width: 756px)") and add a listener. I wasn't able to get it to work though. Any help would be greatly appreciated. Thank you. -
Django template table format
As I iterate results. There are rows that can be merged, however, relative columns will have multiple rows. For example: Currently: Domain ID----sub Domain Title---- Sub domain ID A1-----------------A1 title-----------A1.1 A1-----------------A1 title-----------A1.2 I would like it to be like this. With first two columns with merged rows Domain ID----sub Domain Title---- Sub domain ID A1----------------A1 title------------A1.1 ---------------------------------------- A1.2 <table class="table table-sm"> <tr> <th>Domain ID</th> <th>Sub Domain title</th> <th>Sub domain ID</th> </tr> {% for record in a6titles %} <tr> <td>A6</td> <td>A6 title</td> <td>titles: {{ record }}</td> </tr> {% endfor %} </table> -
aiohttp api uses db from django app, seems as if database is not migrated
Both the api and the main app are at heroku, but in different apps. When I make a call like: curl -u tok_ElzI2xIIiQ4nHVnJIYW7: -F file=@a.csv http://myapp.herokuapp.com/api/x/ I get the following error: traceback: 2020-01-12T02:24:50.854345+00:00 app[web.1]: Error handling request 2020-01-12T02:24:50.854360+00:00 app[web.1]: Traceback (most recent call last): 2020-01-12T02:24:50.854362+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiohttp/web_protocol.py", line 418, in start 2020-01-12T02:24:50.854364+00:00 app[web.1]: resp = await task 2020-01-12T02:24:50.854366+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiohttp/web_app.py", line 458, in _handle 2020-01-12T02:24:50.854367+00:00 app[web.1]: resp = await handler(request) 2020-01-12T02:24:50.854369+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiohttp/web_middlewares.py", line 119, in impl 2020-01-12T02:24:50.854370+00:00 app[web.1]: return await handler(request) 2020-01-12T02:24:50.854372+00:00 app[web.1]: File "/app/application.py", line 30, in common_middleware 2020-01-12T02:24:50.854374+00:00 app[web.1]: response = await handler(request) 2020-01-12T02:24:50.854376+00:00 app[web.1]: File "/app/application.py", line 91, in authentication_middleware 2020-01-12T02:24:50.854378+00:00 app[web.1]: (token,), 2020-01-12T02:24:50.854380+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiopg/cursor.py", line 118, in execute 2020-01-12T02:24:50.854381+00:00 app[web.1]: yield from self._conn._poll(waiter, timeout) 2020-01-12T02:24:50.854383+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiopg/connection.py", line 244, in _poll 2020-01-12T02:24:50.854384+00:00 app[web.1]: yield from asyncio.wait_for(self._waiter, timeout, loop=self._loop) 2020-01-12T02:24:50.854386+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/asyncio/tasks.py", line 358, in wait_for 2020-01-12T02:24:50.854387+00:00 app[web.1]: return fut.result() 2020-01-12T02:24:50.854389+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/aiopg/connection.py", line 141, in _ready 2020-01-12T02:24:50.854390+00:00 app[web.1]: state = self._conn.poll() 2020-01-12T02:24:50.854392+00:00 app[web.1]: psycopg2.ProgrammingError: relation "users_usertoken" does not exist 2020-01-12T02:24:50.854393+00:00 app[web.1]: LINE 1: ...ertoken.id as id, first_request, valid_until FROM users_user... What is going on here? The main app (whose database the api uses) does not have any β¦ -
Django template tags - arrange result of queryset
I am trying to format my results in a table. <tr> <td>A6</td> <td>A6 title</td> <td> {% for record in a6titles %} titles: {{ record }} {% endfor %} </td> </tr> The data displays in a single row. I would like each result item to be displayed in its own row. I am sure this is very simple; however, I am very new to this.