Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Django Models
I have been working on Django. But it’s quite new to me can you guys please help me actually I am trying to create a backend work using Django which has 2 models but how do I create I am not able to understand and add it to the admin page. The image shows 2 models 1st model stores the basics over the layout of jobs and while clicking on them it is transferred to the 2nd model which stores detail of that info. Please help me with it code guys. enter image description here -
load csv into sqlite3 db (django)
I am trying to load the csv files I upload to my sqlite3 db. I am able to upload the csv into a folder but it doesn't appear on my db. The db table structure contains as many columns as the csv with the corresponding data types; but the column names in the db table structure are different as in the csv, as some of the columns names in the csv contain spaces and special characters (like accents for example). My goal is to allow the user to upload a csv file that will be loaded to the db. I was also wondering if its possible to increment the db each time a new csv is loaded (for example: I upload a file now which is loaded to the db then the second time I add, the newer details are added to the db without deleting the previous ones). Apologies if I am unclear and asking too many things at once. Here is my model, form, function (handle upload) & views .py files: models.py class UploadForm(models.Model): file = models.FileField() class Meta: db_table = "db_table" forms.py class UploadForm(forms.ModelForm): class Meta: model = UploadForm fields = "__all__" functions.py def handle_uploaded_file(f): with open('vps_app/static/upload/'+f.name, … -
How to access two fields in two separate HTML pages to carry out a JavaScript function in a Django project?
I have two models: class Package(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) treatment=ForeignKey(Treatment, on_delete=CASCADE) patient_type=ForeignKey(PatientType, on_delete=CASCADE) date_of_admission=models.DateField(default=None) max_fractions=models.IntegerField(default=None) total_package=models.DecimalField(max_digits=10, decimal_places=2) class Receivables(models.Model): rt_number=ForeignKey(Patient, on_delete=CASCADE) discount=models.DecimalField(max_digits=9, decimal_places=2, default=None) approved_package=models.DecimalField(max_digits=10, decimal_places=2, default=None) proposed_fractions=models.IntegerField() done_fractions=models.IntegerField() base_value=models.DecimalField(max_digits=10, decimal_places=2) expected_value=models.DecimalField(max_digits=10, decimal_places=2) forms.py: class PackageForm(ModelForm): class Meta: model=Package fields='__all__' widgets={ "patient_type" : forms.Select(attrs={"onblur":"mf();"}), "max_fractions" : forms.NumberInput(attrs={"onfocus":"mf();", "onblur":"tp();"}), "total_package" : forms.NumberInput(attrs={"onfocus":"tp();", "onblur":"onLoad();"}), } class ReceivablesForm(ModelForm): class Meta: model=Receivables fields='__all__' widgets={ "approved_package":forms.NumberInput(attrs={"onfocus":"onLoad();"} ) } views.py: def package_view(request): if request.method=='POST': fm_package=PackageForm(request.POST, prefix='package_form') if fm_package.is_valid(): fm_package.save() fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) else: fm_package=PackageForm(prefix='package_form') return render (request, 'account/package.html', {'form5':fm_package}) def receivables_view(request): if request.method=='POST': fm_receivables=ReceivablesForm(request.POST) if fm_receivables.is_valid(): fm_receivables.save() fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) else: fm_receivables=ReceivablesForm() return render(request, 'account/receivables.html', {'form6':fm_receivables}) templates-package: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Package Form</title> </head> <body> <form action="" method="post" novalidate> {% csrf_token %} {{form5.as_p}} <button onclick="tots()" type="submit">Save</button> </form> <script src="{% static 'account/js/myjs.js' %}"></script> <script src="{% static 'account/js/test.js' %}"></script> </body> </html> Its source page view for total package field: <p><label for="id_package_form-total_package">Total package:</label> <input type="number" name="package_form-total_package" onfocus="tp();" onblur="onLoad();" step="0.01" required id="id_package_form-total_package"></p> <button onclick="tots()" type="submit">Save</button> templates-receivables: <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Receivables</title> </head> <body> <form action="" method="post"> … -
problem with applying migrations in the project
я хочу сделать миграции в своем проекте, прописываю python3 manage.py makemigrations и получаю такую ошибку Traceback (most recent call last): File "/Users/work/Projects/ims/api/manage.py", line 21, in <module> main() File "/Users/work/Projects/ims/api/manage.py", line 17, in main execute_from_command_line(sys.argv) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 224, in create import_module(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'corsheaders' for more details on how I arrived at this error, you can go to my previous question [https://stackoverflow.com/questions/68228238/cant-make-migrations/68228429?noredirect=1#comment120585207_68228429] init.py """A pure Python implementation of import.""" __all__ = ['__import__', 'import_module', 'invalidate_caches', 'reload'] # Bootstrap help ##################################################### # Until bootstrapping is complete, DO NOT import any modules that attempt # to import importlib._bootstrap (directly or indirectly). Since this # partially initialised package would be present in sys.modules, those # modules would get an uninitialised copy of the source version, instead # of a fully initialised version (either the frozen one or the one # initialised … -
empty pdf is my export result of xhtml2pdf library
empty pdf is my export result of xhtml2pdf library while it works properly on my coworkers machine. I'm defiantly sure that code is not the problem (it works on others machine with exact dependencies and I'm purely using the simple xhtml2pdf's doc example) there is no errors I have dual boot windows10 and I have this result on both my operating systems I even think maybe it's bios thing dajngo 3.0.8 python 3.8 xhtml2pdf 0.2.5 -
Using Barba with Django
My Issue After incorporating Barba js animation library into my Django Project, it started to break. My current login will randomly be logged out when I click on a navigation link. This said navigation link is triggering the animation. My script.js function pageTransition() { var tl = gsap.timeline(); tl.to('#main-wrapper', { duration: 0.1, opacity: 1, transformOrigin: "bottom"}) } function contentAnimation() { var tl = gsap.timeline(); tl.from('#content-wrapper', {duration: 0.8, translateY: 50, opacity: 0}) tl.from('#header-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") tl.from('#instructions-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") tl.from('#messages-wrapper', {duration: 0.8, translateY: 50, opacity: 0}, "-=0.6") } function delay(n) { n = n || 2000; return new Promise(done => { setTimeout(() => { done(); }, n); }); } barba.init({ sync: false, transitions: [{ leave(data) { const done = this.async(); pageTransition(); delay(100); done(); }, enter(data) { contentAnimation(); }, once(data) { contentAnimation(); }, }] }) My base.html The nav is redacted but do let me know if you'd like to see the full nav. <body data-barba="wrapper"> <main data-barba="container" role="main" id="main-wrapper" class="container content-wrapper"> <nav> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" data-menu="logout" href="{% url 'logout' %}"> Logout </a> </li> <li class="nav-item"> <a class="nav-link" data-menu="settings" href="{% url 'settings' request.user.userprofile.id %}"> Settings </a> </li> </ul> </nav> … -
Make React pages only visible to authenticated users? (Using Django DRF for backend)
I have my JWT authentication working and I can sign up and log in via my React project, and I want to redirect the authenticated users to the homepage, where the Nav Bar will say 'log out' rather than 'log in' and 'sign up'. In Django, I would just place a {% if user.is_authenticated %} in my template, but I'm not sure how to approach this from React itself. Thanks in advance! -
Django/Docker/Logging: ValueError: Unable to configure handler 'files_debug''
I try to implement logging in my django project (Django/Postgresql/Docker/Celery) but got an error when I deploy my project in linux server (but it work locally) FileNotFoundError: [Errno 2] No such file or directory: '/usr/src/app/logs/debug.log' I've read about a solution in this SO post: Django: Unable to configure handler 'syslog' but fisrt I do not even understand why this solution should works and I do not manage to implement it in my project. I use Docker/docker-compose so I install netcat with Dockerfile and then try to RUN nc -lU /logs/debug.log /logs/info.log but it failed (no such file or directory) Dockerfile # Pull the official base image FROM python:3.8.3-alpine # Set a work directory WORKDIR /usr/src/app # Set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install psycopg2 dependencies RUN apk update && apk add postgresql-dev gcc g++ python3-dev musl-dev netcat-openbsd # create UNIX socket for logs files #RUN nc -lU /logs/debug.log /logs/info.log ... settings.py ... LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'loggers': { 'django': { 'handlers':['files_info','files_debug'], 'propagate': True, 'level':'INFO', }, }, 'handlers': { 'files_info': { 'level': 'INFO', 'class': 'logging.FileHandler', 'filename': './logs/info.log', 'formatter': 'mereva', }, 'files_debug': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': './logs/debug.log', 'formatter': 'mereva', }, }, 'formatters': { … -
I have a confusion between profile model and User object in Django
forms.py class UserForm(UserCreationForm): ## email = forms.EmailField() class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email'] class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ['mobile', 'address', 'image'] models.py class Profile(models.Model): name = models.OneToOneField(User,on_delete=models.CASCADE) mobile = models.IntegerField(null=True) address = models.CharField(max_length=350,null=True) image = models.ImageField(upload_to='profile_pics', default='default.png',null=True) def __str__(self): return str(self.name.username)+' Profile' @receiver(post_save,sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User, dispatch_uid='save_new_user_profile') def save_profile(sender, instance, created, **kwargs): user = instance if created: profile = Profile(user=user) profile.save() views.py @login_required def profile_page(request,name): user = User.objects.filter(username=name) if request.method == 'POST': user_form = UserForm(request.POST) profile_form = ProfileForm(request.POST,request.FILES) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() Profile.objects.create(user=request.user) messages.success(request,'Your profile has been updated successfully!') return redirect('homepage') else: profile_form = ProfileForm() context = { 'user':request.user, 'user_form':user_form, 'profile_form':profile_form, } return render(request,'profile.html',context) Here I have a confusion within the differences in User object and the Profile model that I defined myself. For the fields in Profile that I created is it possible to use together with the UserCreationForm so I do not need to separate two different kinds of forms? Also, could someone help me explain when and how to use the signals in order to create or update the user profile page? Should I provide an instance if … -
Show secret key of django-otp TOTPDevice
I am using django-otp for 2FA on my Django app. In the docs we are given TOTPDevice.config_url, which can be used to generate a QR code or as a link to set up 2FA with Google Auth or similar. How can I get ONLY the secret key from a TOTPDevice object? A workaround would be to get the parameter from the URL, but it sounds odd there is not built-in way to get it? I noticed a TOTPDevice.key which is in hex format, but converting into ascii or utf-8 does not give the correct secret key. -
Django filter when value none or not or certain value
I want to filter my model values. I have three fields. This fields can be null or None or certain value. How to prevent filter error when value null or not: queryset = Info.objects.filter(tag_id=tag.objects.get(pk=tag_id), entryDate__gte=startDate, exitDate__lte=endDate) -
How to pass environment variables to Azure deployment?
I'm trying to get my API to work when deploying to Azure. My problem at the moment is that for some reason my Django app doesn't find the environment variables defined in my be-configmap.yaml -file. It tries to use a .env file (which doesnt exist) when executing python manage.py runserver 0.0.0.0:8000;. Here is my backend-deployment.yaml: apiVersion: apps/v1 kind: Deployment metadata: name: backend spec: replicas: 1 selector: matchLabels: name: backend strategy: {} template: metadata: labels: name: backend spec: containers: - args: - sh - -c - ls; python manage.py makemigrations; python manage.py migrate; python manage.py runserver 0.0.0.0:8000; env: - name: POSTGRES_USER value: xxx - name: POSTGRES_PASSWORD valueFrom: configMapKeyRef: key: DATABASE_PASSWORD name: backendSecrets - name: DATABASE_PASSWORD valueFrom: configMapKeyRef: key: DATABASE_PASSWORD name: backendSecrets image: myappcrwe.azurecr.io/backend:latest imagePullPolicy: Always name: container-backend ports: - containerPort: 8000 restartPolicy: Always serviceAccountName: "" volumes: null status: {} And this is my be-configmap.yaml: apiVersion: v1 kind: ConfigMap metadata: name: backendSecrets data: DEBUG: xxx SECRET_KEY: xxx DATABASE_NAME: xxx DATABASE_USER: xxx DATABASE_PASSWORD: xxx DATABASE_PORT: xxx Could someone look at these if there are some errors why it doesn't fin the variables? -
Nested select_related to get data from various models django ORM
i have 5 models below: class Products: product_name=models.CharField(max_length=300,blank=True) product_price=models.IntegerField(blank=True) class ProductImages(models.Model): image=models.ImageField(upload_to='product_images',null=True,blank=True) image_product=models.ForeignKey(Product,on_delete=models.CASCADE) class ProductModel(models.Model): model_product=models.ForeignKey(Product,null=True,on_delete=models.CASCADE) model_name=models.CharField(max_length=130,blank=True) class Colour(models.Model): colour_name=models.CharField(max_length=20,blank=True) colour_product=models.ForeignKey(Product,on_delete=models.CASCADE) class Sale: name=models.CharField(max_length=30,null=True,blank=True) class ProductSale: saleid=models.ForeignKey(Sale,on_delete=models.CASCADE) product=models.ForeignKey(Product,on_delete=models.CASCADE) I am filtering and getting products present in ProductSale on the basis of sale id prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product') Now i have product ids, but i want additional details also that is product images,colour,Model which is present in ProductImages model,Colour model,ProductModel model.How can i achieve this in most optimize way below is my try but its taking time and not optimized. prod=ProductSale.objects.filter(sale=sale.id).prefetch_related('product') for prod in prod: pm=ProductModel.objects.filter(model_product=prod.product_id).values() pc=Colour.objects.filter(colour_product=prod.product_id).values() images=prod.product.productimages_set.all().order_by('id')[:2].values() sale_product.append({"product_id":prod.product.id,"product_name":prod.product.product_name,"stock":prod.product.product_quantity,"product_price":prod.product.product_price, "sale_price":prod.product.sale_price,"saleprice_startdate":prod.product.saleprice_startdate, "saleprice_enddate":prod.product.saleprice_enddate,"product_category":prod.product.category_name,"product_reviews":review_product,"review_count":len(pr), "product_images":images,'product_colour':pc,'product_model':pm}) How can i optimize the query get the data in a format which i am using in a dictionary, Kindly help badly stuck in this. -
Queryset with annotate Subquery with OuterRef and Sum
I'm trying to return the sum of fields from another model inside a Subquery. My main queryset returns all users of type company. I have to return the total of credits used by taking the data from CreditOrder and Sum the credit_used field My CreditOrder model class CreditOrder(ClusterableModel): credit = ParentalKey( Credit, on_delete=models.CASCADE, related_name="credit_order" ) order = ParentalKey(Order, on_delete=models.CASCADE, related_name="credit_order") credit_used = models.DecimalField( max_digits=12, decimal_places=2, null=True, blank=True ) My queryset def get_queryset(self, request): qs = super().get_queryset(request) qs = qs.filter(user_type='company') credits_used_subquery = Subquery(CreditOrder.objects.filter(credit__font__company__id=OuterRef('id')).order_by() .values('credit_used').annotate(credit_used_sum=Sum('credit_used')) .values('credit_used_sum'), output_field=DecimalField()) qs = qs.annotate( _credits_used_sum=credits_used_subquery ) return qs But this error is returning me: django.db.utils.ProgrammingError: more than one row returned by a subquery used as an expression -
How to implement writing to the Python/Django database on the server side using the methods of the PyDriller library?
Good afternoon. Help me solve the problem. I'm trying to parse the commit data from github. The user enters the URL of the repository in the form on the "index" page, from there the string is read and written to the database. Next, on the server side, using the Pydriller library, I want to implement getting data about comets (the user does not enter them himself). The results page should display the results - the entered URL and the data itself. To get the comet data (not in the django project, but by creating a Platonic file separately and running it), I use the following code: for commit in Repository(url_text).traverse_commits(): commit_url = url_text + '/commit/' + commit.hash print('Hash: {}; ' .format(commit.hash)) if I execute the "commit.hash" method, I will get a string in the output. Now I want to implement this in my project. There is an implemented class and a model, for example models.py: class UrlRepository(models.Model): # full path to the repository url_text = models.CharField('URL адрес репозитория', max_length=255) def __str__(self): return self.url_text class Meta: verbose_name = 'URL адрес' verbose_name_plural = 'Список URL адресов' class Commit(models.Model): commit_hash = models.CharField('Hash', max_length=50, blank=True) forms.py: class UrlRepositoryForm(ModelForm): class Meta: model = UrlRepository fields … -
How do I individually render radio buttons and file field in django?
I need to individually render radio buttons and the filefield in django. How do I do that? models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) title = models.CharField(max_length=300) description = models.TextField(null=True, blank= True) highpriority = models.CharField(max_length=200, blank=True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.title forms.py: PRIORITY_CHOICES= [ ('high', 'High'), ('low', 'Low'), ] class ComplaintForm(ModelForm): highpriority = forms.CharField(label='Priority', widget=forms.RadioSelect(choices=PRIORITY_CHOICES)) class Meta: model = Complaint fields = ['title', 'description'] #'highpriority', 'document'] def clean(self): cleaned_data = super(ComplaintForm, self).clean() title = cleaned_data.get('title') description = cleaned_data.get('description') if not title and not description: raise forms.ValidationError('You have to write something!') return cleaned_data views.py: def NewComplaint(request): user = request.user if request.method == 'POST': form = ComplaintForm(request.POST) print(form) if form.is_valid(): print("hello") cmp_obj = form.save(commit=False) cmp_obj.user = user cmp_obj.save() submitbutton= request.POST.get('submit') if submitbutton: messages.success(request, 'Submitted!') context = {'form': form} return render(request, 'new.html', context) else: form = ComplaintForm() context = {'form': form} return render(request,'new.html',context) template: <!-- Middle Container --> <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">New Complaint</h1> <form class="" action="" method="POST" enctype="multipart/form-data"> {% csrf_token %} <div class="form-control col-lg-10 comp-title-field" name="title">{{form.title}}</div> <p class="desc">Description</p> <button type="button" class="btn btn-secondary preview-btn">Preview</button> <div class="Descr " name="description">{{form.description}}</div> {{message}} <button type="file" name="myfile" class="btn btn-secondary attach-btn"><i class="fas fa-file-upload"></i> Attachment</button> … -
Filtering the specific data for response in DRF
I have following response data [ { "id": 7, "name": "Default Group", "permissions": [ 22, 24 ] }, { "id": 10, "name": "Another Group", "permissions": [ 1, 2, 22, 24 ] }, { "id": 11, "name": "New Group", "permissions": [ 10, 11, 12, 5, 6, 7, 8 ] }] But I want to remove the dictionary whose id = 10 from the response data ,how can I do that ? I have following lines of code.. class GetUserGroupList(APIView): def post(self, request, *args, **kwargs): groups = Group.objects.all() serializer = GroupSerializer(groups, many=True) return Response(serializer.data) In serializers.py class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'permissions',) Any help would be appreciated !! -
how to show related product in Django?
I have about 10 + models where I'm showing the 3 of them. Where the name is motors, drum, slide. Now in these three models, one field is the same which is the name code. Trying to explain: models.py class Motors(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) class Drum(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) class Sliders(models.Model): . . code = models.CharField(max_length=10) . . . def __str__(self): return str(self.id) Now in the above model, they have the same field as code. And in the code, they have the same name like for eg: in one model the code is DD1, DD2, DD3 and another model code is DD1, DD2, DD3. Now in the Above, the codes are matching. So, if the user selects one motor with Code DD1. Then show the related 2 models with code DD1 or if the user selects one drum with code DD1. Then show related two models items in Django I had used add to cart functionality the code goes here. views.py def addProductMotor(request): user = request.user motor_id = request.GET.get('motor_id') motor_cart = Motor.objects.get(id=motor_id) Cart(user=user, motor=motor_cart).save() return redirect('main:index') In the above, I add one … -
Test of creating new post with image not working. Django
I'm learning Django and created easy blog-like site, where user can create new post. When I try add new post with image on site all work fine, but when I try run test, he don't create new post with image and returning error. Why and how can I fix it? test_forms.py: class PostCreateFormTests(TestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.author = User.objects.create_user(username='author') settings.MEDIA_ROOT = tempfile.mkdtemp(dir=settings.BASE_DIR) cls.small_gif = ( b'\x47\x49\x46\x38\x39\x61\x02\x00' b'\x01\x00\x80\x00\x00\x00\x00\x00' b'\xFF\xFF\xFF\x21\xF9\x04\x00\x00' b'\x00\x00\x00\x2C\x00\x00\x00\x00' b'\x02\x00\x01\x00\x00\x02\x02\x0C' b'\x0A\x00\x3B' ) cls.uploaded = SimpleUploadedFile( name='big.gif', content=cls.small_gif, content_type='image/gif' ) cls.group = Group.objects.create( title='test group', slug='test-test', description='super-mega-test-group', ) cls.post = Post.objects.create( text='Тестовый текст', author=cls.author, group=cls.group, image=cls.uploaded, ) @classmethod def tearDownClass(self): shutil.rmtree(settings.MEDIA_ROOT, ignore_errors=True) super().tearDownClass() def setUp(self): self.guest_client = Client() self.authorized_client = Client() self.authorized_client.force_login(self.author) def test_create_post(self): """Form create new post.""" posts_count = Post.objects.count() form_data = { 'text': 'Test text', 'group': self.group.id, 'image': self.uploaded, # If I comment this line test will work fine. } response = self.authorized_client.post( reverse('new_post'), data=form_data, follow=True ) self.assertEqual(response.status_code, HTTPStatus.OK) self.assertEqual(Post.objects.count(), posts_count + 1) post_get = Post.objects.get(pk=2) self.assertEqual(post_get.text, form_data['text']) self.assertEqual(post_get.group, self.group) self.assertEqual(post_get.author, form_data['author']) self.assertEqual(post_get.image, 'posts/big.gif') # and this views.py: @login_required def new_post(request): form = PostForm(request.POST or None, files=request.FILES or None) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('index') return render(request, 'new.html', {'form': form}) ) The error … -
Show liked post by ManyToMany Users
I am building a small Blog app in Django. I am making a functionality in which user_x can add multiple users as favorite ( With the help of ManyToManyField ) and user_x will be able to see the liked posts of favorite users. BUT when i try to access posts which are liked by request.user's favorite users. Then it is nothing showing. models.py class BlogPost(models.Model): post_user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=509) likes = models.ManyToManyField(User, related_name='likes_of_post', blank=True) class FavouriteUsers(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) favourite_users = models.ManyToManyField(User, related_name='favourite_users', blank=True) views.py def favourite_users_page(request): users = FavouriteUsers.objects.filter(favourite_users=request.user) context = {'users':users} return render(request, 'favourite_users.html', context) favourite_users.html {% for use in users %} {% for pos in use.post_set.likes.all %} {{ pos.title }} {% endfor %} {% endfor %} I have also tried :- {% for pos in likes.all %} {{ pos }} {% endfor %} BUT it is showing all users which liked by post but i am trying to show only favorite users. Any help would be Much Appreciated. -
Import data from a CSV file without id as column
I would like to know if it's possible to import data but with a table that does not have a column named id My import are doing fine with every table that contained a column id but with the one that does not contained a column id it does not work. I got a row_error saying : Error: 'id' -
Including CSRF token in HTTP POST request to a Django server by using HttpUrlConnection class in Android
In my Django project, the view method to handle a HTTP POST request is as : def receive_message(request): if request.method == "POST": data = request.body print(str(data, 'UTF-8')) return HttpResponse(str(data, 'UTF-8'), content_type="application/json") And my code in Android project to make that HTTP POST request is as : HttpURLConnection connection=null; BufferedWriter writer=null; BufferedReader reader=null; if (strings==null){ uploadStatus=UploadStatus.IDLE; return null; } try{ uploadStatus=UploadStatus.PROCESSING; URL url = new URL(strings[0]); connection = (HttpURLConnection) url.openConnection(); CookieManager cookieManager = new CookieManager(); CookieHandler.setDefault(cookieManager); cookieManager.setCookiePolicy(CookiePolicy.ACCEPT_ALL); if (cookieManager.getCookieStore().getCookies().size() > 0) { List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies(); if (cookies != null) { for (HttpCookie cookie : cookies) { connection.setRequestProperty("Cookie", cookie.getName() + "=" + cookie.getValue()); } } } Log.d(TAG, "doInBackground: connecting"); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/json"); connection.setRequestProperty("Accept", "application/json"); Log.d(TAG, "doInBackground: connected"); Log.d(TAG, "doInBackground: connecting input stream"); Log.d(TAG, "doInBackground: response code is : "+connection.getResponseCode()); Log.d(TAG, "doInBackground: response message is "+connection.getResponseMessage()); StringBuilder result = new StringBuilder(); reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String line; // while(null != (line = reader.readLine())) { for(String line = reader.readLine(); line != null; line = reader.readLine()) { result.append(line).append("\n"); } Log.d(TAG, "doInBackground: input stream connected"); uploadStatus=UploadStatus.OK; return result.toString(); } catch(MalformedURLException e) { Log.e(TAG, "doInBackground: Invalid URL " + e.getMessage() ); } catch(IOException e) { Log.e(TAG, "doInBackground: IO Exception writing data: " + e.getMessage()); … -
What are the server requirements on Amazon EC2 to run Django for about 1000 users?
To tell you the truth, I'm actually a beginner and not so good at English. Database aside (already on another server), let's suppose there are 1000 users surfing simultaneously on the website. They can retrieve a restaurant menu, do some groceries, pantries, takeouts and search for them (there are multiple restaurants). I'll need the minimal requirements for these tasks. If you some tools to do it, I'll take it too. But, I need it to be free (no online account due to country constraints). -
CurrentDate variable not display as Value in input box
I was wondering what's wrong with the form I made. It's a Date Input text box where it automatically populates the current date. Could someone point out what's wrong? from datetime import date today = date.today() currentDate = today.strftime("%m/%d/%Y") class DateInput(forms.DateInput): input_type = 'date' class salesForm(forms.Form): entryDateField = forms.DateField(label="Entry Date", widget=DateInput(attrs={'value': currentDate, 'readonly': 'readonly', 'class':'col-sm-8'})) -
Django: Quantity matching query does not exist
I am trying to build a food ordering web app for a restaurant. I want the customer to be able to select the quantity of items that he/she orders, but I don't know exactly how do I do it. Being the site admin, I want to see what items a customer has ordered along with their quantity. Here is my code snippet: views.py class Order(View): def get(self, request, *args, **kwargs): sandwiches = MenuItem.objects.filter(category__name__contains='Sandwich') pizzas = MenuItem.objects.filter(category__name__contains='Pizza') drinks = MenuItem.objects.filter(category__name__contains='Drink') # pass into context context = { 'sandwiches': sandwiches, 'pizzas': pizzas, 'drinks': drinks, } # render the template return render(request, 'customer/order.html', context) def post(self, request, *args, **kwargs): name = request.POST.get('name') email = request.POST.get('email') order_items = { 'items': [] } items = request.POST.getlist('items[]') for item in items: menu_item = MenuItem.objects.get(pk=int(item)) item_quantity = Quantity.objects.get(pk=int(item)) item_data = { 'id': menu_item.pk, 'name': menu_item.name, 'price': menu_item.price, 'count': item_quantity.count } order_items['items'].append(item_data) price = 0 item_ids = [] for item in order_items['items']: price += item['price']*item['count'] item_ids.append(item['id']) order = OrderModel.objects.create( price=price, name=name, email=email ) order.items.add(*item_ids) context = { 'items': order_items['items'], 'price': price } return render(request, 'customer/order_confirmation.html', context) models.py from django.db import models class MenuItem(models.Model): name = models.CharField(max_length=100) description = models.TextField() image = models.ImageField(upload_to='menu_images/') price = models.DecimalField(max_digits=5, decimal_places=2) category = …