Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
convert downloaded image into jpeg format and save locally
I have succesfully obtained the profile picture url from facebook api.But want to save in a a image feild. I tried some code from stack overflow , but the stored image contains nothing.Help me with it? here's my code Models.py class Userinfo (models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length = 200) email = models.CharField(max_length = 200) city = models.CharField(max_length = 100, null = True) headline = models.CharField(max_length = 200, null= True) contact_number = models.CharField(max_length = 200,null = True) gender = models.IntegerField(null = True) image_url = models.CharField(max_length = 500, null = True) image_file = models.ImageField(upload_to='media/profile_pics/',blank =True) interests = models.CharField(max_length = 400,null = True) about = models.CharField(max_length = 400, null = True) fb_link = models.CharField(max_length = 400, null = True) linkedin_link = models.CharField(max_length = 400, null = True) headline = models.CharField(max_length = 100, null = True) def __str__(self): return self.name def save(self, *args, **kwargs): if self.image_url and not self.image_file: img_temp = NamedTemporaryFile(delete=True) img_temp.write(urlopen(self.image_url).read()) img_temp.flush() self.image_file.save(f"image_{self.pk}", File(img_temp)) super(Userinfo, self).save(*args, **kwargs) i can succesfully save the image to media/profile_pics but the image format is not in jpeg its like this ffd8 ffe0 0010 4a46 4946 0001 0200 0001 0001 0000 ffed 009c 5068 6f74 6f73 686f 7020 332e 3000 3842 494d 0404 0000 … -
Find any exists with conditions in one queryset Django rest framework
Now i have 2 model like this: class RequestSession(models.Model): request = models.ForeignKey(ServiceRequest) start_time = models.DateTimeField(null=True, blank=True) class ServiceRequest(models.Model): post_time = models.DateTimeField(default=timezone.now) Now i want find all ServiceRequest have one or more RequestSession have start_time__gte=now() with one query from ServiceRequest. I want it keep instance queryset for paging auto in django It will have result same this : result = [] queryset = ServiceRequest.objects.all() current_time = timezone.now().replace(second=0, microsecond=0) for service_request in queryset: if RequestSession.objects.filter(start_time__gte=current_time, request=service_request).exists(): result.append(service_request) But like you see, it return array. I hoop it is queryset How to do it? Thank you -
How use TemplateView with 2 methods (get and post)
I am trying to use Templateview in Django to render a page with options for both adding to the database and retrieving some info from the database and displaying it. I am basing it on the tutorial at https://www.youtube.com/watch?v=VxOsCKMStuw views.py: class TestView(TemplateView): template_name = 'app/sensor_name_tmpl.html' def get(self, request): form = SensorForm() posts = Sensor.objects.all() args = {'form': form, 'posts': posts} return render(request, self.template_name, args) def post(self, request): form = SensorForm(request.POST) if form.is_valid(): form.save() text = form.cleaned_data['post'] form = SensorForm() return redirect('sensor_name_tmpl:sensor_name_tmpl') args = {'form': form, 'text': text} return render(request, self.template_name, args) urls.py: urlpatterns = [ path('', views.index, name='index'), url(r'^form1/$', views.get_sensor_name, name='GiveSensorName1'), #url(r'^form2/$', TestView.as_view(), name='sensor_name_tmpl.html'), path('form2/', TestView.as_view(), name='app/sensor_name_tmpl.html'), url(r'^nested_admin/', include('nested_admin.urls')), ] The page renders the template but doesn't populate it with either the formfields or the data from the database. -
Django Rendering images in Email templates
I have created the email template as shown below {% load staticfiles %} <h1 style="color:red; background-image:url('../images/contact.jfif')">Welcome {{contact_name}}!</h1><br> Your username is {{ contact_email }} and your content is {{ form_content }}. <img src="{{ request.get_host }}{% static 'images/logo.png' %}" alt="ddddd" /> - xyz </div> But the image is not getting displayed in the email and showing error Can anyone help me by providing the solution -
when i change my port my template of django-suit change
I'm using django-suit v2 and everything is working properly. But at this moment I want to open my port's, so that everyone who is connected to my network can work on the program. So I do (python manage.pt runserver 0.0.0.0:9191) When I do this, my forms, popus and even the widget of date does not work -
How to make controllers in Django
I have knowledge about PHP frameworks and Node js framework but now i am learning Django. So please help me to know that how to make controllers in Django. Thanks in advance. -
How to debug gunicorn [6383] [CRITICAL] WORKER TIMEOUT?
In my busy Django 1.8 site, I get loads of 502 errors due to gunicorn worker timeout: [2019-06-11 04:56:29 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:6550) [2019-06-11 04:56:31 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:6439) [2019-06-11 04:56:31 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:7210) [2019-06-11 04:56:33 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:6429) [2019-06-11 04:56:46 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:6562) [2019-06-11 04:59:41 +0000] [6383] [CRITICAL] WORKER TIMEOUT (pid:6560) gunicorn.version 19.9.0 Here is my guniconrn.sh configuration #!/bin/bash NAME="myapp" SOCKFILE=/tmp/gunicorn.sock USER=myuser GROUP=www-data NUM_WORKERS=48 DJANGO_SETTINGS_MODULE=myapp.settings DJANGO_WSGI_MODULE=myapp.wsgi MAX_REQ=20000 REQ_TIMEOUT=10 LOG_FILE=/var/log/gunicorn/error.log echo "Starting $NAME as `whoami`" cd $DJANGODIR source /home/myuser/.myappenv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/myuser/.myappenv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --user=$USER --group=$GROUP \ --bind=unix:$SOCKFILE \ --log-level=error \ --log-file $LOG_FILE \ --max-requests=$MAX_REQ \ --timeout=$REQ_TIMEOUT --worker-class="egg:meinheld # --worker-class=eventlet --threads=2000` The server has 128GB of RAM and a 24 core CPU. The error usually happens when the load is +20 I have tweaked a lot of parameters from NUM_WORKERS, REQ_TIMEOUT, worker-class and threads. But none seem to have much effect. So I've ran out of ideas and appreciate your hints. -
Moviepy waiting for resource
I am using moviepy to insert a text into different parts of the video in my Django project. Here is my code. txt = TextClip('Hello', font="Tox-Typewriter") video = VideoFileClip("videofile.mp4").subclip(0,31) final_clip = CompositeVideoClip([video, txt]).set_duration(video.duration) final_clip.write_videofile("media/{}.mp4".format('hello'), fps=24,threads=4,logger=None) final_clip.close() I am getting the video written to a file in 10s and showing the video in browser. The issue is when there are simultaneous requests to the server. Say there are 5 simultaneous requests coming to the server, then each response will take 50 s each. Instead of giving each response in 10s. It seems that there is some resource which is used by all these requests, and one is waiting for the another to release the resource. But could not find out where it is happening. I have tried using 5 separate file for each request thinking that all the requests opening same file is the problem, but did not work out. Please help me to find a solution. -
Why my sidebar jumps down when i click on a tag?
I made a central css file, and now my sidebar jumps when i click on the tag. At the frontpage everything is fine. Also at the post_detail page the sidebar is where it has to be. Just when i click on the tag it jumps down. I added also some screenshots, so you can see what i mean. I inspected the website, but everything looks fine. Maybe you have some advice? The URL of my site is code-reminder.com -
Why does my Django Project not recognize apps installed on the settings?
I am trying to build my portfolio in Django and encountered an error after installing my app. It seems like it doesn't recognize the app on my INSTALLED_APPS. I've tried using 'blog' and 'blog.apps.BlogConfig' but nothing seems to be recognized. I run the runserver with python manage.py runserver and python manage.py runserver but both returns ModuleNotFoundError: No module named 'blog.urls' This is the whole traceback Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 917, in _bootstrap_inner self.run() File "/usr/local/Cellar/python/3.7.3/Frameworks/Python.framework/Versions/3.7/lib/python3.7/threading.py", line 865, in run self._target(*self._args, **self._kwargs) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 117, in inner_run self.check(display_num_errors=True) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/management/base.py", line 390, in check include_deployment_checks=include_deployment_checks, File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/management/base.py", line 377, in _run_checks return checks.run_checks(**kwargs) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/checks/registry.py", line 72, in run_checks new_errors = check(app_configs=app_configs) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 398, in check for pattern in self.url_patterns: File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 579, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/Users/usr/django-portfolio/env/lib/python3.7/site-packages/django/urls/resolvers.py", line 572, in urlconf_module return import_module(self.urlconf_name) File "/Users/usr/django-portfolio/env/lib/python3.7/importlib/__init__.py", line 127, in … -
Parallel Processing in Django
I get a file from the user. Once the file has been uploaded and saved, Now this file has to be analysed. Since it is a huge file and analysis takes minimum 1 hour (say), I have a field in the model saying the status of the analysis as Analysing or Analysis Done. The script for analysing is a separate python file and the analysis has to be done there. How do I go about doing this? I want this script to run at the background. Also I have to deploy in apache server. How should I proceed? Should I use threads? How do I go about using external python scripts in threads? I came to know about CronTabs, But I don't know how can I implement in this situation. I can't use Celery, since Celery has been stopped for Windows I came to know about Django Management Commands. But since I deploy using an Apache server, I don't know whether I can do that. -
Django 2.2 | Auto-reload doesn't detect changes in new apps
Just created a new project with Django CLI. My project split into multiple apps so the structure is like this: project app1/ .. migrations/ views/ __init__.py apps.py urls.py core/ .. migrations/ views/ __init__.py apps.py urls.py project/ settings/ __init__.py common.py development.py __init__.py urls.py wsgi.py I'm using Docker to build the environment and make sure that both apps registered in the INSTALLED_APPS property. The problem is that the Django doesn't listen to app1 app, but only to core app. Also, if I add another folder under the core app, it's doesn't listen to this folder as well. I've changed the BASE_DIR property to support the new structure: BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) Any suggestions? -
Reference a ManyToManyField in the __str__ method of a django model
In the str method of a Django model I am trying to reference a field that is a ManyToManyField. class Level(models.Model): code = models.CharField(max_length=10) name = models.CharField(max_length=60) def __str__(self): return self.code class Excercise(models.Model): title = models.CharField(max_length=100, unique=True) level = models.ManyToManyField(Level) def __str__(self): return self.level.code + ') ' + self.title[:20] The last line of the code return self.level.code + ') ' + self.title[:20] Produces the error: 'ManyRelatedManager' object has no attribute 'code'. I use Python 3.6 and Django 2.2.2 -
How to use some models inside Meta of ModelsResource (django-import-export)?
I have some models, and I created ModelResource classes for them. Next I had tested view (def) one of them it is works, all is ok. But ,my task is an excel form with fields from diffrient models. So what i have to do? I have to create multimodel resource (I havn't found how to do this in django-import-export docs) or I need integrate some resources in a united view? this my view def realreport(request): renter_info = RentersRes() datasetrent = renter_info.export() response = HttpResponse(datasetrent.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="renter_info.xls"' return response -
Write Django API view for sign in function
I dont have any experience on writing API, so i need to write API for sign in function. I need to enter login and password and if it is correct then i have a permission to enter to the website.Here is what i have: Thats my view for sign in class CustomLoginView(LoginView): template_name = 'accounts/sign_in.html' form_class = SigninForm def form_valid(self, form): super().form_valid(form) user = form.get_user() if form.get_cook_role(): user.profile.cook_role = form.get_cook_role() if form.get_role(): user.profile.role = form.get_role() user.profile.save() auth_login(self.request, form.get_user()) return HttpResponseRedirect(self.get_success_url()) thats my model of User: class Profile(ProfileMixin, models.Model): organization = models.ForeignKey(Organization, null=True, on_delete=models.CASCADE) user = models.OneToOneField(User, on_delete=models.CASCADE) online = models.BooleanField(default=False) avatar = models.ImageField(upload_to='profile/avatars/', null=True, blank=True) gender = models.CharField(max_length=10, blank=True, choices=GENDER_CHOICES.get_choices()) role = models.PositiveIntegerField('Роль пользователя', default=STAFF_ROLES.COOK, choices=STAFF_ROLES.choices) cook_role = models.ForeignKey(CookRole, verbose_name='Роль на кухне', null=True, blank=True, related_name='users', on_delete=models.CASCADE) birthday = models.DateField(null=True, blank=True) here is my urls urlpatterns = [ url(r'^signin/', views.CustomLoginView.as_view(), name='signin'), url(r'^signout/$', views.sign_out, name='signout'), ] Please describe the steps that i should follow in order to write API with which i can sign in to the system -
how to make specific model field dynamic from another model
I have two models Damaged and Product.In the Product model the quantity of the product depends upon the value of damaged_quantity which is stored in another table.For example if the damaged_quantity is in damaged table then the value of quantity in product should be 'quantity-damaged_quantity' if the 'damaged.product_id == product.id' .I tried like this but it is not working models.py class Damaged(models.Model): product = models.ForeignKey('Product', on_delete=models.CASCADE) damaged_quantity = models.IntegerField(default=0) def __str__(self): return self.product class Product(models.Model): name = models.CharField(max_length=250) category = models.ForeignKey(Category,on_delete=models.CASCADE) quantity = models.IntegerField() def save(self, *args, **kwargs): damaged_quantity = self.damaged_set.all().aggregate(sum=Sum('damaged_quantity')).get('sum', 0) if damaged_quantity is None: self.damaged_quantity = 0 else: self.damaged_quantity = damaged_quantity self.quantity = self.quantity - self.damaged_quantity super(Product, self).save(*args, **kwargs) -
My App is not visible in the django admin
I have this code: from django.contrib import admin from test_app.models import Master, Detail class DetailInline(admin.TabularInline): model = Detail class MasterAdmin(admin.ModelAdmin): inlines = [DetailInline] admin.register(Master, MasterAdmin) But somehow it does not get displayed in the django admin index page. Other apps are listed, and their admin.py file looks similar. What's wrong with this code? -
QuesrySet eror in django
I have some models: class OrdersTrigger(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) order_trigger = models.ForeignKey(Order, related_name='trigger', on_delete=models.CASCADE) .... created_at = models.DateTimeField(auto_now_add=True) class Order(models.Model): from_bank = models.ForeignKey(Bank, on_delete=models.CASCADE) to_bank = models.ForeignKey(Bank, related_name='to', on_delete=models.CASCADE) I'm getting list of orders from this model using filters : orders = OrdersTrigger.objects.filter(Q(order__from_bank_=baseBank) & Q(order__to_bank=quoteBank))\ .filter(created_at__gte=latest_time).order_by('-created_at') when i try to iterates through the list: for order in orders: or for order in orders.all(): I'm receiving an error: The QuerySet value for an exact lookup must be limited to one result using slicing. Can you help me with this? I can not understand how to fix this error. -
Django test: DRF api cannot access the object created by the Model.objects.create method
I'm writing unittest for my project. I use DjangoRestFramework. And in one of my test case method, I created an object using the Model.objects.create() method, but when I use self.client.get('/api/model/{id}/') after that, I got a 404 Not Found response. def test_0002_company_update_username(self): company = m.Company.objects.create(name='CompanyName') # the following line prints out the object correctly print(m.Company.objects.all()) resp = self.client.get('/api/company/{}/'.format(company.id)) # whlile the below line yields a `404` response, but we expected to get the object we just created, why? print(resp, resp.status_code) -
Django Gregorian Date Validation Error for Persian Jalai Date
I want to use Persian (Jalali) Calender in my project. The prolem occurs with date validation where the input month is second (2 or feb) and the date is 31th. In Jalali calender 31 for date and 2 for date is valid but fails the Gregorian Validation. I tried to use django-jalali package with offers a jDateField, but oddly enough, it uses Gregorian validation regardless of the local settings. How can I cleanly get around this issue? -
how to view image in Django application
I need to view only the image in HTML page. Like : http://localhost:8000/media/project_name/imagenav.jpg Example page : https://s3-media3.fl.yelpcdn.com/bphoto/c7ed05m9lC2EmA3Aruue7A/o.jpg Thanks & Regards, Mohamed Naveen -
null value in column "list_name" violates not-null constraint DETAIL:
I created a function makeList to insert items into the list.Whenever I try to check the API through postman for a POST request, I get the following error null value in column "list_name" violates not-null constraint DETAIL: Failing row contains (16, null). Views Function if request.method == 'POST': list_item = request.POST.get('list_item') ListCategory.objects.create(list_name=list_item) # return something not yet decided full_list = ListCategory.objects.order_by('id') full_list = serializers.serialize('json',full_list) return HttpResponse(full_list, content_type='application/json') Postman Screenshot -
I am getting AttributeError at /issues/ 'WSGIRequest' object has no attribute 'errors' when I am trying to submit the Issue and Feedback form
I created a feedback column in the UserProfile model later and created a form for it only for logged in Users. Also, I created an Issue Model later on. On clicking submit it gives the above error. The feedback entry does not get stored to the entry for it's username instead it cretes a new entry with a primary key. models.py Roles = ( ('sales', 'SALES'), ('operations', 'OPERATIONS'), ('cashier', 'CASHIER'), ('frontdesk', 'FRONTDESK'), ('client', 'CLIENT'), ) class UserProfile(models.Model): user = models.OneToOneField(User,on_delete=models.CASCADE, default=None, null=True) role = models.CharField(max_length=50, choices=Roles, default='client') feedback = models.TextField(default=None, null=True) def __str__(self): return self.user.username class Issue(models.Model): Issues= ( ('Centre', 'Issue about Centre'), ('Appointment', 'Issue about Appointment'), ('Payment', 'Issue about Payment'), ('Others', 'Others'), ) Issue = models.CharField(max_length=50, choices=Issues, default=None) Description = models.TextField() username = models.ForeignKey(User, on_delete = models.CASCADE) def __str__(self): return self.username.username forms.py(related): class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('role',) class FeedbackForm(forms.ModelForm): class Meta(): model = UserProfile fields = ('feedback',) class IssueForm(forms.ModelForm): class Meta(): model = Issue fields = '__all__' views.py(for issues and feedback): @login_required def feedback(request): if request.method =='POST': form = FeedbackForm(request.POST) if form.is_valid(): form.save(request.POST) else: form = FeedbackForm() return render(request, 'NewApp/feedback.html',{'form':form}) @login_required def issues(request): if request.method == 'POST': form = IssueForm(request.POST) if form.is_valid(): form = … -
How to add a data to database in templates which have a foreign key to users?
I'm new in python and I have code that show me a list of pages,hashtags and etc. Now I want to add a new page to the list and these pages have foreign key to users in Models.Please guide me how can I do so in views. I have these codes: in Models: class pages(models.Model): userr = models.ForeignKey(User, on_delete=models.CASCADE) id = models.UUIDField(primary_key=True, default=uuid.uuid4) name = models.CharField(max_length = 300, null=False, blank=False) def __str__(self): pgs = str(self.name) return (pgs) -
How to edit the dropdown in the django admin site
So I have three classes as shown below. When I'm entering the data for table4, when I enter the topic name, I want only questions of that chosen topic to come in the dropdown for the question field. Is there any way to do this? Also, in my admin.py, I have only registered the tables. class table5(models.Model): topic_name=models.CharField(max_length=222,primary_key=True) def __str__(self): return self.topic_name class table3(models.Model): id1=models.IntegerField(default=0) topic=models.ForeignKey(table5, related_name='topic1',on_delete=models.CASCADE) question=models.CharField(max_length=222,primary_key=True) answer=models.CharField(max_length=222) def __str__(self): return self.question class table4(models.Model): username = models.CharField(max_length=222,primary_key=True) topic=models.ForeignKey(table5, related_name='topic111',on_delete=models.CASCADE) question1=models.ForeignKey(table3, related_name='question3',on_delete=models.CASCADE) answer = models.CharField(max_length=222) def __str__(self): return self.username