Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Get first object of query-set in Django templates
I understand that Django separates data and presentation such that Object.filter(id=value).all() isn't possible through templates. What I'm struggling to understand is the best practice for achieving this same type of end result. For example, in one of my apps I've data for products, which include some one-to-many relationships with images. That's to say, one product may have many images. in my AppName/views.py file, I've got the following: def index(request): response = render_to_response('AppName/index.html', context={ 'products': Product.objects.all(), }) return response in my AppName/templates/AppName/index.html file, there's a section with the following: {% for product in products %} <li>{{ product.name }}: ${{ product.price }}</li> {% endfor %} What I'd like to be able to do, is include the equivalent of {{product.images.first().url}} in the mix. What's the typical approach for this? -
Recover database after ran heroku pg:reset DATABASE
I accidently ran this command and it seems like I've lost all my database. $heroku pg:reset DATABASE Is there anyway I can recover my database... I truly appreciate your help in resolving the problem!! -
Getting 404 error messages after placing Django Python app in Docker Container
I am trying to get some template information to display on a web page served in from a Docker container. It is using uWSGI. The name of the template is base.html There are "decorations" associated with the base.html file that are located in the static directory. To be more specific, it resides in the static/wforms/assets directory. Below is how the assets directory is being used in the template. <link href="{% static 'wforms/assets/global/plugins/font-awesome/css/font-awesome.min.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'wforms/assets/global/plugins/simple-line-icons/simple-line-icons.min.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'wforms/assets/global/plugins/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet" type="text/css" /> Whenever I go to a page that uses the base.html template, the decorations are not found and the resulting web page is a mess. Everything works fine in PyCharm. The problem happens when moving everything to the directory structure in a Docker Container. Below is the directory structure in PyCharm. I start the container like this: docker run -it --rm -p 8888:8888 -v /home/dockcclubdjango/apps/wforms/assets:/code/backendworkproj/static/wforms/assets --name my-running-app my-python-app As an FYI, the /home/dockcclubdjango/apps/wforms/assets does exist and has the correct info in it. Then, I attempt to go to the web home page. The page shows up but all of the "decorations" are not present. So, the page looks somewhat … -
Can't download Django throught terminal
I am trying to download and install Django through the terminal but for some reason, I keep getting an error. I ran the command "sudo pip install Django". This is what is printed out in the terminal. Collecting Django Downloading Django-2.0.tar.gz (8.0MB) 100% |████████████████████████████████| 8.0MB 121kB/s Complete output from command python setup.py egg_info: Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/pip-build-Y1GrsP/Django/setup.py", line 32, in <module> version = __import__('django').get_version() File "django/__init__.py", line 1, in <module> from django.utils.version import get_version File "django/utils/version.py", line 61, in <module> @functools.lru_cache() AttributeError: 'module' object has no attribute 'lru_cache' ---------------------------------------- Command "python setup.py egg_info" failed with error code 1 in /private/tmp/pip-build-Y1GrsP/Django/ -
Can't parse a static JSON file in Django 1.8
I have the following tree: myDjangoSite/ ... myApp/ ... static/ ... myApp/ myData.json And I have this view.py file: import json from django.shortcuts import render from django.contrib.staticfiles.templatetags.staticfiles import static url = static('myApp/myData.json') json_data = open(url) def helloWorld(request): return render(request, 'myApp/index.html') ...and when I access to the webpage, the browsers shows this message: IOError at / [Errno 2] No such file or directory: '/static/myApp/myData.json' I don't understand why it says "no such file or directory", if the file DOES exist and how to solve it. -
Django form fields as template variables
The main question is if it is possible to specifify specific form fields at different given locations in your html template in any smooth way. e.g. {{ form.password }} However, that does not seem to work. (I swear that I have seen this somewhere, but I just can't find it anymore on the internet) My view for signing up new users is inheriting from UserCreationForm and looks kind of like this: views.py def signup(request): if request.method == "POST": form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') raw_password = form.cleaned_data.get('password1') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('home') else: form = UserCreationForm() return render(request, 'core/authentication/registration_form.html', {'form': form}) It sends this form straight to the template registration_form.html, this is how I wish it worked: <form class="form" method="POST" action=""> <div class="card-body"> <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons users_circle-08"></i> </span> {{ form.first_name }} </div> </div> This is how it actually works (for now): <form class="form" method="POST" action=""> <div class="card-body"> <div class="input-group form-group-no-border"> <span class="input-group-addon"> <i class="now-ui-icons users_circle-08"></i> </span> <input type="text" class="form-control" placeholder="First Name..."> </div> </div> This might be a stupid question, but oh well I am curious. Thank you in advance -
How to control Python's stdout encoding under Apache/WSGI
I'm writing a Django app, and it prints Unicode to stdout. It works perfectly on the development server, but with Apache and modwsgi I get UnicodeEncodeError: 'ascii' codec can't encode characters .... So, the stdout encoding is forced to ASCII. I've found a number of solutions, all of which seem like they should work according to documentation, but none work for me: I tried setting the PYTHONIOENCODING variable to utf-8, using the SetEnv directive. I also tried setting LANG, LC_ALL, LC_CTYPE to en_US.UTF-8 using SetEnv and PassEnv. Finally, I tried adding lang=en_US.UTF-8 locale=en_US.UTF-8 to the WSGIDaemonProcess directive. The variables are seen in the environment (reflected e.g. on Django error pages in debug mode), but the error still occurs. Why don't these things work and what should I do? Overriding stdout in the code that works fine outside Apache or encoding everything manually doesn't feel like the right approach. Versions: Python 2.7.14, Apache 2.4.29, mod_wsgi 4.5.20 on Arch Linux -
Django Oauth2 Implicit Token Authorization Fail
I've written a chrome extension that uses Chrome's identity API to initiate a webauthflow with a Django Site I have made. Through a button in my extension, I am able to launch and interactive webflow, log into my site (supposedly), and receive an auth token the GET request to my site to receive user information. The main issue here though it that my server is not authenticating according to the profile that has just logged in through the app; it always autheticates to the admin. I am confused about how exactly to use all the different backends, middleware, etc. to get my desired flow: My current settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( # 'rest_framework.authentication.BasicAuthentication', 'oauth2_provider.contrib.rest_framework.OAuth2Authentication', 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ) } OAUTH2_PROVIDER = { # this is the list of available scopes 'SCOPES': {'read': 'Read scope', 'write': 'Write scope', 'groups': 'Access to your groups'} } AUTHENTICATION_BACKENDS = ( # Uncomment following if you want to access the admin 'oauth2_provider.backends.OAuth2Backend', 'django.contrib.auth.backends.ModelBackend', 'django.contrib.auth.backends.RemoteUserBackend', # '...', ) MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'corsheaders.middleware.CorsMiddleware' ] My Views.py @login_required() def secret_page(request, *args, **kwargs): if request.method == 'GET': receivedurl = request.GET.get('url') print(receivedurl) currentcacheduser = auth.get_user(request) return HttpResponse(currentcacheduser, … -
Ajax powered like button in Django
I have built the next architecture for the like button, but it does not work: models.py class Comentario (models.Model): titulo = models.CharField(max_length=50) autor = models.ForeignKey (Perfil, null=True, blank=True, on_delete=models.CASCADE) archivo = models.FileField(upload_to='media/%Y/%m/%d', null=True, blank=True) slug= models.SlugField(default=0) likes = models.ManyToManyField(Perfil, related_name="likes") def __str__(self): return (self.titulo) @property def total_likes(self): return self.likes.count() def save(self, *args, **kwargs): self.slug=slugify(self.titulo) super(Comentario, self).save(*args, **kwargs) views.py try: from django.utils import simplejson as json except ImportError: import json def like (request): if request.method=='POST': perfil=request.user slug=request.POST.get('slug', None) comentario=get_object_or_404(Comentario, slug=slug) if comentario.objects.filter(perfil__id=perfil.id).exists(): comentario.likes.remove(perfil_id) else: comentario.likes.add(perfil_id) context={'likes_count':comentario.total_likes} return HttpResponse(json.dumps(context), content_type='home/json') urls.py url(r'^like/$', login_required(views.like), name='like') .html <input type="button" id="like" name='{{ comentario_slug }}' value="Like" /> <script> $('#like').click(function(){ $.ajax("/home/like/",{ type: "POST", url: "{% url 'home:like' %}", data: {'slug': $(this).attr('titulo'), 'csrfmiddlewaretoken': '{{ csrf_token }}'}, dataType: "json", success: function(response) { alert(' likes count is now ' + response.likes_count); }, error: function(rs, e) { alert(rs.responseText); } }); }) </script> When I push the button like it does not do anything. The console tells me: POST htt jquery.min.js:4 p:/127.0.0.1.8000/home/like/404 (not found) and: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js Which is the problem? thank you for your help -
django - UNIQUE constraint failed: one_file.user_id
I am making a website in which user can upload files and those files are displayed in user's profile. I had displayed a file in user's profile but when I add 2nd file, it gives an error as: IntegrityError at /profile UNIQUE constraint failed: one_file.user_id models.py: class file(models.Model): title = models.CharField(max_length=250) file_type = models.CharField(max_length=12) description = models.TextField(max_length=6000) user = models.OneToOneField(User, on_delete=models.CASCADE) def get_absolute_url(self): return reverse('one:user') def __str__(self): return self.title views.py: def profile(request): if request.user.is_authenticated(): name= request.user.username form_class = file_form template_name = 'one/profile.html' content = file.objects.all() if request.method=='GET': form = form_class(None) return render(request,template_name,{'form':form,'name':name, 'content':content}) elif request.method=='POST': form = form_class(request.POST) if form.is_valid(): FILE = form.save(commit = False) FILE.user = request.user FILE.save() return HttpResponseRedirect('/profile') tempalte: logged in as: {{name}} <br> <a href="/logout">logout</a> <br> <form method="post" action=""> {% csrf_token %} {% include 'one/form-template.html' %} <button type="submit"> add file </button> </form> <br> <h3>my files</h3> {% for files in content %} <p>{{files.title}}</p> <br> {%endfor%} -
Django - Auto run scripts at certain time on Live Server
Newbie here. I have a lot of different functions in a Python program that downloads a bunch of data from the internet, manipulates it, and displays it to the public. I have bunch of links to different tables of data, and I figure it would be very inconvenient for people to have to wait for the data to download when they clicked the link on my website. How can I configure Django to run the scripts that download the data at say, like 6am? And save some type of cached template of the data so people could quickly view that data for the entire day, and then refresh and update the data for the next day. Your insight and guidance would be very appreciated! Thank you! and Happy holidays! -
Assistance with passing multiple objects via a list to Jsonresponse in Django
I have a code in Django where 5 random numbers are selected and then based on those 5 numbers 5 more queries are made from the database. One this is done I would like to pass all 5 objects from database to the template via json., however I am not sure how to proceed with this. This is what I have now: class multiplePull(TemplateView): template_name = 'gacha/multiplePull.html' def randomStar(self): choice = [5,4,3] probability = [0.1, 0.2, 0.7] star = random.choices(choice, probability) return star[0] def post(self, request): multi = [] characters = [] for x in range(5): star = self.randomStar() multi.append(star) for star in multi: character = Characters.objects.filter(stars=star).order_by('?')[:1] for obj in character: characters.append(obj) return JsonResponse(json.dumps(characters), safe=False) As it is now I get the following error: TypeError: Object of type 'QuerySet' is not JSON serializable How can I do this to make it work? I think I am missing something still but can't really find a solution. This works fine when I simply send this as context data but I don't know how to pass all 5 objects via Json. I would appreciate all help. Thanks you. -
Django Designing Models for Dating App Matches
I’m working on a dating app for a hackathon project. We have a series of questions that users fill out, and then every few days we are going to send suggested matches. If anyone has a good tutorial for these kinds of matching algorithms, it would be very appreciated. One idea is to assign a point value for each question and then to do a def comparison(person_a, person_b) function where you iterate through these questions, and where there’s a common answer, you add in a point. So the higher the score, the better the match. I understand this so far, but I’m struggling to see how to save this data in the database. In python, I could take each user and then iterate through all the other users with this comparison function and make a dictionary for each person that lists all the other users and a score for them. And then to suggest matches, I iterate through the dictionary list and if that person hasn’t been matched up already with that person, then make a match. person1_dictionary_of_matches = {‘person2’: 3, ‘person3’: 5, ‘person4’: 10, ‘person5’: 12, ‘person6’: 2,……,‘person200’:10} person_1_list_of_prior_matches = [‘person3’, 'person4'] I'm struggling on how to represent this … -
How to filter the options for a ForeignKey based on an other ForeignKey
I need to filter the options for a ForeignKey based on an other ForeignKey. class LabValue(models.Model): measurement = models.ForeignKey( 'LabMeasurement', on_delete=models.CASCADE) unit = models.ForeignKey( LabMeasurementUnit, on_delete=models.CASCADE, limit_choices_to={'parameter__id': self.measurement.parameter.id}, ) How can I retrieve self.measurement.parameter.id? If I manually enter an ID like for example "1" the query works. -
Designing code for proper error handling in a Django / Python app?
I'm in the midst of building a Django app and am hoping to get some advice on the proper way to handle errors and bugs in my code. Here's a common situation exemplary of the problems I have: a user purchases a product. To process the purchase, my views need to perform a number of actions: First, the view should create a User object in the database. If that is successful, the view should create an Order object and assign it to the newly-created User. If that is successful, my code should create a Product object and add it to the newly created Order. This is all well and good when no errors occur - but I find that the occasional error is inevitable in my code, and I want my app to deal with errors gracefully, rather than crashing outright. For example, if, for any reason, an Order object cannot be created, the view should show the user an error and remove the User object that was previously created. And, it should throw a graceful error message rather than crashing outright and serving the user a Http 500 error. The only way I can think of to do this … -
model messages on django
I create model for messages , user can have many read messages. Message can read many users. Is similar to group chat in slack. class Message(models.Model): user = models.ForeignKey(User) users_read = models.ManyToManyField(User, related_name='read_messages') date_created=models.DateTimeField(auto_now_add=True) text = models.CharField(max_length=500) Right i make references in my models? sorry for my english, i learning him -
What are the benefit of Python Django?
I would like to know some of the benefits of using Python Django? This can include security features, ease of use or any other aspect that make Django stand out. -
How to solve faceook/linkedin Authentication process canceled error?
I have a project in AWS cloud9, when i tryed to login via LinkedIn or Facebook (i write my code in python and i use Django v1.8.4). After i Press the button "allow access" to my LinkedIn or Facebook account i get this error page: facebook linkedin Traceback: Environment: Request Method: GET Request URL: http://8011118167a14663bf26f276beae74fe.vfs.cloud9.us-east-2.amazonaws.com:80/complete/facebook/?redirect_state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR&code=AQCHwhQV29jyqzxZ8_qtAQD6D_baKZvcdaMOL889co7q6N_rerhEvteJ3-1iE-vIhyX87qAHfCTN4XgoFF0IQT_MyWHsIf28ggfZt3IqUMXFODBsXaYY_PJJCvDRniv20gqMF9Pq1Lm2L1x-OFAOsqLsIboYZDrmG6ceFpADyzdKOXZRsy44uiXKhZIzht3VI45je8JbWowZJa-YUcRD1zY5OQnniW5ujq3IYe2l0z6nha6hq7Lk0lzLD5BR4I5O9sd7CdMxeRXX0NBmc9Qz4av2j2xsiHQq9zBASy03dSwENwQ2veIOhpQCMrIkkXwfNGQ&state=s9F0XdwpzEpFx26DcClydCC2TI5gRICR Django Version: 1.8.4 Python Version: 2.7.12 Installed Applications: ('django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_social_project', 'django_social_app', 'social.apps.django_app.default', 'facebook_auth') Installed Middleware: ('django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware') Traceback: File "/usr/local/lib64/python2.7/site-packages/django/core/handlers/base.py" in get_response 132. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/local/lib64/python2.7/site-packages/django/views/decorators/csrf.py" in wrapped_view 58. return view_func(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/utils.py" in wrapper 51. return func(request, backend, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/apps/django_app/views.py" in complete 28. redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/actions.py" in do_complete 43. user = backend.complete(user=user, *args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/backends/base.py" in complete 41. return self.auth_complete(*args, **kwargs) File "/usr/local/lib/python2.7/site-packages/social/utils.py" in wrapper 232. raise AuthCanceled(args[0]) Exception Type: AuthCanceled at /complete/facebook/ Exception Value: Authentication process canceled I saw How to solve Authentication process canceled error? but It does not work. -
Having problems with a query in Django
I'm building my first app within Django and I'm trying to query a "load" based on the company that i've attached to the load. Here's the model in question. class Load(models.Model): company = models.ForeignKey(UserCompany, null=True, on_delete=models.CASCADE) load_number = models.IntegerField() carrier = models.CharField(max_length=255) pickup_date = models.DateField() delivery_date = models.DateField() shipper = models.CharField(max_length=255) consignee = models.CharField(max_length=255) po_number = models.CharField(max_length=255) pu_number = models.CharField(max_length=255) pieces = models.IntegerField() description = models.TextField() date_created = models.DateTimeField(blank=True, null=True) def publish(self): self.date_created = timezone.now() self.save() def __str__(self): return str(self.load_number) Now I'm trying to display a list on a page, but only display the loads attached to a specific company. The user needs to be attached to that company as well so here are my user models. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User # Create your models here. class UserCompany(models.Model): company_name = models.CharField(max_length=200) def __unicode__(self): return self.company_name def __str__(self): return self.company_name # User Model class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # Additional Classes profile_pic = models.ImageField(upload_to='profile_pics', blank=True) company = models.ForeignKey(UserCompany, null=True,on_delete=models.CASCADE) def __str__(self): return self.user.username Then i'm trying to query the "loads" within this view. # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render, get_object_or_404 … -
Deploying app on Heroku (code=H10 desc="App crashed") Issue
I tried to deploy my app on heroku, but somehow I got this error page. I've run "$ heroku logs" on terminal and got the following messages. 2017-12-23T16:14:37.940528+00:00 heroku[router]:at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=79f89451-07b7-45b8-bf6d-1230092bcc1a fwd="123.193.63.120" dyno=web.1 connect=5001ms service= status=503 bytes= protocol=https 2017-12-23T16:14:38.308115+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=www.textory.tw request_id=520f0dab-1a19-42ed-bee5-60846b6c7631 fwd="123.193.63.120" dyno= connect= service= status=503 bytes= protocol=https Here is my Procfile web: gunicorn textory.wsgi VENV *.pyc __pycache__ staticfiles db.sqlite3 settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_cdn") STATICFILES_STORAGE ='whitenoise.storage.CompressedManifestStaticFilesStorage' -
Why do we pass request as a parameter in the render method of django?
I have noticed that when using the render() function, we pass request as the first parameter, what's the use of this? Also, can somebody explain using an example, when would it be necessary to use render() function instead of render_to_response() function for rending templates? -
How do Meta field names correspond to model attributes
I am writing a Django Model and different Forms to modify the model's data. For simplification let's say my model is as follows: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField() # (...) some other properties __identity_card_front = models.FileField(blank=True) class IdentityCardForm(forms.ModelForm): class Meta: model = Profile fields = ('__identity_card_front',) My question is: must the fields names correspond to the attributes of Profile class (the exact name of the variables definition)? Do these strings determine the HTML form field name that will be searched in form validation? And if so, how can I customise it? I don't want to have to obligatorily call my field name '__identity_card_front', but instead maybe something like 'id_front', 'idf', etc. I have seen labels might be used, but I was not clear how Django treats fields tags. I could not find either a good explanation on the Docs without getting lost around low-level class definitions and properties. Note: I am using django-2.0 -
How to dynamically delete object using django formset
Imagine E-commerce shop. User opens his cart (order), sees products, want to delete a few. The question is how to delete it dynamically using ajax. here we render template with two "elements" - ORDER (order_form) which contains customer's information and SET_OF_ORDERED_ITEMS (formset) views.py def show_cart(request): OrderItemFormSet = inlineformset_factory(Order, OrderItem, form=OrderItemForm, extra=0, can_delete=True) order = Order.objects.get(pk=request.session['order_id']) if request.method == 'GET': order_form = OrderForm(instance=order) formset = OrderItemFormSet(instance=order) return render(request, 'ordersys/cart.html', {'order_form': order_form, 'formset': formset}) elif request.method == 'POST': filled_form = OrderForm(request.POST, instance=order) filled_formset = OrderItemFormSet(request.POST, instance=order) if filled_form.is_valid() and filled_formset.is_valid(): filled_form.save() filled_formset.save() return redirect('catalog:index') else: return render(request, 'ordersys/cart.html', {'order_form': filled_form, 'formset': filled_formset}) template cart.html <form action="... > {{ formset.management_form }} # set of ordered_item forms {% for ordered_item_form in formset %} {{ ordered_item_form.id }} {{ ordered_item_form.instance.name }} {{ ordered_item_form.quantity }} <button type="button" onclick="delete_item_with_ajax();"> DELETE </button> {% endfor %} ... # here i render order_form's fields such as ADDRESS, PHONE_NUMBER... but it is not important for our example ... <button type="submit"> SUBMIT </button> </form> If user press "DELETE" button, it removes ordered_item_form element from the DOM and calls ajax function which passes ID of removable item to the function, which unties ordered_item from the order by deleting it from database. views.py def delete_order_item(request): … -
Django: how to send form data from one page to the next?
The basic problem is that I can not find out a way of taking the form data to pass on to the next page? Extra information: I read somewhere that I should use session, which seems sensible, however, serialization appears not to work with forms without a model, however, I could be wrong. When I click submit the error is 'AttributeError: 'BoundField' object has no attribute '_meta'. Form class ItemCounterForm(Form): item = CharField(max_length=30) counter = IntegerFeild(min_value=1, max_value=1000) def __init__(self, *args, **kwargs): super(ItemCounterForm, self).__init__(*args, **kwargs) View class ItemCounterView(View): FormSet = formset_factory(ItemCounterForm) def get(self, request, *args, **kwargs): context = { 'form': self.FormSet() } return render(request, 'app:template', context) def post(self, request, *args, **kwargs): form = self.FormSet(self.request.POST or None) if form.is_valid(): for single_form in form: data_form = serializers.serialize('json', single_form) request.session['form'] = data_form return HttpResponseRedirect(reverse_lazy('app:next_page') else: context = { 'form': self.FormSet() } return render(request, 'app:template', context) Thank you for your time. -
Configuring a uwsgi.ini file so that a DJango project will work within a Docker container
I am trying to set the uwsgi.ini file so that it will work with a docker container. In the Dockerfile, I have exposed port 8888. Below are the pieces of the Dockerfile that are related to this problem: Dockerfile EXPOSE 8888 ENV DOCKER_CONTAINER=1 #CMD ["uwsgi", "--ini", "/code/uwsgi.ini"] <<< right now, this is commented out CMD ["/bin/bash"] Above, the CMD to run the uwsgi.ini file is commented out because, for me, it did not work initially. I changed the CMD to "/bin/bash" so that I could log in to the OS level of the container. After doing so, I then ran the code below: uwsgi --http 923b235d270e:8888 --chdir=/code/backendworkproj --module=backendworkproj.wsgi:application --env DJANGO_SETTINGS_MODULE=backendworkproj.settings --master --pidfile=/tmp/backendworkproj-master.pid --socket=127.0.0.1:49152 --processes=5 --uid=1000 --gid=2000 --harakiri=20 --max-requests=5000 --vacuum Once complete, I was able to go to port 8888 on the machine and see the website. So, in short, everything worked. The problem I am facing now is to convert the command above to something that will work in the uwgsi.ini file If you look at part of the command above, I used : --http 923b235d270e:8888 to specify a port. The 923b235d270e is associated with the container (since 127.0.0.1 did not work) How can I represent this (and env variables …