Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
File Upload using Django Rest Framework getting error "No file was submitted."
While trying to upload the file using Postman with Content-Type - multipart/form-data in the headers.I am passing both the fields.But getting the error Error:{"upload_to": ["This field is required."],"file_object": ["No file was submitted."]} urls.py from django.conf.urls import include, url from rest_framework_nested import routers from utils.views import TemporaryImageView from . import views router = routers.SimpleRouter(trailing_slash=False) urlpatterns = [ url(r'^', include(router.urls)), url(r'^upload-temp-image/$', TemporaryImageView.as_view()) ] #views.py from rest_framework import viewsets, filters import django_filters.rest_framework from rest_framework.generics import CreateAPIView from rest_framework.parsers import FileUploadParser, MultiPartParser, FormParser from utils.serializers.temporary_image import TemporaryImageSerializer class TemporaryImageView(CreateAPIView): parser_classes = (MultiPartParser,) serializer_class = TemporaryImageSerializer #serializers.py from rest_framework import serializers from utils.models.tempfile import TemporaryFile class TemporaryImageSerializer(serializers.ModelSerializer): choices = (('Company Logo','/company/logos/'), ) upload_to = serializers.ChoiceField(choices=choices) file_object = serializers.ImageField() class Meta: model = TemporaryFile fields = ('upload_to', 'file_object') #models.py from django.db import models class TemporaryFile(models.Model): """ a temporary file to backend """ file_object = models.FileField(blank=False, null=False) timestamp = models.DateTimeField(auto_now_add=True) def __unicode__(self): return str(self.id) Please help...I don't know what is wrong.Thanks in advance. -
Access a queryset's 'values_list' in Django template
I am trying to access the values_list of a query_set in a template. In a view I have used the following if statement to determine whether an Outcome (model) exists for a given Participant (model): if not form.cleaned_data['timepoint'] in patient.outcome_set.values_list('timepoint', flat=True): This worked perfectly - now I want to be able to do something similar with the values_list in a template. However, when I try to limit the values_list to just the timepoint variable on the model, it throws a TemplateSyntaxError Could not parse the remainder: '('template')' from 'patient.outcome_set.values_list('template')' If I put print toe values_list to the screen using {{ patient.outcome_set.values_list }} it prints all the values of each outcome fine, but I can't work out how to limit the values_list to just the timepoint variable. Current template: <table> <thead> <tr> <th>Patient</th> <th>Baseline</th> <th>Follow-up</th> </tr> </thead> <tbody> {% for patient in patients %} <tr> <td>{{ patient.name }}</td> {% if 'baseline' in patient.outcome_set.values_list('timepoint') %} <td>INSERT TICK</td> {% else %} <td>INSERT CROSS</td> {% endif %} {% if 'followup' in patient.outcome_set.values_list('timepoint') %} <td>INSERT TICK</td> {% else %} <td>INSERT CROSS</td> {% endif %} </tr> {% endfor %} </tbody> </table> -
how we use Two factor Authentication in our django project
how we use django otp in our project i tried to much to generate two factor authentication verification by Two factor Authentication in my project but i didn't get it. i want to say if someone have that please give me the answer to get it and please describe it full and step and step. i tried by two factor authentication docs but i didn't get clear. I am quite familiar with django but not able to understand what exactly what i do for django otp -
Django ModelViewSet PATCH request return model fields updated
class MerchantStampCardViewSet(viewsets.ModelViewSet): ''' A view set for listing/retrieving/updating/deleting stamp cards for the current merchant ''' permission_classes = (IsMerchantAndAuthenticated, ) def get_serializer_class(self): if self.request.method == 'GET': return StampCardSerializerWithRewards else: return StampCardSerializer I'm trying to make this code return the fields changed in the response body. The model class has a couple fields like name, city, province, zip code and address and through the front-end the user can only change one at a time, but I want the body of the 200 response to contain the field name changed and the new value just to confirm that a change was successful and nothing went wrong. So for example if the user changes the name to Billy. The response should be 200 and the body should say {name : 'Billy'} How do I do this? -
django 2 Custom User: Attribute Error (password not passing/hashing properly)
I have implemented a custom user setup for django 2. However I can't seem to find out source of this error that occurs anytime I attempt to register. AttributeError at /register/ 'AnonymousUser' object has no attribute '_meta' When I get this error, the password is passed without a hash and not saved to the db, while the other values pass through fine. models.py from django.db import models from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import AbstractBaseUser from django.contrib.auth.models import PermissionsMixin from django.utils.translation import ugettext_lazy as _ class MyUserManager(BaseUserManager): def _create_user(self, email, password): if not email: raise ValueError('The Email must be set') email = self.normalize_email(email) user = self.model(email=email,) user.set_password(password) user.save() return user def create_superuser(self, email, password): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError('Superuser must have is_staff=True.') if extra_fields.get('is_superuser') is not True: raise ValueError('Superuser must have is_superuser=True.') return self._create_user(email, password) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(unique=True, null=True) is_staff = models.BooleanField( _('staff status'), default=False, help_text=_('Designates whether the user can log into this site.'), ) is_active = models.BooleanField( _('active'), default=True, help_text=_( 'Designates whether this user should be treated as active. ' 'Unselect this instead of deleting accounts.' ), ) USERNAME_FIELD = 'email' objects = MyUserManager() def __str__(self): return self.email … -
Rendering A List of Dictionaries in Django
I have the following model in my django project (the objects are basically a list of dictionaries): def bill_sum(request): titles = Summary.objects.values('title') summary = Summary.objects.values('summary') summary_text = Summary.objects.values('summary_text') action_date = Summary.objects.values('action_date') action_desc = Summary.objects.values('action_desc') context = {'title':titles, 'summary':summary, 'summary_text':summary_text, 'action_date': action_date, 'action_desc':action_desc, } return render(request,'billsummary.html',context) In my template I can generate a list of titles by the following html code: <!doctype html> <html> <body> {% for t in title %} <h1>{{t.title}}</h1> {% endfor %} </body> </html> However, when I try to add additional information (such as a loop for all the summary objects, nothing renders except the titles. What am I missing? How do I render a list of dictionaries (i.e. a Json data file) from my views into a template? -
Disable option charField choices depending on another atribute (Django)
So, I have the following in my models.py: UNITY_CHOICES = ( ('g', 'Gram(s)'), ('kg', 'Kilogram(s)'), ('l', 'Liter(s)'), ('cl', 'Centiliter(s)'), ) class Recipe_Ingredient(models.Model): recipe = models.ForeignKey(Recipe, on_delete=models.CASCADE) ingredient = models.ForeignKey(Ingredient, on_delete=models.CASCADE) quantity = models.FloatField() cost = models.DecimalField(max_digits=20, decimal_places=2) quantityUnit = models.CharField( max_length=2, choices=UNITY_CHOICES, default=GRAM, ) class Ingredient(models.Model): name = models.CharField(max_length=200) articleNumber = models.IntegerField(unique=True) costPrice = models.DecimalField(max_digits=20, decimal_places=2) costAmout = models.FloatField() costUnity = models.CharField( max_length=2, choices=UNITY_CHOICES, default=GRAM, ) And I have a simple form to add this model to my database: class Recipe_IngredientForm(forms.ModelForm): class Meta: model = Recipe_Ingredient fields = ('quantity', 'quantityUnit', 'ingredient') So I was wondering if there's a way of filtering the quantityUnit available choices depending on the ingredient chosen. I'll try to make it clear by an example: Let's say I choose to add Potato and the costUnity for Potato is 'g', then I want to make 'kg' and 'g' the only choices for quantityUnit. Is that a good example? I can try to think of something better if it's not clear enough. Anyway, is it possible to do such thing? Thanks. -
How can I update a Model and do something with this object or other?
My model has 7 fields, but I want update a only field. I'm using CBC(generic.UpdateView) with model and form_class. My forms works normally, but, I want do things depending on value for this Field. I dont know what method override. ModelA: atribute_a atribute_b atribute_c I need change onlye atribute_a, but atribute_b is a dateTime, and a I want update atribute_b with timezone.now() when update atribute_a, and after that I want update a another object with ForeignKey with atribute_c for example. basically in a UpdateView, I want this: In a some method(save, post, dispatch or other) atribute_b = timezone.now() if atribute_a == 'abc': ModelB.objects.filter(atribute_c=atribute_c).update(atribute_c = atribute_c+1) -
Call python function from django html template?
There are similar questions asked on stackoverflow but all the ones I saw gave instructions on how to route the user to a specific url on button click, I need just to call a function. My setup looks like this: My views.py has the following view (note I am not using a model): class CBDetailView(LoginRequiredMixin, ListView): template_name = 'cb_detail.html' login_url = 'login' def get_queryset(self): return CBData.getAllBoards() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) pkid = self.kwargs['pk'] context['cb'] = CBData.getBoardById(pkid) pins = CBData.getPinsByCBId(pkid) context['pins'] = pins watchers = CBData.getWatchersByCBId(pkid) context['watchers'] = watchers misc = {} misc['user']=self.request.user.email misc['watcher_count'] = watchers.__len__ if pins: misc['pin_count'] = pins.__len__ context['misc'] = misc return context This view is associated with a template that looks a bit like this: {% extends 'base.html' %} {% block content %} {% if cb %} <h1>{{ cb.title }}</h1> <form method="get"> <a class="btn btn-info ml-2" href="{% url 'pin_add' cb.corkboard_id %}" role="button">Add Pin</a> {% if cb.email != misc.user %} <a class="btn btn-info ml-2" role="button">Watch CB</a> <a class="btn btn-info ml-2" role="button">Follow User</a> {% endif %} </form> Lets say I have another function sitting somewhere in my .py files that looks like this: def some_function(pk,email): # do something with pk and email How would I go about … -
is there a way to authenticate user and password using django?
Is there away to authenticate username and password in Django. all i can find is https://simpleisbetterthancomplex.com/tutorial/2017/02/18/how-to-create-user-sign-up-view.html this it is just uses username authentication -
comment system doesnt store in my database
each time i try to comment, i get don't get an error but yet my comments doesn,t seem to be stored in my Comments database but below the list of stored cComments in the database, it counts but doesnt show in the database and secondly, in my templates were i have {% with comments.count as total_comments %} <h2>{{ total_comments }} comment{{ total_comments|pluralize }}</h2> {% endwith %}, if my form is valid and stored, i want to to automatically count the list of my comments, here is a piece of mu code for better understanding.... views.py: def SecondDetail(request,seconds): seconds =get_object_or_404(Second,id=seconds) comments = seconds.comments.filter(approved=True) if request.method == 'POST': form = CommentForm(data=request.POST) if form.is_valid(): new_comment = form.save(commit=False) new_comment.seconds = seconds new_comment.save() return HttpResponse("thanks for commenting") else: form = CommentForm() return render (request, 'home/second_detail.html', {'form':form,'comments':comments,'seconds':seconds}) my url.py url(r'^news/(?P<seconds>\d+)/$', views.SecondDetail,name='post_detail') and my second_detail.html(template) {% with comments.count as total_comments %} <h2>{{ total_comments }} comment{{ total_comments|pluralize }}</h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{ forloop.counter }} by {{ comment.name }} {{ comment.created }} </p> {{ comment.body|linebreaks }} </div> {% empty %} <p>There are no comments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% … -
What would I use to make a web app that searches the website for the price of an item and give 70% of the items value
For example it would search for the average price of a couch on the internet and find $100. It would then display $70. -
Problem with Facebook Key, Django Allauth
I am learning Django and I am in the situation of making a Login with facebook. But I have this problem ... Any solution? Attached photos. image 1 -
django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')
I'm a news for python and djnago, when I run a django project, it's error like: django.db.utils.OperationalError: (2026, 'SSL connection error: SSL_CTX_set_tmp_dh failed')' mysql Server version: 8.0.13 MySQL Community Server - GPL. I can't find this error on the web. -
CouchDB write/read only (no edit) user
Toolchain/frameworks I'm using django==2.1.3 and python-cloudant==2.1.3 and running CouchDB ver. 2.2.0, and pretty much doing all of my setup/configuration through Fauxton. I like to think that I know my way around python/django in general, and I'm testing this approach in a small little project to see how it works Problem Description Suppose I have a fairly simple CRUD application with just 1 model: class Asset(models.Model): asset_id = models.CharField(max_length=32) asset_name = models.CharField(max_length=32) and I have a view that I use to create the asset class CreateAssetView(views.View): def get(self, request, *args, **kwargs): #some code here def post(self, request, *args, **kwargs): #some code here| #log request data into database client = CouchDB('myusername', 'mypassword', url='http://127.0.0.1:5984', connect=True) db = client['assets'] log_data = {'view_name': self.view_name, 'post_data': post_data,'user': request.user.username, 'time': str(timezone.now())} return render(...) I understand that I should be doing the logging portion using a middleware (which I plan to) and probably just use django's CreateView in that case, I'm doing this approach for now just during early development. What I'm having a problem wrapping my head around is creating a user with myusername and mypassword that has the permissions to: Write new documents Read old documents not edit already created documents I could even settle for … -
How can I verify that all related fields in a Django REST Framework serializer specify objects with the same owner?
I have a Django app that uses django-organizations for supporting shared accounts, and rest_framework for an API. I have a custom model for authentication that relates the user to an API token specific to an organization. I have a model with a few foreign keys, a serializer with related fields, and a ModelViewSet for the API views. I want to make sure that any API calls for creating or modifying instances of my model verify that the objects specified for the related fields have the same owner (organization). class Bar(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE) class Foo(models.Model): uuid = models.UUIDField( default=uuid.uuid4, editable=False, unique=True) organization = models.ForeignKey( Organization, on_delete=models.CASCADE) bar = models.ForeignKey( Bar, on_delete=models.CASCADE) class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ('uuid', 'organization', 'bar') bar = serializers.SlugRelatedField( slug_field='uuid', queryset=Bar.objects.all()) How can I verify that related objects belong to the same account? Ideally, I'd be able to override the queryset specified for each RelatedField in the serializer, but I don't think that's possible. -
Form field required despite setting required attr to false
I've managed to do something really strange. I have a web app in Django (2.1, also using Bootstrap, jQuery) that is misbehaving. In my forms.py, I have defined: caption = forms.CharField(widget=forms.TextInput( attrs={ 'required': False, 'class': "roll-caption", 'placeholder': "Caption", } )) In the model.py, caption = models.CharField(max_length=200, null=True, blank=True) The class and placeholder render just fine. I've covered every base I can think of. But, the form field is being rendered as required in html. Needless to say, I am confused. The form field is sitting inside of some divs, but that shouldn't affect it, I thought. Any idea what I've managed to do? -
Django app not running inside Django project in Cpanel. Showing Passenger error
When I install a python app it is working...After installing Django project it is also working. But, I install a Django app inside the Django project and connect it with app setting file like the blog it is showing always "Web application could not be started by the Phusion Passenger application server." Domain: domain.com Project App Folder: domain.com/app Apps Inside Project: domain.com/app/blog In app.setting file "INSTALLED_APP" Section if I add app name like "blog" it is not working and showing the error of passenger. If I remove the app name from "INSTALLED_APP" it is working with Django default the first page. -
How to send FormData attribute with an array of strings from React Client to Django + Django Rest Framework API
How can I send JSON.stringify(array) data within form-data and decode the JSON with my Django api? I'm trying to add the functionality to upload an array of date-strings within a form originally we sent the post data using JSON and sending arrays of data worked, however, when we switched to using form-data in order to make uploading an image easier we started having problems with array types. since form data has to be sent using a string type I converted the date-string array using JSON.stringify() const myForm = new FormData(); myForm.set("date_strings", JSON.stringify(dateStrings)); when I post myForm to my Django + DRF API it responds with { "date_strings": [ "Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]." ], "status_code": 400 } In Postman I verified that sending a single date-string works, but when I send a string-array I get the same error. I believe my Django API tests if the request.data is valid, sees that date_strings are a JSON string, then responds with a 400 Error. def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) Attempted Solutions: converting the JSON string to an array in the PostViewset create method I can't change request.data['publish_dates'] because it is not mutable … -
How to implement a toggle option allowing customers to reduce quantity or remove items during checkout
This is my current checkout screen where I display the orders placed along with the quantity, weight and total weight of the order. I'm not sure how to implement an option which allows a customer to delete items at checkout or alter quantity. How would I be able to go about doing that? Also, is it possible to implement a functionality where I can check the total weight and if the total weight exceeds a particular limit, I have a message below indicating it is overweight and if the customer alters the quantity or deletes items, the message is removed. Views.py def checkout(request): try: current_order = Order.objects.filter(owner=1).get(status="pre-place") except Order.DoesNotExist: return HttpResponse("Your current order is empty<br><a href=\"browse\">Go back</a>") else: total_weight = 0 items = OrderDetail.objects.filter(orderID=current_order) template_name = 'store/checkout.html' order_details = [] for item in items: weight = item.supplyID.weight * item.quantity order_details.append((item, weight)) total_weight +=weight return render(request, template_name, {'order_details': order_details, 'current_order': current_order,'Total_Weight': total_weight}) Template <h1>Your current order</h1> <a href="{% url 'store:browse' %}">return to selecting supplies</a> <br><br> <table> <tr><th>name</th><th>item weight(kg)</th><th>qty</th><th>total weight(kg)</th></tr> {% for order_detail, weight in order_details %} <tr> <td>{{ order_detail.supplyID.name }}</td> <td>{{ order_detail.supplyID.weight }}</td> <td>{{ order_detail.quantity }}</td> <td>{{ weight }}</td> </tr> {% endfor %} </table> <p>The total weight of your order is: … -
How to Mock Django model objects.all query_set in a unittest without accessing the database?
I have the following function: def build_dict(): app_config = {} for keypair in models.Applify.objects.all(): app_config.update({keypair.key: keypair.value}) return app_config What I am trying to do is have a test file where I am faking the Applify queryset. So far what I have that is not working is this: test_mock_list = [ mock.Mock(id=1, key='something_1', value=False), mock.Mock(id=2, key='something_2', value=False) ] with mock.patch('models.Applify.objects.all', return_value=test_mock_list): # perform assertion test. What I am getting is an error saying. Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. I am not trying to actually connect to the database, so I don't want to use the @pytest.mark.django_db decorator. So how can I fake the queryset successfully? -
Are Django settings shared across uwsgi workers?
I have a Django app, with a setting (in my settings.py file) that's populated dynamically in my App Config's ready() function. Ie in settings.py I have: POPULATE_THIS = None and then in apps.py in ready I have: def ready(self): if POPULATE_THIS is None: POPULATE_THIS = ... some code which instantiates an object I need that's effectively a singleton ... This seems to work ok. But I'm now at the point where rather than just running the dev server locally (ie python manage.py runserver), I'm now running the Django app through uwsgi (proxied behind nginx), and uwsgi is configured to run 10 worker processes (ie my uwsgi ini file has processes = 10 and threads = 1). I'm seeing evidence that even though there are 10 uwsgi processes , ready() is still called exactly once on app startup and the value of POPULATE_THIS is the same across all workers (doing a str on it is giving the same memory address). My question: How is that value shared across the uwsgi processes, as I thought separate processes are distinct and do not share any memory? And am I correct in assuming that ready() is going to be called once per app startup … -
Getting a "django.db.utils.DataError: value too long for type character varying(20)" error while migrating in django
Everything works fine when i try to migrate on my local server but when i try to migrate on heroku it give me this DataError. Here's the traceback. Also i'm a beginner in django so i'm unable to understand this error. Operations to perform: Apply all migrations: admin, auth, contenttypes, mrpash, sessions Running migrations: Applying mrpash.0002_auto_20181108_1931...Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site- packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.DataError: value too long for type character varying(20) The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 381, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 353, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 203, in handle fake_initial=fake_initial, File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration state = migration.apply(state, schema_editor) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 124, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 84, in … -
How to use SplitDateTimeWidget?
I'm trying to figure out how to use and render Django's SplitDateTimeWidget. If I have a DateTimeField named some_timestamp in my model then how do I render it in two different places in the template and then combine those two fields together during Form submission? Django documentation provides absolutely no help apart from saying that this thing actually exists. -
what is {% block content %} and {% endblock content %} for in Django?
so I just started reading a book on Django (for beginners) and I came across the following code snipet: <header> <a href="{% url 'home' %}">Home</a> | <a href="{% url 'about' %}">About</a> </header> {% block content %} {% endblock content %} Could anyone possibly explain to me what is the use of {% block content %} and {% endblock content %}? Thank you very much in advance!