Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how I can open page for each user in list and add more information python django
I have a list of users in the table. I want when I click on any user it open "user_information page". "user_information page" has two buttons "ADD MORE" and "SAVE". The "SAVE" button saves the information and shows them as a block, and it should save for that user. The "ADD MORE" button allows user to fill the fields with different information (user name, work address, user position) -
Django: Only the First Image getting to Database with every pickd instance even though all images are properly read from the excel sheet
Hey guys I am having trouble extracting image links from an excel sheet and saving to database in django. The problem is, even though all image links are being extracted correctly, only the first image is getting into database. For example, if Picked is a model, and PickedImage has a foreign key to Picked. then even after extracting all images, only the first image is getting stored in database. if I provide 6 different images to PickedImage for a single Picked instance. The rest of the images are in the list but not getting stored to database instead the first image will be stored 6 times. This is the code, can someone help. for pickd in data['pickd']: # loop to create pickd image model instance if pickd['title'] is None or pickd['title'] == '': continue i += 1 try: if pickd['image1'] is not None: bulk_image.append(Image(picks=instance[i], images=downloadImage(pickd['image1'], pickd['title']).open(mode='rb'), main=True)) if pickd['image2'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image2'], pickd['title']).open(mode='rb'))) if pickd['image3'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image3'], pickd['title']).open(mode='rb'))) if pickd['image4'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image4'], pickd['title']).open(mode='rb'))) if pickd['image5'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image5'], pickd['title']).open(mode='rb'))) if pickd['image6'] is not None: bulk_image.append(Image(picks=instance[i],images=downloadImage(pickd['image6'], pickd['title']).open(mode='rb'))) except Exception as e: continue def downloadImage(url, Name): """ Method to download images from a given url """ … -
request.user always returns AnonymousUser
I have created a django model which includes a foreign key to a user as follows: from authentication.models import User from django.db import models class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) My serializers.py file is as follows: class EventSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Event fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request'] My views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user = request.user instance.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) What I need to do is to go to a URL and login as a user. Then I need to go to another URL and add with POST request some details about the event and save the details as well as the user in the database. However after login and POST request I get the following error: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x7f7daf1469d0>": "Event.user" must be a "User" instance. It seems that it always returns an AnonymousUser, although I have logged in. Any idea of … -
how to create a python django model for elasticsearch with base library
In my view I query elasticsearch db but it isn't good pratice. I want follow mvc pattern, so how to create a python django model for elasticsearch? I use simple base elasticsearch library. Please, guide me. controller-view view_home.py from django.shortcuts import render, redirect from django.conf import settings from pygiustizia.models.model_users import Users from pygiustizia.models.model_docfields import * import logging import json from elasticsearch import Elasticsearch from django.http import JsonResponse from django.template.loader import render_to_string def show_results(request): print('####### show_results ########') ELASTICSEARCH_URL = getattr(settings, 'ELASTICSEARCH_URL', 'localhost:9200') ELASTICSEARCH_INDEX = getattr(settings, 'ELASTICSEARCH_INDEX', 'civile') print(ELASTICSEARCH_INDEX) esSearchPageClient = Elasticsearch([ELASTICSEARCH_URL]) size = 2 fromSize = 0 bodyPageAllDoc={ "size": size, "from": fromSize, "query": { "match": { "distretto": "MI"} }, "_source": ["text"], "sort": [{"_id": "asc"}] } resPage = esSearchPageClient.search(index=ELASTICSEARCH_INDEX, body=bodyPageAllDoc) #print(resPage) html = render_to_string('pygiustizia/home/process_show_results.html') return JsonResponse({'cat':1,'html':html}) -
Streaming video using Python - two different site users
I want to make a website where users can join that can be seen through their webcams. I mean streaming video of two different users of the site through their webcams e.g. on a laptop. I will be setting up the website probably on AWS. I want to do this using Python (Flask/Django, nginx, Ubuntu etc). Can you recommend a library/some sources to make this possible? OpenCV? Or something else? -
Django Ajax POST request fail to redirect
I am trying to create a website to capture picture from client's camera and save it in the database. However after everything was saved, I cant seem to redirect the page. views.py def facial_capture(request): if request.method == 'POST': file = request.FILES['snap'] if file: student = Student.objects.get(id=request.session['id']) if student: FaceImage.objects.create(student=student, image=file) return HttpResponse("{'status': 1}", content_type='application/json') return HttpResponse("{'status': 0}", content_type='application/json') return render(request, 'id_capture/facial_capture.html') face_capture.html {% block body %} <div class="container"> <form>{% csrf_token %} <video id="video" width="640" height="480" autoplay></video> <button id="send">Submit</button> <canvas id="image_canvas" width="640" height="480"></canvas> </form> </div> {% endblock %} face_capture.js $(document).ready(function () { var video = document.getElementById('video'); var canvas = document.getElementById('image_canvas'); var context = canvas.getContext('2d'); var w = 640, h = 480; if(navigator.mediaDevices && navigator.mediaDevices.getUserMedia) { navigator.mediaDevices.getUserMedia({ video: true }).then(stream => { video.srcObject = stream; video.play(); }); } document.getElementById("send").addEventListener("click", function() { context.translate(w, 0); context.scale(-1, 1); context.drawImage(video, 0, 0, w, h); canvas.toBlob(upload, "image/jpeg"); }); function upload(file) { var formData = new FormData(); formData.append("snap", file); const csrftoken = document.querySelector('[name=csrfmiddlewaretoken]').value; $.ajax({ headers: {'X-CSRFToken': csrftoken}, type: 'POST', url: '/signup/facial_capture', data: formData, cache: false, processData: false, contentType: false, enctype: 'multipart/form-data', success: function(data){ console.log('response received'); if (data.status == 1) { console.log('status ok'); window.location.href = "login"; } else { console.log('status failed'); window.location.reload(); } } }) } }); I assume … -
How to fix absolute import problem in Django?
I try to figure it out why can't I import a module but I have no success. My structure is very simple: exitinterview firm stressz -models.py performance -emails.py I want to import Projects class from stressz.models into emails.py like this: from stressz.models import Project But I always get this error: ModuleNotFoundError: No module named 'stressz' I have stressz in my settings.py in the INSTALLED_APPS -
Picking last item in before a time in django
Here i have to filter this model by created_at and after that i have to pick the last item per user this is my model: class UserWorkPattern(models.Model): user = models.ForeignKey("profile.User", on_delete=models.CASCADE) work_pattern = models.ForeignKey("workpattern.WorkPattern", on_delete=models.CASCADE) offset = models.ForeignKey('workpattern.ShiftPeriod', on_delete=models.CASCADE, null=True, blank=True, verbose_name='shift offset', help_text='delivered shift period.') created_at = models.DateTimeField(default=now) updated_at = models.DateTimeField(default=now) def __str__(self): return str(self.user) + ' - ' + str(self.work_pattern) How can i do that by writing a query and not pythonic way! -
I can't send file to django server through angular and error says: The submitted data was not a file. Check the encoding type on the form
my code is like this and I send data through httpClient and it returns error on upload my angular version is 13 and django version is 4 and I'm using django rest framework for restApi ng component const data={ "image_url":this.imgFile, "caption": this.caption, 'author':1 }; console.log(data); this.service.createPost(data).subscribe(res=>console.warn(res)); } onFileChanged(event:any) { const reader = new FileReader(); this.file = event.target.files[0]; if(!this. file) return reader.readAsDataURL(this.file); reader.onload = () => { this.imgFile = reader.result as string; }; } django model caption = models.CharField(max_length=4000) likes = models.IntegerField(default=0, blank=True) is_liked = models.BooleanField(default=False, blank=True) date = models.DateTimeField(auto_now_add=True) image_url = models.ImageField(upload_to='images', blank=True) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __unicode__(self): return (self.caption) def __str__(self): return self.caption + ' | ' + str(self.likes) django view def get(self, req): data = Post.objects.all() serialized = PostSerializer(data, many=True) return Response(serialized.data) def post(self, request): serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) django Serializer class PostSerializer(serializers.ModelSerializer): # image_url = ThumbnailerSerializer(alias='avatar') class Meta: model = Post fields = '__all__' def create(self, validated_data): return Post.objects.create(**validated_data) -
How to apply a for statement to simplify repeated code in Django queryset
The filter is applied according to team_parameter(request.GET.get('team)) and it has very repetitive code. At the end of the if statement, no filter is applied only if team_parameter is 'ALL'. I think a for statement is necessary to minimize this code, but I did not know how to apply it, so I asked a question. Please let me know which loops are needed to simplify the code below. Help. [views.py] team_parameter = request.GET.get('team') if team_parameter == 'A' and not team_parameter: monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='A')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'B': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='B')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), feb=Count('client_id', filter=Q(enroll_date__gte='2022-02-01', enroll_date__lte='2022-02-28')), mar=Count('client_id', filter=Q(enroll_date__gte='2022-03-01', enroll_date__lte='2022-03-31')), apr=Count('client_id', filter=Q(enroll_date__gte='2022-04-01', enroll_date__lte='2022-04-30')), may=Count('client_id', filter=Q(enroll_date__gte='2022-05-01', enroll_date__lte='2022-05-31')), jun=Count('client_id', filter=Q(enroll_date__gte='2022-06-01', enroll_date__lte='2022-06-30')), jul=Count('client_id', filter=Q(enroll_date__gte='2022-07-01', enroll_date__lte='2022-07-31')), aug=Count('client_id', filter=Q(enroll_date__gte='2022-08-01', enroll_date__lte='2022-08-31')), sept=Count('client_id', filter=Q(enroll_date__gte='2022-09-01', enroll_date__lte='2022-09-30')), oct=Count('client_id', filter=Q(enroll_date__gte='2022-10-01', enroll_date__lte='2022-10-31')), nov=Count('client_id', filter=Q(enroll_date__gte='2022-11-01', enroll_date__lte='2022-11-30')), dec=Count('client_id', filter=Q(enroll_date__gte='2022-12-01', enroll_date__lte='2022-12-31')),)\ .values_list('uploader_id__first_name', 'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sept', 'oct','nov', 'dec')\ .order_by('uploader_id__first_name') elif team_parameter == 'C': monthly_enroll = Feedback.objects.filter(uploader_id__contact__team='C')\ .values('uploader_id__first_name').distinct().order_by('uploader_id__first_name')\ .annotate(jan=Count('client_id', filter=Q(enroll_date__gte='2022-01-01', enroll_date__lte='2022-01-31')), … -
how to work with foreign key field in django
Hi Everyone i am working work django framework, where i used to upload excel file in Dailytrip table, current i get car_mumber from car table, but now i need to store car_number from Car_team table also team_id, i am storing car_id and team_id in car_team table also i need to store team_id in dailytrip table automaticlly based on car_id(car_number) i am to much confuse how to i work that, pls help me out models.py class Car_team(BaseModel): team = models.ForeignKey( Team, models.CASCADE, verbose_name='Team', null=True, ) car=models.ForeignKey( Car, models.CASCADE, verbose_name='Car', null=True) city =models.ForeignKey( City, models.CASCADE, verbose_name='City', ) start_date=models.DateField(null=True, blank=True) end_date=models.DateField(null=True, blank=True) views.py def add_payout_uber_daily_data(request): if request.method == 'POST': form = UberPerformanceDataForm(request.POST, request.FILES, request=request) if form.is_valid(): date = form.cleaned_data['date'] excel_file = request.FILES['file'] df = pd.read_excel(excel_file) is_na = pd.isna(df['Date']).sum().sum() + pd.isna(df['Name']).sum().sum() + pd.isna(df['UUID']).sum().sum() + pd.isna(df['Net Fare With Toll']).sum().sum() + pd.isna(df['Trips']).sum().sum() + pd.isna(df['Uber KMs']).sum().sum() + pd.isna(df['CashCollected']).sum().sum() + pd.isna(df['UberToll']).sum().sum() + pd.isna(df['Tips']).sum().sum() + pd.isna(df['Hours Online']).sum().sum() + pd.isna(df['Ratings']).sum().sum() + pd.isna(df['Acceptance Rate']).sum().sum() + pd.isna(df['Cancellation Rate']).sum().sum() error_list = [] if is_na > 0: error_list.append('Found #N/A or blank values in the sheet. Please correct and re-upload') context = {'error_list': error_list, 'menu_payout': 'active','submenu_daily_data': 'active','form': form, } return render(request, 'add_payout_uber_daily_data.html', context=context) date_match = True for d in df['Date']: if str(d.strftime("%Y-%m-%d")) != str(date): date_match … -
Django authentication with phone number and OTP
In my Django app, I have to authenticate with phone number and OTP on every login. I don't want to store passwords in the user table. How can i customize the Django user model and authentication backend for this?. please help me to figure this out. -
Wagtail and allauth - allauth is inheriting site name from django not wagtail
I am using allauth with wagtail. I have name my site 'mysite' in the wagtail admin, but when sign up emails refer to 'example.com' My settings.py has apps in the following order [ ... 'django.contrib.auth', 'django.contrib.sites', "allauth", "allauth.account", "allauth.socialaccount", "allauth.account", "allauth.socialaccount", 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', ] It sounds as though this might be related to the conflict between django and wagtail described here https://github.com/wagtail/wagtail/issues/2840. However it looks as though that issue has been closed and I am using recent version (Django==3.2.11, django-allauth==0.47.0, wagtail==2.15.1) -
Update django model database with ForeignKey by using serializer
I have created a django model which includes a foreign key to a user as follows: from authentication.models import User from django.db import models class Event(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) My serializers.py file is as follows: class EventSerializer(serializers.ModelSerializer): user = UserSerializer(many=True, read_only=True) class Meta: model = Event fields = ['user', 'dr_notice_period', 'dr_duration', 'dr_request'] What I need to do is to go to a url and with a POST request to upload the data to the database, but without specifically specifying the user. My views.py is as follows: from rest_framework.response import Response from rest_framework.decorators import api_view from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): instance = serializer.save(commit=False) instance.user = request.user instance.save() return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) As I study I thought that by using commit=False in save would solve the problem, but I am getting the following error: 'commit' is not a valid keyword argument to the 'save()' method. If you need to access data before committing to the database then inspect 'serializer.validated_data' instead. You can also pass additional keyword arguments to … -
Login logic in React via Django Rest
I implemented Django rest_auth to use it as authentication backend for my app. This works find when testing via Postman. However, if I now send a login POST request from the client (React) it returns Success: {password: Array(1)}password: Array(1)0: "This field is required."length: 1[[Prototype]]: Array(0)[[Prototype]]: Object When I log the transmitted formData in the submitHandler I get {username: 'admin', password: 'sonne123'} password: "sonne123" username: "admin" which to me looks fine. I'm not sure how to debug this and where the bug might be. import {Fragment, useState, useReducer} from "react"; import {Link} from "react-router-dom"; // Initiate Form reduced const formReducer = (state, event) => { return { ...state, [event.name]: event.value } }; const Login = () => { const [formData, setFormData] = useReducer(formReducer, {}); const [logging, setLogging] = useState(false); const submitHandler = event => { console.log(formData) event.preventDefault(); setLogging(true); } fetch('http://127.0.0.1:8000/api/user/auth/login/', { method: 'POST', body: JSON.stringify({formData}), headers: {'Content-Type': 'application/json'}, }) .then(res => res.json()) .then(result => { console.log('Success:', result); }) const changeHandler = event => { setFormData({ name: event.target.name, value: event.target.value, }); }; return ( <Fragment> <form onSubmit={submitHandler}> <div className="text-lg text-sx-purple-dark text-center mb-4">Login to your Salaryx Account</div> <div> <div className="relative top-3 left-4 pl-2 pr-2 text-sx-purple-dark-soft bg-sx-white-plain w-max">Username*</div> <input type="text" className="w-full mb-4 h-auto text-sm … -
how do i store django media on remote unix server
I have two app servers 10.22.33.54 and 10.22.33.56 and I am trying to integrate media on another server IP 10.22.30.40 I created a media directory so what are the method I can use in Django to manage media files? -
Django DeleteView strange behavior
So I have a problem with a Django class-based Delete View. Actually, the delete view works just fine as it deletes the chosen entry, but the problem occurs when I want to redirect to the DetailView URL of the page where all entries are. DeleteView As you can see in the code above, I am using reverse lazy with a pk of the page before. But after I confirm to delete it seems like Django is trying to get to the same delete URL once again and I am always getting the same error. Error It seems like it's trying to get to the URL of the entry that was just deleted so obviously there is none found. I can't understand what am I doing wrong? Please help. urls.py -
Can't seem to know why this error is occuring
The same code on above is working but not on this line -
VS code not opening from terminal with code . command in windows 11
When I try to open with "code ." command from the windows terminal, it is throwing an error. code : The term 'code' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + code . + ~~~~ + CategoryInfo : ObjectNotFound: (code:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException It was opening fine before. No idea what happened. I tried reinstalling and the issue still remains -
Django how to get the value of other fields in annotate Max?
I want to get the value of other fields('status') in annotate Max or Min,how can I do it? DB user time status name_a 2022-01-03 11:23:40.000000 3 name_a 2022-01-03 17:56:41.000000 4 name_a 2022-01-03 22:24:28.000000 1 # data_1 = Attendance.objects.filter(user__in=user_list) data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time")).annotate(e_time=Max("time")) #print {'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28)} i want to get: {'user': 'name_a', 'time__date': datetime.date(2022, 1, 3), 'count': 3, 's_time': datetime.datetime(2022, 1, 3, 11, 23, 40), 'e_time': datetime.datetime(2022, 1, 3, 22, 24, 28), 's_status': '3', 'e_status': '1' } I tried adding filter but I didn't succeed data_2 = data_1.values('user', 'time__date').annotate(count=Count('time__date')).annotate(s_time=Min("time"), e_time=Max("time")).annotate(s_status=F("status"),filter=Q(time=Min("time"))).annotate(e_status=F("status"),filter=Q(time=Max("time"))) -
Do I need multiple custom permission classes for different object types?
Now for a example I have a course model with community has the foreign key. In my custom permission class has_object_permission I would check if UserCommunity.objects.filter(user=request.user, community=obj.community,role="admin").exists() Grant access Now I have various different models, for example a course post which has a foreign key to the Course and I can thus access the community from this course key. Do I need to create multiple custom permission classes for these different objects? Is there a better way. I've named my first permission class as IsCommunityAdminOrCreator, now all I can imagine happening is IsCommunityAdminOrCreatorCoursePost IsCommunityAdminOrCreatorCourseChallenge And so on... -
How customize permissions in django (not in DRF)?
How customize permissions for updating and deleting objects just for creator (author) in view.py (CRUD classes)? I know classes LoginRequiredMixin and PermissionRequiredMixin, but I cant customize them to make permission just for creator (author) to change exact object. I know how customize permission in DRF using class IsAdminOrReadOnly, for example: class IsOwnerOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True return bool(obj.user == request.user or request.user.is_staff) The question is: How customize permissions in django (not in DRF)? Thank you in advance. I hope you could give me piece of advice, link to the article, or documentation, or example of code to solve this problem. I've read Custom users and permissions, but I haven't got how to solve my exact task. -
cannot connect to mysql database ubuntu 20.4 (VPS) "ModuleNotFoundError: No module named 'MySQLdb'"
I am working on the setup of my first unmanaged vps(ubuntu 20.4) and following the document to connect my django site to mysql server "https://www.digitalocean.com/community/tutorials/how-to-create-a-django-app-and-connect-it-to-a-database" able to setup python/django/virtualenv mysql server - tested from mysql workbench on my local machine-Ok apache2 working ok. able to see the welcome screen with sqlite3. now moving to mysql. i tried both the way('ENGINE': 'django.db.backends.mysql' and option file '/etc/mysql/my.cnf' to connect to mysql server from django project. None of the alternatives working. activated virtualenv, installed mysqldb using a) sudo apt install libmysqlclient-dev default-libmysqlclient-dev b) pip install wheel c) pip install mysqlclient while trying to migrate following error encountered. tried with all the option available on stakoverflow, i found none of them working. Error: " (envFusion) worker@server:~/fusion/fusionerp$ python manage.py makemigrations Traceback (most recent call last): File "/home/worker/fusion/envFusion/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 15, in import MySQLdb as Database ModuleNotFoundError: No module named 'MySQLdb' The above exception was the direct cause of the following exception: . . File "/home/worker/fusion/envFusion/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 17, in raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? " -
Potential Django/Celery/amqp threading issues
I'm currently working with a system which provides a Django backend to serve up a rest API. In addition to this we provide updates to a RabbitMQ instance using celery upon change to records within the Django app. uwsgi is used to host multiple (5) instances of the Django backend, and also has an attach-daemon setting which launches 5 celery worker instances, ie: attach-daemon = %(home)/bin/celery --app=djangoProject.worker.app worker -c 5 -l INFO We have recently added some functionality which increases the rate of updates in some circumstances and have discovered we are not generally getting UnexpectedFrame errors from within the amgqp library: amqp.exceptions.UnexpectedFrame: Received 0x00 while expecting 0xce We suspect this is some form of threading type issue, but looking for any advice to overcome the problem. Looking for any advice on how to over come this sort of issue, or to at least further diagnose where the fault lies. -
Django Static Assets Not Found (404) in Docker Container
I've recently configured my Django project with Docker. When I run my container, my Django app running but is missing (404) all of the static assets: GET http://localhost:8000/static/theme/css/sb-admin-2.min.css net::ERR_ABORTED 404 (Not Found) The assets load without issue outside of the Docker container. My Django project is configured to use WhiteNoise. I know that many people say it's not worth the trouble, and just migrate static assets to S3. I'll resort to that if I must, but I'd really like to try and get this to work for my local environment configuration. Here's the relevant configuration: project structure: - cs-webapp - cs - settings.py - urls.py - wsgi.py - staticfiles/ ... - webapp - migrations/ - models/ - views/ ... Dockerfile docker-compose.yml manage.py ... settings.py BASE_DIR = Path(__file__).resolve().parent.parent print("!!!!!! BASE_DIR IS " + str(BASE_DIR)) # this prints '/app' STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' #STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' docker-compose.yml version: '3' services: app: build: context: . ports: - "8000:8000" volumes: - /app command: > sh -c "sleep 10; python manage.py collectstatic --noinput && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" env_file: - .env - db.env depends_on: - db rabbitmq: ... celery-worker: ... celery-beat: ... db: ... Dockerfile FROM python:3.7-alpine …