Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Error in the pythonanywhere.com deployed content done in Django
I deployed a Text to Speech program in pythonanywhere.com, the code was written in Django. which works fine in my local system. But after deployment it shows an error OSError at /checker libespeak.so.1: cannot open shared object file: No such file or directory You can check the link to the webapp: http://maqboolthoufeeq.pythonanywhere.com i have tried with all packages installed, but nothing works This is the settings.py file import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR,'templates') STATIC_DIR = os.path.join(BASE_DIR,'static') SECRET_KEY = ')hu2$o^tr^()chmvuc3(uom45j1ulbf641((5%2%nb%k^-6t#6' DEBUG = True ALLOWED_HOSTS = ['maqboolthoufeeq.pythonanywhere.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'generator', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'randomgen.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATE_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'randomgen.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True … -
how do I prepare STATICFILES_DIRS well
enter image description hereI want to correct path it doesn't work I use django v:2.1 -
django-oscar translation - how to compile? In a virtualenv?
i set up a new django project with the following parameters: Django: 2.2.3 Python: 3.5.2 django-oscar: 2.0 The project is in virtualenv and at the moment i' m using the default sqlite database and the django testserver if needed. I set up the application based on the official document ( https://django-oscar.readthedocs.io/en/2.0.0/internals/getting_started.html ), and i' d like to use translation for hungarian, which is 0% ready based on transifex ( https://www.transifex.com/codeinthehole/django-oscar/ ) (of course i' d contribute if ready) . I found the translation files in the virtualenv: ~/.virtualenvs/ws/lib/python3.5/site-packages/oscar/locale$ ls -l hu* -R hu: total 4 drwxrwxr-x 2 lenovo lenovo 4096 júl 28 08:15 LC_MESSAGES hu/LC_MESSAGES: total 252 -rw-rw-r-- 1 lenovo lenovo 454 júl 28 08:15 django.mo -rw-rw-r-- 1 lenovo lenovo 250927 júl 28 08:15 django.po hu_HU: total 4 drwxrwxr-x 2 lenovo lenovo 4096 júl 28 13:16 LC_MESSAGES hu_HU/LC_MESSAGES: total 500 -rw-rw-r-- 1 lenovo lenovo 470 júl 28 08:15 django.mo -rw-rw-r-- 1 lenovo lenovo 250951 júl 28 13:16 django.po . I edited the django.po file from the hu_HU directory, but my problem is that i can' t create the related django.mo file with makemessages and compilemessages. I tried to follow this translation tutorial: https://django-oscar.readthedocs.io/en/releases-1.6/topics/translation.html , but it does not seem to … -
Extending AbstractBaseUser not hitting ModelBackend - Django
I'm extending AbstractBaseUser with my custom user model. I can create a superuser via shell successfully with the UserManager() below which is created in the database correctly. For testing, I've created a superuser with the username test & password of test. I can run this test user against the check_password("test", "test") method which returns True as expected, but if I try to login via /admin I get "Password Incorrect" with a 200 status code on the POST. User Model class User(AbstractBaseUser): USERNAME_FIELD = ('username') REQUIRED_FIELDS = ('email', 'password') username = models.CharField(max_length=15, unique=True) twitch_id = models.IntegerField(null=True) avatar = models.URLField(null=True, blank=True) is_live = models.BooleanField(default=False) email = models.EmailField(unique=True) password = models.CharField(max_length=50, default="password") register_date = models.DateTimeField(auto_now=True) twitch_token = models.ForeignKey(TwitchToken, on_delete=models.SET_NULL, null=True) twitter_token = models.ForeignKey(TwitterToken, on_delete=models.SET_NULL, null=True) # attempted giving flags from original User model is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) objects = UserManager() class Meta: db_table = 'users_user' def __str__(self): return self.username """ Properties are redundant with flags above @property def is_admin(self): return self.admin @property def is_active(self): return self.active @property def is_staff(self): return self.staff @property def is_superuser(self): return self.superuser """ UserManager() class UserManager(BaseUserManager): def create_user(self, username, email, password): """ Creates and saves a User with the given email … -
Custom graphene queries not added
I'm using graphene-django for my graphql API. The propblem is that all my custom queries get not picked up by graphene in the schema. I'm doing everything like this tutorial explains. main schema.py import graphene from item.schema import ItemQuery class Query(ItemQuery, graphene.ObjectType): pass schema = graphene.Schema(query=Query) item schema.py import graphene from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from item.models import UserItem, Item, ItemPrice class UserItemType(DjangoObjectType): class Meta: model = UserItem interfaces = (graphene.Node,) class ItemType(DjangoObjectType): class Meta: model = Item interfaces = (graphene.Node,) class ItemPriceType(DjangoObjectType): class Meta: model = ItemPrice filter_fields = ['item_id'] interfaces = (graphene.Node,) class ItemQuery(graphene.ObjectType): def user_item(self, info): user = info.context.user if not user.is_anonymous: try: return UserItem.objects.entry_set() \ .get(id=id, user_id=user.id) except UserItem.DoesNotExist as ex: return None def user_items(self, info): user = info.context.user if not user.is_anonymous: return UserItem.objects.entry_set() \ .filter(user_id=user.id) \ .all() item_prices = DjangoFilterConnectionField(ItemPriceType) The item_prices query gets picked up by graphene but user_item and user_items not. I'm doing nothing different than the tutorial and can't seem to figure out why they don't get picked up. -
Using django how can I send page-refresh without pressing enter in input field
In my app I have an input field in which the user can write a string. When he presses enter it activates a request for editing the database and the new data gets displayed. I want however that this request is being sent every time the user writes a letter into the input field. How can I achieve this? views.py def search_movie(request): # create new object and save it and redirect title = request.POST['content'] print('title') for item in movie_class.objects.all(): if item.title == title or not title: item.show_movie = True else: item.show_movie = False item.save() movieView(request) return HttpResponseRedirect('/movies/') template <form action="/search_movie/" method="post"> {% csrf_token %} <input type = "text" name = "content"/> <button type="submit">Upload text</button> </form> -
How to add element without submitting to another page
I would like to add a topping to my pizza using XMLHttpRequest without submitting to another page but I can't wrap my mind around how to implement it. So far I'm posting to add_topping route and getting a JsonResponse without any problem. But instead of going to the view, I would like to do it with JavaScript. I have already searched for similar problems but or they are all with PHP or with jquery but I would like to implement it using normal JavaScript with XMLHttpResponse. HTML <form id="add_topping" action="{% url 'orders:add_topping' %}" method="post"> {% csrf_token %} <div class="form-row align-items-center"> <div class="form-group col-auto"> <select class="form-control" name="topping_selected" id="topping_selected"> {% for topping in topping_list %} <option value="{{ topping }}">{{ topping }}</option> {% endfor %} </select> </div> <div class="form-group col-auto"> <button class="btn btn-secondary" type="submit">Add topping</button> </div> </div> </form> views.py def add_topping(request): # If request is not a POST request, return index if request.method == 'POST': # Get the data from the POST request topping_selected = request.POST.get('topping_selected') return JsonResponse({"success":True, "topping_added": topping_selected}) # Else return false return JsonResponse({"success":False}) JavaScript // Function to add topping document.querySelector('#add_topping').onsubmit = function() { // Create request object const request = new XMLHttpRequest(); // Variables to determine the size and topping … -
'NoneType' object has no attribute '__dict__' when overriding form_valid()
I'm trying to override the form_valid function of a CreateView so it sends an email to the user when the form is saved. It saves the element in the database and correctly sends the email, but afterwards it shows the 'NoneType' object has no attribute 'dict' error when trying to redirect. I tried overriding the get_success_url method but it didn't send the message I need to send to the template after it's done. I also tried changing the return redirect(self.get_success_url()) to return redirect(success_url) and the same happens, it redirects with no error but the template misses the message. ###views.py class createpetition(SuccessMessageMixin, CreateView): model = PQS form_class = CrearPeticion template_name = "peticion/createpetition.html" success_url = reverse_lazy('createpetition') success_message = "e" def form_valid(self, form): peticion = form.save() usuario = peticion.nombreUsuario usuario.enviarCorreo('Artemis - Nueva petición registrada con éxito','¡Gracias por comunicarte con nosotros!\n\nTu mensaje:\n\n' + peticion.descripcion) return redirect(self.get_success_url()) ###user models.py def enviarCorreo(self, asunto, mensaje): contenido = render_to_string('correo_base.html',{'mensaje':mensaje}) send_mail(asunto,contenido,'admin@artemis.com',[self.correo])``` -
How to apply delay for a single user in django without disturbing the whole server?
I am building a django website and for certain reasons I have to send an email to user containing a link consisting of a token, although the token is always unique and is of 100 alphanumeric characters yet I want to delay the loading time of the user if link with wrong token is used. The function related to this in my views.py is something like this- import time def my_function(request,token): if User.objects.filter(uid=token): return HttpResponse("Yes") else: time.sleep(5) return HttpResponse("No") But the problem here is that the sleep function not only affects the current user but instead the whole server. Is there any possible way to add this delay in backend or in frontend? If not then is there any other way to punish for entering url with wrong token? -
Django Rest Framework - Latest child per instance
Using Django Rest Framework, I'm building a web application that saves information on Products and its Prices. A Product can have multiple Prices over time. My models look like this: class Product(models.Model): name = models.CharField(max_length=100) class Price(models.Model): product = models.ForeignKey(Product, related_name='prices', on_delete=models.CASCADE) price = models.DecimalField(max_digits=6, decimal_places=2, default=0) date = models.DateField(default=datetime.date.today) I've set up the following serializers: class PriceSerializer(serializers.ModelSerializer): class Meta: model = Price fields = ('price', 'date') class ProductSerializer(serializers.ModelSerializer): prices = PriceSerializer(many=True, read_only=True) class Meta: model = Product fields = ('name', 'prices') Now, I want to create an APIView that shows all products with their latest price. Like so: [ { "name": "Product A", "price_latest": 1.00 }, { "name": "Product B", "price_latest": 2.00 } ] Does anyone have any idea on how to achieve this? -
Sub-classing the user model from models.Model directly instead of using custom user models
Everywhere, everyone seems to be using "custom user model" derived from either AbstractUser or AbstractBaseUser class. Why nobody directly sub-classes the user model from models.Model? Won't that be much easier and simpler? What additional functionality does using these custom user models provide? -
Celery can't connect to aws RDS and instead using 127.0.0.1
I have a django app running on Elastic beanstalk with celery and redis. The celery task that is failing is to process a photo and save some results in the database (which is a postgres RDS) and it's failing because it's trying to connect to the database on localhost:5432. I have a debug task which doesn't interact with the database and I can see that it is received and executed. My settings file has the following ALLOWED_HOSTS = [ "localhost", "127.0.0.1", ".elasticbeanstalk.com", ] if 'RDS_DB_NAME' in os.environ: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': os.environ['RDS_DB_NAME'], 'USER': os.environ['RDS_USERNAME'], 'PASSWORD': os.environ['RDS_PASSWORD'], 'HOST': os.environ['RDS_HOSTNAME'], 'PORT': os.environ['RDS_PORT'], } } else: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'woodpecker', 'USER': os.environ.get("DB_USER"), 'PASSWORD': os.environ.get("DB_PASS"), 'HOST': 'localhost', 'PORT': '', } } CELERY_BROKER_URL = 'redis://localhost' celery config file from __future__ import absolute_import import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') # DON'T FORGET TO CHANGE THIS ACCORDINGLY # os.environ.setdefault('FORKED_BY_MULTIPROCESSING', '1') app = Celery('myapp') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) I'm still having a problem running celery with supervisord so for now I do the following to start celery after logging to the ec2 instance source /opt/python/run/venv/bin/activate cd /opt/python/current/app/ celery worker -A myapp --loglevel=DEBUG a … -
TypeError in Diffie Hellman using Django and JQuery
I'm trying to develop Diffie Hellman using Django and JQuery, not a full-fledged website, but just to practice and demonstrate Diffie Hellman. Here is my HTML/Javascript code. function getRandomInt(max) { return Math.floor(Math.random() * Math.floor(max)); } var BigInt1 = window.bigInt; var x = BigInt1(getRandomInt(17)); var prime = BigInt1('{{ prime_num }}'); var base = BigInt1('{{ base_num }}'); console.log("Prime:" + prime.value + "\n", "Base: " + base.value + "\n", "Private Key:+" + x + "\n") // Diffie Hellman $(function(event) { var level1KeySelf = base.modPow(x, prime); console.log("Level1 " + level1KeySelf.value); var key; $.ajax({ type: 'GET', url: "{% url 'Shenzen:diffiehellman' %}", data: { step: 'calcval', level1: level1KeySelf }, success: function(data, status, xhr) { var level1KeyOther = BigInt1(data['firstkey']); key = level1KeyOther.modPow(x, prime); $("#keyid").attr("keyval", key); }, error: function(xhr, status, e) { console.log("error"); }, async: true, datatype: 'json' }); }) <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="keydiv" id="keyid" keyval="" hidden></div> Here is my Django View: def diffiehellman(request): bytes_y = os.urandom(32) y = int.from_bytes(bytes_y,'little') if request.method == 'GET': step = request.GET['step'] if step == 'calcval': level1KeySelf = pow(base_num,y,prime) level1KeyOther = request.GET['level1'] key = pow(level1KeyOther,y,prime) return JsonResponse({'firstkey':level1keySelf}) elif step == 'success': return JsonResponse({'success':'success'}) return HttpResponse('') else: return HttpResponse('failed! require a GET request.') I get the following TypeError in Firefox signin is a view … -
Django: TypeError Missing 1 required positional argument
So I am working on my first python project using django. It's a simple first project that shows methods of POST, GET, PUT, and DELETE. I've gotten the methods of POST and PUT down. But PUT is not working out the way I thought it would work. So I have a database of information with simple info like first name, last name, and a e-mail. I have two functions in my views with one that renders a page of the database of information and one that links to a page that "updates/edits" that one specific instance of info. So here is my model: class Information(models.Model): """Placeholder code that the viewer will be seeing.""" info_id = models.AutoField(primary_key=True,unique=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) e_mail = models.CharField(max_length=200) date_added = models.DateTimeField(auto_now_add=True) def __str__(self): """Return information.""" return f"Info ID: {self.info_id}, First Name: {self.first_name}, Last Name: {self.last_name}, E-mail: {self.e_mail}" Here is my urls: # Page(s) that shows the viewer an example of PUT. path('PUTData/', views.put_data, name='put_data'), # Page that shows all info. path('PUT/', views.put, name='put'), Here is my views with the two functions: def put_data(request): put_data = Information.objects.order_by('date_added') context = {'put_data': put_data} return render(request, 'just_projects/put_data.html', context) def put(request, info_id): info = Information.objects.get(id=info_id) if request.method != … -
What is the significance of numbers written in django server along with GET?
I am building a django website and i noticed that within my server there often occur several lines like - [28/Jul/2019 22:52:24] "GET /media/images/product_images/Q0jsuTaUwKhgOhhO.jpg HTTP/1.1" 200 2981629 In lines like these what does the number 200 and 2981629 signify? Also, does printing of these lines in my command line slow my server? -
How to get the path to a FieldField considering the upload_to() function
I am making an app with Django and I am working with an ImageField. I have this function as the upload_to argument: def group_directory_path(instance, filename): # file will be uploaded to MEDIA_ROOT/group_<id>/time/<filename> return 'Groups/group_{0}/{1}/{2}'.format(instance.id, get_time(), filename) However, I want to resize the group image, so I need to access the group.photo ImageField FieldFile. My problem is that when try to get the FieldFile path with group.photo.path, I get /media/429760_490645240984035_288529563_n.JPG but I there is no file in this directory, because the file is in /media/Groups/group_2/2-3-2019-23-54/429760_490645240984035_288529563_n.JPG instead. How do I get the right file path? -
I make tags to articles, but they do not appear on the page
I have a function that processes the request by tags and sorts articles with similar tags and displays them in a template. But for some reason, they simply do not appear on the page. I fill them in the model using TaggableManager PS tags should appear on the article and when I click on them, the request should be processed and execute the post _search function and sent to the page with articles with similar tags. models.py class Articles(models.Model): title = models.CharField(max_length= 200) post = models.TextField() date = models.DateTimeField() img = models.ImageField(upload_to='', default="default_value") tags = TaggableManager() article_like = models.IntegerField(default='0') article_dislike = models.IntegerField(default='0') view = models.IntegerField(default='0') datesArticle = models.DateTimeField(auto_now=True) class Meta: ordering = ['-datesArticle'] def __str__(self): return self.title views.py def ArticleDetailView(request, pk): Articles.objects.filter(pk=pk).update(view=F('view') + 1) Articles.objects.all() article_details = Articles.objects.filter(pk=pk).first() if request.method == 'POST': comment_form = Comments(request.POST) comment_form.save() else: comment_form = Comments() commentss = CommentModel.objects.all() return render(request, 'news/post.html', {'article_details': article_details, 'comment_form': comment_form, 'comments': commentss, }) def tags_list(request, tag_slug=None): object_list = Articles.objects.all() tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) object_list = object_list.filter(tags__in=[tag]) paginator = Paginator(object_list, 3) # 3 posts in each page page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first … -
how to add two class as ForeignKey at a time in one fiield in django?
In models: team_player = models.ManyToManyField(FirstTeamPlayer and SecondTeamPlayer, blank=True, related_name="team_player_set") why don't it possible?? I only get SecondTeamPlayer this queryset data. how can i get these two class in here?? -
How correct initialize a class instance using kwargs
I try to initialize a class with ihertitance structure. I already read a lot of questions here, but still can't figure out how should I do this. My model: class BaseCrudEntity(models.Model): pass class Meta: abstract = True class Person(BaseCrudEntity): Name = models.CharField(max_length = 255) def __init__(self, *args, **kwargs): if args: self.Name = args super().__init__(self, *args) pass And here I call it: p = Person("Test2") p.save() As a result I have an error: int() argument must be a string, a bytes-like object or a number, not 'Person' Here my traceback: http://dpaste.com/2BJFF38 How should I initialize class instance? Why in shell I see None: >>> from person.models.person import * >>> p = Person('Tttt') >>> p <Person: Tttt None> What am I doing wrong? -
static Invalid block tag inside template file
I'm having the invalid block tag issue while trying to reference the styles.css file from my app file structure, even having configured everything as the django documentation (and several other answers here in stack overflow) . I'm using django 2.2.3 in a python3.6 venv along with pureCSS lib. Here's an overview of my project's files and configuration regarding the templates and the static dir/files: 1- settings.py INSTALLED_APPS and STATIC_URL definition: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'pyonlinecourses.core', ] ... STATIC_URL = '/static/' 2- settings.py TEMPLATES definitions: TEMPLATES_DIR = os.path.join(BASE_DIR, "pyonlinecourses/core/templates/") TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [TEMPLATES_DIR], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.core.context_processors.static', ], }, }, ] 3- Django project directory structure: - pyonlinecourses - core - migrations - static - css - templates - home **(issue located in this file)** 5- static tag definition and reference in html file <!doctype html> {& load static &} <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="PyOnline Courses - Simple distance education virtual learning environment" /> <title>PyOnline MOOC</title> <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.3.0/pure-min.css"> <link rel="stylesheet" href="{% static 'css/styles.css' %}" /> </head> I'm at a loss trying to identify the source of the … -
How can I nest a serializer before it is being defined?
I have these serializers class OrderItemSerializer(serializers.ModelSerializer): product = ProductSerializer(read_only=True) order = ??????????????? class Meta: model = OrderItem exclude = ['id'] class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True, read_only=True) url = serializers.HyperlinkedIdentityField( lookup_field='slug', view_name='api:order-detail') class Meta: model = Order fields = '__all__' I need to use OrderSerializer inside the OrderItemSerializer but if I do so it doesn't work because of the OrderSerializer did not get defined yet. right now I get this result when I query for the Order item. { "price": "334.00", "quantity": 1, "order": 1 } and the wanted behavior is to get the serialized order object instead of the primary key but without losing the order_items inside of the OrderSerializer -
merge/remove elements from a ManyToMany relationship (using through table) when saving model
I'm developping an app to manage commands for a restaurant. as the commands can evolve through the diner, for more clarity, I want to merge the command's lines that contain the same product. For instance, if you command 2 buckets of chicken, then later another one, I want the final Command model instance to contain only one line (bucket of chicken, 3) instead of two. I have a function (fusion_atoms) which detects similar lines and merge them. I tried to call it in the save method of Command model, and also during pre_save and post_save signals. It doesn't work. I'm quite a noob in python and django, and I think I'm not doing this the right way. models.py: class Command_Atom(models.Model): command = models.ForeignKey("Command", on_delete=models.CASCADE) produit = models.ForeignKey(Produit, on_delete=models.CASCADE) quantite = models.PositiveSmallIntegerField(default=1) @property def total(self): return self.produit.prix * self.quantite class Command (models.Model): client = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) table = models.PositiveSmallIntegerField(default=0) produits = models.ManyToManyField(Produit, through="Command_Atom") @property def atoms(self): return Command_Atom.objects.filter(command_id=self.id) def fusion_atoms(self): lines = self.atoms.all().order_by('produit','prod_options') i = 1 current_line = lines[0] to_be_deleted = [] while i < len(lines): if current_line.produit == lines[i].produit: print('merge') current_line.quantite += lines[i].quantite current_line.save() to_be_deleted.append(lines[i]) else: current_line = lines[i] i += 1 for l in to_be_deleted: l.delete() def save(self): … -
TypeError at /api/register/ argument should be a bytes-like object or ASCII string, not 'InMemoryUploadedFile'
I am trying to upload an image in my project and I am trying a solution for it. I have made some changes in the views.py but I am continuously getting the above error. What is wrong in my code? Please help as I am new to rest. class UserCreate(generics.ListCreateAPIView): serializer_class = UserProfileSerializer queryset = UserProfile.objects.all() parser_classes = (FormParser,MultiPartParser) def post(self, request): print(request.data) serializer= UserProfileSerializer(data=request.data) if serializer.is_valid(): imgstr64=serializer.validated_data['avatar'] imgdata = base64.b64decode(imgstr64) fname = '/tmp/%s.jpg'%(str(Userprofile.id)) with open(fname,'wb') as f: f.write(imgdata) imgname = '%s.jpg'%(str(Userprofile.id)) UserProfile.avatar.save(imgname,File(open(fname,'r'))) os.remove(fname) serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Cannot reset migrations in Django project?
What I did: Delete db.sqlite3 file. Delete all files in migrations folder (including init file) Then command in cmd: python manage.py makemigrations No changes detected python manage.py migrate Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying admin.0003_logentry_add_action_flag_choices... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying auth.0009_alter_user_last_name_max_length... OK Applying auth.0010_alter_group_name_max_length... OK Applying auth.0011_update_proxy_permissions... OK Applying sessions.0001_initial... OK But migrations folder is still empty. I have some models in models.py, also tried to add new row to some of them, but result was the same. What I'm doing wrong? -
Using regrouped variable of django template in javascript
From my view function, I have sent some data to django template. In the template, data are grouped using regroup method. {% regroup data|dictsort:"month" by month as data_month_list %} Is there any way to use the data_month_list in javascript?