Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
My view doesn't work, here is my urls.py, i can't understand what i'm doing wrong. It just returns "Page not found"
My view doesn't work, here is my urls.py, i can't understand what i'm doing wrong. It just returns "Page not found" from django.contrib import admin from django.views.generic import TemplateView from django.urls import path, include from django.conf.urls import url, include from django.contrib.auth.decorators import login_required from carts.views import cart_home, cart_update from . import views urlpatterns = [ url(r'^cart/', include("carts.urls", namespace='cart')), ] views.py from django.shortcuts import render, redirect from billing.models import BillingProfile from orders.models import Order from products.models import Product from .models import Cart # Create your views here. def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, 'carts/home.html', {"cart": cart_obj}) -
Filtering a table using datetimepicker
I have a table that contains some data and I currently have a jQuery that filters data in the table so that only data that contains the users input will appear without having to refresh the page: <script> //No Results message $(document).ready(function () { (function ($) { $("#myInput").keyup(function () { var rex = new RegExp($(this).val(), "i"); $("#myTable tr").hide(); $("#myTable tr").filter(function () { return rex.test($(this).text()); }).show(); $(".noResults").hide(); if($("#myTable tr:visible").length == 0) { $(".noResults").show(); } }) }(jQuery)); }); </script> Now i want to implement datetimepicker so that the date/week i pick will also filter out the data in the table. However this does not work. The jQuery only works when I type my query in, not when i select a date from the calendar that appears. -
Sentry error - Temporary failure in name resolution
I got an error on my server. DEBUG 2019-01-20 08:38:01,498 base 32461 140474717611392 Sending message of length 7076 to https://sentry.theinvaders.pro/api/30/store/ ERROR 2019-01-20 08:38:01,505 base 32461 140474190894848 Sentry responded with an error: (url: https://sentry.theinvaders.pro/api/30/store/) Traceback (most recent call last): File "/usr/lib/python3.6/urllib/request.py", line 1318, in do_open encode_chunked=req.has_header('Transfer-encoding')) File "/usr/lib/python3.6/http/client.py", line 1239, in request self._send_request(method, url, body, headers, encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1285, in _send_request self.endheaders(body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1234, in endheaders self._send_output(message_body, encode_chunked=encode_chunked) File "/usr/lib/python3.6/http/client.py", line 1026, in _send_output self.send(msg) File "/usr/lib/python3.6/http/client.py", line 964, in send self.connect() File "/var/www/mass/var/venv/lib/python3.6/site-packages/raven/utils/http.py", line 31, in connect timeout=self.timeout, File "/usr/lib/python3.6/socket.py", line 704, in create_connection for res in getaddrinfo(host, port, 0, SOCK_STREAM): File "/usr/lib/python3.6/socket.py", line 745, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): socket.gaierror: [Errno -3] Temporary failure in name resolution During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/var/www/mass/var/venv/lib/python3.6/site-packages/raven/transport/threaded.py", line 165, in send_sync super(ThreadedHTTPTransport, self).send(url, data, headers) File "/var/www/mass/var/venv/lib/python3.6/site-packages/raven/transport/http.py", line 43, in send ca_certs=self.ca_certs, File "/var/www/mass/var/venv/lib/python3.6/site-packages/raven/utils/http.py", line 66, in urlopen return opener.open(url, data, timeout) File "/usr/lib/python3.6/urllib/request.py", line 526, in open response = self._open(req, data) File "/usr/lib/python3.6/urllib/request.py", line 544, in _open '_open', req) File "/usr/lib/python3.6/urllib/request.py", line 504, in _call_chain result = func(*args) File "/var/www/mass/var/venv/lib/python3.6/site-packages/raven/utils/http.py", line … -
Django populate form using Function based view with multiple forms and submit buttons
I'm using Django 2.1 with python 3.6 and postgreSQL. I have to display 3 different forms in the same template. So I created a view in which I putted the 3 forms, but this doesn't show them populated as if using a CBV with generic.UpdateView. I need to add the current information of the models that are being updated inside each form field. I also created this but because I didn't found a lot of information about how to create a FBV with multiple forms in Django. I imagine that there are few things that are not correct in the view, so all suggestions are welcome. The view: def project_update_view(request, pk): project = Project.objects.get(pk=pk) if request.method == 'POST': general_form = UpdateProjectGeneralForm(request.POST) investment_form = UpdateProjectInvestorDetailsForm(request.POST) create_job_form = UpdateProjectAddWorkersForm(request.POST) if general_form.is_valid(): general_form.instance.user = request.user general_form.instance.history_change_reason = 'Project Updated' general_form.save() messages.success(request, 'Project updated!') return HttpResponseRedirect(request.path_info) if investment_form.is_valid(): investment_form.instance.user = request.user investment_form.instance.history_change_reason = 'Investor Details Updated' investment_form.save() messages.success(request, 'Investment details updated!') return HttpResponseRedirect(request.path_info) if create_job_form.is_valid(): create_job_form.instance.project = project create_job_form.instance.history_change_reason = 'New Job Added' create_job_form.save() messages.success(request, 'Job created!') return HttpResponseRedirect(request.path_info) else: general_form = UpdateProjectGeneralForm() investment_form = UpdateProjectInvestorDetailsForm() create_job_form = UpdateProjectAddWorkersForm() return render(request, 'webplatform/project_edit.html', { 'general_form': general_form, 'investment_form': investment_form, 'create_job_form': create_job_form, 'project': project, }) The forms: … -
Overriding generic.ListView methods for AJAX requests DJANGO
I recently started using django's inbuilt generic views (Create, Update, etc) So I'm updating most of my old views to use them, one of them is the ListView, with pagination. So now, it works right,when i GET that page, it displays the objects as directed, and the pagination works fine. But i want to use AJAX on the pagination so that i just click a "More" button and it gets the next page's objects via ajax and are appended onto the end of the . So i've modified some generic views before to incorporate AJAX like the: class Delete(LoginRequiredMixin, UserPassesTestMixin, DeleteView): login_url = LOGIN_URL model = Items success_url = reverse_lazy('web:member-area') def test_func(self): return not self.request.user.is_superuser and self.get_object().created_by == self.request.user def delete(self, request, *args, **kwargs): response = super().delete(request) if self.request.is_ajax(): return JsonResponse({'success': 1}, status=200) else: return response In the above snippet you can see i included the part where it returns something different if the request is AJAX The current View that i'm working on is as follows: class Items(ListView): model = Items paginate_by = 5 context_object_name = 'items' template_name = 'web/items/index.html' which works fine on normal GET requests, so the problem is i dont know which super() method(s) to override … -
Django Rest Framework JWT - OperationalError: no such table: auth_user
I'm developing a Django application for Windows with Pyhton 2.7.15. I need to implement an authentication mechanism with Django Rest framework JWT where I simply need to verify a token (and not to generate it). The token's payload is something like this: Payload { "iss": "customIssuer", "username": "customUser" } For this reason, I configure my setting.py in this way: ... REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_jwt.authentication.JSONWebTokenAuthentication', 'rest_framework.authentication.TokenAuthentication' ), } JWT_AUTH = { 'JWT_ISSUER': 'customIssuer' } ... and my urls.py in this way: ... from rest_framework_jwt.views import verify_jwt_token urlpatterns = [ ... url(r'^api-token-verify/', verify_jwt_token), ... ] Then, if I try to send a POST request with the above token, I get this error: Traceback (most recent call last): File "C:\Software\Workspace\py2_env\lib\site-packages\django\core\handlers\exception.py", line 41, in inner response = get_response(request) File "C:\Software\Workspace\py2_env\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Software\Workspace\py2_env\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Software\Workspace\py2_env\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view return view_func(*args, **kwargs) File "C:\Software\Workspace\py2_env\lib\site-packages\django\views\generic\base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "C:\Software\Workspace\py2_env\lib\site-packages\rest_framework\views.py", line 489, in dispatch response = self.handle_exception(exc) File "C:\Software\Workspace\py2_env\lib\site-packages\rest_framework\views.py", line 449, in handle_exception self.raise_uncaught_exception(exc) File "C:\Software\Workspace\py2_env\lib\site-packages\rest_framework\views.py", line 486, in dispatch response = handler(request, *args, **kwargs) File "C:\Software\Workspace\py2_env\lib\site-packages\rest_framework_jwt\views.py", line … -
File upload in django 1.9
I am trying to make a small app in which a user can upload a file and the list of files will be displayed after the file are uploaded . So need help regarding this issue. and if this is done using model forms that would be great -
lack of foreign key in admin model?
I get the following error when trying to update my database: class 'artdb.admin.RoleInline': (admin.E202) 'artdb.Role' has no ForeignKey to 'artdb.Person' I want ot have a many to many relation between Person and Role model.py (not showing all classes): class Person(models.Model): mail=models.EmailField() firstName=models.CharField(max_length=200) lastName=models.CharField(max_length=200) phoneNumber=PhoneNumberField() streetAdress=models.CharField(max_length=200) zipcode=models.CharField(max_length=200) city=models.CharField(max_length=200,default="Göteborg") country=models.CharField(max_length=200,default="Sweden") def __str__(self): return "%s %s" % (self.firstName,self.lastName) class Meta: ordering = ('firstName','lastName') class Role(models.Model): role=models.CharField(max_length=200) person=models.ManyToManyField(Person) def __str__(self): return self.role class Meta: ordering = ('role',) admin.py (not showing all classes): from django.contrib import admin from .models import Role from .models import Address from .models import Date from .models import Person from .models import Name # Register your models here. admin.site.register(Role) admin.site.register(Address) admin.site.register(Date) admin.site.register(Name) admin.site.register(Person) class RoleInline(admin.TabularInline): model=Role extra=3 class PersonInline(admin.ModelAdmin): fieldsets=[ (None,{'fields': ['mail','firstName','lastName','phoneNumber','streetAdress','zipcode','city','country']}), ] inlines = [RoleInline] search_fields = ['firstName'] #admin.site.register(Name,NameInline) admin.site.register(Person,PersonInline) it has worked before with run manage.py makemigrations artdb I don't see the errorin the models. -
nested serialize filter output in serializer
In this example: class TrackSerializer(serializers.ModelSerializer): class Meta: model = Track fields = ('order', 'title', 'duration') class AlbumSerializer(serializers.ModelSerializer): tracks = TrackSerializer(many=True) class Meta: model = Album fields = ('album_name', 'artist', 'tracks') this output occurs: 'album_name': 'The Grey Album', 'artist': 'Danger Mouse', 'tracks': [ {'order': 1, 'title': 'Public Service Announcement', 'duration': 245}, {'order': 2, 'title': 'What More Can I Say', 'duration': 264}, {'order': 3, 'title': 'Encore', 'duration': 159}, enter code here how Can I define I want just tracks that has orded:1? -
Nginx can't find file i specified using a path
I'm trying to serve a user a file using Nginx and later on when I figured out this problem first, then serve it with a protected url. Right now I have some code which specifies the path to the file the user wants to download. However my browser returns File not found. My views def download_item(request, pk): item = get_object_or_404(Usertasks, pk=pk) output_path = item.OutputPath response = HttpResponse() print(output_path) response["Content-Disposition"] = "attachment; filename={0}".format(output_path) response['X-Accel-Redirect'] = output_path return response My terminal prints out Not Found: /home/django/copypaste/cleanup/var/media/admin/output/123.txt and this path is correct and the filename is 123.txt for testing purposes Nginx sites-enabled config # mysite_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///home/django/copypaste/cleanup/usegolem.sock; # for a file socket # server 127.0.0.1:8001; # for a web port socket (we'll use this first) } # configuration of the server server { # the port your site will be served on listen 8000; # the domain name it will serve for server_name 127.0.0.1; # substitute your machine's IP address or FQDN charset utf-8; # max upload size client_max_body_size 250M; # adjust to taste # Django media location /media { alias /home/django/copypaste/cleanup/var/media; # your Django project's media files - amend as … -
django csv file validation in model form clean method
Following is the FileModel to upload a csv file in my Django application: class File(models.Model): uploaded_by = models.ForeignKey( User, on_delete=models.CASCADE, ) csv_file = models.FileField( upload_to='csvfiles/', ) On invocation of the /upload_file url pattern, the upload_csv_file view executes as follows: def upload_csv_file(request): if request.method == 'POST': csv_form = CSVForm(request.POST, request.FILES) if csv_form.is_valid(): file_uploaded = csv_form.save(commit=False) file_uploaded.uploaded_by = request.user csv_form.save() return HttpResponse("<h1>Your csv file was uploaded</h1>") elif request.method == 'GET': csv_form = CSVForm() return render(request, './mysite/upload_file.html', {'csv_form': csv_form}) In forms.py I am validating the following: file extension (.csv) file size (5 mb) class CSVForm(forms.ModelForm): class Meta: model = File fields = ('csv_file',) def clean_csv_file(self): uploaded_csv_file = self.cleaned_data['csv_file'] if uploaded_csv_file: filename = uploaded_csv_file.name if filename.endswith(settings.FILE_UPLOAD_TYPE): if uploaded_csv_file.size < int(settings.MAX_UPLOAD_SIZE): return True else: raise forms.ValidationError( "File size must not exceed 5 MB") else: raise forms.ValidationError("Please upload .csv extension files only") return uploaded_csv_file def clean(self): cleaned_data = super(CSVForm, self).clean() uploaded_csv_file = cleaned_data.get('csv_file') return uploaded_csv_file However i encounter the following error on submitting the file upload button: Attribute error: 'bool' object has no attribute 'get' I am unsure whether the 'def clean_csv_file(self)' is being invoked or not. There are ways to validate file extension and size within the function-based view, but I would like to validate … -
Is it possible to send multiple CSRF protected POST requests without reloading the page (Django)?
I'm creating a single page with a form and an optional login functionality. After the user has logged in (using AJAX) the form's CSRF token becomes invalid (as specified in the Django documentation: https://docs.djangoproject.com/en/2.0/ref/csrf/#why-might-a-user-encounter-a-csrf-validation-failure-after-logging-in). So the page needs to be reloaded to get a new valid CSRF token. But I would like the page not to be reloaded. Is there a common practice to do this? e.g. seperately generate a new token and then send as response after every successful login (AJAX request)? -
How to generate a Django one-time download link
i would like to secure downloadable files in my project but dont know how to accomplish that. Each time the post_detail view get's called a new download link should get generated with a validity of 60 min and which also can only be access ones. models.py class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(verbose_name="Post Title", max_length=25) content = models.TextField(verbose_name="Post Content", max_length=5000) tag = models.CharField(verbose_name="Tags/Meta - (sep. by comma)", max_length=50, blank=True) category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True) postattachment = fields.FileField( verbose_name="Post Attachment", blank=True, null=True, upload_to=get_file_path_user_uploads, validators=[file_extension_postattachment, file_size_postattachment] published_date = models.DateField(auto_now_add=True, null=True) def publish(self): self.published_date = timezone.now() self.save() class Meta: verbose_name = "Post" verbose_name_plural = "Post(s)" ordering = ['-title'] def __str__(self): return self.title views.py def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) list_comments = Comment.objects.get_queryset().filter(post_id=pk).order_by('-pk') paginator = Paginator(list_comments, 10) page = request.GET.get('commentpage') comments = paginator.get_page(page) return render(request, 'MyProject/post_detail.html', {'post': post, 'comments': comments}) If smb. maybe has some practice example it would be really helpful. Thanks in advance -
Increment object on save
I am trying to increment an object everytime I save it, so that one user can have multiple instances of an object, which I can then call accordingly in an html template. HTML <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals.instrument }}</p> <p class="date">{{ goals.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals.goal }}</p> </div> </div> </div> </div> <div class="col-md-6 outer"> <div class="box"> <div class="words"> <div> <p class="ins">{{ goals1.instrument }}</p> <p class="date">{{ goals1.goal_date }}</p> </div> <div> <br /> <br /> <p>{{ goals1.goal }}</p> </div> </div> </div> </div> models.py class Goals(models.Model): user = models.OneToOneField(User, default=None, null=True, on_delete=models.CASCADE) goal = models.CharField(max_length=2000) instrument = models.CharField(max_length=255, choices=instrument_list, blank=True) goal_date = models.DateField(auto_now=False, auto_now_add=False) def __str__(self): return self.goals @receiver(post_save, sender=User) def create_user_goals(sender, instance, created, **kwargs): if created: Goals.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_goals(sender, instance, **kwargs): instance.goals.save() class GoalsForm(ModelForm): class Meta: model = Goals exclude = ('user',) views.py def goal_creation(request): if request.method == 'POST': form = GoalsForm(request.POST, instance=request.user.goals) if form.is_valid(): goals = form.save(commit=False) goals.user = request.user goals.save() return redirect('/student/goal-progress') else: form = GoalsForm() form = GoalsForm() context = {'form': form} return render(request, 'student/goal_creation.html', context) def goal_progress(request): form = GoalsForm goals = request.user.goals context = {'form' : form, 'goals' : goals} return render(request, 'student/goal_progress.html', context) … -
Cannot dump fixtures for django.contrib.auth. Why does `python manage.py dumpdata auth` return an empty list?
The problem: $ python manage.py dumpdata auth.user [] But I do have users: $ python manage.py shell Python 3.6.8 (default, Dec 24 2018, 19:24:27) [GCC 5.4.0 20160609] on linux Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from django.contrib.auth.models import User >>> User.objects.all().count() 3 And loaddata works fine: $ cat user.json [ { "model": "auth.user", "fields": { "username": "fixture_user" } } ] $ python manage.py loaddata user.json Installed 1 object(s) from 1 fixture(s) My Django version: $ pip show Django Name: Django Version: 1.11.7 My database is a local PostgreSQL database. What could I be doing wrong? -
Unique together constraint for two FK to same model, without order
How could I do a unique_together for a model: class Team(models.Model: user_a = models.ForeignKey(User, related_name='a') user_b = models.ForeignKey(User, related_name='b') And I want to make sure user_a and user_b can't be a duplicate, doesn't matter which order they are. So user_a=1, user_b=2 would constraint user_a=2, user_b=1 also, instead of exact duplicate. Is there a way to do this, without custom logic to check for saving the Team? I'm currently just letting them duplicate, then removing the duplicate fields with a RawSQL query. -
list user contacts based on join in system or not
I have a lot of users in my web service (in django). Each user have some contacts that maybe them join in my service or not. I want to get list user contacts with a field that show each contact was joined in my service or not. I look up for best practice. please help me. -
For loop in Django
I have two question. First question: Python script that shows me the precipitation for a certain period.For example, I'm getting an initial year-month and a final year-month. Initial: year:2000 month:3 Final year1:2005 month:4 Now, instead of seeing: 2000/3,2000/4,2000/5,2000/6..........2005/1,2005/2,2005/3,2005/4 she works like this(look in the hooked picture): 2000/3, 2000/4, 2001/3, 2001/4........2005/3,2005/4. I want to work for me like the first case. def period_month_prec(year,month,year1,month1): for i in range (year,year1+1,1): for j in range(month,month1+1,1): ...................... Second question: How to write the output(picture) from the script in csv.fileenter image description here This is what my views.py script looks like , which saves me only the first result: def monthly_period(request): if request.method == "POST" : form = PeriodMonthlyForm(request.POST) if form.is_valid(): data = form.cleaned_data year = data.get('year') month = data.get('month') year1 = data.get('year1') month1 = data.get('month1') lon = data.get('lon') lat = data.get ('lat') inter = data.get('inter') point = period_month_prec(year,month,year1,month1,lon,lat) args = {'point':point} response = HttpResponse(content_type='text/txt') response['Content-Disposition'] = 'attachment; filename="precipitation.txt"' writer = csv.writer(response) writer.writerow([point]) return response else: form = PeriodMonthlyForm() active_period_monthly = True return render (request, 'carpatclimapp/home.html',{'form':form, 'active_period_monthly': active_period_monthly}) -
How to change an output variable in a form
I want to get the "user", when someone is posting a File. It, works somehow, but still displays an error. i Tryed allready to override the "form_valid" , but i allways get a TypeError. #forms.py class CreateMemesForm(forms.ModelForm): class Meta: model = Meme exclude = ["author"] #models.py class Meme(models.Model): uploaded_at = models.DateTimeField( auto_now_add=True) title = models.CharField(max_length=255) author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True) file = models.FileField(blank=True, upload_to="memes") #views.py class UploadMemes(LoginRequiredMixin, FormView): form_class = CreateMemesForm template_name = "memes/meme_form.html" def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super(ModelFormMixin, self).form_valid(form) #error i get super(type, obj): obj must be an instance or subtype of type It should get the author as CustomUser object. -
Integrity Error On ManyToManyField Django - Foreign Key
Error django.db.utils.IntegrityError: (1452, 'Cannot add or update a child row: a foreign key constraint fails (django_apollo.jobs_job_users, CONSTRAINT jobs_job_users_jobs_id_2172345a_fk_jobs_id FOREIGN KEY (jobs_id) REFERENCES jobs (id))') views.py # Ajax @login_required def AjaxClockJobCreate(request, user_id): form = JobFormInClock(request.POST, instance=User.objects.get(id=user_id)) user11 = get_object_or_404(User, pk=user_id) print('printing', user11.id) if request.method == "POST" and request.is_ajax() and form.is_valid(): form.instance.job_start_date = datetime.datetime.now() form.instance.job_start_time = datetime.datetime.now() form.instance.job_end_date = datetime.datetime.now() + datetime.timedelta(days=1) form.instance.job_end_time = datetime.datetime.now() + datetime.timedelta(hours=15) form.instance.job_created_on = datetime.datetime.now() form.instance.job_updated_on = datetime.datetime.now() form.instance.job_status = 'Active' form.instance.job_company = request.user.userprofile.user_company form.instance.job_created_by = request.user form.instance.job_updated_by = request.user form.save() form.instance.user_jobs.add(user11.id) # ManyToManyField lastest_entry = Jobs.objects.latest('id') data = { 'job_value': lastest_entry.id, 'job_name': lastest_entry.job_name, 'error_message': 'Could not enter job.' } return JsonResponse(data) Models.py class Jobs(models.Model): job_company = models.ForeignKey(Company, on_delete=models.CASCADE) job_group = models.ForeignKey(Groups, on_delete=models.CASCADE) job_users = models.ManyToManyField(User,related_name='user_jobs', blank=True) job_name = models.CharField(max_length=30) job_number = models.CharField(max_length=30) job_description = models.CharField(max_length=100, blank=True, null=True) job_start_date = models.DateField(blank=True, null=True) job_start_time = models.TimeField(blank=True, null=True) job_end_date = models.DateField(blank=True, null=True) job_end_time = models.TimeField(blank=True, null=True) job_created_on = models.DateTimeField(auto_now_add=True) job_created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_created_bys') job_updated_on = models.DateTimeField(auto_now=True) job_updated_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='job_updated_bys') job_is_deleted = models.BooleanField(default=False) job_deleted_at = models.DateTimeField(blank=True, null=True) ACTIVE = 'Active' INACTIVE = 'Inactive' JOB_ACTIVE_CHOICES = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), ) job_status = models.CharField( max_length=8, choices=JOB_ACTIVE_CHOICES, default=INACTIVE, ) class Meta: db_table = "jobs" def __str__(self) : return … -
Tune RabbitMQ Server to handle more request
The scenario is that we are pushing messages in JSON format in bulk to an HTTP end point which we call as the coordinator. The coordinator does two things: Encrypt the message Pushes this message via RabbitMQ and celery to a message broker over TCP. We are able to process 1k requests per second with 2 workers and 8 concurrencies. The configuration of server is 8 CPU 32 GB RAM. The challenge is to tune RabbitMQ to handle around 40k requests per second on the same infrastructure. Our Stack: Django, Python, Celery, RabbitMQ, Mongo, Docker, AWS can this be done ? and How ? -
Django doesn't work with multiple pyplots in template
I try to show multiple histograms in Django template. In the HTML file I have the following code: {% for value, data in histograms %} <div class="col-xs-12 col-md-6"> <img src="{% url 'histogram' %}?value={{ value }}&data={{ data|join:"," }}"> </div> {% endfor %} urls.py: url(r'^histogram.png$', views.histogram, name="histogram"), and, finally, the view: import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as pyplot def histogram(request): data = [float(val) for val in request.GET['data'].split(',')] binwidth = 0.5 fig, ax = pyplot.subplots() ax.hist(data, bins=numpy.arange(min(data), max(data) + binwidth, binwidth)) ax.set_title(request.GET['value']) f = BytesIO() pyplot.savefig(f, format='png') pyplot.clf() pyplot.cla() pyplot.close(fig) response = HttpResponse(f.getvalue(), content_type='image/png') return response Without matplotlib.use('Agg') I get Segmentation fault: 11. Using Agg I get some histograms completely white and others it looks exactly the same even they have different data. Any ideas, please? If I view only one, in the browser, by direct URL (histogram.png?value=25&data=13.37,19.1,20.0,8.9,13.6,14.0,14.6,14.4,12.4,14.9,12.5,12.7,13.6,12.8,13.0,11.0,14.0,14.1,9.5,17.5,14.7,11.6) is shown correctly. -
Django database foreign key limitations
my question is so simple. suppose we have a model that has foreign key field to another model. class B(models.Model): ..... class A(models.Model): foo_b = models.ForeignKey(B, on_delete=models.SET_NULL, null=True) if we have many fields foo_b that related to B model. is this wrong or can slow and cause lag to my database connections or not?performance is more matter here so I need to choose carefully. -
the view didn't return an HttpResponse object. It returned None
For testing my form loggin, in the view index i return a dictionary. When i clicked on the submit button i receive this message error : The view accueil.views.index didn't return an HttpResponse object. It returned None instead. Where i made a mistake? def index(request): formConnex = ConnexionForm() if request.method=='POST': formConnex =ConnexionForm(request.POST) if formConnex.is_valid(): envoi = True surnom = formConnex.cleaned_data['surnom'] password = formConnex.cleaned_data['passeword'] formConnex = ConnexionForm() dicInfoCon = { 'surnom_key':email, 'password_key':password, 'envoi_key':envoi } return render(request,'accueil/index.html',dicInfoCon) else: envoi = False formConnex = ConnexionForm() return render(request,'accueil/index.html','formConnex_Key':formConnex}) -
Program works when I run it on the IDE (Pycharm) but not when I run it on the terminal?
So I've written a desktop application on Python. It works fine when I run it by manually clicking 'Run main' through the IDE but when I do: python main.py the terminal does find the program but doesn't recognize the libaries. I've tried installing the libaries/modules a couple of times on the terminal and it says i've installed them but i guess not. These are the libaries/modules that refuses to work. from iconsdk.icon_service import IconService from iconsdk.providers.http_provider import HTTPProvider The output on the console (when I run 'python main.py') is this: Traceback (most recent call last): File "main.py", line 1, in import gui File "/Users/adam/PycharmProjects/igotmemed/gui.py", line 9, in import blockgen File "/Users/adam/PycharmProjects/igotmemed/blockgen.py", line 2, in from iconsdk.providers.http_provider import HTTPProvider File "/Users/adam/miniconda3/lib/python3.7/site-packages/iconsdk/providers/http_provider.py", line 17, in import requests File "/Users/adam/miniconda3/lib/python3.7/site-packages/requests/init.py", line 43, in import urllib3 File "/Users/adam/miniconda3/lib/python3.7/site-packages/urllib3/init.py", line 8, in from .connectionpool import ( File "/Users/adam/miniconda3/lib/python3.7/site-packages/urllib3/connectionpool.py", line 26, in from .packages.ssl_match_hostname import CertificateError ImportError: cannot import name 'CertificateError' from 'urllib3.packages.ssl_match_hostname' (unknown location) Something significant to note is 'CertificateError'.