Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can I insert an ajax multiple file loader into django admin form?
In my django project I'm having a model containing (above all) multiple audio files with their descriptors. Descriptor is an info, that can be uptained from the audio file itself with some preprocessing. So I wanted to have an ajax form inside of my django admin model form, which could load multiple files, process them and display the resulted descriptors for each file uploaded (without saving the whole model form). What is important, that files has to be loaded automatically, because there can be a lot of audios attached to each model entity. I made a fake field in admin model and wrote a custom widget for it, like this: <form action="process_and_load_samples/" method="POST" id="samples_form"> <input name="samples" id="id_samples" type="file" multiple> <input type="submit" value="load samples" form="samples_form"> </form> But when I load the admin page, I see that django somehow stripped off my form tags and included my custom inputs inside the model form. So 1) How can implement such loader? 2) Why and how does django stripes off form tags? -
Django - HTTP and WebSockets
We have an existing large Django 1.11 & Django-rest-framework application served by wsgi. We noticed that we might want to use a WebSocker for some requests (for example: get all running tasks - live updating) There is already a GET URL for that: /api/tasks?running=ture So we would like to use same methods and serve this data via WebSocket (Same port is important) Is it possible? How? -
Elasticsearch- pyes - Using range filter with histograms
I'm using Elasticsearch -0.9 and with pyes version 0.20.1. What i want to do is put in a range filter for histogram queries i found 2 seperate implementations for this i.e DateHistogramFacet whose constructor takes in field, timezone, interval but not facet_filter And another one is Facet Which takes in facet_filter as constructor args I'm not able to figure out how to put the range filter inside the histogram, The end result should look something like: { "facets": { "histoLow": { "date_histogram": { "field": "updated_timestamp", "interval": "minute", "time_zone": "+05:00", "post_zone": "+05:00" }, "facet_filter": { "range": { "age": { "lt": 50, "gte": 12 } } } } } Thanks in advance. Cheers! -
Django Rest Ajax 400
Simple situation. Using Django REST to create GET/POST API. GET works fine, but my post is going crazy. Yes, I am passing the csrf_token. It keeps throwing "non_field_errors": ["Invalid data. Expected a dictionary, but got str." I have a funny feeling, it has to do with the FK on the BlogComment Model, but i'm kind of lost on this one. Or it may be that my object i'm sending via ajax is completely wrong. Any help is appreciated. MODELS.py class BlogPost(models.Model): date = models.DateField(auto_now_add=True) title = models.CharField(max_length=300) slug = models.SlugField(max_length=100, blank=True, null=True) post_body = models.TextField(max_length=5000) post_featured_image = models.FileField(blank=True, null=True) post_secondary_image = models.FileField(blank=True, null=True) def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.title) print self.slug super(BlogPost, self).save(*args, **kwargs) def __unicode__(self): return self.title class BlogComment(models.Model): blog_post = models.ForeignKey(BlogPost) date = models.DateField(auto_now_add=True) comment_body = models.TextField(max_length=5000) post_author_first_name = models.CharField(max_length=100, blank=True, null=True) post_author_img = models.CharField(max_length=100, blank=True, null=True) SERIALIZERS.py class BlogCommentSerializer(serializers.ModelSerializer): class Meta: model = BlogComment fields = ('comment_body', 'post_author_first_name', 'post_author_img' ) Django REST View class BlogCommentSerializerView(APIView): def get(self, request, pk): blog_post = BlogPost.objects.get(id=pk) comments = blog_post.blogcomment_set.all() serializer = BlogCommentSerializer(comments, many=True) return Response(serializer.data) def post(self, request, pk): data = json.dumps(request.data) serializer = BlogCommentSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) AJAX CALL var … -
Django tables 2 creating custom calculated fields
def calculateTotalVists(days): total = 0 for i in days: total += i return total class ClientTable(tables.Table): class Meta: model = Client fields = ('id', 'name', 'phone') attrs = {'class': 'table table-striped table-bordered', 'id': 'clients'} The client model has the field "days" which is a list. I would like to create a custom column which displays the result after days is passed into calculateTotalVists(). However I'm not how I can use accessors with functions. -
pip install django error using virtualenv
I have set the virtual environment having (website) username[`/public_html/website] Have django project in /public_html/website directory When i try to install django using pip install django Gives following error Collecting django Could not find a version that satisfies the requirement django (from versions:) No mathcing distribution for django I have tried which pip it gives public_html/website/bin/pip When I try python manage.py runserver Gives error couldnt import django How should I install django in virtualenv and then runserver? -
Using ImageMagick in Python/Django application results in permission errors on Linux
I use ImageMagick executables in my Django application and all of them work perfect on Windows machine. However, on a Linux machine, I'm getting errors, when I try to run one specific command: command = ["convert", "input1.tif", "-write", "mpc:red", "+delete", "input2.tif", "-write","mpc:NIR","+delete","(","mpc:NIR","mpc:red","-evaluate-sequence","subtract",")","(","mpc:red","mpc:NIR","-evaluate-sequence","add",")","-evaluate-sequence","divide","-normalize","output.tif"] subprocess.call(command) This command triggers convert utility, which itself produces some cache files (named red and NIR), but the problem is that for some strange reason convert can not create these files and throws such error messages: convert: unable to open image 'red': Permission denied @ error/blob.c/OpenBlob/3094. convert: unable to open image 'NIR': Permission denied @ error/blob.c/OpenBlob/3094. convert: unable to open image 'NIR': No such file or directory @ error/blob.c/OpenBlob/3094. convert: unable to open image 'red': No such file or directory @ error/blob.c/OpenBlob/3094. I should add that on Windows this command works great and does what it should do. And on Linux it also works if I run it in Python shell. The problem pops up, when I call this utility in my Django web application. -
ImproperlyConfigured: Application labels aren't unique, duplicates: sites
Here is the full error: File "C:\Python34\lib\site-packages\django\apps\registry.py", line 89, in populate "duplicates: %s" % app_config.label) django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: sites Im following django-allauth documentations to make a functionality in my website such that users could login to my website using facebook. But when I added 'django.contrib.sites',to my installed app_list, it showed me that error. Here is my installed apps list. INSTALLED_APPS = ( # The following apps are required: 'django.contrib.auth', 'django.contrib.sites', 'allauth', 'allauth.account', 'allauth.socialaccount', #'django.contrib.sites', # ... include the providers you want to enable: 'allauth.socialaccount.providers.amazon', 'allauth.socialaccount.providers.angellist', 'allauth.socialaccount.providers.asana', 'allauth.socialaccount.providers.auth0', 'allauth.socialaccount.providers.baidu', 'allauth.socialaccount.providers.basecamp', 'allauth.socialaccount.providers.bitbucket', 'allauth.socialaccount.providers.bitbucket_oauth2', 'allauth.socialaccount.providers.bitly', 'allauth.socialaccount.providers.coinbase', 'allauth.socialaccount.providers.daum', 'allauth.socialaccount.providers.digitalocean', 'allauth.socialaccount.providers.discord', 'allauth.socialaccount.providers.douban', 'allauth.socialaccount.providers.draugiem', 'allauth.socialaccount.providers.dropbox', 'allauth.socialaccount.providers.dropbox_oauth2', #'allauth.socialaccount.providers.dwolla', 'allauth.socialaccount.providers.edmodo', 'allauth.socialaccount.providers.eveonline', 'allauth.socialaccount.providers.evernote', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.feedly', 'allauth.socialaccount.providers.fivehundredpx', 'allauth.socialaccount.providers.flickr', 'allauth.socialaccount.providers.foursquare', 'allauth.socialaccount.providers.fxa', 'allauth.socialaccount.providers.github', 'allauth.socialaccount.providers.gitlab', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.hubic', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.kakao', 'allauth.socialaccount.providers.line', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.linkedin_oauth2', 'allauth.socialaccount.providers.mailru', 'allauth.socialaccount.providers.mailchimp', 'allauth.socialaccount.providers.naver', 'allauth.socialaccount.providers.odnoklassniki', 'allauth.socialaccount.providers.openid', 'allauth.socialaccount.providers.orcid', 'allauth.socialaccount.providers.paypal', 'allauth.socialaccount.providers.persona', 'allauth.socialaccount.providers.pinterest', 'allauth.socialaccount.providers.reddit', 'allauth.socialaccount.providers.robinhood', 'allauth.socialaccount.providers.shopify', 'allauth.socialaccount.providers.slack', 'allauth.socialaccount.providers.soundcloud', 'allauth.socialaccount.providers.spotify', 'allauth.socialaccount.providers.stackexchange', 'allauth.socialaccount.providers.stripe', #'allauth.socialaccount.providers.trello', #'allauth.socialaccount.providers.tumblr', 'allauth.socialaccount.providers.twentythreeandme', #'allauth.socialaccount.providers.twitch', #'allauth.socialaccount.providers.twitter', 'allauth.socialaccount.providers.untappd', #'allauth.socialaccount.providers.vimeo', 'allauth.socialaccount.providers.vk', 'allauth.socialaccount.providers.weibo', 'allauth.socialaccount.providers.weixin', 'allauth.socialaccount.providers.windowslive', 'allauth.socialaccount.providers.xing', 'django.contrib.sites', ) SITE_ID = 1 -
How do i filter lists of objects in django template?
I want to create a filter box where I can filter lists of objects: **models.py** class Personal(models.Model): first_name = models.CharField(max_length=128) last_name = models.CharField(max_length=128) email = models.EmailField() age = models.DateField(null=True) non_veg = models.BooleanField(default=False) alcohol = models.BooleanField(default=False) pure_veg = models.BooleanField(default=False) **forms.py** class PersonForm(forms.ModelForm): class Meta: model = Personal fields = ['first_name', 'last_name', 'email', 'age', 'non-veg', 'alcohol', 'pure_veg'] **views.py** def my_personal(request): my_data = Personal.objects.all() return render(request, "personal.html", data) **personal.html** <body> <div id="filter_list"> <h3>Filter By</h3> <h4>Age</h4> <select> <option value="1"> From 18 to 20 years</option> <option value="2"> From 21 to 25 years</option> <option value="3"> From 26 to 30 years</option> <option value="4"> From 31 to 35 years</option> <option value="5"> From 36 to 40 years</option> <option value="6"> Above 40 years</option> </select> <h4>Likes</h4> <input type="checkbox" name="non_veg"> Non-Veg Food <input type="checkbox" name="alcohol"> Alcohol <input type="checkbox" name="pet_allowed"> Pure Veg <input type="submit" name="submit" value="Apply filters"> </body> with the above example if I select the age 18 to 20 years and tick non-veg Food checkbox and click on apply filter, it should show the persons who likes non-veg with age limit 18 to 20 years on the SAME PAGE. -
Update list of objects with AJAX
Can someone say where I did mistake? I am tring to update list of comments with ajax after success adding but finally see this page. New comment is in the database but it seems like I miss something. After submit it redirect me to "task_comment_add" url but i need to stay in the same page just update list of objects (task-comments). urls.py: url(r'^(?P<project_code>[0-9a-f-]+)/(?P<group_task_code>[0-9a-f-]+)/(?P<task_code>[0-9a-f-]+)/task_comment_add/$', task_comment_add, name='task_comment_add'), views.py: def task_comment_add(request, project_code, group_task_code, task_code): data = dict() project = get_object_or_404(Project, pk=project_code, status='open') group_task = get_object_or_404(GroupTask, pk=group_task_code) task = get_object_or_404(Task, pk=task_code) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.author = request.user comment.save() task.comments.add(comment) data['form_is_valid'] = True data['html_task_comment'] = render_to_string('project/task_comment_list.html', {'task': task}) else: data['form_is_valid'] = False else: form = CommentForm() context = {'project': project, 'group_task': group_task, 'task': task, 'form': form} data['html_task_comment_form'] = render_to_string('project/task_comment_form.html', context, request=request) return JsonResponse(data) html: <form method="post" id="task-comment-form" action="{% url 'project:task_comment_add' project_code=project.code group_task_code=group_task.code task_code=task.code %}"> </form> JS: $("#task-comment-form").submit(function(event) { event.preventDefault(); console.log(event.preventDefault()); var form = $(this); $.ajax({ url: form.attr("action"), data: form.serialize(), type: form.attr("method"), dataType: 'json', success: function (data) { if (data.form_is_valid) { $("#task-comments").html(data.html_task_comment); } else { $("#task-comment-form").html(data.html_task_comment_form); } } }); $("#task-comment-form")[0].reset(); return false; }); -
(django) error while overriding save() - name 'self' is not defined
I'm trying to override the method save() of my model: class Article(models.Model): number = models.PositiveIntegerField(editable=False) def save(self, *args, **kwargs): if not self.pk: #means: if objects wasn't saved before self.number = Article.objects.count() +1 #number is 1-based super(Article, self).save(*args, **kwargs) Now I tried to add a new article from the admin page. The error I get: self.number = Article.objects.count() +1 NameError: name 'self' is not defined What am I doing wrong? Some optional information: number is some kind of ID, to order the objects in my way but these IDs shouldn't be changed manually number is not allowed to be empty or blank, so I have to set a value before saving the first time (that's what I'm trying with that code snippet) When an object is saved, the default number should be equal to the number of all objects (after saving), in 1-based counting to change the order of the objects admin actions will be used Do you miss some information? -
Dockerized Django On Ubuntu
I am using: Ubuntu 16.04. Docker version 1.12.6. I want to containerize my existing Django app., knowing that everything goes well in this app. => no bugs, no errors... My Dockerfile: FROM django ADD . /BackendServer WORKDIR /BackendServer RUN pip install -r requirements.txt CMD [ "python", "BackendServer/manage.py runserver 0.0.0.0:8000" ] requirements.txt djangorestframework gunicorn Now everything goes well, except the last line when executing the manage.py python, it says: "python: can't open file 'BackendServer/manage.py runserver 0.0.0.0:8000': [Errno 2] No such file or directory". So, I execute the following command: "sudo docker run backendserver ./BackendServer/manage.py runserver 0.0.0.0:8000" I got no errors and still the server is not running!! Here is the output, it stuck here and nothing happenes What shall I do so that I can access the django server !? Please help!! Additional note: here is the execution of "ls BackendServer" in the container. thanks in advance! -
Showing Django view in template
I'm trying to pass a list of objects of my model Job to a template for display, but my template is showing up empty. My views.py: from django.shortcuts import render from .models import Job def job_list(request): jobs = Job.objects.all() return render(request, 'student/profile.html', {'jobs': jobs}) My models.py: from django.db import models class Job(models.Model): company_id = models.IntegerField(unique=True) company = models.CharField(max_length=50) description = models.TextField(max_length=200) minimum_cgpa = models.DecimalField(max_digits=4, decimal_places=2) def __unicode__(self): return unicode(self.company_id) My template student/profile.html: <p><br/> <ul> {% for job in jobs %} <li>{{ job.company }}</li> {% endfor %} </ul> </p> I'm not getting any output in my template file. What am I doing wrong? Thanks in advance. -
Loading django fixtures, IntegrityError
Trying to copy data from one DB instance to another with fixtures. There are several tables, and one of them (product_brand) which has a foreign key to products_brand_owner doesn't load: django.db.utils.IntegrityError: Problem installing fixtures: The row in table 'products_brand' with primary key 'YARDLEY' has an invalid foreign key: products_brand.brand_owner contains a value '' that does not have a corresponding value in products_brand_owner.name. The item in question is: { "model": "products.brand", "pk": "YARDLEY", "fields": { "owner": null, "url": "http://www.yardleyoflondon.com/", "description": "" } } Relevant models: class brand_owner(Model): name = CharField(primary_key=True, max_length=255) url = CharField(max_length=128, blank=True, null=True) email = CharField(max_length=128, blank=True, null=True) phone = CharField(max_length=32, blank=True, null=True) address = CharField(max_length=128, blank=True, null=True) country = CharField(max_length=32, blank=True, null=True) description = TextField(blank=True, null=True) class Meta: verbose_name = 'Brand owner' def __str__(self): return self.name class Brand(Model): name = CharField(primary_key=True, max_length=255) owner = ForeignKey(brand_owner, on_delete=CASCADE, db_column='brand_owner', blank=True, null=True) url = CharField(max_length=128, blank=True, null=True) description = TextField(blank=True, null=True) #tags = JSONField(blank=True, null=True) def __str__(self): return self.name I see no problem, the key can be null, so I believe it's perfectly valid situation. Maybe someone has encountered this problem before? I'm learning django, and was probably sticking my dirty crooked fingers in wrong places (mixing migrations and direct … -
Django reading Jsonfield
I tried to read the Django docs on this and tried a few ways to extract data to display in a template from a json object without success. Below is an example of the json file stored in a postgresql jsonfield { "customer_user": { "fields": { "city": "London", "country": 1, "created_at": "2016-12-24T23:37:09.420Z", "region": 1, "updated_at": "2016-12-24T23:37:09.420Z", "user": 1 }, "model": "customer.customeruser", "pk": 1 }, "customer_user_addresses": [], "model": "accounts.user", "pk": 1 } } Firstly I want to call the "customer_user" out into a variable like customer_user = Application.objects.only('customer_user') Then past that to a Django template? to be used in: City: {{ customer_user.fields.city }} To troubleshoot it would be good to be able to pprint(customer_user) too or something similar. -
Import csv file from local to EC2
I am working on Django. I want to get csv file from remote system. My code is running on ec2. I want to import file on ec2 server. How I can do from Django. def upload(request): if request.method == 'POST' and request.FILES['file']: file = request.FILES['file'] fs.save(file.name, file) return HttpResponse("status") It will store the file as tempfile and I can't read this file. -
Best way to fetch and display request parameters in generic CreateView
I have a model class MyModel(models.Model): slug = models.UUIDField(default=uuid4, blank=True, editable=False) advertiser = models.ForeignKey(Advertiser) position = models.SmallIntegerField(choices=POSITION_CHOICES) share_type = models.CharField(max_length=80) country = CountryField(countries=MyCountries, default='DE') # some other Fields. Edited in a ModelForm This view is called by a url containg position, share_type, country as parameters. I would like to display these parameters in the template. What is the best way to do this. I already have these possibilies 1) use get_context_date and store this in the context def get_context_data(self, **kwargs): ctx = super(MyModel, self).get_context_data(**kwargs) ctx['share_type'] = self.kwargs.get('share_type', None) ctx['country'] = self.kwargs.get('country', None) ctx['postal_code'] = self.kwargs.get('postal_code', None) ctx['position'] = int(self.kwargs.get('position', None)) return ctx This can then be used in the template 2) use the view variant def share_type(self): ret = self.kwargs.get('share_type', None) return ret def country(self): ret = self.kwargs.get('country', None) return ret like <div class="row"> <strong> <div class="col-sm-3"> Type : {{ view.share_type }} <div class="col-sm-3"> Country : {{ view.country }} I think both way are somewhat redundant. Does anybody know a more generic approach to this. Kind regards Michaek -
django-celery-beat periodic tasks on admin panel do not get executed
I've done everything exactly like here http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html#beat-custom-schedulers. Created task in tasks.py: @shared_task def just_log(): logging.error("Logging") I've added this in admin panel as periodic task with an interval of 5 seconds. I've started the celery beat service with this command: celery -A proj beat -l info -S django In terminal every 5 seconds this message is shown: [2017-04-16 09:54:08,747: INFO/MainProcess] Scheduler: Sending due task test_task (proj.tasks.just_log) But the task itself not getting executed. What is the problem? -
Latest django-mongodb-engine
I'm following the guide to setup django-mongodb. But this line pip install git+https://github.com/django-nonrel/django@nonrel-1.5 always reverts my django to 1.5. Is there anyway that I can use lastest django? -
how to retrieve variables values from json using python
i have json file look like this. {"-Kh8M0qTdXJ-vBXr1G8v":{"email":"maad@yahoo.com","user":"amad"},"-Kh8M0v7KubmISGYrzks":{"email":"maad@yahoo.com","user":"amad"},"-KhB5OYsWias6j4Mc-pX":{"email":"faraz@yahoo.com","user":"faraz"},"-KhBBZ5Ii6kHPoUFhbj8":{"email":"zeeshan@gmail.com","user":"zeeshan"},"-KhBDTyGM9LaojajmtQv":{"email":"Ali@gmail.com","user":"Ali"}} and i want to print all email and user values. can any one help, how can i fetch these values from json by using python. -
Custom Field does not return value
in a Django projet, I need to work wit GTIN then I've created a basic custom field which looks like: class GTINField(models.CharField): description = _("GTIN Code") default_error_messages = { 'blank': _('GTIN code is required.'), 'invalid': _('Enter a valid GTIN code.'), } empty_strings_allowed = False default_validators = [validate_gtin] def __init__(self, *args, **kwargs): kwargs['max_length'] = 14 super(GTINField, self).__init__(*args, **kwargs) def deconstruct(self): name, path, args, kwargs = super(GTINField, self).deconstruct() del kwargs["max_length"] return name, path, args, kwargs The validator is: @deconstructible class GTINValidator: message = _('Enter a valid gtin code.') code = 'invalid' def __call__(self, value): if not self._is_valid_code(value): raise ValidationError(self.message, code=self.code) def _is_valid_code(self, code): if not code.isdigit(): return False elif len(code) not in (8, 12, 13, 14): return False else: return int(code[-1]) == self._get_gtin_checksum(code[:-1]) def _get_gtin_checksum(self, code): total = 0 for (i, c) in enumerate(code): if i % 2 == 1: total = total + int(c) else: total = total + (3 * int(c)) check_digit = (10 - (total % 10)) % 10 return check_digit validate_gtin = GTINValidator() Now, I would like to format my field (remove "-" in the string) in the clean() method but I cannot get the field value, Pdb always returns (Pdb) self.ean <gtinfield.fields.GTINField> Is there something that I've … -
Creating multiple object with one request in Django and Django Rest Framework
I am using Django as the backend server and Vue.js for the front end Movie app. I have a Ticket model class MovieTicket(models.Model): show = models.ForeignKey(Show) seat = models.ForeignKey(Seat) user = models.ForeignKey(User) purchased_at = models.DateTimeField(default=timezone.now) qrcode = models.ImageField(upload_to='qrcode', blank=True, null=True) qrcode_data = models.CharField(max_length=255, unique=True, blank=True) class Meta: unique_together = ('show', 'seat') And its related Serializer class MovieTicketSerializer(serializers.ModelSerializer): class Meta: model = MovieTicket fields = '__all__' To buy a new Ticket there's a view which is mapped to this url http://dev.site.com/api/movies/buy-ticket/: @api_view(['POST']) @permission_classes([IsAuthenticated]) def buy_ticket(request): serialized = MovieTicketSerializer(data=request.data) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) Now from the front end (Vue.js) I can create a new movie ticket: const formBody = { show: this.$store.state.showSelected.showTime.id, user: this.$store.state.user.id, // selectedSeats is an array of seats that have been selected by the user. Here I am passing the first seat object. seat: this.$store.state.selectedSeats[0].seat.id }; this.$http.post("http://dev.site.com/api/movies/buy-ticket/", formBody) .then(function (response) { console.log(response.data); }) .catch(function (response) { console.log(response); }); return; If the form was valid, this will create a new MovieTicket Object. Now, suppose if the user selected multiple seats, I can loop through each selectedSeats array and get the seat ids. But what I am confused is how can I pass multiple seat.id if … -
(Django) save(*args, **kwargs) vs. save(**kwargs)
When I searched for overriding the save method I found to different things: def save(self, **kwargs): pass and: def save(self, *args, **kwargs): pass What's better? -
Showing Validation Error like a popup,instead of loading another page in Django
I have also created a simple registration form for a blog asking for Username and Registration Name from the user. When enter an invalid entry for the Registration Number django, by default redirects me to page displaying the object could not be created because the data could not be validated. Instead of redirecting to that page, how do I display "Invalid registration Number" in a similar popup. My views.py: def post_new(request,): if request.method=="POST": authorform=NewAuthor(request.POST) form=NewPost(request.POST) if form.is_valid(): new_post=form.save(commit=False) new_author=authorform.save(commit=False) new_post.published_date=timezone.now() new_author.save() new_post.author=new_author new_post.save() return redirect('post_detail',pk=new_post.id) else: form=NewPost() authorform=NewAuthor() return render(request,'justablog/post_new.html',{'form':form,'authorform':authorform}) My models.py: from django.db import models from django.utils import timezone # Create your models here. from django.core.validators import RegexValidator class Author(models.Model): Username=models.CharField(max_length=30) RegNo=models.CharField(max_length=9,validators=[RegexValidator( regex=r'^[0-9]{2}[A-Z]{3}[0-9]{4}', message=("Invalid Registration Number"), code='invalid_regno' ),]) def __str__(self): return self.Username+'('+self.RegNo+')' class Post(models.Model): title = models.CharField(max_length=50) body = models.TextField(max_length=1000) author = models.ForeignKey(Author,null=True) published_date=models.DateTimeField(blank=True,null=True) def publish(self): self.published_date=timezone.now() self.author.save() self.save() def __str__(self): return self.title My forms.py; class NewPost(forms.ModelForm): class Meta: model=Post fields=('title','body',) class NewAuthor(forms.ModelForm): class Meta: model=Author fields=('Username','RegNo',) -
How to limit connections to a port and redirect other requests to another port?
I would like to limit the number of connections to my server to X. This can be done by iptables -A INPUT -p tcp --dport ABCD -m connlimit --connlimit-above X --connlimit-mask 0 -j DROP Also, I would like to redirect the dropped requests to another port, say PQRS. How do I do this?