Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the value of a model form and assign it to its key in another model form
Suppose I have three models A, B, and C. I also created two model forms from these models. I want to know that is there a way to get the value of the B model form and assign it to its key in the c model form in views? class A(models.Model): name = models.CharField(max_length=200) class B(models.Model): name = models.CharField(max_length=200) class C(models.Model): a= models.ForeignKey(A, on_delete=models.CASCADE) b= models.ForeignKey(B, on_delete=models.CASCADE) answer = models.SmallIntegerField(choices=RATING_CHOICES) class BForm(ModelForm): class Meta: CHOICES = B.objects.all() model = B fields = ('name',) widgets = {'name': Select(choices=( (x.id, x.name) for x in CHOICES ))} class CForm(ModelForm): class Meta: model = C fields = ('answer',) widgets = { 'answer': RadioSelect(choices=RATING_CHOICES),} def index(request): a1 = A.objects.get(id=1) a2 = A.objects.get(id=2) if request.method == "POST": b_form = BForm(request.POST) form = CForm(request.POST, prefix='a1') form1 = CForm(request.POST, prefix='a2') if (form.is_valid and form1.is_valid()): b_form.save() z = form.save(commit=False) z.a= a1 z.b = # I could not figure out this z.save() z = form1.save(commit=False) z.a = a2 z.b = # I could not figure out this z.save() -
How to correct schemas/ sitemap XML file Url, missing " / " forward slash inbetween in django projects
This is the xml file in which inside URL you can see that some of the tittle inside URL missing forward slashes, kindly let me know if you have a way to include those inside it: <url> <loc>http://example.**comAccountant**</loc> <lastmod>2020-12-21</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**comProject** Budgeting Analysis</loc> <lastmod>2020-12-24</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.comAccounts Officer</loc> <lastmod>2020-12-24</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**comhello** my firen</loc> <lastmod>2021-01-02</lastmod> <changefreq>daily</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.**com/blog/blogs/**</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.com/blog/contact/</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> <url> <loc>http://example.com/blog/search/</loc> <changefreq>yearly</changefreq> <priority>0.8</priority> </url> </urlset>``` -
Error in Installing spacy en_core_web_lg on Heroku app
Am deploying my ML model on Heroku using Django, I need en_core_web_lg for my application but couldn't install it My requirements.txt is like: .. git+git://github.com/explosion/spacy-models/releases/download/en_core_web_lg-2.1.0/en_core_web_lg-2.1.0.tar.gz git+git://github.com/Prabhat-git-99/text_process_prabhat99.git .. The Error is: ERROR: Command errored out with exit status 128: git clone -q git://github.com/explosion/spacy-models/releases/download/en_core_web_lg-2.1.0/en_core_web_lg-2.1.0.tar.gz /tmp/pip-req-build-nzvnjf6t Check the logs for full command output. -
Playback state control of spotify web player sdk using spotify api
I am creating a webapp using django and react in which multiple user can control playback of a spotify player (play/pause, skip). This is useful in case of a house party or something where people are listening to a common device . I am thinking if i can integrate the spotify web player sdk and all users can listen to synced playback and control at the sametime remotely. I understand single spotify account needs to register that webapp to be used as device. My question is if can i control the state of playback if the page is opened by multiple users so that they listen to a song synchronously. -
How to get current authenticated user id using Vuejs and Django Rest...?
I am using Vuejs as my frontend and I would simply like to get the current logged in user's id from Django Rest and display it. How would I do this? serializer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' view class CustomerRetrieveView(generics.RetrieveAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer class CustomerUpdateView(generics.UpdateAPIView): queryset = Customer.objects.all() serializer_class = CreateCustomerSerializer permission_class = permissions.IsAuthenticatedOrReadOnly class CustomerCreateView(generics.CreateAPIView): queryset = Customer.objects.all() serializer_class = CreateCustomerSerializer class CustomerListView(generics.ListAPIView): queryset = Customer.objects.all() serializer_class = CustomerSerializer url path('customers/<int:pk>', views.CustomerRetrieveView.as_view()), path('customers/update/<int:pk>', views.CustomerUpdateView.as_view()), path('customers/all', views.CustomerListView.as_view()), path('customers/new', views.CustomerCreateView.as_view()), script vue update(event) { event.preventDefault(); this.axios .post(`http://127.0.0.1:8000/api/v1/customers/new`, {'user': **???**, 'phone': this.phone }) .then(response => {console.log(response) ;this.$router.push('/') }) .catch(err => { console.error(err) }) } -
problem of django form in posting request
I'm working on a project and I made a form but when I submit sth it doesn't send it to database although in cmd it shows that request method is post.I really don'tkhow how to deal with it. thats template code: {%extends 'base.html'%} {%block title%} <title>projects</title> {%endblock title%} {%block content%} <div class="container"> </br> <form method="post"> {% csrf_token %} <div class="form-group"> <input type="text" class="form-control" name="project" placeholder="new project?"> </div> <button type="submit" class="btn btn-primary">add</button> </form> </br> </br> <table class="table"> <thead class="thead-dark"> <tr> <th scope="col"> project-title</th> <th scope="col">update</th> <th scope="col">delete</th> <th scope="col">divide</th> </tr> </thead> <tbody> {% for obj in all_projects %} <tr> <td>{{ obj.proTitle }}</td> <td>{{ obj.done }}</td> <td>Delete</td> <td>Devide</td> </tr> {% endfor %} </tbody> </table> </div> {%endblock content%} any advise will be greatly appreciated:)) -
Error in Paytm Django integration in "production" mode
I was working on to integrate Paytm into my Django project. It worked pretty fine in the demo run, i.e., staging. While I was trying to run it for the production it started throwing errors. The checksum isn't matching in production. Paytm/Checksum.py # pip install pycryptodome import base64 import string import random import hashlib from Crypto.Cipher import AES IV = "@@@@&&&&####$$$$" BLOCK_SIZE = 16 def generate_checksum(param_dict, merchant_key, salt=None): params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_refund_checksum(param_dict, merchant_key, salt=None): for i in param_dict: if("|" in param_dict[i]): param_dict = {} exit() params_string = __get_param_string__(param_dict) salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def generate_checksum_by_str(param_str, merchant_key, salt=None): params_string = param_str salt = salt if salt else __id_generator__(4) final_string = '%s|%s' % (params_string, salt) hasher = hashlib.sha256(final_string.encode()) hash_string = hasher.hexdigest() hash_string += salt return __encode__(hash_string, IV, merchant_key) def verify_checksum(param_dict, merchant_key, checksum): # Remove checksum if 'CHECKSUMHASH' in param_dict: param_dict.pop('CHECKSUMHASH') # Get salt paytm_hash = __decode__(checksum, IV, merchant_key) salt = paytm_hash[-4:] calculated_checksum = generate_checksum(param_dict, … -
django module 'appname' has no attribute 'models'
Everything was working fine until today after I deleted venv and re-created it with pycharm. Now, whatever command I run with django, It throws up this error: AttributeError: module 'api_backend' has no attribute 'models' full traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\core\management\__init__.py", line 401, in execute_f rom_command_line utility.execute() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\core\management\__init__.py", line 377, in execute django.setup() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\apps\registry.py", line 114, in populate app_config.import_models() File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\venv\lib\site-packages\django\apps\config.py", line 211, in import_models self.models_module = import_module(models_module_name) File "C:\Users\iyapp\AppData\Local\Programs\Python\Python36-32\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\models\__init__.py", line 2, in <module> from .data_sheets import * File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\models\data_sheets.py", line 2, in <module> from api_backend.managers.positions import PositionalManager File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\__init__.py", line 1, in <module> from .field_data import FieldDataManager File "C:\Users\iyapp\OneDrive\Desktop\python projects\DataSheet-ledger\api_backend\managers\field_data.py", line 3, in <module> import api_backend.models as api_models AttributeError: module 'api_backend' has no attribute … -
Can't be able to emit the event from outside of socket IO context
Here below is my other file logic (apart from socket io context) in which a signal will be called when the user will be deleted by admin. @receiver(models.signals.post_delete, sender=Driverprofile) def delete_user_object(sender, instance, *args, **kwargs): print("Driver going to delete") instance.user.profile.delete() # call socket method loop = asyncio.new_event_loop() loop.run_until_complete(user_deleted(instance.user.id)) loop.close() instance.user.delete() and here below is my socket io context (last method is for user delete in which i want to emit an event to the connected user) #!/usr/bin/env python # from .models import * import asyncio import uvicorn import socketio, pdb import pickle # from registration.models import * sio = socketio.AsyncServer(async_mode='asgi', cors_allowed_origins="*") app = socketio.ASGIApp(sio) background_task_started = False users = {} async def background_task(): """Example of how to send server generated events to clients.""" count = 0 while True: await sio.sleep(10) count += 1 # io.to(socketid).emit('message', 'for your eyes only'); # pdb.set_trace() await sio.emit('my_response', {'data': 'Server generated event'}) @sio.on('login') async def login(sid, message): global users users[sid] = int(message['userId']) print("Login users", users) filename = 'dogs' outfile = open(filename,'wb') pickle.dump(users,outfile) outfile.close() await sio.emit('my_response', {'data': ''}, room=sid) @sio.on('my_broadcast_event') async def test_broadcast_message(sid, message): await sio.emit('my_response', {'data': message['data']}) @sio.on('join') async def join(sid, message): sio.enter_room(sid, message['room']) await sio.emit('my_response', {'data': 'Entered room: ' + message['room']}, room=sid) @sio.on('leave') async def … -
Python crash course chapter 18. No learning_log directory is created
I'm doing exercises in the 'Python Crash Course' book in Chapter 18. I can't create the learning_log directory and manage.py, init.py, settings.py, urls.py, wsgi.py files. I made the creation of a virtual environment with the command: python -m venv ll_env I am using Windows so I used the command to activate the virtual environment: ll_env\Scripts\activate The environment has been activated because the name (ll_env) is displayed before the prompt. Then I installed the Django framework with the command: pip install django Installed successfully.But when I used the command: django-admin.py startproject learning_log . Unfortunately, the learning_log directory and the previously mentioned files are not created. I installed django version 3.1.4 and the book is version 2.2. Is there a problem here? Is there any other command to create this directory and files? Let me add that I was doing it all in the PyCharm terminal. -
Why doesn't the csrf_exempt work on my view in Django?
I am making a fetch request to one of the Urls as: function like(id){ fetch(`/likepost/${id}`, { method:'PUT', body: JSON.stringify({ 'id':id }) }) .then(response => response.json()) .then(result => { console.log(result) }) and the url maps to this view: path('likepost/<int:post_id>', views.likepost,name='like') and the view is defined as: @csrf_exempt def likepost(request, post_id): if request.method == 'PUT': data = json.loads(request.body) id = data.get('id') post = Post.objects.get(pk=id) post.likes = post.likes+1 post.save() return JsonResponse({'message':'liked succcessfuly'}) else: return JsonResponse({'Message':'request should be post'}) but I am getting this error: Forbidden (CSRF token missing or incorrect.): /likepost/12 even though I have used csrf_exempt, can anyone help me? -
Plotly Dash App in Django throws TypeError on __init__() Positional Arguments
I have been following the example here exactly https://thinkinfi.com/integrate-plotly-dash-in-django/ it works fine if I set the virtual environment up with packages of the exact packages it has specified. However I am trying to follow this method and implement it into an existing Django project, so I would prefer to use the latest versions of the packages. With these versions instead django-plotly-dash==1.5.0 dash==1.18.1 dash-bootstrap-components==0.11.1 dash-daq==0.5.0 dpd-static-support==0.0.5 whitenoise==5.2.0 I got this error Exception inside application: __init__() takes 1 positional argument but 2 were given Traceback (most recent call last): File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/channels/routing.py", line 150, in __call__ return await application( File "/home/jasontam/Personal/GitProjects/dashboard_django/newEnv/lib/python3.8/site-packages/asgiref/compatibility.py", line 33, in new_application instance = application(scope) TypeError: __init__() takes 1 positional argument but 2 were given Does anyone have any ideas how to resolve it? I have a similar setup going fine (except that … -
Django DB cyclic model prevention Queryset
I am working on a project where I need have cyclic entries. Think, a recipe might have a sub recipe and that might have a sub recipe. The issue is one of those sub recipes might have its parents' parent as a child. So I am trying to prevent this or at least not wanting to have to proved the user with an option to select that item. To do this. I wanted to check on the server side if there is cycle. A classic loop detection. So I was going to either implement BFS or DFS, possible DFS to minimize the memory usage and check each child and their child and so forth until I visit all nodes and keep a visited dict to keep the ids of all the models entries I see. The issue is queryset is not providing some of the basic functions to do pop and push. I can convert the query set to list but that could be expensive and run out of memory. It is unlikely to have 100000 depth recipe but in theory it can happen. Is there an alternative to this? I was thinking maybe pass the visited list to filter … -
How many Django models is appropriate?
I'm making a Django project from a pre-existing epidemiological Excel model and I'm not familiar with how best to make use of Django models. The examples in the tutorial seem to fit 'just right' (e.g. one object is obviously the parent of another), and my data does not. My data consists of the following: A country, which has a name, a population of males and a population of females. However the population depends on the year (2019 to 2030). A cancer, which has a type (e.g. Breast cancer), a set of stages (e.g. Stage IV breast cancer). Cancer types interact with countries. E.g. the likelihood of dying from Stage III lung cancer is different in Australia than Uganda. This data currently lives in a bunch of json files, one which has the population per year of countries, one which has the proportion of people in an age group for a country, one which has the likelihood of dying from a cancer etc. I created these json files by exporting them from pandas dataframes, which we took from the lookup tables in Excel. I presume I could import each of these json files as its own model, but I get the … -
How to Change Django InMemoryField to PIL Image object?
Here Take a look at my code : profile_picture = self.validated_data.get('profile_picture',False) if profile_picture: pic = profile_picture.read() Now , I want to crop the image if it's not in a particular resuloution ; i want to convet pic to PIL.Image.Image obj, how do I do that? -
How can I enable users to select their workspace when using Sign in with Slack?
I'm having some trouble with getting Sign in with Slack to work like I want it to. Specifically, I'm seeking to build a platform that people can use for their Slack workspaces, and depending on which workspace they are signing into, different content (in this case, saved slack posts) show up. I've incorporated Sign in with Slack to my website following the Slack provided tutorial. I use https://slack.com/oauth/v2/authorize?user_scope=identity.basic,identity.email,identity.team,identity.avatar&client_id to trigger the process. My redirect URI passes the code parameter to here @csrf_exempt @api_view(['GET', 'POST']) def auth(request): code = request.data['code'] url = 'https://slack.com/api/oauth.v2.access?client_id={}&client_secret={}&code={}'.format(SLACK_CLIENT_ID, SLACK_CLIENT_SECRET, code) response = requests.get(url) response_dict = json.loads(response.text) print(response_dict) if response_dict.get('ok'): user_id = response_dict['authed_user']['id'] team_id = response_dict['team']['id'] access_token = response_dict['authed_user']['access_token'] client = WebClient(token=access_token) user_profile = client.users_identity() email = user_profile.get('user').get('email') display_name = user_profile.get('user').get('name') image = user_profile.get('user').get('image_48') userObject = User.objects.get_or_create(username= user_id + team_id, user_id=user_id, team_id=team_id, email=email)[0] userObject.first_name=display_name userObject.last_name='' userObject.image=image userObject.save() response_dict['model_id'] = userObject.id return Response(json.dumps(response_dict), status=status.HTTP_200_OK) else: return Response(None, status=status.HTTP_400_BAD_REQUEST) I have a couple questions. How do I enable the user to sign into any slack workspace they want when they click the Sign in with Slack button? Currently it defaults to just one workspace and I am not sure how to change that. When I manually enter a different … -
Django Rest Framework - "unique_together" internal server error. How to respond with error
I currently have a model called "Review" where I have a "unique_together" constraint so one user can only write one review per post. class Review(models.Model): created = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, related_name='reviews', on_delete=models.SET_NULL, null=True) post = models.ForeignKey(Post, related_name='reviews', on_delete=models.CASCADE) rating = models.IntegerField() comment = models.TextField(blank=True, null=True) class Meta: unique_together = ['user', 'post'] And in my View I am grabbing the user from the request (I'm using token authentication) and use that user to save the object by overwriting the "perform_create" method: class ReviewCreateView(CreateAPIView): permission_classes = [IsAuthenticated] serializer_class = ReviewCreateSerializer def perform_create(self, serializer): serializer.save(user=self.request.user) And my serializer looks like this: class ReviewCreateSerializer(ModelSerializer): class Meta: model = Review fields = ['post', 'rating', 'comment'] When I try to submit two reviews to the same post by the same user I get an internal server error. The body of my HTTP POST request looks like this: { "post" : 11, "rating": 1, "comment": "this is a great post" } Instead of getting an error response (for example 403 error). I get this Django server error instead: django.db.utils.IntegrityError: duplicate key value violates unique constraint After spending some time researching I saw that Django Rest Framework provides the "UniqueTogetherValidator". Which I added like this: class ReviewCreateSerializer(ModelSerializer): … -
Ive pushed my django app to production, but when i open the media files it raises a django.views.static.serve error
Page not found (404) Request Method: GET Request URL: http://limitless-cliffs-18209.herokuapp.com/media/image/IMG_2516.JPG Raised by: django.views.static.serve "/code/media/image/IMG_2516.JPG" does not exist -
How to display JSON objects to the template from rapidAPI using Django
Here is my python code for the GET request from django.shortcuts import render import requests def index(request): url = "https://quotes-inspirational-quotes-motivational-quotes.p.rapidapi.com/quote" querystring = {"token":"ipworld.info"} headers = { 'x-rapidapi-key': "fae2454b29mshf5c9ff8e23af3bep105c25jsnc78186056962", 'x-rapidapi-host': "quotes-inspirational-quotes-motivational-quotes.p.rapidapi.com" } response = requests.request("GET", url, headers=headers, params=querystring).json() print(response) return render(request, 'olops/index.html', {'response': response}) Here is the response from postman click me Here is my code for my template {% for i in response %} {{ i }} {% endfor %} Here is the output in my web page html template output When I add {{i.text}} or {{i.author}} in the template, it's not returning the value. How can I proceed with outputting JSON objects with Django? Thank you -
Django - Hosting Platform query
I have built a Django local web application which I want to host on some platform now. I am using Postgres SQL as database. Any recommendations of hosting platforms with cheaper or free plans? My website will be used by few users only (<50), so I don't need very powerful server/CPU etc. -
Why django TemplateSyntaxError is raised in here?
Im tring to iterate through context of my view and get 'ga:deviceCategory' values only , the code that I'm running in HTML is: <div class="card-body"> {% for i in pvdc %} <p>{{ i.get('ga:deviceCategory') }}</p> {% endfor %} </div> My view in django is : def dashboard(request): context = {'pvdc': [{'ga:deviceCategory': 'desktop', 'ga:pageviews': 673, 'ga:avgSessionDuration': 53.4447946}, {'ga:deviceCategory': 'mobile', 'ga:pageviews': 2373, 'ga:avgSessionDuration': 69.62674418604651}, {'ga:deviceCategory': 'tablet', 'ga:pageviews': 322, 'ga:avgSessionDuration': 26.205426356589147}]} return render(request, 'user/index.html', context) The syntax error that I receive is: Could not parse the remainder: '('ga:deviceCategory')' from 'i.get('ga:deviceCategory')' what is the problem here and how can i get the values? -
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another
Django Querying: How do i query an account page through a blog post that the account owner has created? aka link from one to another. So I have an account model and a blog post model, with the author as the foreign key. I am unsure of how i can do the querying of the account. Can anyone advise how this is normally done? Because I tried to do user_id=request.user.id but this would take me to my own account view. Thanks! html <a class="dropdown-item" href="{% url 'account:view' %}">{{blog_post.author}}</a> views.py def detail_blog_view(request, slug): context = {} blog_post = get_object_or_404(BlogPost, slug=slug) context['blog_post'] = blog_post return render(request, 'HomeFeed/detail_blog.html', context) urls.py for accounts: path('<user_id>/', account_view, name="view"), models.py class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) class BlogPost(models.Model): title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Retrieve the same values whose data is there or exists and not the rest.In django
I want to have a data that does not have any empty value in database or in row. I wrote like this in my code. faq = FAQ.objects.values('question','answer','field_id') this the output in my terminal {'question': None, 'answer': None, 'field_id': None} {'question': 'Test question', 'answer': '<p>Testsaddsf description</p>\r\n', 'field_id': 'TestTest'} i don't want None value data. -
upload image and already saved image, this two parts want to display on two different html template
i use modelformset_factory to upload image, but i want to separate the already saved image(A in the below link) and upload image(B in the below link) on two different html template. How do i resolve this problem? thanks for your help!! enter image description here here is my code below: views.py def post_image(request): PictureFormSet = modelformset_factory(Picture, form=PictureForm, extra=3) if request.method == 'POST': formset = PictureFormSet(request.POST, request.FILES) if formset.is_valid(): formset.save() return HttpResponse("Upload done!!") else: return HttpResponse("Upload Failed!!") else: formset = PictureFormSet() return render(request, "Image.html", {"formset": formset}) models.py class Picture(models.Model): article = models.ForeignKey("Article", related_name="article_photo", on_delete=models.CASCADE) photo = models.ImageField(upload_to="photo", height_field=None, width_field=None, max_length=100) first_photo = models.BooleanField(default=False) urls.py path('post/image/', post_image), html <html lang="zh-Hant-TW"> <head> <meta charset="UTF-8"> <title>post_image</title> </head> <form action="" method="POST" enctype="multipart/form-data">{% csrf_token %} {{ formset.management_form }} <table> {% for form in formset %} {{ form }} {% endfor %} </table> <input type="submit" value="Sumbit"> </form> -
how to get cart and order for a user who sell the product using django
I am building an ecommerce web-application using django where people come and sell their products. Recently i have done the coding where user come ,login and sell their products and another user come and buy these thing .All the order are coming to the admin panel. but i want the user that sell the products get these specific orders . but how the user who sell ,can get their orders and cart . I do not have any logic kindly anyone please guide me. Thnak you