Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
LookupError: Model 'User.user' not registered
I get this error every time I try to run manage.py makemigrations manage.py migrate or manage.py runserver. Full Traceback: https://pastebin.com/19G8Av5m Short version: LookupError: Model 'User.user' not registered. Thanks for your help. -
Overriding or Changing Admin Templates in Django 1.11
My general goal is to make the data in /admin/my_app/my_model/<id>/change/ not editable or the link that goes to that page to go to another URL that's just view instead of change. I'm having a lot of trouble figuring out how to extend these templates. A lot of tutorials and docs I see talks of changing the templates in /templates/admin but I get the feeling that that's been deprecated in 1.11. -
using file stored on aws s3 storage -- media storage as input of a process in django view
I am trying to make my django app in production in aws, i used elastic beanstalk to deploy it so the ec2 instance is created and connected to an rds database mysql instance and i use a bucket in amazon s3 storage to store my media files on it. When user upload a video, it is stored in s3 as : "https://bucketname.s3.amazonaws.com/media/videos/videoname.mp4". In django developpement mode, i was using the video filename as an input to a batch script which gives a video as output. My view in developpement mode is as follow: def get(request): # get video var = Video.objects.order_by('id').last() v = '/home/myproject/media/videos/' + str(var) # call process subprocess.call("./step1.sh %s" % (str(v)), shell=True) return render(request, 'endexecut.html') In production mode in aws (Problem), i tried: v = 'https://bucketname.s3.amazonaws.com/media/videos/' + str(var) but the batch process doesn't accept the url as input to process. How can i use my video file from s3 bucket to do process with in my view as i described ? Thank you in advance. -
Django form test fails
I'm trying to perform a simple test on my form to confirm that it's not valid when there is no data given and is valid when data is given. When running tests with pytest (py.test) the test with no data works fine but I'm getting this error for the test with data present: AssertionError: Should be valid if data is given E assert False is True E + where False = <bound method BaseForm.is_valid of <PostForm bound=True, valid=False, fields=(title;content;author;image;published;draft;category;read_time)>>() E + where <bound method BaseForm.is_valid of <PostForm bound=True, valid=False, fields=(title;content;author;image;published;draft;category;read_time)>> = <PostForm bound=True, valid=False, fields=(title;content;author;image;published;draft;category;read_time)>.is_valid posts/tests/test_forms.py:21: AssertionError my models.py: from django.db import models from django.core.urlresolvers import reverse from django.conf import settings from django.db.models.signals import pre_save from django.utils import timezone from django.utils.text import slugify from .utils import read_time class Category(models.Model): name = models.CharField(max_length=120, unique=True) timestamp = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now_add=False, auto_now=True) slug = models.SlugField(unique=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.id: # to prevent changing slug on updates self.slug = slugify(self.name) return super(Category, self).save(*args, **kwargs) def upload_location(instance, filename): return '%s/%s'%(instance.id, filename) class PostManager(models.Manager): def active(self): return super(PostManager, self).filter(draft=False, published__lte=timezone.now()) class Post(models.Model): title = models.CharField(max_length=120) slug = models.SlugField(unique=True) content = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = … -
Break loop in one consumer from another consumer
I'm building web-app with Django and Django Channels that utilizes websockets. When user clicks the button in browser, websocket sends data to my server and consumer on the server starts to send messages to the client once per second (in loop). I want to create another button that will stop this data sending process. When user clicks on this new button, websocket sends another data to server and consumer on the server must somehow stop the loop in previous consumer. Also I will require this to stop the loop when client disconnects. I've tried to use channel session. I made second consumer to update value in channel session, but channel session values didn't get updated in first consumer. Here is simplified code. Browser: var socket = new WebSocket("ws://" + window.location.host + "/socket/"); $('#button1').on('click', function() { socket.send(JSON.stringify({action: 'start_getting_values'})) }); $('#button2').on('click', function() { socket.send(JSON.stringify({action: 'stop_getting_values'})) }); Consumer on server: @channel_session def ws_message(message): text = json.loads(message.content['text']) if text['action'] == 'start_getting_values': while True: # Getting some data here # ... message.reply_channel.send({"text": some_data}, immediately=True) time.sleep(1) if text['action'] == 'stop_getting_values': do_something_to_stop_the_loop_above() -
How do I compare a CombinedResponse object value with an int?
I'm trying to annotate a query with a percentage that repsents how "complete" the business logic is. I don't want that percentage to go over 100%. I currently have this in my query: .annotate(completion=max(100, Count('id')/F('something_tricky') ) The issue is that Count/F is a CombinedExpression, which is unorderable, so can't be used in max. It won't let me cast it to an int either: int() argument must be a string, a bytes-like object or a number, not 'CombinedExpression' Or to a String. How do I get the completion value as an int out of this query? -
Configure apache to respond with error page for incorrect hosts
django docs: You should also configure the Web server that sits in front of Django to validate the host. It should respond with a static error page or ignore requests for incorrect hosts instead of forwarding the request to Django. This way you’ll avoid spurious errors in your Django logs (or emails if you have error reporting configured that way). For example, on nginx you might setup a default server to return “444 No Response” on an unrecognized host: I am using Apache and this works: http://serverip -> 404 error http://www.example.com -> https://www.example.com -> django site http://example.com -> https://example.com -> django site Now I have a problem with https://serverip I get a not secure message by my browser because I only have a SSL Cert for example.com, www.example.com and after I accept the security warning I see the django site but I want 404 error page. How can I achieve this or do I misunderstand the django docs? -
I have some troubles in Django when I want to start my database? [duplicate]
This question already has an answer here: Django debug toolbar import error of analysisdebug_toolbar 1 answer I don't konw how to solve this problem -
Error occurred while reading WSGI handler - Deploy django to azure web app
Very related to this post but I don't have the priviledge to comment there so I had to make a new post. Deploy a simple VS2017 Django app to Azure - server error I followed Silencer's tutorial there and I am getting this error from \LogFiles\wfastcgi.log: 2017-07-28 08:28:57.746719: Activating virtualenv with D:\home\site\wwwroot\env\Scripts\python.exe 2017-07-28 08:28:57.777987: Error occurred while reading WSGI handler: Traceback (most recent call last): File "D:\home\python360x64\wfastcgi.py", line 791, in main env, handler = read_wsgi_handler(response.physical_path) File "D:\home\python360x64\wfastcgi.py", line 633, in read_wsgi_handler handler = get_wsgi_handler(os.getenv("WSGI_HANDLER")) File "D:\home\python360x64\wfastcgi.py", line 605, in get_wsgi_handler handler = handler() File ".\ptvs_virtualenv_proxy.py", line 99, in get_virtualenv_handler execfile(activate_this, dict(__file__=activate_this)) File ".\ptvs_virtualenv_proxy.py", line 27, in execfile code = f.read() File "D:\Repos\azure-python-siteextensions\source_packages\python.3.6.0\tools\Lib\encodings\cp1252.py", line 23, in decode UnicodeDecodeError: 'charmap' codec can't decode byte 0x90 in position 2: character maps to <undefined> I have installed python360x64 as an extension in azure portal, I am using this https://github.com/Azure/azure-sdk-for-python/blob/master/examples/AzureResourceViewer/ptvs_virtualenv_proxy.py And my web.config: <configuration> <system.diagnostics> <trace> <listeners> <add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" name="AzureDiagnostics"> <filter type="" /> </add> </listeners> </trace> </system.diagnostics> <appSettings> <add key="WSGI_ALT_VIRTUALENV_HANDLER" value="django.core.wsgi.get_wsgi_application()" /> <add key="WSGI_ALT_VIRTUALENV_ACTIVATE_THIS" value="D:\home\site\wwwroot\env\Scripts\python.exe" /> <add key="WSGI_HANDLER" value="ptvs_virtualenv_proxy.get_virtualenv_handler()" /> <add key="PYTHONPATH" value="D:\home\site\wwwroot" /> <add key="DJANGO_SETTINGS_MODULE" value="DjangoWebProject.settings" /> <add key="WSGI_LOG" value="D:\home\LogFiles\wfastcgi.log"/> </appSettings> <system.web> <compilation debug="true" targetFramework="4.0" /> </system.web> <system.webServer> <modules runAllManagedModulesForAllRequests="true" … -
Django SerializerModel does not return the fields
I create an Django REST API with Serializer but if i test the serializer I receive just an empty result. Actually I should receive an >>> from heating.serializers import RoomSerializer >>> s = RoomSerializer() >>> print(repr(s)) RoomSerializer(): ... LIST OF FIELDS WITH SOME ADDITIONAL INFOMRATION... >>> Model class Room(models.Model): id = models.IntegerField(auto_created=True, primary_key=True) name = models.CharField(max_length=100, blank=True, default='') description = models.TextField() class Meta: ordering = ['id'] Serializer class RoomSerializer(serializers.ModelSerializer): class Meta: model = Room fields = ('id', 'name', 'description') Shell output >>> from heating.serializers import RoomSerializer >>> s = RoomSerializer() >>> print(repr(s)) RoomSerializer(): >>> I strongly belive, that there is a mistake in my code, but I have no clue where? -
Django - Get distinct data from field
I'm looking for getting distinct objects from my database with distinct() command. I have this model : class CoefficientIntervention(models.Model): Technicien = models.FloatField(verbose_name="Coefficient Technicien") Ingenieur = models.FloatField(verbose_name="Coefficient Ingénieur") Consultant = models.FloatField(verbose_name="Coefficient Consultant") Architecte = models.FloatField(verbose_name="Coefficient Architecte") Societe = models.ForeignKey(Societe, related_name="ste", verbose_name="Société", default="") def __unicode__(self): return unicode (self.id, self.Technicien, self.Ingenieur, self.Consultant, self.Architecte, self.Societe) My form looks like : class CoefficientFormulaire(forms.ModelForm) : Societe = CustomLabelModelChoiceField(Societe.objects.filter(), required=True, label = "Societe", label_func=lambda obj: '%s %s' % (obj.id, obj.Nom)) class Meta : model = CoefficientIntervention fields = ['Technicien', 'Ingenieur', 'Architecte', 'Consultant','Societe'] And my view is really simple : @login_required def Identity_Societe_Coefficient(request) : if not request.user.is_superuser : raise Http404 coefficient = CoefficientIntervention.objects.order_by('Societe').values('Societe').distinct() print coefficient if request.method == 'POST': form = CoefficientFormulaire(request.POST or None) if form.is_valid() : # Vérification sur la validité des données post = form.save() messages.success(request, 'Le formulaire a été enregistré !') return HttpResponseRedirect(reverse('Coefficient')) else: messages.error(request, "Le formulaire est invalide !") else: form = CoefficientFormulaire() context = { "coefficient" : coefficient, "form" : form, } return render(request, 'Identity_Societe_Coefficient.html', context) My table has 3 lines for example : If I print coefficient, I get : <QuerySet [{'Societe': 2L}, {'Societe': 3L}]> But I would like to display distinct objects in my array and take the last one each … -
DateTimeField migration error in django
Previously my models' DateTimeField was initiated like order_date = models.DateTimeField(default=datetime.today) which was throwing TypeError: Required argument 'year' (pos 1) not found when i tried to instantiate a blank object. I fixed it with datetime.datetime.now(). But now when i try to migrate it shows the same error TypeError: Required argument 'year' (pos 1) not found when i make a clean a migration in a fresh db its not having any problem. I dont want to go on the route of making a fresh db since i don't have the permissions to do that in production. Is there any way to fix this? Traceback: Running migrations: Rendering model states... DONE Applying xyz.0016_auto_20170728_0758...Traceback (most recent call last): File "manage.py", line 9, in <module> execute_from_command_line(sys.argv) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 221, in handle executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/db/migrations/executor.py", line 110, in migrate self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/db/migrations/executor.py", line 147, in apply_migration state = migration.apply(state, schema_editor) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/db/migrations/migration.py", line 115, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/Users/sayok/projects/invenv1/lib/python2.7/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards schema_editor.alter_field(from_model, … -
django-cron does not run all CronJob classes
I have several CronJob classes saved in the settings.py of a Django project. Here is how the list looks like: CRON_CLASSES = [ "tracking.cron.MyCronJob", "tracking.cron.UpdatePagesFieldsCronJob", "tracking.cron.KeywordUpdateOLD", "tracking.cron.KeywordUpdateNEW", "tracking.cron.UpdatePageMetricEntries", "tracking.cron.UpdateTimeOnSiteAfter", "tracking.cron.UpdateAvgWatchedContent", "tracking.cron.CheckPageDuplicates", "tracking.cron.WidgetContribution", ] Now, inspecting the Django administration I see that the first is failing all the time and all the others are not even called. I tried to have a look inside the documentation, but I haven't found any clue. Anyone has experienced similar issues? -
Clean url in django app. without ?page=1 patern
I want to have in my url pattern with list view like here: host:8000/archive/2/ I define page_kwarg in my view but I still recived: host:8000/en/2 Code form main url file: url(_(r'^archive'), include('events.urls_archive', namespace='archive')), Here is url in my app: url('^/(?P<page>\d+)/$', ArchiveListView.as_view(), name="list"), Here is code of my view: class ArchiveListView(ListView): model = Booking queryset = Booking.objects.filter(period__type='archive').order_by('-date_start') paginate_by = 80 page_kwarg = 'page' Here is my template code: {% if is_paginated %} {% if page_obj.has_previous %} <a href="/{{ page_obj.previous_page_number }}" class="arrow left"><h4>Previous</h4></a> {% endif %} <span class="arrow header"><h4>Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}</h4></span> {% if page_obj.has_next %} <a href="/{{ page_obj.next_page_number }}" class="arrow right"><h4>Next</h4></a> {% endif %} {% endif %} Please for any hint. Thanks. -
Django: Is there a way to move from a GET request to a POST request if the requested data is not found?
I am making a weather API using Django where a user calls something like: http://127.0.0.1:8000/weather/<latitude>,<longitude> My application is supposed to query the database and return the data if found. If the data is not present or outdated, the app will create or modify an entry by accessing a 3rd party weather API to pull relevant data. Right now, I'm using the get_or_create() function within my get function in views.py to accomplish this. From what I've read, doing this is bad practice and any database modification should be done as a POST or PUT. I'm uncertain if this is something that I can do or if I am approaching this problem in the wrong direction. My app doesn't currently do everything I said it should do, but it does create entries if they don't exist. What I want is for my app to jump to a POST/PUT after determining that the entry needs to be created or updated. views.py def get(self, request, *args, **kwargs): # Process latitude and longitude coordinates from URL coordinates = kwargs.pop('location', None).split(",") latitude = coordinates[0] longitude = coordinates[1] # Retrieve the Location by latitude and longitude # If it doesn't exist, create an entry to generate a … -
pip install django on go daddy shows error
When i run command pip install django, on go daddy it gives me the following error: I tried to copy django packages manually into the site-packages of go daddy. I copied it from my local machine. I removed all of them.(I don't know if there is something remaining or not. But i have checked it again) Can you please help with this? DEPRECATION: Python 2.6 is no longer supported by the Python core team, please upgrade your Python. A future version of pip will drop support for Python 2.6 Collecting django Using cached Django-1.11.3-py2.py3-none-any.whl Requirement already satisfied: pytz in /usr/lib/python2.6/site-packages (from django) Installing collected packages: django Exception: Traceback (most recent call last): File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/req/req_set.py", line 784, in install **kwargs File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/home/lmtech123/.local/lib/python2.6/site-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib64/python2.6/os.py", line 157, in makedirs mkdir(name, mode) OSError: [Errno 30] Read-only file system: '/usr/lib64/python2.6/site-packages/Django-1.11.3.dist-info' -
Django URL in template with slug
I have a template (home.html) where I want to list all the items in my model, and when I click on them, it will take the user to the details page of the item. home.html: {% for item in menuitems %} <div class="col-md-4"> <h2><a href="{% url 'show_menuitem' slug=instance.slug %}">{{ item }}</a></h2> <p> </p> </div> {% endfor %} urls.py: urlpatterns = [url(r'^menuitem/(?P<menuitem_slug>[-\w]+)/$', menu_views.show_menuitem, name = 'show_menuitem'), ] views.py: def home(request): page_title = 'samplepagetitle' template_name="home.html" menuitems = MenuItem.objects.all() context = { 'page_title':page_title, 'menuitems':menuitems, } return render(request, template_name, context) models.py: class MenuItem(models.Model): name = models.CharField(max_length=250, blank=False, unique=True) slug = models.SlugField(max_length=250, unique=True, def __str__(self): return self.name @models.permalink def get_absolute_url(self): return ('show_menuitem', (), { 'menuitem_slug': self.slug }) I keep getting a NoReverseMatch error, which says: Reverse for 'show_menuitem' with keyword arguments '{'slug': ''}' not found. 1 pattern(s) tried: ['menuitem/(?P[-\w]+)/$'] Why is it giving me this error? Is my for loop set wrong in my template file? -
Error while displaying image from admin panel in django
I was trying to upload image from django admin panel and i made the following changes.However, I am getting this error when I tried to load the image in wine_list page and review_list.The images are stored in media however, it isnt being displayed: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/static/media/download_1.jpg Raised by: django.views.static.serve 'media\download_1.jpg' could not be found here is a code for wine_list {% extends 'base.html' %} {% block title %} <h2>Wine list</h2> {% endblock %} {% block content %} {% if wine_list %} {% load static %} <div> {% for wine in wine_list %} <div><ul> <li> <h4><a href="{% url 'reviews:wine_detail' wine.id %}"> {{ wine.name}}</a> <br> <a><img src="{% static wine.images.url %}" height="200"></a> <br> <br> here is code for the image section in review_list: {% extends 'base.html' %} {% block title %} <h2>Latest reviews</h2> {% load static %} {% endblock %} {% block content %} {% if latest_review_list %} <div class="row"> {% for review in latest_review_list %} <div class="col-xs-6 col-lg-4"> <h4><a href="{% url 'reviews:review_detail' review.id %}"> {{ review.wine.name }} </a></h4> <br> <a><img src="{% static review.wine.images.url %}" height="200"></a> urls.py for winerama folder from django.conf.urls import include, url from django.contrib import admin from django.conf import settings from django.conf.urls.static import … -
Why csrftoken cookie works?
I am upgrading from Django 1.4.3 to Django 11.3. I have a web page with 2 different forms. Both forms are loaded with {%csrf_token%}. The flow is - the user logins in using form 1 ( ajax ) and then the second form is displayed. The user enters data in the second form and submits using ajax. Now, this request was failing if I did ( worked under Django 1.4.3 ) - csrfmiddlewaretoken = $form.find('input[name="csrfmiddlewaretoken"]').val(); Now, to fix this I am getting csrftoken value from cookie and sending the cookie as part of ajax and it works - csrfmiddlewaretoken = _getHelperCookie('csrftoken'); I am confused why getting the client cookie works? After login, Django calls rotate_token; what actually does this affect? -
Django on Apache 500 Internal Server Error
I'm building a Django project with 2 apps and hosting on apache(wsgi). When INSTALLED_APPS is not modified, I can see Django's welcome page. But when I register apps to my SETTINGS.py : ... INSTALLED_APPS = [ ... 'Firstapp', 'Secondapp', ] Apache returns 500 Internal Server Error. Where should I see the problem? -
Django input as hour and minutes, saved as minutes
In my django webapp, I'm creating a form where a user inputs the time taken to complete an activity in hours and minutes (eg. 2 hours, 33 minutes). I want the input to appear client side as hours and minutes, but save to the model as just minutes (eg. 153) Currently, the input is only given in minutes. I worry this is fairly ugly/unreadable: models.py: class Activity(models.Model): time_taken = models.PositiveIntegerField(default=0) add_activity.html: <form id="add_session_form" method="post" action="" enctype="multipart/form-data"> {% csrf_token %} {{ add_activity_form.as_p }} <input type="submit" name="submit" value="Add Activity" /> </form> Could somebody please assist me in altering the form's input so that users individually enter the hours AND minutes, whilst only storing the time in minutes. -
Django - Exclude current post from side bar
I am playing with django but im having trouble with my templates. In my post detail im including a recent posts side bar from a templatetag but i want to exclude the current post if it is in fact one of the most recent. My original hope was to use .exclude(id__post_detail=post) in the blog_tag but i think i might be missing an important concept, do i need to request post_detail return its response and then i can do that? Or perhaps define query in the view and then call it to the blog_tag? Many thanks in advance. 1.blog_tags.py from django import template register = template.Library() from django.db import models from django.utils import timezone from ..models import Post @register.inclusion_tag('blog/sidebar.html') def sidebar_latest(request, count=5): latest_posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')[:count] return {'latest_posts': latest_posts} views def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) post_detail {% extends 'blog/base.html' %} {% load blog_tags %} {% block content %} <div class="col-sm-12 col-md-9"> <div class="post"> <h1>{{ post.title }}</h1> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <p>{{ post.text|linebreaksbr }}</p> </div> </div> <div class="col-sm-12 col-md-3"> {% sidebar_latest 3 %} </div> {% endblock %} -
add different class when loop completes 2 or 4 in django template
I need to achieve this in forloop, How i can I achieve this.when forloop counter reaches 2 it has to change the class of div. <div class="form-row field-orientation"> // first 2 fileds <div class="form-field"> <label>label1</label> <p>1920 X 1080</p> </div> <div class="form-field"> <label>Label 2 </label> <p>Landscape</p> </div> </div> <div class="form-row field-launched_time"> // last 2 fileds <div class="form-field"> <label>Label 3</label> <p>-</p> </div> <div class="form-field"> <label>Label 4</label> <p>-</p> </div> </div> I have following code like this: {% for line in fieldset %} <div class="form-row field-orientation"> {% for field in line %} <div class="form-field"> <label>{{ field.label_tag }}</label> <p>{{ field.contents }}</p> </div> {% endfor %} </div> {% endfor %} -
How to solve this type of forms-list views in Django?
I use listview to get a list of items, each item has approve and reject button of it's own. On clicking either of the buttons, item corresponding to the button should be updated with 1 on Approval and -1 on Rejected. So far I have been able to get the list of Items with Class Based ListView and have added a post method to the LisView to handle form submissions. Is this the right way to do it or is there any better alternative to it? -
Rename a directory after extracting zip archive uploaded by user
I'm trying to rename the directory after extracting it in a temporary directory.The archive upload by user. What I mean, User will upload a .tar OR .zip file then I will make a temporary directory and extract user's file into that directory, now I want to rename it extracted directory which is inside temporary directory. Here's what I have tried: In my views.py if form.is_valid(): deployment = TarWithoutDocker() deployment.name = form.cleaned_data['name'] deployment.user = request.user deployment.archive = form.cleaned_data['archive'] deployment.save() tmpdir = tempfile.mkdtemp() saved_umask = os.umask(0o077) path = os.path.join(tmpdir) arpath = deployment.archive.path patoolib.extract_archive(arpath, outdir=path) os.rename(path + '/' + deployment.archive.name[:-4], 'archive') print(path+'/'+deployment.archive.name[:-4]) But when I print print(path+'/'+deployment.archive.name[:-4]) it should print users' file name without .zip OR .tar extension. See what it prints out: archives/frequent_sign_in_form-web_Free18-07-2017_1046736122_9aAbZpD.zip patool: Extracting /Users/abdul/Documents/IGui/media/archives/frequent_sign_in_form-web_Free18-07-2017_1046736122_9aAbZpD.zip ... patool: ... /Users/abdul/Documents/IGui/media/archives/frequent_sign_in_form-web_Free18-07-2017_1046736122_9aAbZpD.zip extracted to `/var/folders/g2/8fzl8mjj5xxfqdfvrl7v3q_40000gn/T/tmpj8gzegdq'. [28/Jul/2017 05:16:08] "POST /user/deployment/new/awd HTTP/1.1" 302 0 [28/Jul/2017 05:16:08] "GET /user/deployment/new/awd HTTP/1.1" 200 15289