Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
MultipleObjectsReturned at /cart/ in Django
i'm a beginner and i am getting this error "Exception Value: get() returned more than one Order -- it returned 2!" views.py def cart(request): customer=request.user.customer order,created=Order.objects.get_or_create(customer=customer,complete=False) items=order.orderitem_set.all() context={ 'items':items } return render(request, 'catalog/cart.html',context) models.py class Order(models.Model): customer=models.ForeignKey(Customer,on_delete=models.SET_NULL, blank=True, null=True) date_orderd=models.DateTimeField(auto_now_add=True) complete=models.BooleanField(default=False, null=True, blank=False) transaction_id=models.CharField(max_length=200, null=True) def __str__(self): return str(self.id) class OrderItem(models.Model): product=models.ForeignKey(Product, on_delete=models.SET_NULL, null=True) order=models.ForeignKey(Order, on_delete=models.SET_NULL, null=True) quantity=models.IntegerField(default=0, null=True, blank=True) date_added=models.DateTimeField(auto_now_add=True) thanks. -
How to convert k8s resources into django models in real time?
How to convert K8S resources into Django models in real time and retain the mapping relationship between K8S resources, such as a cluster with multiple workloads. The K8S resource data I obtained through API is json data, which I converted into list data. I did not find a way to convert the list to Django's Queryset in real time, and it can also support ORM operations. I found a link to discuss how to convert list data into Django's QuerySet, but the solution can't solve my problem.I need help. -
I am getting object has no attribute update in my Django Website
I have a crud application and would like to update the items. I have checked some solutions online which explains that the .update method can't be used like this but for only a queryset. I don't know how to update the information manually. Thanks views.py def UpdateReservation(request, pk): table_exists = Reservation.objects.get(id=pk) form = ReservationForm(instance=table_exists) if request.method == "POST": if request.POST['table']: request.POST = request.POST.copy() table_exists = Reservation.objects.get(id=pk) try: if table_exists: time = form['time'] people = form['people'] comment = form['comment'] date_reserved = form['date_reserved'] email = form['email'] phone = form['phone'] first_name = form['first_name'] resrv = table_exists.update(email=email, first_name=first_name, people=people, time=time, date_reserved=date_reserved, comment=comment, table=table_exists) resrv.save() messages.success(request, "you have successfully edited.") return redirect(request.path) else: messages.error(request, "Unable to edit.") return redirect(request.path) except Exception as e: messages.error(request, "Unknown error" + str(e)) return redirect(request.path) context = {"form":form} return render(request, "dashboard/super/admin/update_reserve.html", context) After trying that, it returns the error, Unknown error'Reservation' object has no attribute 'update' -
Passing object from View.py to Template.html with Django
I am building my first application with Django, and I would like to add model object to a template. in the views.py I have : @login_required(login_url="/login/") def index(request): return render(request, "index.html") @login_required(login_url="/login/") def pages(request): context = {} # All resource paths end in .html. # Pick out the html file name from the url. And load that template. try: load_template = request.path.split('/')[-1] html_template = loader.get_template( load_template ) return HttpResponse(html_template.render(context, request)) except template.TemplateDoesNotExist: html_template = loader.get_template( 'error-404.html' ) return HttpResponse(html_template.render(context, request)) except: html_template = loader.get_template( 'error-500.html' ) return HttpResponse(html_template.render(context, request)) def restricted_list(request): restrictednames = Restrictednames.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, '/restricted_list.html', {'restrictednames': restrictednames}) the object i am looking to pass through is restrictednames. in the template I have : <body> {{ restrictednames }} </body> But nothing shows up. The page http://127.0.0.1:8000/restricted_list.html does not seem to be loading using def restricted_list(request) function. I am sure this is fairly simple, but not familiar with the Django structure yet. Does anyone sees what I am not doing right please ? -
How can I use a JSON file such as a database to store new and old objects?
I get the JSON objects from one of the sites and I want to attach these objects into a JSON file. the task is: I want to use JSON file as a database to save all information from the site I get objects from it so, the data I will show it breaking into 2 data which titled by the date like so: first: will be new data that will appear in the news.html second: will be old data that will appear in the old.html the problems that I'm facing are, which file handling I have to use (r, a, w)? of course, will not be r because I want data to be written when new data comes from the request so, in this case, I should use (a or, w), but if I used w will override all data that exists in JSON file. and if I used a I will face 3 challenges in every request process I do: the main curly braces will repeat with new data that appended to File but I need to repeat data into the main curlies itself. curly braces will not be separated by a comma. in every request process that occurs … -
update a Model field in DetailView
As a newbie in Django, I'm sure there is something obvious I'm not seeing. I have a user model with a one to one relationship to a userprofile model, where I'm storing the profile photo. I mixed DetailView and Formview because I want the user to go to his details page and update just the photo, but somehow its not working for me. I know I could do the job with UpdateView, but for didactic purposes, can anyone tell me why this is not working? I'm trying to updated the model fields in the form_valid method but this is not working, they just remain with the old values. I thought at the beginning it was the photo that could not be updated because of some errors on my side, but I've tried also updating other string fields and it doesnt work. Here the code: (the commented out fields are the places where I tried updating several model fields using get_object_or_404 and other functions) class UserDetail(FormMixin, DetailView): template_name = "users/user_detail.html" model = User form_class = forms.UserPhotoForm def get_success_url(self): return reverse('users:user_detail', args=[str(self.get_object().pk)]) def get_context_data(self, **kwargs): user = self.get_object() form = forms.UserPhotoForm(instance=user) context = super().get_context_data(**kwargs) context['user_rating'] = CotizacionReview.objects.filter(cotizacion__user=self.get_object()).aggregate(Avg('nota')) context['form'] = form return context … -
Can't obtain token with graphql_jwt even with valid login credentials
I am using Django 3.1.4 alongside the most recent version of this library and trying to obtain a token but I keep getting: { "errors": [ { "message": "Please enter valid credentials", "locations": [ { "line": 2, "column": 3 } ], "path": [ "tokenAuth" ] } ], "data": { "tokenAuth": null } } I have done everything right but this keeps happening. I am using a custom user model and I have created my own authentication backend as mentioned in #46. If I try logging in with an email, it throws that error, but if I use a username, it works fine. Anyone experiencing something similar? Here's my setup: ... # settings.py AUTHENTICATION_BACKENDS = [ "graphql_jwt.backends.JSONWebTokenBackend", "django.contrib.auth.backends.ModelBackend", "apps.auth.EmailBackend", ] GRAPHENE = { "SCHEMA": "cnapi.schema.schema", "SCHEMA_INDENT": 4, "MIDDLEWARE": ["graphql_jwt.middleware.JSONWebTokenMiddleware"], } GRAPHQL_JWT = { "JWT_VERIFY_EXPIRATION": True, "JWT_EXPIRATION_DELTA": timedelta(days=30), "JWT_PAYLOAD_HANDLER": "apps.accounts.auth.jwt_payload", "JWT_PAYLOAD_GET_USERNAME_HANDLER": ( lambda payload: payload.get("email") or payload.get("mobile") ), "JWT_GET_USER_BY_NATURAL_KEY_HANDLER": "apps.auth.get_user_by_natural_key", } # backends.py class EmailBackend(BaseBackend): def authenticate(self, request, username=None, password=None, **kwargs): if username is not None: try: user = get_user_model().objects.get(email__iexact=username) except ObjectDoesNotExist: """Not found, try another backend""" else: if user.check_password(password) and user.is_active: return user return None def get_user_by_natural_key(username): try: return get_user_model().objects.get(email__iexact=username) except ObjectDoesNotExist: return None def jwt_payload(user, context=None): payload = { "mobile": … -
How to deal with Django translations / .po-files?
We have lot of problem in a project I'm working on now, regarding the texts. What we have now is a generated -po-file (committed in git) and one of the administrators of the site changes this file on github and then goes for the entire deploy process. Obviously, this is not ideal, very time consuming and error prone. Ideally you don't want to risk crashing the entire site from just changing one word on the site. I haven't found any good way of dealing with django translations from searching myself. Do you have any suggestions how to deal with this? https://phrase.com/ looks interesting, but isn't free. This looks interesting too, but means that we have to change quite a bit of code: https://github.com/dreipol/django-translator I'm thinking of writing something on my own that reads the po-file into the db and use those texts when compiling. But it feels like I would be reinventing a few wheels if I did that. Also, this would have to restart the server which feels a bit iffy. How do you deal with these translation issues? EDIT: All texts are generated using either the trans-template tag or ugettext -
Wagtail Contact Form but with a Template
So I have seen the tuorials and they are suggesting I make a Contact page so it is creatable within the admin section of WagtailAdmin but I don't want that. I already have a pre created contact Template page and I don't want to use the Wagtail way to auto generate form elements. Is there a way in which I can use my custom HTML template instead of having an auto generated one that I have to create within WagtailAdmin? I just want to be able to recive the input via a View and then process the data, is there a way in which I can accomplish this? Thanks. -
Django: Download .xls file
I have a button which downloads a excel file with extension .xls. I am using module xlrd to parse the file and return it back to the user. However it appears to add the object name into the excel file instead of the data. How can I return the file to the user with the data rather than the objects name? View def download_file(self, testname): import csv, socket, os, xlrd extension = '.xls' path = r"C:\tests\{}_Report{}".format(testname, extension) try: f = xlrd.open_workbook(path) response = HttpResponse(f, content_type='application/ms-excel') response['Content-Disposition'] = 'attachment; filename={}_Report{}'.format(testname, extension) return response except Exception as Error: return HttpResponse(Error) return redirect('emissions_dashboard:overview_view_record') Excel result Download successful: Content: Note: I understand this is an old file format but is required for this particular project. -
Django: checkbox values not printing to new template
I am working on a Django project that serves as a grocery store. I am trying to set it up so that when people click on checkboxes and press the confirm purchase button, then the values from the checkboxes will print to a new HTML template. The problem I am having is that when I go to the new template it doesn't print the values from the checkboxes. Views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html context_object_name = 'posts' def inventory(request): products = request.POST.getlist('products') for product in products: a = Post.objects.get(title=product) a.quantity = a.quantity -1 a.save() print(products) return render(request, 'blog/confirm.html') Home.html {% extends "blog/base.html" %} {% block content %} <form action="{% url 'inventory' %}" method="POST" id="menuForm"> {% for post in posts %} {% if post.quantity > 0 %} <article class="media content-section"> <div class="media-body"> <div class="article-metadata"> <a class="mr-2">{{ post.category }}</a> </div> <h2><a class="article-title" >{{ post.title }}</a></h2> <p class="article-content"> Price: ${{ post.Price }}</p> <p class="article-content"> Sale: ${{ post.Sale }}</p> <input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }} </input> </div> </article> {% else %} {% endif %} {% endfor %} <button type="submit" form="menuForm">Confirm Purchase</button> </form> {% endblock content %} confirm.html {% extends … -
Post input of choicefield into django models
I am building a basic form through which data can be entered into django model database. Everything works fine except the choicefield which does not post value to the database.I want the user to select from 'Morning' and 'Evening' (default value should be blank) which can then be posted to 'time' model. Following is my models.py: date = models.DateTimeField(auto_now_add=True, null=True) time = models.CharField(max_length=200, null=True, blank=True) cow1 = models.FloatField(null=True, blank=True) cow2 = models.FloatField(null=True, blank=True) cow3 = models.FloatField(null=True, blank=True) cow4 = models.FloatField(null=True, blank=True) Views.py: def home(request): if request.method=="POST": cow1 = request.POST.get("cow1", False) cow2 = request.POST.get("cow2", False) cow3 = request.POST.get("cow3", False) cow4 = request.POST.get("cow4", False) time = request.POST.get("time", False) ins = models.cow(cow1=cow1, cow2=cow2, cow3=cow3, cow4=cow4, time=time) ins.save() return render(request, 'dataentry/home.html') And home.html: <form action = "" method = "POST"> {% csrf_token %} <label for="cow1">cow1</label> <input id="cow1" type="number" name="cow1"> <label for="cow2">cow2</label> <input id="cow2" type="number" name="cow2"> <label for="cow3">cow3</label> <input id="cow3" type="number" name="cow3"> <label for="cow4">cow4</label> <input id="cow4" type="number" name="cow4"> <label for="time">Time</label> <select form="time" name="time" id="time"> <option value="time">Morning</option> <option value="time">Evening</option> </select> <input type="submit" value="OK"> </form> Little help will be appreciated. THANKS! -
Programming the MIT Beergame in Django
I am at the moment trying to setup the MIT Beergame with a combination of Django + Channels + A-Frame for my professor. I have some experience of writing websites in Django but I've never programmed something on a comparable complexity scale as the Beergame in Django and I'm not sure how to structure everything correctly. In the game orders have to be passed from player to player in a turn-based manner with some delay and the overall costs of inventory and backorders have to be calculated every round. So I'm asking myself now: Which logic has to be in the model layer? Can I do all the calculations there? Should I rather put everything in the front-end and read it out and send it to the database with JS? How do I automatically setup a new channels instance if there are enough players in the lobby? How can I combine everything with channels to optimize usability and performance? This is how I structured the model layer so far (more a less a draft): import json import random import string from collections import defaultdict from django.core.serializers.json import DjangoJSONEncoder from django.db import models from tum_vr.users.models import User # TODO: Decide where … -
How to pause and continue a function in python
I am very new to python, i have a function where am uploading a csv file and saving it in my db, it's working, but what i want to do now is that suppose the csv file am uploading has 500 rows, so when i upload it instead of saving the file with 500 rows it should take 100 rows from that file save it and then move to another 100 save it as another file and so on till the whole file is completed. Here is my code: def bulk_uploads_trial_users_upload(request): if is_super_admin_authonticated(request) : try: data = json.loads(request.body) super_admin = int(request.session.get('super_admin_id')) file_name = (BulkUpload.objects.all().count()) + 1 file_ext = data.get('Name').split('.')[-1] current_timestamp = int(datetime.datetime.now().timestamp()) print(data.get('File', None)) Info = BulkUpload.objects.create( upload_type = 1, file_path = save_document(data.get('File', None), 'csv_upload', file_name, file_ext), upload_timestamp = current_timestamp, process_status = 1, created_by = super_admin ) Info.file_name = str(file_name) + '.' + file_ext Info.save() return HttpResponse(json.dumps({"status": 1}), content_type='application/json') except Exception as e: print(e) return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=401) else: return HttpResponse(json.dumps({"status": 0}), content_type='application/json', status=403) -
Error in Dockerizing Django with Postgres and Pgadmin
docker- compose.yml version: "3.3" services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres # - POSTGRES_HOST_AUTH_METHOD="trust" - POSTGRES_PORT=5432 ports: - "5432:5432" pgadmin: image: dpage/pgadmin4 depends_on: - db ports: - "5051:80" environment: PGADMIN_DEFAULT_EMAIL: pgadmin4@pgadmin4.com PGADMIN_DEFAULT_PASSWORD: pgadmin4 restart: always web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - "8000:8000" links: - db:db depends_on: - db settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': 'db', 'PORT': 5432, } } Error while executing python3 manage.py makemigrations: django.db.utils.OperationalError: could not translate host name "db" to address: Temporary failure in name resolution I tried adding - POSTGRES_HOST_AUTH_METHOD="trust" however the error remained. I also tried changing 'HOST': 'db' to 'HOST': 'localhost' and then I can run the make migrations but I get this error: Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? I saw many similar questions but none of the answers seems to fix the problem. Any suggestions according to my docker-compose and setting? -
Django StatReloader is not watching files in app
I have two apps in my project, products app and users app that I created with command python manage.py createapp and I added the two apps to the INSTALLED_APPS in settings.py every model in both apps is registered in admin.py and tested in the shell and the admin page. My problem is that everything except the models.py file in the products app is not "being watched" or something like that, I tried to use signals.py in the products app but didn't work, I used the same code in the users app and it worked (I edited the import lines). Also when I tried to make a class-based view in the users app extend a fictional class running python manage.py runserver gives an error but doing the same thing in the products app will run the program successfully. Does anyone know how can I solve this? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'products', 'crispy_forms', ] -
How to add data from one model to other django?
I am using generics to represent views class PersonRetrieveView(generics.ListAPIView): queryset = Person.objects.all() serializer_class = PersonSerializer and class CommentRetrieveView(generics.RetrieveAPIView): queryset = Comment.objects.all() serializer_class = CommentSerializer Person data looks like { "id": 2, "user": { "first_name": "Testuser", "last_name": "TestUser1", "id": 2 }, "name": "Test 2", "city": "California", "status": "NotActive", "phone_number": "9876543222", "age": 22, "height": 180 } and Comment { "id": 1, "comment": "test", "person": 2 } Comment linked to Person by id. How can i add data from comment to PersonRetrieveView ? Serializers looks like this class PersonSerializer(serializers.ModelSerializer): user = UserSerializer() # comment = CommentSerializer() class Meta: model = Person fields = '__all__' class CommentSerializer(serializers.ModelSerializer): class Meta: model = Comment fields = '__all__' -
how to pin ssl certificate in andoid and django?
my team and me developing an android app with kotlin, Django, and Django rest framework.. they asking we need SSL pinning to the app side. any changes required in the Django REST API endpoints!. we already using HTTPS on the server-side with let's encrypt.. any additional changes required in server-side API endpoints!. -
botocore.exceptions.ClientError (InvalidAccessKeyId)
I am new to docker and in our dev env, we have S3 access key id and AWS secret access key. We are using the digital ocean spaces to offload our dev env static files. We need to run the collect static command manually to update the media and static files. The whole process was working fine for the last couple of months but I am recently facing this error. After some research, I updated the Acess key id and AWS secret access key but this error remains the same. Can anyone please help me with this issue? enter image description here -
problem when restoring postgresql database for a django application
I am trying to transfer my testing server's database to my working PC. So I do this: (Postgres 12.5) pg_dump -U nutrition -d mednutrition_db --clean -f mednut_bak.sql and then I try to restore it like this on my Postgres 9.5 psql -U chris mednutrition_db < mednut_bak.sql This simple method was working fine for me. But now it seems there is a problem which I cannot solve. I noticed that django creates ID fields using this default value (for example): nextval('django_migrations_id_seq'::regclass) However, when I restore the database, the default value for the ID fields remains empty, and of course I cannot insert any new data to the restored database. How can I resolve this? -
how can i use the numpy in django?
I'm trying to do a process numpy,matplotlib, scipy. but it raise an error that i dont know what is it. my code is: def add_user_order(request): new_order_form = sp_UserNewOrderForm(request.POST or None) if request.method == 'POST': upload_file = request.FILES['document'] if not upload_file.name.endswith('.xlsx'): return redirect('/error1') read = pd.read_excel( upload_file) if new_order_form.is_valid(): order = sp_Order.objects.filter(owner_id=request.user.id).first() if order is None: order = sp_Order.objects.create(owner_id=request.user.id) fs = FileSystemStorage() fs.delete(upload_file.name) name = new_order_form.cleaned_data.get('name') x = read['x'].tolist() y = read['y'].tolist() poly = np.polyfit(x, y, 10) poly_y = np.poly1d(poly)(x) smooth = [round(i, 3) for i in poly_y] poly = np.polyfit(x, y, 10) poly_y = np.poly1d(poly)(x) hull = [round(i, 3) for i in poly_y] for filename in os.listdir('spectrum_order/zip_file'): if filename.endswith(".xlsx") or filename.endswith(".xls"): read = pd.read_excel('spectrum_order/zip_file/' + filename) labels = read['x'].tolist() b = [float(n) for s in labels for n in s.strip().split(' ')] x1 = b[::2] y1 = b[1::2] correlation, p_value = stats.pearsonr(y, y1) if correlation >= 0: plt.plot(x, y) plt.plot(x1, y1) plt.savefig(f'./spectrum_order/image/{filename}.png', dpi=300) return correlation return redirect('/open_sp_order') error is: 'numpy.float64' object has no attribute 'get' when I delete line 29 to 41(for filename...) this code work. please help. -
Which authentication Mechanism to choose to develop web app using Angular + Django rest framework
Can we use the Token/JWT authentication mechanisms to integrate the Django rest framework application with the Angular frontend? Or we need to use session authentication to develop a web app? -
TypeError: ModelBase object got multiple values for keyword argument Django
Got an error - Exception Value: ModelBase object got multiple values for keyword argument voucher. Trying to insert two rows with these two dictionaries. if form.is_valid(): debit_tr ={ 'voucher': newvoucher, 'descirption': 'Purchase Order: '+ self.request.POST.get('purchase_id'), 'debit':self.request.POST.get('total_amount'), 'account':self.request.POST.get('debit_account') } credit_tr ={ 'voucher': newvoucher, 'descirption': 'Purchase Order: '+ self.request.POST.get('purchase_id'), 'credit':self.request.POST.get('paid_amount'), 'account':self.request.POST.get('credit_account') } j = Journal(**debit_tr, **credit_tr) j.save() -
How to change the tz in records stored by the usage of django-auditlog in django admin panel
I am using the django-auditlog library to store audit logs concerning some of my models. I noticed that despite the fact that I have defined the time zone in settings.py all the models containing fields of type DateTimeField are stored in UTC time in my admin panel in Log entries section. Here is my settings.py part concerning time and time zone configurations : USE_L10N = True TIME_ZONE = 'Europe/Athens' USE_TZ = True What to do in order the log audit records to be in timezone defined by me and not in UTC? -
compare html input dates in python
I have two Html date inputs and I want to compare them in my Django views this is my views.py start = request.POST.get('start_date') end = request.POST.get('end_date') d1 = time.strptime(start, "%Y-%m-%d") d2 = time.strptime(end, "%Y-%m-%d") if d1 > d2: return False I have entered 05-05-2020 in start_date and 06-05-2020 in the end_date my javascript function is comparing dates correctly but the python function is returning False in these values I have also tried d1 = datetime.datetime.strptime(start, "%Y-%m-%d") d2 = datetime.datetime.strptime(end, "%Y-%m-%d") but the same issue what am I doing wrong?