Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Send Form By Authenticated User
i stuck when trying to send data or save data with django form by user it self (logged). When i test why form "From" user must be selectable not automatic selected by user it self. class ValidationCreate(forms.ModelForm): class Meta: model = About fields = '__all__' def upload(request): upload = ValidationCreate() if request.method == 'POST': upload = ValidationCreate(request.POST, request.FILES) if upload.is_valid(): upload.save() return redirect('validation') else: return HttpResponse("""your form is wrong, reload on <a href = "{% url 'validation' %}">reload</a>""") else: return render(request, 'upload_form.html', {'about_form': upload}) sample -
Test if a certain method is called during an object initialization Python
I have a superclass that calls a certain independent method during its initialization. Something like class MasterClass: def __init__(self, *args, **kwargs): if type(self).__name__ == "SpecificClass": call_a_module_method() I want to test that a subclass of this class called SpecificClass will get call_a_module_method method called. -
"The connection was reset" in localhost:8000 using django and docker
After running docker-compose up, Starting docker_django ... done Attaching to docker_django docker_django | Watching for file changes with StatReloader docker_django | Performing system checks... docker_django | System check identified no issues (0 silenced). docker_django | February 12, 2020 - 07:26:35 docker_django | Django version 3.0.3, using settings 'backend.settings' docker_django | Starting development server at http://127.0.0.1:8000/ docker_django | Quit the server with CONTROL-C. when i connect to http://127.0.0.1:8000/ it shows this There is no problem / error running the docker-compose command but only when visiting the site. Im using ubuntu 19.10 and the project has django v3. Dockerfile FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY . /code/ RUN pip install -r requirements.txt docker-compose.yml version: '3' services: web: build: . container_name: docker_django command: python manage.py runserver volumes: - .:/code ports: - "8000:8000" -
How to change the login page 'site_header' of django-admin-honeypot?
urlpatterns = [ path('admin/', include('admin_honeypot.urls')), path('control/', admin.site.urls), ] The default admin_honeypot's login page has 'Django Administrator' as a site_header. How could I change this as 'Log In'? -
Multi-step form data not saving in database in Django
I am trying to set up multi-step form using django-formtools. What I noticed however is that my data is not saving in the database after submitting the form. How can this issue be resolved? Is there something I am missing currently? Here is my views.py class FormWizardView(SessionWizardView): template_name = "accounts/testforms.html" form_list = [EmployeeSignUpForm, FormStepTwo] def done(self, form_list, **kwargs): return render(self.request, 'accounts/done.html', { 'form_data': [form.cleaned_data for form in form_list], }) def get(self, request, *args, **kwargs): try: return self.render(self.get_form()) except KeyError: return super().get(request, *args, **kwargs) -
Python Django Count Dictionary using For Loop Per Key
Hi I'm new to python programming. I need to create a dictionary using for loop and count the status per parent key I have a parent and each parent has many sensors. Now I have to count the status(Up/Down) of each parentid Expected Results: Device Name Up Sensors Down Sensors Device-01 1 1 Device-02 2 Below is the example of API result that i get: { "sensors": [ { "objid": 3227, "parentid": 3222, "device": "Device-1", "sensor": "GPON 0/0/0", "status": "Up", }, { "objid": 3228, "parentid": 3222, "device": "Device-1", "sensor": "GPON 0/0/1", "status": "Down", }, { "objid": 3229, "parentid": 3223, "device": "Device-2", "sensor": "GPON 0/0/1", "status": "Up", }, { "objid": 3230, "parentid": 3223, "device": "Device-2", "sensor": "GPON 0/0/2", "status": "Up", }, } Below is my views.py. I know how to count all sensors. My problem is how can I get the specific count per parent def dashboard(request): response = requests.get('http://sample_api_url') data = response.json() all_up_sensors = 0 all_down_sensors = 0 all_devices = dict() for device in data['sensors']: parentid = device['parentid'] if device['status'] == "Up": all_up_sensors +=1 else: all_down_sensors +=1 device_info = { "device" : device['device'], "up_sensors" : ????, "down_sensors" : ????, } all_devices[parentid] = device_info context = { "all_devices": all_devices, "all_up_sensors": all_up_sensors, … -
Which way of creating Likes is the best option in Django and Postgres?
I have Post Model. and I have to add likes to this model. So there are two ways: Create likes field with ManyToMany relationship 1: class Post(models.Model): title = models.CharField() likes = models.ManyToMany(settings.AUTH_USER_MODEL) or create another model for PostLike 2: class PostLike(models.Model): post = models.ForeignKey(Post) author = models.ForeignKey(settings.AUTH_USER_MODEL) Which way is the best or at least right way to implement liking feature in Django, Python ways or SQL way? -
Impossible to use djanog-allauth when there is already an `account` app?
My django application already has an app called account. Does it mean that it is ABSOLUTELY impossible to use django all-auth because of the name conflict? Due to the existing data, the app account cannot be renamed. settings.py: INSTALLED_APPS = [ ... 'account', ... # For allauth: 'django.contrib.sites', 'allauth', 'allauth.account', # Name conflict ... If so, is there a good alternative? -
DRF HawkREST authentication failed with postman
Im using this library: https://hawkrest.readthedocs.io/en/latest/ In my settings.py: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'hawkrest.HawkAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } HAWK_CREDENTIALS = { 'script-user': { 'id': 'script-user', 'key': 'aabbcc', 'algorithm': 'sha256' }, } In postman: In console output: access denied: MisComputedContentHash: Our hash b'l0mKQ9ZG6Df44jdvH1FthWGvtKN93umZdmQCqd7YcgI=' (sha256) did not match theirs -
How to deploy django website in ubuntu 18.04 + plesk + apache in digitalocean droplet
In my droplet is running several PHP websites, recently I tried to deploy a Django website that I build. But it's doesn't work properly. I will explain the step that I did. 1, Pointed a Domain name to my droplet. 2, Added Domain name using Plesk Add Domain Option. 3, Uploaded the Django files to httpdocs by Plesk file manager. 4, Connected the server through ssh and type python manage.py runserver 0:8000 5, My Django Website is successfully running. Here are the real issues occurs, We need to type exact port number to view the website every time. Eg:- **xyz.com:8000 ** As well as the Django webserver is down after sometimes. I am newbie to Django all I have experience in deploying a PHP website. If my procedure is wrong please guide me to correct procedure. Thanks in Advance. -
How to the get primary key in API using a javascripts
Im using Django classbased views CRUD but my frontend is DataTables API RestFramework, My problem is how can I get the Primary Key per rows to Edit and Delete the Data? I can display all the data in DataTables but I can't edit and delete since primary key is not found. Thank You. JS <script> $(document).ready(function() { var table = $('#table').DataTable({ "ajax": "/api/mlist/?format=datatables", "columns": [ { "data": "A_Id", "render": function(data, type, row, meta){ if(type === 'display'){ data = '<a href="/List/Details/' + data + '">' + data + '</a>'; } return data; } }, }); </script> Table.html <table id="table" class="table table-striped table-bordered" style="width:100%" data-server-side="true" data-ajax="/api/mlist/?format=datatables"> <thead> <tr> <th>Act No</th> </tr> </thead> </table> -
Running Django docker-stack-prod.yml on local machine not working
I'm using two different docker-stack.yml files to separate my production settings from my development settings. environment: - ENVIRONMENT=production - SECRET_KEY=6k(*** - DEBUG=0 - ALLOWED_HOST=*** environment: - ENVIRONMENT=development - ALLOWED_HOST=localhost 127.0.0.1 web - SECRET_KEY=6k(*** - DEBUG=1 I'm trying to run the production settings on my local machine just to make sure that everything is working. As i expect the production docker-stack.yml is not working when I run it. After running the python manage.py check --deploy, I got a list of settings to enable for Production, and the book that I was reading put them under and If statement for production. I've done all of that and running python manage.py check --deploy, there is no issue. However, when I now try to comment out the if statement and everything under it and then run python manage.py check --deploy, it keeps saying that there is no issues. When there should be as I've removed the settings recommended for production. If I change the environment from production to development however, everything works as intended, deployment errors and all. import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ENVIRONMENT = os.environ.get("ENVIRONMENT", default="production") # Quick-start development settings - unsuitable for … -
Invalid model identifier: 'users.user'
I am using the default User model in my django project(app name is users). I am trying to write fixtures for testing but I am getting the error "Invalid model identifier: 'users.user'" How can I use the default user model in my fixtures. What would be the app name? Here is my fixtures.py for users { "model": "User.user", "pk": "1", "fields": { "username": "aarti", "password": "asdf1234", "email":"aarti@gmail.com" } } -
How to do a duplicate copy of an object in django rest framework?
I am making a duplicate of an object. It is working except the time field related to the day field which i am unable to copy.Can anyone explain what is wrong with my code. models.py class Facility(models.Model): id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False) name = models.CharField(max_length=250, blank=True, null=True) description = models.CharField(max_length=1000, blank=True, null=True) class FacilityDaySlot(models.Model): day_slot_id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable= False) facility = models.ForeignKey(Facility, on_delete=models.CASCADE, blank=True, null=True, related_name='days') open_time = models.TimeField(blank=True, null=True) close_time = models.TimeField(blank=True, null=True) class FacilityTimeSlot(models.Model): id = models.UUIDField(primary_key=True, default=uuid_generate_v1mc, editable=False) day_slot = models.ForeignKey(FacilityDaySlot, on_delete=models.CASCADE, blank=True, null=True, related_name="times") start_slot_time = models.TimeField(blank=True, null=True) end_slot_time = models.TimeField(blank=True, null=True) views.py @api_view(["POST"]) @permission_classes((AllowAny,)) def facility_clone(request): """ Generate the duplicate Facility with out publish, FacilitySport, FacilityLevel""" facility_id = request.data.get("facility_id", None) if facility_id: try: current_facility = get_object_or_404(Facility, id=facility_id) old_facility_id = current_facility.id current_facility.id = None current_facility.is_draft = True # do not publish for duplicated facility current_facility.is_published = False current_facility.save() new_facility = get_object_or_404(Facility, id=current_facility.id) current_facility = get_object_or_404(Facility, id=old_facility_id) for day_slot in FacilityDaySlot.objects.filter(facility_id=current_facility.id): day_slot.day_slot_id = None day_slot.facility_id = new_facility.id day_slot.save() for time_slot in day_slot.times.all(): time_slot.id = None time_slot.day_slot = day_slot time_slot.save() message = { 'message': 'duplicate facility created and id is {}'.format(new_facility.id) } return Response(message, status=status.HTTP_201_CREATED) except Exception as e: logger.error('error while creating duplicate event %s', e) message … -
How to Upload Images to a Cloud Storage(Imgur) in python(django) Application
How to Upload Images to a Cloud Storage(Imgur) in python(django) Application. currently i am storing my images in my image files in python(django). i want to store those images to cloud storage(imgur). i already read the docs but i am not sure how to do this. any help, would be appreciated. -
how to resolve error while installing mysqlclient
I am working on a Django project and I want to connect it with MySQL. I tried the following command: pip install mysqlclient but it is showing me the following error: error: Microsoft Visual C++ 14.0 is required. I installed Microsoft Visual in my PC but still, this problem occurs. -
Django include from with var unexpected result
I have an unexpected result from this code foo.html {{ include "bar.html" with x="xx.html" y="y1"}} {{ include "bar.html" with x="yy.html" y="y2"}} {{ include "bar.html" y="y3"}} bar.html {% if x %} x {{include x}} {% else %} pass {% endif %} While I run the foo.html that gives me a result y1 xx <render xx.html> y2 xx <render xx.html> <--- why this render xx and not yy y3 xx <render xx.html> <--- still printing x and rendering xx.html django : 3.0.3 python : 3.6.9 -
passing parameter from js to django
I have a function in views.py def time (request): date = Registration.objects.filter(date_visit=date_use) time_list=[] for a in date: time_list.append(date.time_visit) return JsonResponse({'time_list':time_list}) I want to pass there the date_use parameter from my field in the form. I calculate the field values like this $(document).ready(function() { $('.pole').change('input', function() { var val = $(this).val(); }); }); how can i pass val value to date_use? -
How to access webcam in OpenCV on PythonAnywhere through Javascript?
I have developed a WebApplication in Django that has a view method which contains the OpevCV code that when triggered opens the User Webcam to detect its face. This app works fine in my localserver but when I have hosted it on PythonAnywhere it says camera not found as my PA hosting doesnt serve a camera. So someone suggested me to open the webcam through javascript as it deals with the client machine and then pass its feed to server machine which is my hosting. But as i am a rookie in Python i am not able to figure how to perform the above task. I found this piece of js code but i dont know how and where to add this in my Django App. Code for getting the feed with Javascript var video = document.querySelector("#videoElement"); if (navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({video: true}).then(function(stream) { video.srcObject = stream; }).catch(function(err0r) { console.log("Something went wrong!"); }); } My Python code for opening the camera and detecting faces is as follows (it works in localserver) import cv2 cascade = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml') cam = cv2.VideoCapture(0) while True: ret, frame = cam.read() frame = cv2.flip(frame, 1) if ret: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3) for … -
Django Structlog is not printing or writing log message to console or file
I have installed django-structlog 1.4.1 for my Django project. I have followed all the steps which has been described in that link. In my settings.py file: import structlog MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django_structlog.middlewares.RequestMiddleware', ] LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "json_formatter": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.JSONRenderer(), }, "plain_console": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.dev.ConsoleRenderer(), }, "key_value": { "()": structlog.stdlib.ProcessorFormatter, "processor": structlog.processors.KeyValueRenderer(key_order=['timestamp', 'level', 'event', 'logger']), }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "plain_console", }, "json_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "log/json.log", "formatter": "json_formatter", }, "flat_line_file": { "class": "logging.handlers.WatchedFileHandler", "filename": "log/flat_line.log", "formatter": "key_value", }, }, "loggers": { "django_structlog": { "handlers": ["console", "flat_line_file", "json_file"], "level": "DEBUG", }, "django_structlog_demo_project": { "handlers": ["console", "flat_line_file", "json_file"], "level": "DEBUG", }, } } structlog.configure( processors=[ structlog.stdlib.filter_by_level, structlog.processors.TimeStamper(fmt="iso"), structlog.stdlib.add_logger_name, structlog.stdlib.add_log_level, structlog.stdlib.PositionalArgumentsFormatter(), structlog.processors.StackInfoRenderer(), structlog.processors.format_exc_info, structlog.processors.UnicodeDecoder(), structlog.processors.ExceptionPrettyPrinter(), structlog.stdlib.ProcessorFormatter.wrap_for_formatter, ], context_class=structlog.threadlocal.wrap_dict(dict), logger_factory=structlog.stdlib.LoggerFactory(), wrapper_class=structlog.stdlib.BoundLogger, cache_logger_on_first_use=True, ) In my views.py: from django.http.response import HttpResponse import structlog logger = structlog.get_logger(__name__) def func(request): logger.debug("debug message", bar="Buz") logger.info("info message", bar="Buz") logger.warning("warning message", bar="Buz") logger.error("error message", bar="Buz") logger.critical("critical message", bar="Buz") return HttpResponse('success') Output in json.log: {"request_id": "7903fdfb-e99a-4360-a8f0-769696520cc9", "user_id": null, "ip": "127.0.0.1", "request": "<WSGIRequest: GET '/test'>", "user_agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36", "event": "request_started", "timestamp": … -
python3 is not recognized as an internal or external command, operable program or batch file showing for creating django runserver
(venv) C:\Users\Inter-Wave\PycharmProjects\PyShop>python3 manage.py runserver 'python3' is not recognized as an internal or external command, operable program or batch file. -
How to make one API call for models.objects.all() using JsonResponse in Django?
models.py class Game(models.Model): name = models.CharField(max_length=80, null=True) year_published = models.IntegerField(null=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class GameImage(models.Model): game = models.ForeignKey(Game,on_delete = models.CASCADE, related_name='image') image = models.FileField(upload_to='uploads/', null = True, blank = True) class GamePost(models.Model): postType = models.CharField(max_length=30) game = models.ForeignKey(Game,on_delete = models.CASCADE) For This models I want one API call to display list of games using below requires: Required fields are game_name, game_image, created_at, updated_at, post_count I django json data or Rest framework json. -
Django foreign key, how to fill fields automatically
I'm trying to fill fields automatically in my createview. What I want is for the logged in user (Technician in this case) to create a Job Docket, without having to choose it from a list, I want to be able to exclude the field from the form. I need to do this for another field too, called "job". They are both currently producing the default drop down list of items in the db. Is form_valid the correct method to be using or is it get_initial, I've been getting conflicting advice and nothing seems to work. Whats the best way to do this? Using Django 3. User str is first_name Job str is company_name which is a foreign key to the company model which str is company_name. If that helps. Job Docket Model: class JobDocket(models.Model): EQUIPMENT_TYPE = ( ('1', 'Air Conditioning'), ('2', 'Heating/Heat-Pump'), ('3', 'Refrigeration'), ('4', 'Ventilation/Extraction'), ('5', 'Electrical/Controls'), ) job = models.ForeignKey(Job, on_delete=models.CASCADE) technician = models.ForeignKey(User, on_delete=models.CASCADE) site_equipment = models.CharField(choices=EQUIPMENT_TYPE, max_length=50, default='1') date = models.DateField(default=date.today()) start_time = models.TimeField() end_time = models.TimeField() rate = models.FloatField(default=80.00) mileage = models.IntegerField() description = models.CharField(max_length=1000, help_text='Description of work carried out', blank=False) created = models.DateTimeField(default=now, blank=True) def __str__(self): return str(self.technician) def get_absolute_url(self): return reverse('jobs:detail', kwargs={'pk': self.pk}) … -
Django many-to-many multiple filtering
I have a model that is as follows: class NetworkDevice(models.Model): name = models.CharField(max_length=30) class NetworkInterface(models.Model): intname = models.CharField(max_length=30) device = models.ForeignKey(NetworkDevice) class NetworkMac(models.Model): macaddr = models.CharField(max_length=30) interface = models.ManyToManyField(NetworkInterface) I want to create a device detail page that shows only the MACs learned off the interfaces assigned to that a particular device. The issue is that the same mac address lives off different interfaces on different devices. if i pass my template something like: macs = NetworkMac.objects.filter(interface__device__name='<some device name>') Doing this gives me all the MAC addresses for that device, but because the MACs are shared, it also gives me the MACs associated with interfaces on other devices. So when i try to display this in my template, it ends giving me nothing or if i use |first, it will often give me the interface for a different device depending on the order the devices were added to the database. What i really need is a query i can run that will return all the macs for a single device only learned on the interfaces that are associated with said device. -
How to modify error response in ModelViewSet class if detail not found for Django REST Framework?
I tried to implement this answer to create a custom base Response class for all my ModelViewSet classes. My problem is at the retrieve function. If the Id of instance I'm looking for not found, I can't seem to change the Response with my modified response_format. It still gives the default response. What should I change my if condition into? views.py: class ResponseInfo(object): def __init__(self, **args): self.response = { "message": args.get('message', 'success'), "error": args.get('error', ), "data": args.get('data', []), } class LanguageView(viewsets.ModelViewSet): def __init__(self, **kwargs): self.response_format = ResponseInfo().response super(LanguageView, self).__init__(**kwargs) permission_classes = [permissions.DjangoModelPermissions] queryset = Language.objects.all() serializer_class = LanguageSerializer def list(self, request, *args, **kwargs): # call the original 'list' to get the original response. response_data = super(LanguageView, self).list(request, *args, **kwargs) # customize the response data. self.response_format['data'] = response_data.data if not response_data.data: self.response_format['message'] = 'List is empty.' self.response_format['error'] = response_data.status_code return Response(self.response_format) def retrieve(self, request, *args, **kwargs): response_data = super(LanguageView, self).retrieve(request, *args, **kwargs) self.response_format['data'] = response_data.data if not response_data.data: self.response_format['message'] = 'Instance not found.' self.response_format['error'] = response_data.status_code return Response(self.response_format) The JSON response when instance is found. E.g http://127.0.0.1:8000/languages/1/: { "message": "success", "error": null, "data": { "id": 1, "name": "English", "icon": "http://127.0.0.1:8000/media/language_icons/English.png", "xml": "http://127.0.0.1:8000/media/-", "abbreviation": "En" } } The JSON response when instance …