Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rest universal linking -- json file path not found
I have a Django REST framework that is integrating universal app linking for iOS https://developer.apple.com/library/archive/documentation/General/Conceptual/AppSearch/UniversalLinks.html The main point is that I have a json file called "apple-app-site-association" in my root directory (as instructed) that controls the redirect. When I put this through an aasa validator https://branch.io/resources/aasa-validator/ it returns a 400. My server logs show Not Found: /.well-known/apple-app-site-association I can't find any resources doing this with django, so I'm a little stuck on what to try or do next. -
expecting one result, but django .filter() returns multiple
I am chaining the filters and expecting one result to return -because according to the conditions result should be one- but it returns related rows as well... // taking the ID from the parent table. pid = Budgets.objects.filter(project_name=direct["project_name"]).values("id")[0]["id"] // checking the row exist or not. exists = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").exists() if exists == True: // if it's exist then return it with the according criterias value = Advertisements.objects.filter(budgets_id=pid).filter(saved_date="2020-02").filter(ad_kind="gsn").values_list("ad_kind", flat=True)[0] print(value) // the problem occurs here. normally filter(ad_kind="gsn") should filter it till gsn left. But it doesn't. And it return other kinds too... Any idea what can be causing this problem? -
How to POST on Postman without having to change DEBUG = True to false in Django settings?
Getting an issue when running "python3 manage.py runserver" link -
Which URL does CreateView in Django redirects to when the success_url is not provided?
I am learning Class-based views in Django(inheriting from generic views) and stumbled upon a code for CreateView which did not provide any success_url. But after creation, I am getting redirected to DetailView (i.e, the page describing a particular object, in this case the object just created). I am not sure how this redirection is happening. Can anyone help me with this? # ...other imports... # ... from django.views.generic.edit import CreateView #... other views... class TweetCreateView(FormUserNeededMixin, CreateView): form_class = TweetModelForm template_name = "tweets/create_view.html" class TweetDetailView(DetailView): model = Tweet #...other views... Thanks. -
Asking user to select a local directory
I've been looking everywhere in the hope of finding a good implementation of allowing a user to select a local directory for, in this case, selecting where to download files. The best method I found was through tkinter with the filedialog method but I thought this couldn't be the best approach. -
Error in Django ModelForm. Select a valid choice. That choice is not one of the valid choices
I have a Model and a ModelForm. The ModelForm has a dependent dropdown list implemented with JQuery. The category dropdown changes accordingly each time a choice from the gender dropdown is selected (Done with JQuery). Whenever I try to save the ModelForm in my views, I get an error saying that the choice that I have selected is not valid. Does it have to do with the choices/options to the category dropdown being added after a choice from the gender dropdown has been selected? Does it cause some conflict with the default empty two-tuple of the category field? The errors occur on the category field. In models.py, GENDER_CHOICES = [ ('Male', 'Male'), ('Female', 'Female'), ] class Person(models.Model): name = models.CharField(max_length=50, unique=True) gender = models.CharField(max_length=7, choices=GENDER_CHOICES) category = models.CharField(max_length=20, choices=[('', ''), ]) In forms.py, class PersonForm(ModelForm): class Meta: model = Person fields = [ 'name', 'gender', 'category', ] In views.py, def personform_page(request): context = {} if request.method == 'POST': personform = PersonForm(request.POST) if personform.is_valid(): personform.save() return redirect('personform_page') context['personform'] = personform else: personform = PersonForm() context['personform'] = personform context['male_categories'] = MALE_CATEGORIES context['female_categories'] = FEMALE_CATEGORIES return render(request, 'app1/personform_page.html', context=context) In app1/personform_page.html, <form class="form-class" action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% for field in … -
Import Error when running task on python anywhere
I am trying to create a task to run daily using python anywhere and keep getting the error: Traceback (most recent call last): File "/home/10Cents/10-cents-app/Django/10cents/webdesign/cent/tasks.py", line 3, in from . import views ImportError: attempted relative import with no known parent package file structure -
Too much view logic in django template
i am currently building an e commerce platform. I am working on the Order part of the app which creates an order after two people agree to enter into a transaction. Issue is that the order model has a lot of fields and as i want my template to look different depending on many values such as; has payment been made? Has the product been shipped? has a dispute been raised? I also want the page to look different depending on if its the buyer viewing the page or the seller. Obviously if the seller is viewing the page i dont want him to see the checkout button, or the buyer to see the mark item as posted etc. So i currently have this working however there is a LOT of if statements in my template to do so and the view has a lot of logic as well. My question is, is there a better (more efficient and faster) way to do this as i know most logic should be kept out of the template. If this won't slow my site down then that is acceptable but if it is then i really need to change it. The Model … -
type object 'User' has no attribute 'get_user_by_token' in flask python
I am trying to combine Flask-User and Flask-Login but when I try logging in I get this error: File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 2446, in wsgi_app response = self.full_dispatch_request() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1951, in full_dispatch_request rv = self.handle_user_exception(e) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1820, in handle_user_exception reraise(exc_type, exc_value, tb) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\_compat.py", line 39, in reraise raise value File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1949, in full_dispatch_request rv = self.dispatch_request() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 1935, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "C:\Users\asus\Desktop\group-17-electronic-voting-system\vote\routes.py", line 12, in home return render_template('home.html',title='Home') File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\templating.py", line 136, in render_template ctx.app.update_template_context(context) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask\app.py", line 838, in update_template_context context.update(func()) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\utils.py", line 379, in _user_context_processor return dict(current_user=_get_user()) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\utils.py", line 346, in _get_user current_app.login_manager._load_user() File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_login\login_manager.py", line 318, in _load_user user = self._user_callback(user_id) File "c:\users\asus\appdata\local\programs\python\python38-32\lib\site-packages\flask_user\user_manager.py", line 130, in load_user_by_user_token user = self.db_manager.UserClass.get_user_by_token(user_token) AttributeError: type object 'User' has no attribute 'get_user_by_token' Any help would be appreciated. -
django.db.utils.OperationalError: could not connect to server: Con nection refused
I have dockerized aplication build in Django and using as database postgis but when I'm trying to run containers I'm getting error "django.db.utils.OperationalError: could not connect to server" There are logs from Docker Terminal: $ docker-compose up Recreating database ... done Recreating boss_support_web_1 ... done Attaching to boss_support_postgres_1, boss_support_web_1 postgres_1 | Add rule to pg_hba: 0.0.0.0/0 postgres_1 | Add rule to pg_hba: replication replicator postgres_1 | Setup master database postgres_1 | 2020-03-19 00:04:22.426 UTC [28] LOG: listening on IPv4 address " 127.0.0.1", port 5432 postgres_1 | 2020-03-19 00:04:22.428 UTC [28] LOG: listening on Unix socket "/ var/run/postgresql/.s.PGSQL.5432" postgres_1 | 2020-03-19 00:04:22.451 UTC [35] LOG: database system was interru pted; last known up at 2020-03-18 23:43:38 UTC postgres_1 | 2020-03-19 00:04:22.486 UTC [40] postgres@postgres FATAL: the dat abase system is starting up postgres_1 | psql: FATAL: the database system is starting up postgres_1 | 2020-03-19 00:04:22.594 UTC [35] LOG: database system was not pro perly shut down; automatic recovery in progress postgres_1 | 2020-03-19 00:04:22.596 UTC [35] LOG: redo starts at 0/40FDE210 postgres_1 | 2020-03-19 00:04:22.597 UTC [35] LOG: invalid record length at 0/ 40FDE248: wanted 24, got 0 postgres_1 | 2020-03-19 00:04:22.597 UTC [35] LOG: redo done at 0/40FDE210 postgres_1 … -
Why is my Django serializer telling me an attribute doesn't exist when I see it defined in my model?
I'm using Python 3.7 and the Django rest framework to serialize some models into JSOn data. I have this data = { 'articlestats': ArticleStatSerializer(articlestats, many=True).data, and then I have defined the following serializers ... class LabelSerializer(serializers.ModelSerializer): class Meta: model = Label fields = ['name'] ... class ArticleSerializer(serializers.ModelSerializer): label = LabelSerializer() class Meta: model = Article fields = ['id', 'title', 'path', 'url', 'label'] class ArticleStatSerializer(serializers.ModelSerializer): article = ArticleSerializer() class Meta: model = ArticleStat fields = ['id', 'article', 'score'] I have defined my Label model like so ... class Label(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Meta: unique_together = ("name",) but I'm getting this error when Django processes my serialize line ... AttributeError: Got AttributeError when attempting to get a value for field `name` on serializer `LabelSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `str` instance. Original exception text was: 'str' object has no attribute 'name'. Not sure why it's complaining. The "name" attribute is right there. What else should I be doing? -
Creating .ebextensions directory in Django on Mac
I am trying to add an .ebextensions directory to my site root in Django. In the terminal I was able to create the file with no error, cd into the directory, and then add a django.config file (following this tutorial: https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html#python-django-configure-for-eb) However, when I view the parent directory of the .ebextensions directory, the file is not there! When I try recreating the directory in the terminal I get the following error: "mkdir: .ebextensions: File exists" When I try to manually create a folder titled .ebextensions in Finder, I get the following error: "You can't use a name that begins with a dot "." because these names are reserved for the system. Please choose another name." Any advice? -
Django uploading image in custom template
forms.py from django import forms from .models import VideoPost class PostForm(forms.ModelForm): class Meta: model = VideoPost fields = ('category', 'title', 'slug', 'content', 'video', 'image',) models.py class VideoPost(models.Model): category = models.ForeignKey('Category', on_delete=models.CASCADE) title = models.CharField(max_length=100) slug = models.SlugField(max_length=100, unique = True) author = models.ForeignKey(User, on_delete=models.CASCADE) video = models.CharField(max_length=100, blank=True) content = RichTextUploadingField() image = models.ImageField(upload_to='images', null=True, blank=True) date_posted = models.DateTimeField(default=timezone.now) def _get_unique_slug(self, *args, **kwargs): self.slug = slugify(self.title) super(VideoPost, self).save(*args, **kwargs) def __unicode__(self): return self.title views.py def post_new(request): if request.method == "POST": form = PostForm(request.POST, request.FILES) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.published_date = timezone.now() post.save() return render(request, 'stories/post_detail.html') else: form = PostForm() return render(request, 'stories/post_new.html', {'form': form}) settings.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) LOGIN_REDIRECT_URL = 'home' MEDIA_URL = 'static/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media') This is not on django built in admin page, I wanted to make a custom post template. All other form inputs work just fine, and all the data are stored in db correctly except image. the image field in database is always blank no matter what image I put in there, and even in my static/media/image path, it's empty. Any help would be much appreciated. -
django-taggit-autosuggest in non admin page
So I've implemented the autosuggest for taggit, however I cant seem to get it to work on my form page and not just my admin page.I've followed the instructions as best I could but still seem to get no results, any help is appreciated. I'm using Python 3 if that makes any difference and Django 3.0.3 Taggit-autosuggest install guide: https://pypi.org/project/django-taggit-autosuggest/ head of HTML <head> <meta charset="utf-8"> <script src="jquery-3.4.1.min.js"></script> <link href='{{ STATIC_URL }}jquery-autosuggest/css/autoSuggest-upshot.css' type='text/css' media='all' rel='stylesheet' /> <script type='text/javascript' src='{{ STATIC_URL }}jquery-autosuggest/js/jquery.autoSuggest.minified.js'> </script> <link rel="stylesheet" href="{%static 'guide/style.css'%}"> {% if title %} <title>{{title}}</title> {% else %} <title>Audit Help center</title> {% endif %} </head> Form HTML {% extends 'guide/base.html' %} {% block content %} {% load static %} <div class ='content-section'> <form method="POST"> {% csrf_token %} <fieldset class ="form-group"> <legend class ="border-bottom mb-4">Post 1</legend> {{form|safe}} </fieldset> <div class="form-group"> <button class = "btn" type="submit">Save</button> </div> </form> </div> {% endblock content %} -
Volunteer search for an app related to the corona virus
Corona-Help.org is an initiative of volunteers. The initiative has the goal of connecting People in Need (elderly people, high risk people) with volunteers, which offer to go shopping, dog walking etc. to protect the People in Need to get in contact with the environment too much. The goals of the project: Offer a phone hotline for People in Need (elderly people, high risk people) for registering as Person in Need Offer a web application to Street Volunteers where they can find and connect to People in Need At the moment, we need people who have experience with django3/python3 specifically django rest framework. Others are also welcome. If you are interested in helping us join corona-helporg.slack.com. Thanks -
get_queryset in DetailView
I want to implement a search form to my template. Template is for a DetailView that show the details of 'agents'. The problem is when i search a name that there is not in database, i got this error: Page not found ... No agents found matching the query views.py: class AgentsDetailView(LoginRequiredMixin, generic.DetailView): model = models.agents template_name = 'agent/agent_detail.html' def get_queryset(self): query = self.request.GET.get('q') if query: return models.agents.objects.filter(Q(users__user__first_name__contains=query) | Q(users__user__last_name__contains=query) | Q(users__id_number__contains=query) | Q(users__mobile__contains=query)) else: return models.agents.objects.all() models.py: class agents(models.Model): agent_type = models.ForeignKey(types, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=100) address = models.TextField(blank=True, null=True) phone = models.CharField(max_length=20) is_producer = models.BooleanField(default=False) serial = models.TextField(default='') users = models.ManyToManyField(user_models.users, through='user_agent') def __str__(self): return self.name def get_absolute_url(self): return reverse('agent_detail', args=[str(self.id)]) agent_detail.html: {% block content %} <h1>name: {{ agents.name }}</h1> <form method="GET" action="" id="searchform"> <input class="searchfield" id="searchbox" name="q" type="text" placeholder="Search..."/> <button name="search" type="submit" value="{{ request.GET.q }}">Search</button> </form> {% if agents.users %} <p><strong>Users:</strong> <br> {% for users in agents.users.all %} <li>{{ users }}</li> <hr> {% endfor %} </p> {% else %} <p>There are no agent in database.</p> {% endif %} <p><strong>Serial:</strong> {{ agents.serial }}</p> <p><strong>Agent Type:</strong> {{ agents.agent_type }}</p> <p><strong>Address:</strong> {{ agents.address }}</p> <p><strong>Phone Number:</strong> {{ agents.phone }}</p> <p><strong>Is Producer?:</strong> {{ agents.is_producer }}</p> {% endblock %} -
can I filter against the URL with a Django Rest Framework ViewSet?
Is there a way to filter against the URL (as described here) using a DRF ViewSet? I have the following sort of code: models.py: class Author(models.Model): name = models.CharField() class Book(models.Model): title = models.CharField() author = models.ForeignKey(Author, related_name="books") views.py: class BookViewSet(viewsets.ReadOnlyModelViewSet): serializer_class = BookSerializer def get_queryset(self): author = self.kwargs["author"] return Book.objects.filter(author__name=author) urls.py: api_router = SimpleRouter() api_router.register(r"books/<str:author>", BookViewSet) urlpatterns = [ path("", include(api_router.urls)) ] But this pattern actually matches the URL /books/<str:author> (with the angle brackets) instead of letting my enter something like /books/shakespeare and get back all books with the author "shakespeare". Is it possible to do this kind of a filter with a ViewSet? -
Can I avoid the need for authentication when testing Django Rest Framework
I am trying to use DRF testing for the first time, so I created the following TestCase: class TestInventoryActionInputNoSeriable(TestCase): def setUp(self): self.repository = create_repository() self.not_seriable_product = create_not_seriable_product() def test_post_inventory_input_not_seriable(self): client = APIClient() response = client.post('/api/inventory/execute_action/', { 'action': 'input', 'repository': self.repository.id, 'product': self.not_seriable_product.id, 'amount': 1, }) self.assertEqual(response.status_code, 200) inventory_actions = models.InventoryAction.objects.all() inventory_inputs = models.InventoryInput.objects.all() kardexs = models.Kardex.objects.all() self.assertEqual(len(inventory_actions), 1) self.assertEqual(len(inventory_inputs), 1) self.assertEqual(len(kardexs), 1) inventory_action = inventory_actions.first() inventory_input = inventory_inputs.first() kardex = kardexs.first() self.assertEqual(inventory_action.action_content_type.model, 'inventoryinput') self.assertEqual(inventory_action.action_object_id, inventory_input.id) self.assertEqual(kardex.type, models.KARDEX_INPUT) self.assertEqual(kardex.repository_id, self.repository_id) self.assertEqual(kardex.product_id, self.not_seriable_product.id) self.assertEqual(kardex.amount, 1) self.assertEqual(kardex.stock, 1) But I get the following result: (TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test Creating test database for alias 'default'... System check identified no issues (0 silenced). F ====================================================================== FAIL: test_post_inventory_input_not_seriable (inventory.tests.TestInventoryActionInputNoSeriable) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/hugovillalobos/Documents/Code/TCDigitalProject/TCDigitalBackend/TCDigital/inventory/tests.py", line 31, in test_post_inventory_input_not_seriable self.assertEqual(response.status_code, 200) AssertionError: 401 != 200 ---------------------------------------------------------------------- Ran 1 test in 0.083s FAILED (failures=1) Destroying test database for alias 'default'... Which means that the request was rejected because of authentication failure. I followed DRF authentication documentation: def test_post_inventory_input_not_seriable(self): token = Token.objects.get(user__username='admin') client = APIClient() client.credentials(HTTP_AUTHORIZATION='token '+token.key) response = client.post('/api/inventory/execute_action/', { 'action': 'input', 'repository': self.repository.id, 'product': self.not_seriable_product.id, 'amount': 1, }) self.assertEqual(response.status_code, 200) ... But I get this error: (TCDigitalVenv) MacBook-Pro-de-Hugo:TCDigital hugovillalobos$ python manage.py test … -
Django : ForeignKey data insertion issue (can't add product
I'm new to django My problem is, in django-admin-interface whenever I try to create a product with a category, that is already occupied by another existing product, I get an error : Product with this Category already exists in admin-UI for example : I have created 1 product i-phone with category electronic , It saves into DB. Now if I create another product Google-nexus with same category i.e. electronic, I can't create the product because of this error is shown in django-admin-interface : Product with this Category already exists I created 3 models in my app like below models.py from django.db import models class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name class Product(models.Model): product_name = models.CharField(max_length=255) tags = models.ManyToManyField(Tag) image = models.ImageField(upload_to='images') category = models.OneToOneField(Category, on_delete=models.CASCADE) description = models.TextField() def __str__(self): return self.product_name forms.py from django import forms from.models import Product class ProductForm(forms.ModelForm): class Meta: model = Product fields = ('product_name', 'category', 'description', 'image', 'tags') def __init__(self,*args,**kwargs): super(ProductForm,self).__init__(*args,**kwargs) self.fields['category'].empty_label = 'Select' self.fields['image'].required = False Do I have wrong model relationship.? error snapshot of django-admin -
The current project's Python requirement (^2.7) is not compatible with some of the required packages Python requirement
I keep receiving this error when I run poetry add django confidential Using version ^3.0.4 for django Using version ^2.3.0 for confidential Updating dependencies Resolving dependencies... (0.0s) [SolverProblemError] The current project's Python requirement (^2.7) is not compatible with some of the required packages Python requirement: - django requires Python >=3.6 Because no versions of django match >3.0.4,<4.0.0 and django (3.0.4) requires Python >=3.6, django is forbidden. So, because pythontest depends on django (^3.0.4), version solving failed. When I check my python version I see 3.8.2 and my Django version is 3.0.4 so I'm not sure what else the issue could be. -
NoReverseMatch - I am creating a sample crm
This is my error: Reverse for 'create_order' with no arguments not found. 1 pattern(s) tried: ['create_order/(?P[^/]+)/$'] My codes are here: from django.urls import path from . import views urlpatterns = [ path('', views.home, name="home"), path('products/', views.products, name='products'), path('customer/<str:pk_test>/', views.customer, name="customer"), path('create_order/<str:pk>/', views.createOrder, name="create_order"), path('update_order/<str:pk>/', views.updateOrder, name="update_order"), path('delete_order/<str:pk>/', views.deleteOrder, name="delete_order"), ] def createOrder(request, pk): OrderFormSet = inlineformset_factory(Customer, Order, fields=('product','status'), extra=10) # form = OrderForm() customer = Customer.objects.get(id=pk) formset = OrderFormSet(queryset=Order.objects.none(),instance=customer) # form = OrderForm(initial={'customer':customer}) if request.method == 'POST': # print('Printing POST', request.POST) # form = OrderForm(request.POST) formset = OrderFormSet(request.POST, instance=customer) if formset.is_valid(): formset.save() # return HttpResponse('<h1>Congratulations</h1> <a href="/">Please return to home<a/>') return redirect('/') context = {'formset':formset } return render(request, 'accounts/order_form.html', context) Where am I doing wrong? Please help me. -
Could not find a version that satisfies the requirement pywin32==227 heroku
I am having this issue with heroku. i am trying to push my application to heroku but it seems that heroku can not install pywin32=227 but i do not know why is this happening. i hope that someone can help me whit this issue. Requirements.txt: appdirs==1.4.3 asgiref==3.2.3 awsebcli==3.17.1 botocore==1.14.17 cement==2.8.2 certifi==2019.11.28 chardet==3.0.4 colorama==0.3.9 distlib==0.3.0 dj-database-url==0.5.0 Django==2.1.15 django-pyodbc-azure==2.1.0.0 docutils==0.15.2 filelock==3.0.12 future==0.16.0 gunicorn==20.0.4 idna==2.7 importlib-metadata==1.5.0 jmespath==0.9.5 pathspec==0.5.9 Pillow==7.0.0 psycopg2==2.8.4 pyodbc==4.0.30 pypiwin32==223 python-dateutil==2.8.0 python-decouple==3.3 pytz==2019.3 pywin32==227 PyYAML==5.2 requests==2.20.1 semantic-version==2.5.0 six==1.11.0 sqlparse==0.3.1 stripe==2.43.0 termcolor==1.1.0 urllib3==1.24.3 virtualenv==20.0.7 wcwidth==0.1.8 whitenoise==5.0.1 zipp==3.1.0 I'm developing on Windows 10 Professional, and the application works fine there: C:\Users\GuGarza\test>git push heroku master Enumerating objects: 363, done. Counting objects: 100% (363/363), done. Delta compression using up to 4 threads Compressing objects: 100% (348/348), done. Writing objects: 100% (363/363), 257.21 KiB | 1.42 MiB/s, done. Total 363 (delta 107), reused 0 (delta 0) remote: Downloading pytz-2019.3-py2.py3-none-any.whl (509 kB) remote: ERROR: Could not find a version that satisfies the requirement pywin32==227 (from -r /tmp/build_000de559e8272ea11b28b5ee568bf649/requirements.txt (line 28)) (from versions: none) remote: ERROR: No matching distribution found for pywin32==227 (from -r /tmp/build_000de559e8272ea11b28b5ee568bf649/requirements.txt (line 28)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected … -
One View Saving Objects to Two Models Django
I have a view that will save the data from its form to one model 'PackingLists', but the same view also creates a pdf which should create a new object and be saved into a separate model 'PackingListDocuments'. Saving the form and updating the 'PackingLists' model is no issue, creating the document is no issue, but how to automatically create a new object in PackingListDocuments I am not sure. models.py class PackingList(models.Model): Reference_Number = models.CharField(max_length=100, null=True) ... class PackingListDocuments(models.Model): Reference_Number = models.ForeignKey(PackingList) PackingListDocument = models.FileField(upload_to='media') views.py def PackingListView(request): if request.method == "POST": form = PackingListForm(request.POST) if form.is_valid(): ... elif 'save' in request.POST: context = request.session['data'] = form.cleaned_data pdf = render_to_pdf('packlist_preview.html', context) filename = "YourPDF_Order{}.pdf" PackingListDocuments.PackingListDocument.save(filename, File(BytesIO(pdf.content))) #this does not work form.save() messages.success(request, "Success: Packing List Has Been Created!") return redirect('HomeView') else: form = PackingListForm() return render(request, 'packlist.html', {'form': form}) -
Django REST: Serialize a ManytoMany field that is within another ManytoMany field
I have a three models with Opportunity being the Serialized model. The Broker model is a M2M field within the Project field. Then the ServiceLines model is a M2M field of Broker model. When I serialize my data, I receive all information about the Broker model related to the Opportunity, however, I do not receive any information on the ServiceLine within the Broker M2M. The following are my Serializers: class ServiceLineSerializer(serializers.ModelSerializer): class Meta: model = ServiceLine fields = ['id', 'servicelinename'] depth = 1 class BrokerSerializer(serializers.ModelSerializer): class Meta: model = Broker fields = ['id', 'fullname', 'primarybl'] depth = 1 primarybl = ServiceLineSerializer(many=True) class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Opportunity fields = [*] depth = 1 broker = BrokerSerializer(many=True) And my models: class Broker(models.Model): firstname = models.CharField(max_length=100, default= "First Name") lastname = models.CharField(max_length=100, default= "Last Name") fullname = models.CharField(max_length=100, default= "Full Name") primarybl = models.ManyToManyField('ServiceLine') class ServiceLine(models.Model): servicelinename = models.CharField(max_length=100) def __str__(self): return self.servicelinename class Opportunity(models.Model): broker = models.ManyToManyField('team.Broker') Thanks for your time! -
Refreshing request in Django
I'm pretty new to Django and I'm trying to build a website, which finds a movie for you. My problem is that sometimes API doesn't find anything and I'm getting error "query must be provided". I'd like to know if there is any way to refresh the request until query is provided? here is my code view def result(req): search_result = req.GET.get('search') movie_genre = req.GET.get('movie_genre') if search_result == '' and movie_genre == 'none': return redirect('/') else: result = search_movie(search_result) if result == None: return redirect('/') else: movie_title = result[0] movie_id = result[1] movie_release_date = result[2] movie_overview = result[3] number_of_movies = result[4] return render(req, 'movie_app/result.html', { 'movie_title': movie_title, 'movie_id': movie_id, 'movie_release_date': movie_release_date, 'movie_overview': movie_overview, 'number_of_movies': number_of_movies, }) Here especially is where I need help: if result == None: return redirect('/') From UX point it seems dumb to redirect to homepage. I'be really thankful for help!