Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django/Plotly - Click events with JS
I'm able to simply display my plot (3D scatter) using Plotly. I'm trying to implement a click event feature. Once I click at any of the plot point I'd like to change its color. According to official Plotly documentation it's not that hard: Plotly - click event All I can see is that the points I click are being clicked (console logs). Does anyone got some clue why I'm not able to the change the color in a real time ? Thanks in advance. Here's my snippets: Template: {% extends 'base.html' %} {% load static %} {% block css %} <script src="{% static 'js/plotly-latest.min.js' %}"></script> {% endblock %} {% block content %} <div id="single_plot"> {{ plot_as_div|safe }} </div> {% endblock %} {% block js %} <script src="{% static 'js/plot_select_markers.js' %}"></script> {% endblock %} plot_select_markers.js $(document).ready(function () { var plot_div_id = $('#single_plot').children().attr('id'); var plotly_scatter_div = document.getElementById(plot_div_id); var color_select = '#7b3294'; plotly_scatter_div.on('plotly_click', function (data) { var pn = '', tn = '', colors = []; for (var i = 0; i < data.points.length; i++) { pn = data.points[i].pointNumber; tn = data.points[i].curveNumber; colors = data.points[i].data.marker.color; } colors[pn] = color_select; var update = { 'marker': { color: colors, size: 7 } }; Plotly.restyle(plotly_scatter_div, update, … -
explanation for in loop Python/Django [duplicate]
This question already has an answer here: Python for-in loop preceded by a variable 4 answers I'm following the official tutorial on Django and i came across this lines def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] output = ', '.join([q.question_text for q in latest_question_list]) return HttpResponse(output) It's everything clear except for the for in loop and i can't find anywhere where to understand how it is written. Why q.question_text is BEFORE the for in loop? I already looked at the other question questioning this line of code, but i cannot fine anywhere some python documentation that explain me how the syntax of this loop works, even though i can understand what it does. Also i'm new to python and i am clearly miss something... -
Django Disable/Exclude Field in CreateView but enable/include it in UpdateView
I would like to exclude/disable a Charfield (with options and a default value) when creating a new object, but when editing this object, I would like to enable / include the Charfield for the user to change it. So far I tried this answer I found here on Stackoverflow, but it wasn't the full solution for me. The Charfield did get disabled but when I tried to create my object, Django would always tell me that the field is required (even though it has a Default Value). My code: class OfferCreateForm(forms.ModelForm): class Meta: model = Offer exclude = ['date', 'number'] def __init__(self, *args, **kwargs): request = kwargs.pop("request", None) super(OfferCreateForm, self).__init__(*args, **kwargs) instance = getattr(self, 'instance', None) if instance and instance.pk: self.fields['status'].widget.attrs['disabled'] = False else: self.fields['status'].widget.attrs['disabled'] = True self.helper = FormHelper() self.helper.form_tag = False self.helper.help_text_inline = True self.helper.add_layout(Layout( Fieldset('Angebot', Row( Div( Field('name'), css_class='col-sm-12' ), Div( Field('category'), css_class='col-sm-6' ), Div( Field('status'), css_class='col-sm-6' ), )), Fieldset('Kunde', Row( Div( Field('customer', css_class='selectize'), css_class='col-sm-6' ), Div( Field('receiver', css_class='selectize'), css_class='col-sm-6' ), )), Fieldset('Kundeninformation', Row( Div( Field('introduction'), css_class='col-sm-12' ), ), ), Fieldset('Zusätzliche Informationen', Row( Div( Field('footer'), css_class='col-sm-12', ), ), ), )) def clean_status(self): instance = getattr(self, 'instance', None) if instance and instance.pk: return instance.status else: return self.cleaned_data['status'] The … -
django.db.migrations.exceptions.InconsistentMigrationHistory issue after creating my own custom user model
i have created my own custom user profile model in django and when i tried to run migrations & migrate command i'm coming up with an error as django.db.migrations.exceptions.InconsistentMigrationHistory: Migration authtoken.0001_initial is applied before its dependency profiles_api.0001_initial on database 'default' here is my models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.contrib.auth.models import BaseUserManager # Create your models here. class UserProfileManager(BaseUserManager): def create_user(self,email,name,password=None): if not email: raise ValueError("email is required") email=self.normalize_email(email) user=self.model(email=email,name=name) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,password): """creates new super user with details """ user=self.create_user(email,name,password) user.is_superuser=True user.is_staff=True user.save(using=self._db) return user class UserProfiles(AbstractBaseUser,PermissionsMixin): email=models.EmailField(max_length=255,unique=True) name=models.CharField(max_length=255) is_active=models.BooleanField(default=True) is_staff=models.BooleanField(default=False) objects=UserProfileManager() USERNAME_FIELD='email' REQUIRED_FIELD=['name'] def get_fullname(self): return self.name def get_shortname(self): return self.name def __str__ (self): return self.email in setting i have added AUTH_USER_MODEL='profiles_api.UserProfiles' and i have tried to remove my initial database like 000init.py files and check if this could work any kind of help is appreciated thanks in advance -
Django & Celery: Do I need transaction.atomic/locking in order to avoid race-conditions?
Users in my app can import data fetched from an API into my Django database. The API uses paging if there are > 100 results to fetch. I obviously don't want the users to wait to for a possibly big number of items to import. So I'm doing the first call to the API in the request, and then delegating the rest to Celery. > User requests an API item with 250 items > Fetch 100 and return > Fetch 150 more in a celery task I'm worried database corruption. I'm running my app on Heroku with the following configuration in the Procfile: web: daphne app.asgi:channel_layer --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py migrate --noinput && python manage.py runworker -v2 celerybeat: celery -A app beat -l info celeryworker: celery -A app worker -l info And I call the task like so: if rginitial_count >= 100: continue_doing_imports.delay(artist_mbid=self.mbid, artist_name=self.name, offset=100) How can I insure consistent behavior? for example, user A is importing data for Artist X, and at the same time user B attempts to subscribe to that same artist, therefore needing to write to his relationships? that's one scenario I can think of. -
Disabling Django Silk for specific URLs
I have an API endpoint on which I can upload a photo using a multipart request. When Silk is trying to parse the request, I get a decoding error. I now want to disable Silk for certain URL endpoints. Is this already possible? If so, how should I configure this? If not, what is the easiest way of temporarily disabling Silk altogether? Link to Github issue: https://github.com/jazzband/django-silk/issues/292 -
How to display values of object for which check box is ticked?
In my django project, there is an object named Point. It is defined like this in models.py : class Point(models.Model): name = models.CharField(max_length = 30, unique = True) # name of the point x = models.IntegerField(default = 1) # x coordinate of point y = models.IntegerField(default = 2) # y coordinate of point z = models.IntegerField(default = 3) # z coordinate of point def __str__(self): return self.name+":("+str(self.x)+","+str(self.y)+","+str(self.z)+")" I want to make an interface which shows all the points with check boxes which can used to display and update points information. It looks like this: This is my code in views.py: def update_here(request): """ Used to update any coordinates of any point. """ points_list = Point.objects.all() if request.method == 'POST': x1 = request.POST['x_value'] y1 = request.POST['y_value'] z1 = request.POST['z_value'] point = Point.objects.get(name = "Vizag") point.x = x1 point.y = y1 point.z = z1 point.save() return redirect('update_here') return render(request,'update_here.html',{'points_list_in_html':points_list}) And my html code I've written till now (I am to display the values in boxes when checkbox of a point is ticked) in update_here.html: <html> <head> <title>Update here</title> <script type="text/javascript"> var helper = { numb : function(numberOfBlanks,xx,yy,zz){ var checked=0; var j=0; var k; for(j=0; j<numberOfBlanks.length; j++){ if(numberOfBlanks[i].checked){ break; } } return j; … -
Django aggregation taking a lot of time
I have a model defined as bellow class Image(model.Models): # Stages STAGE_TRAIN = 'train' STAGE_VAL = 'val' STAGE_TEST = 'test' STAGE_TRASH = 'trash' STAGE_CHOICES = ( (STAGE_TRAIN, 'Train'), (STAGE_VAL, 'Validation'), (STAGE_TEST, 'Test'), (STAGE_TRASH, 'Trash'), ) stage = models.CharField(max_length=5, choices=STAGE_CHOICES, default=STAGE_TRAIN) commit = models.ForeignKey(Commit, on_delete=models.CASCADE, related_name="images", related_query_name="image") In my database I have 170k images and I try to have an endpoint that will count all the images by stage Currently I have something like that base_query = Image.objects.filter(commit=commit_uuid).only('id', 'stage') count_query = base_query.aggregate(count_train=Count('id', filter=Q(stage='train')), count_val=Count('id', filter=Q(stage='val')), count_trash=Count('id', filter=Q(stage='trash'))) but it takes around 40sec and when I try to see the SQL request in my shell I have something that looks ok {'sql': 'SELECT COUNT("image"."id") FILTER (WHERE "image"."stage" = \'train\') AS "count_train", COUNT("image"."id") FILTER (WHERE "image"."stage" = \'val\') AS "count_val", COUNT("image"."id") FILTER (WHERE "image"."stage" = \'trash\') AS "count_trash" FROM "image" WHERE "image"."commit_id" = \'333681ff-886a-42d0-b88a-5d38f1e9fe94\'::uuid', 'time': '42.140'} an other strange thing is that if I change my aggregate function with count_query = base_query.aggregate(count_train=Count('id', filter=Q(stage='train')&Q(commit=commit_uuid)), count_val=Count('id', filter=Q(stage='val')&Q(commit=commit_uuid)), count_trash=Count('id', filter=Q(stage='trash')&Q(commit=commit_uuid))) When I do that the query is twice as fast (still 20sec) and when I display the SQL I see that the filter on the commit is done inside the FILTER So I have two questions: … -
What's the most popular web server or architecture?
I heard some companies use Django only and some use Ruby on Rails and some use Django/RubyOnRails + Java backend (the web server forward all the requests to the Java back server to retrieve data and doing business logic). So, which is the preferred way of hosting a web application? And what are the reasons behind this? -
How to show multiple charts on Django use python-highcharts?
How to show multiple charts on Django use python-highcharts ? When I Show multiple charts,it shows Uncaught Error: Highcharts error #16: www.highcharts.com/errors/16 And other charts always show Loading... Only one chart can show . error detail: "Highcharts already defined in the page This error happens the second time Highcharts or Highstock is loaded in the same page, so the Highcharts namespace is already defined. Keep in mind that the Highcharts.Chart constructor and all features of Highcharts are included in Highstock, so if you are running Chart and StockChart in combination, you only need to load the highstock.js file" Thank you -
Two processes want to access same python file
I have a scenario like Process1 and Process2 want to access same python file(sample.py). With respect to each process some code snippet is written. I don't want Process1 to access Process2 related python code and vice versa. Process A from myapp1 import ABC Process B from myapp2 import DEF from myapp1 import ABC should not be accessible in Process B and from myapp2 import DEF should not be accessible in Process A -
Extending django related field widget wrapper
I am trying to extend the related field widget wrapper, in order to add another custom button to it. The button gets added, but I am losing the drop-down widget. widget.py - class IpRequestWidget(RelatedFieldWidgetWrapper): template_name = 'widgets/custom_widget.html' @property def media(self): js = [static('custom/js/widget.js'), ] css = {'all': [static('custom/css/widget.css'), ]} return forms.Media(js=js, css=css) def get_context(self, name, value, attrs=None): return {'widget': { 'name': name, 'value': value, }} def render(self, name, value, attrs={}): context = self.get_context(name, value, attrs) template = loader.get_template(self.template_name).render(context) return mark_safe(template) custom_widget.html {% extends 'admin/widgets/related_widget_wrapper.html' %} {% load static %} {% block links %} {% spaceless %} <input type="button" onclick="getAvailableIp()" value="Get available IP"/> {% endspaceless %} {% endblock %} Admin form - class IpAddressAdminForm(forms.ModelForm): class Meta: exclude = [] widgets = {'subnet': IpRequestWidget(forms.widgets.Select(), IpAddress._meta.get_field('subnet').remote_field, site)} Output - -
django rest registration api error: this field is required
Hello i want to create a simple registration api for my django rest api But when i want to test the registration with curl i get always get this error: {"username":["This field is required."],"password":["This field is required."]} This is my curl cmd: curl --request POST --url http://localhost:8000/auth/register/ --header 'content-type: application/json' --data '{"username": "user1","password": "hunter2"}' views.py RegistrationApi class RegistrationAPI(generics.GenericAPIView): serializer_class = CreateUserSerializer def post(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() return Response({ "user": UserSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user) }) serializers.py class CreateUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': True}} def create(self, validated_data): user = User.objects.create_user(validated_data['username'], None, validated_data['password']) return user class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username') Maybe there is something wrong with the serializers? I already tried so figure out where the problem is but i cant find it -
Custom schema for class-based view in django rest framework for Sagger
I have the following problem. There are a couple of non-model view in my module. So for them I need to write schema explicitly. I came around two solutions fro this problem: Create a special api_schema_generator() with schema description def api_schema_generator(): api_schema = coreapi.Document( title="Market", content = { "User Adresses": { "int_api_get": coreapi.Link( url="/v1/market/calendar/biz_day/", action="get", description="Get the next buisness day", fields=[ coreapi.Field( name = "region_id", required=True, location="path", description="Unique region ID" ), coreapi.Field( name="base_date", required=False, location="path", description="Unique region ID" ), ] ) } } ) But the main disadvantage of this approach is that there are some views that can be generated automatically, cause they have module serializer. Moreover, I think it is better to describe class schema within class-view. So, the second solution is something like that: class BizDay(GenericAPIView): schema = ManualSchema(fields=[ coreapi.Field( name="region_id", required=True, location="path", description="Unique region ID" ), coreapi.Field( name="base_date", required=False, location="path", description="Unique region ID" ), ]) serializer_class = BizDayReq def get(self, request, version): serializer = BizDayReq(data=request.query_params) serializer.is_valid(True) data = serializer.validated_data regions = data['regions'] base_region = regions[0] days_offset = data['days_offset'] cutoff_region = data['cutoff_region'] cutoff_hour = data['cutoff_hour'] calendar = TradingCalendar(*regions) if data.get('base_date'): dt_now = convert.timestamp_to_datetime(data['base_date'], base_region) else: dt_now = convert.get_current_datetime(base_region) cutoff_dt = convert.get_current_datetime(cutoff_region) cutoff_dt = cutoff_dt.replace(hour=cutoff_hour, minute=0, second=0, microsecond=0) … -
Annotate over a field of intermediate model django
I have the following scheme: class User(AbstractUser): pass class Task(models.Model): pass class Contest(models.Model): tasks = models.ManyToManyField('Task', related_name='contests', blank=True, through='ContestTaskRelationship') participants = models.ManyToManyField('User', related_name='contests_participated', blank=True, through='ContestParticipantRelationship') class ContestTaskRelationship(models.Model): contest = models.ForeignKey('Contest', on_delete=models.CASCADE) task = models.ForeignKey('Task', on_delete=models.CASCADE) cost = models.IntegerField() class ContestParticipantRelationship(models.Model): contest = models.ForeignKey('Contest', on_delete=models.CASCADE) user = models.ForeignKey('User', on_delete=models.CASCADE) task = models.ForeignKey('Task', on_delete=models.CASCADE, related_name='contests_participants_relationship') is_solved = models.BooleanField() Now I get the contest object and need to fetch all tasks over the tasks field, rach annotated with count of users solved it. So, I need to count the number of ContestParticipantRelationship with needed task, needed contest and is_solved set to True. How to make such a query? -
SQL QUERY TO GET DISTINCT DATA FROM PARTICULAR COLUMN WITHOUT ANY CHANGES TO OTHER DATA OF THE COLUMN
My code- select Insurance,PolicyTpe, case when Insurance='Takaful International Company' and PolicyTpe='Self Funded' and Insurance='TIC - BANAGAS' then (select ActiveMemberCount from temp where Insurance='TIC - BANAGAS' and PolicyTpe='Self Funded')+ (select ActiveMemberCount from temp where Insurance='Takaful International Company' and PolicyTpe='Self Funded') when Insurance='Takaful International Company' and PolicyTpe='Medical Policy' and Insurance='TIC - BANAGAS' then (select ActiveMemberCount from temp where Insurance='TIC - BANAGAS' and PolicyTpe='Medical Policy')+ (select ActiveMemberCount from temp where Insurance='Takaful International Company' and PolicyTpe='Medical Policy') else ActiveMemberCount end as ActiveMemberCount from TEMP where Insurance <>'TIC - BANAGAS' order by Insurance OUTPUT Insurance PolicyTpe ActiveMemberCount Bahrain Kuwait Insurance BSC Medical Policy 55 Takaful International Company Medical Policy 12847 Takaful International Company Keep Well 5320 Takaful International Company Self Funded 237 T'azur Company Medical Policy 2610 WANTED THIS OUTPUT Insurance PolicyTpe ActiveMemberCount Bahrain Kuwait Insurance BSC Medical Policy 55 Takaful International Company Medical Policy 12847 Keep Well 5320 Self Funded 237 T'azur Company Medical Policy 2610 -
storing data to database with html form in django
form.valid is not working,when i fill the form the data should store in database using html form and also how to upload image,how to define the form in html page,is there anything wrong in my code,below is my models.py,views.py,forms.py is given,i have search many forums but not able to get answer models.py class Deal(models.Model): Deal_Category = models.CharField(max_length=30, choices=( ('F','Fashion'), ('T', 'Travel') )) Deal_Title = models.CharField(max_length=30,blank=True) Deal_Redemption = models.CharField(max_length=50,blank=True) Deal_Start = models.DateField() Deal_End =models.DateField() Deal_Details = models.CharField(max_length=50,blank =True) Deal_Location= models.CharField(max_length=50,blank =True) Deal_Terms = models.CharField(max_length=50,blank =True) #Images = models.ImageField(upload_to='static/image',blank=True) forms.py class DealForm(forms.ModelForm): class Meta(): model= Deal fields=('Deal_Category','Deal_Title','Deal_Redemption','Deal_Start','Deal_End','Deal_Details', 'Deal_Location','Deal_Terms') def deal_form(request): if request.method == 'POST': form = DealForm(data=request.POST ) print("Deal1") if form.is_valid(): print("Deal2") form.save(commit=True) print("Deal4") -
Django - Redirect to a subclass admin page
I'm creating a web application with Django. In my models.py I have a class BaseProduct and a class DetailProduct, which extends BaseProduct. In my admin.py I have BaseProductAdmin class and DetailProductAdmin class, which extends BaseProductAdmin. I have another class called Channel, with a many to many relation with BaseProduct. In the Channel admin page, I can visualize a list of the BaseProduct objects related to that channel. When I click on a product, the application redirect me to the BaseProduct admin page. When a product of the list is a DetailProduct object, I would like to be redirected on the DetailProduct admin page instead. Any idea on how to do this? -
Geodjango create a new SRID
Hello guys I've been trying to add a shapefile but I'm facing some difficulties since my country's coordinate system isn't part of the gdal library. How can i create a new SRID? -
How to add signal method for my view?
I want to count how may files the user has uploaded. I have added signals.py from django.dispatch import Signal upload_completed = Signal(providing_args=['upload']) And summary.py from django.dispatch import receiver from .signals import upload_completed @receiver(charge_completed) def increment_total_uploads(sender, total, **kwargs): total_u += total to my project. My views upload @login_required def upload(request): # Handle file upload user = request.user if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): newdoc = Document(docfile=request.FILES['docfile']) newdoc.uploaded_by = request.user.profile upload_completed.send(sender=self.__class__, 'upload') #send signal to summary newdoc.save() # Redirect to the document list after POST return HttpResponseRedirect(reverse('upload')) else: form = DocumentForm() # A empty, unbound form # Load documents for the upload page documents = Document.objects.all() # Render list page with the documents and the form return render(request,'upload.html',{'documents': documents, 'form': form}) This effort does not work.I got upload_completed.send(sender=self.__class__, 'upload') ^ SyntaxError: positional argument follows keyword argument How to fix my method? -
Django REST How to filter through a slash?
I'm using Django REST on the API. My Models: class Region(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE) class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='child', on_delete=models.CASCADE) class Ad(models.Model): id = models.IntegerField(primary_key=True, blank=True) title = models.CharField(max_length=30 , help_text='Title ads' , db_column='data') date_create = models.DateTimeField(auto_now=True,help_text='Date Create') description = models.TextField(max_length=300) region = TreeForeignKey(Region,blank=True , null=True, related_name='Reg',on_delete=models.CASCADE) category = TreeForeignKey(Category,blank=True , null=True, related_name='ad',on_delete=models.CASCADE) views = models.IntegerField(blank=True, null=True) price = models.IntegerField(blank=True, null=True) My serializers: class AdSerializer(serializers.ModelSerializer): images = serializers.StringRelatedField(many=True) class Meta: model = Ad fields = ('title', 'description', 'region', 'category','price' , 'date_create','id','views','images') class CategorySerializer(serializers.ModelSerializer): ad = AdSerializer(many=True) child = RecursiveField(allow_null=True,required=False,many=True) class Meta: model = Category fields = ('name','id','ad','child') class RegionSerializer(serializers.ModelSerializer): children = RecursiveField(allow_null=True, required=False,many=True) class Meta: model = Region fields = ('name','id' , 'children') views.py : class AdViewSet(viewsets.ModelViewSet): queryset = Ad.objects.all().order_by('-date_create') serializer_class = AdSerializer how do I now write urls.py, views.py, so I can filter through the slash by region and by category? For example http://localhost:8000/{region}/{category}/. I will be happy for any advice and sorry for in my English -
Django: Column does not exist
So I just pushed an update to the web server and did makemigrations then migrate and everything seems ok, then when I refresh the website page I got this error Traceback: Environment: Request Method: GET Request URL: http://0.0.0.0/ Django Version: 2.0.2 Python Version: 3.5.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'HomePage', 'widget_tweaks', 'Cart'] Installed 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'] Template error: In template /home/django/LovelyMemory/HomePage/templates/HomePage/base.html, error at line 8 column HomePage_product.category_id does not exist LINE 1: SELECT "HomePage_product"."id", "HomePage_product"."category... ^ 1 : {% load static %} 2 : <!DOCTYPE html> 3 : <html lang="en"> 4 : 5 : <head> 6 : <meta charset="utf-8"> 7 : <meta http-equiv="X-UA-Compatible" content="IE=edge"> 8 : <meta name="viewport" content="width =device-width, initial-scale= 1"> 9 : 10 : <title>{% block title %} Lovely Memory {% endblock %}</title> 11 : 12 : <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"/> 13 : <link href="https://stackpath.bootstrapcdn.com/bootswatch/4.1.1/minty/bootstrap.min.css " rel="stylesheet" 14 : integrity="sha384- 4eGtnTOp6je5m6l1Zcp2WUGR9Y7kJZuAiD3Pk2GAW3uNRgHQSIqcrcAxBipzlbWP" crossorigin="anonymous"> 15 : <script defer src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script> 16 : <!--[if lt IE 9]> 17 : <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script> 18 : <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> Traceback: File "/home/django/venv/lib/python3.5/site- packages/django/db/backends/utils.py" in _execute 85. return self.cursor.execute(sql, params) The above exception (column HomePage_product.category_id does not exist LINE 1: SELECT "HomePage_product"."id", "HomePage_product"."category... ^ ) was … -
Overload server django deploy with apache2 and mod_wsgi
I'm with several problem with overload at deploy django with apache2 and mod_wsgi. Follow my steps and setup: Server: Ubuntu 18.04 running at Windows Linux Subsystem (WSL). Install sudo apt install python3 python3-dev python3-pip virtualenv apache2 apache2-dev mysql-server phpmyadmin php-mbstring php-gettex libmysqlclient-dev So, I created a vhost file <VirtualHost *:80> ServerName 127.0.0.20 ServerAlias divisor.local ErrorLog /mnt/d/divisor/logs/error.log CustomLog /mnt/d/divisor/logs/access.log combined #provide from mod_wsgi-express --conf LoadModule wsgi_module "/mnt/d/divisor/env3/lib/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so" Alias /static /mnt/d/divisor/framework/static Alias /media /mnt/d/divisor/framework/media <Directory /mnt/d/divisor/framework> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /mnt/d/divisor/framework/media/> Require all granted </Directory> <Directory /mnt/d/divisor/framework/static/> Require all granted </Directory> WSGIScriptAlias / /mnt/d/divisor/framework/framework/wsgi.py WSGIDaemonProcess divisor display-name=divisor-modwsgi python-path=/mnt/d/divisor/framework/:/mnt/d/divisor/env3/lib/python3.6/site-packages WSGIProcessGroup divisor WSGIApplicationGroup %{GLOBAL} </VirtualHost> With virtualenv active I run: pip install django mod_wsgi When I run apache start. Less than 3 seconds apache overload with 2 proccess. Follow "top" on terminal: PID USER PR NI VIRT RES SHR S %CPU %MEM TIME+ COMMAND 6272 www-data 18 42+ 318844 31608 8692 S 100.7 0.4 0:13.21 apache2 6274 www-data 18 42+ 2017236 8668 3924 S 100.7 0.1 0:12.29 apache2 I try found the problem with sudo lsof -p 6272, log apache2 6272 www-data 0r CHR 1,3 65583669573738507 /dev/null apache2 6272 www-data 1w CHR 1,3 65583669573738507 /dev/null apache2 6272 www-data 3u sock … -
How to Exclude files from coverage?
I am running my unit tests. But i want to exclude some folders and files during tests. Here is my .coverageerc file [run] branch = True source = . omit = Amazon_customers/.coveragerc amazon_customers/tests Amazon_customers/__init__.py Amazon_customers/urls.py Amazon_customers/wsgi.py amazon_customers/test_utils/* /migrations/ /manage.py/ I need exlude these files but it is not working. -
Not able to run cron jobs with django
I followed this link to schedule a cron job: https://github.com/kraiz/django-crontab However, it is not working. Here are snippets of my code. settings.py: CRONJOBS = [ ('2 * * * *', 'LeaveManagement.cron.team_notification' , ' >> /home/nineleaps/Nineleaps/LeaveTracking/cronLog.log')] cron.py: def team_notification(): send_mail("Test", "Hey", 'settings.EMAIL_HOST_USER', ['mahima@nineleaps.com'],fail_silently=False) Running crontab -l command gives this: 2 * * * * /home/nineleaps/Nineleaps/LeaveTracking/venv/bin/python /home/nineleaps/Nineleaps/LeaveTracking/manage.py crontab run 5f84ef47012b65076a7f598581193a10 >> /home/nineleaps/Nineleaps/LeaveTracking/cronLog.log 2>&1 # django-cronjobs for LeaveTracking