Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django+AWS(Ubuntu Instance)+uWsgi+Nginx Fatal Python error: ModuleNotFoundError: No module named 'encodings'
I am deploying a django Rest API webservice in AWS and using uwsgi,inginx. Everything worked fine but webiste was not live even after running the serverConnection timed out was displayed in browser. After running this command sudo uwsgi --ini /etc/uwsgi/sites/Ftlabs.ini i got status log which says Python version: 3.6.9 (default, Nov 7 2019, 10:44:02) [GCC 8.3.0] !!! Python Home is not a directory: /home/ubuntu/venv !!! Set PythonHome to /home/ubuntu/venv Fatal Python error: Py_Initialize: Unable to get the locale encoding ModuleNotFoundError: No module named 'encodings' Current thread 0x00007f3951cf6740 (most recent call first): Aborted As i am beginner and this is my first deployment.I searched every possible keyword but not happen to find a solution. someone please help me with that. And for reference i was following this blog post Complete Guide to Deploy Django Applications on AWS Ubuntu Instance with uWSGI and Nginx -
i m getting application error while i tried to run my app on browser , here is my logs trail
Build failed -- check your build output: https://dashboard.heroku.com/apps/e4bf9e0a-b140-4621-bff8-a3db7868ed46/activity/builds/5bc61c28-f49d-4124-bb64-00fb0fb79292 error code=H14 desc="No web processes running" method=GET path="/" host=pachalibhairav.herokuapp.com request_id=b89caaf1-1a0d-435b-83b2-835bc4cbd732 fwd="27.34.13.152" dyno= connect= service= status=503 bytes= protocol=http -
Grabbing object instance id from request.POST when using javascript e.preventDefault()
I am using a bootstrap modal to list object instances and perform CRUD operations. I wrapped the entire list in a form and pass the id of each object instances to the view using buttons names and value. When I delete the object without using Javascript, the view works fine, but as soon as I add the line e.preventDefault(); then the id of the object is not captured in the request anymore. why is that ? In more detail, the template looks like this: <form action="{% url 'delete_habit' %}" method="POST" id="deleteForm">{% csrf_token %} <div class="row"> <div class="col-12 pb-3"> <table class="modal-table border" id="habitsTable"> <tbody> {% for habit in habits %} <tr class="border js-row-{{habit.id}}"> <td class="border"> <img src="{% static 'img/bars_icon.svg' %}"> </td> <td class="text-left border px-3">{{habit.name}}</td> <td class="border"> <button id="delete-{{habit.id}}" type="submit" value="{{habit.id}}" name="habit_id" class="btn"> <img src="{% static 'img/minus_icon.svg' %}"> </button> </td> </tr> {% endfor %} </tbody> </table> </div> </div> </form> the view: def delete_habit(request): habit_id = request.POST.get('habit_id') --> this fails when e.preventDefault() data = {'habit_deleted': int(habit_id)} habit_to_delete = Habit.objects.filter(id=int(habit_id)).filter( user=request.user) habit_to_delete.delete() return JsonResponse(data) the javascript: var deleteForm = document.getElementById('deleteForm'); if (deleteForm !== null){ deleteForm.addEventListener('submit', function(e){ var formData = new FormData(deleteForm); e.preventDefault(); --> this empties the request (except the csrf token) var request … -
Currently working on Python/Django project.I have to display ppt and doc files onto the browser but it doesnt accept the format
I have tried to you use iframe for the same.. It works well with pdf files,but unable to open ppt and doc files..Is there any solution/api's available in python/django for the same? -
How to Nested Categories in django admin
I want to create muti category in my ecommerce website where sub category will be dependent on main category. Please help me with this class MainCategory(models.Model): # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class SubCategory(models.Model): # perentcategory = models.OneToOneField(MainCategory, on_delete=models.CASCADE, primary_key=True) # name = models.CharField(max_length=50) # date_created = models.DateTimeField(auto_now_add=True) # def __str__(self): # return self.name # class Items(models.Model): # main = models.ForeignKey(SubCategory, on_delete=models.CASCADE) # name = models.CharField(max_length=255) Posting this question 4th time -
Using the URLconf defined in crp1.urls, Django tried these URL patterns,admin/ The current path, register.html, didn't match any of these.**
page not found error in django i got 404 error my url is http://127.0.0.1:8000/register.html and error is like Using the URLconf defined in crp1.urls, Django tried these URL patterns, in this order: [name='index'] register [name='register'] admin/ The current path, register.html, didn't match any of these. i created one folder for projects in that i started reglog application in crp1 forlder and index page i am gettting but when i click form index.html for sing up page its say aboventer code heree error in my application url file i coded: urlpatterns=[path('',views.index, name='index'),path('register', views.register, name='register')] in views file: def index(request): return render(request,'index.html') def register(request): return render(request,'register.html') and in my project name crp1 file i write following code in ''' "crp1.urls: urlpatterns' = [ path('', include('reglog.urls')), path('admin/', admin.site.urls)' ''' and in register.html ''' <a href="register.html"> </a> ''' -
my first django project and the images_url dosent load anything every thing works perfectly but but the images wont load
i am making like a demo website that sells fruits i am following a youtube tutorial by (code with mosh) his images loaded properly but my images wont other things like add to cart button and name of product loaded properly. I am very new to programming so please try not to use complex programming terms for answer and thanks to anyone who will be trying to help me. admin.py from django.contrib import admin from .models import Product, Offer class OfferAdmin(admin.ModelAdmin): list_display = ('code', 'discount') class ProductAdmin(admin.ModelAdmin): list_display = ('name', 'price', 'stock') admin.site.register(Product, ProductAdmin) admin.site.register(Offer, OfferAdmin) apps.py from django.apps import AppConfig class ProductsConfig(AppConfig): name = 'products' models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=255) price = models.FloatField() stock = models.IntegerField() image_url = models.CharField(max_length=2083) class Offer(models.Model): code = models.CharField(max_length=10) description = models.CharField(max_length=255) discount = models.FloatField() urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index), path('new', views.new) ] views.py from django.http import HttpResponse from django.shortcuts import render from .models import Product def index(request): products = Product.objects.all() return render(request, 'index.html', {'products': products}) def new(request): return HttpResponse('New products') -
How to create related objects in serializer and serialize it
Hey, I'm working in Django 2.2. I have problem with serialize data with custom create function. Let's say we have 2 models: class Model1(models.Model): a = models.CharField(max_length=200) b = models.IntegerField() class Model2(models.Model): c = models.ForeignKey(Model1, on_delete=models.CASCADE d = models.CharField(max_length=150) class Model3(models.Model): e = models.ForeignKey(Model1, on_delete=models.CASCADE) This models have serializers: class Model2Serializer(serializer.ModelSerializer): class Meta: model = models.Model2 fields = ['d'] class Model1Serializer(serializer.ModelSerializer): model2_set = Model2Serializer(many=True) class Meta: model = models.Model1 fields = ['a', 'b', 'model2_set'] def create(self, validated_data): model2_params = validated_data.pop(u'model2_set', []) model1 = super(Model1Serializer, self).create(validated_data) model2_objects = [models.Model2(model1=model1, **model2_params) for model2_param in model2_params] models.Model1.objects.bulk_create(model2_objects) return model1 class Model3Serializer(serializer.ModelSerializer): model1 = Model1Serializer() class Meta: model = models.Model3 fields = ['model1'] This custom create function is work good. My problem is that now I want to get nested data in Model3 serializer. -
Django 2.3 Inside get_absolute_url, Reverse for 'post_detail' not found
Main urls.py includes: path('', include('page.urls', namespace='page')) Page app urls.py app_name = 'page' urlpatterns = [ path('', views.home, name='home'), path('page/<slug:slug>/', views.page_detail, name='post_detail'), ] Page app models.py class Page(models.Model): . . . def __str__(self): return '{} by {} {}'.format(self.title, self.created, self.is_active) def get_absolute_url(self): return reverse("page_detail", kwargs= {"slug": self.slug }) In page app views.py: def home(request): pages = Page.objects.filter(is_active=1) context = { "pages":pages } return render(request,'page/home.html', context) def page_detail(request, slug): details = get_object_or_404(Page, slug=slug, is_active='1') return render(request,'page/details.html', {'details': details}) In the menu.html under templates/page: <nav class="collapse navbar-collapse bs-navbar-collapse navbar-right" role="navigation"> <ul class="nav navbar-nav"> {% for obj in pages %} <li><a href='{{obj.get_absolute_url}}'>{{ obj.title }}</a></li> {% endfor %} </ul> </nav> Please tell why i am getting: Reverse for 'page_detail' not found. 'page_detail' is not a valid view function or pattern name. But if I use <li><a href='/page/{{obj.slug}}'>{{ obj.title }}</a></li> in menu.html under templates/page it's working properly. The get_absolute_url is not working properly. Where I'm doing wrong. Please help me. -
Static files not serving on production with AWS, Bitnami Django Stack & Apache
I'm trying to deploy my existing Django project to an AWS Lightsail instance with Bitnami Django Stack & Apache, per Amazon's docs. (https://aws.amazon.com/getting-started/projects/deploy-python-application/?nc1=h_ls) While I was able to set up a new instance to serve my existing project, static files are not being served when the project is configured for production with DEBUG=False. I have run python3 manage.py collectstatic, verified that all my static files are collected in /opt/bitnami/apps/django/django_projects/PROJECT_NAME/static, and made sure the correct path is specified as the Alias for /static in httpd-app.conf: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/PROJECT_NAME/PROJECT_NAME"> Options +MultiViews AllowOverride All <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} </Directory> Alias /static "/opt/bitnami/apps/django/django_projects/PROJECT_NAME/static" WSGIScriptAlias /PROJECT_NAME '/opt/bitnami/apps/django/django_projects/PROJECT_NAME/PROJECT_NAME/wsgi.py' I have specified STATIC_URL and STATIC_ROOT in settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static/") Also, I restarted Apache for each change I have made. When running in the Django development server with DEBUG=True, static files can be accessed. However, in production with DEBUG=False the browser gives 404 when accessed via URL http://IP_ADDRESS/static/FILE_NAME. Please help. Thank you. -
DRF jwt error message type' object is not iterable and 'return [auth() for auth in self.authentication_classes]'
I'm making DRF api and i get TypeError message when I try to request. This message is preventing me from even debugging. I am looking for a way and I checked settings.REST_FRAMEWORK. This is my project code address: https://github.com/jeonyh0924/WPS_DabangAPI/tree/d13d6b440d2a5a1dfd3e17318bee14d02544f6a5 I am studying through the corresponding addres : https://medium.com/analytics-vidhya/django-rest-api-with-json-web-token-jwt-authentication-69536c01ee18 Thanks for reading. Have a nice day :) -
How to override external app template in Django?
I tried overriding a django-recaptcha template without any luck. What am I doing wrong? I am aware of Override templates of external app in Django, but it is outdated. Thanks! django-recaptcha file structure Lib/ --site-packages/ ----captcha/ ------templates/ --------captcha/ ----------includes/ ------------js_v2_checkbox.html my project file structure project/ ----templates/ --------captcha/ ------------includes/ ----------------js_v2_checkbox.html settings.py TEMPLATES = [ { ... 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, ... }, ] -
how to insert foreign key data through Django Model form
How to insert foreign key data through form. Please help . what am I doing wrong So I have two models as follows : class Genre(models.Model): """Model representing a book genre.""" name = models.CharField(max_length=200, help_text='Enter a book genre (e.g. Science Fiction)') def __str__(self): """String for representing the Model object.""" return self.name ass UserItem(models.Model): name= models.CharField(max_length = 50, null=True) genre = models.ForeignKey(Genre, on_delete=models.SET_NULL, null=True) Forms.py : I want to create form to store Item data. Not able to reference Genre and enter value through form. class ItemForm(forms.ModelForm): name = forms.CharField() genre = forms.CharField() class Meta: model = UserItem fields = ['name', 'genre' ] Views.py def item(request): if request.method == 'POST': genre_obj = Genre.objects.get(name=request.POST.get('name')) print("Inside post") item_form = ItemForm(request.POST) if item_form.is_valid(): print("valid form") item_form_obj = ItemForm.save(commit=False) item_form_obj.genre = genre_obj item_form_obj.save() return HttpResponseRedirect(reverse('file_upload') ) else: print("invalid form") return HttpResponseRedirect(reverse('file_list') ) -
I want to use {{ }} in {% %}
```{% if request.user|has_group:"course_{{ couese.id }}" %}``` to achieve: request.user|has_group:"course_1" but doesn't meet the rules.So I want to ask for help,thanks. -
Add multiple images to a blog post using Django Ajax
I am trying to add multiple images to a post using Ajax in Django, but I cannot manage to do that with my current views as to when I upload an image I do not see it being added to the image list and my progress bar does not hide after being 100%. Currently, I have managed to create post object successfully but I do not know how to link and images to a post before the post is created, right now below are my codes: home/views.py class PostImageUpload(LoginRequiredMixin, View): def get(self, request): images = post.image_set.all() return render(self.request, 'home/posts/post_create.html', {'images':images} ) def post(self, request): data = dict() form = ImageForm(self.request.POST, self.request.FILES) if form.is_valid(): image = form.save(False) image.save() data = {'is_valid': True, 'name': image.file.name, 'url': image.file.url} else: data['is_valid'] = False return JsonResponse(data) @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): post = form.save(False) post.author = request.user #post.likes = None post.save() data['form_is_valid'] = True posts = Post.objects.all() posts = Post.objects.order_by('-last_edited') data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts},request=request) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) home/models.py: class Post(models.Model): title = models.CharField(max_length=100) content = models.TextField(validators=[MaxLengthValidator(250)]) author = models.ForeignKey(Profile, on_delete=models.CASCADE) date_posted … -
Django_auth_ldap authentication with Microsoft AD issue
I'm unable to login to django application using AD authentication. Versions: Python 3.7 django-auth-ldap 2.1.1 python-ldap 3.2.0 OS - Windows 10 AD config -- Please see attached image... Here is my settings.py import ldap from django_auth_ldap.config import LDAPSearch AUTH_LDAP_SERVER_URI = 'ldap://Servername_xxx' AUTH_LDAP_ALWAYS_UPDATE_USER = False AUTH_LDAP_SEARCH_DN = "OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET" AUTH_LDAP_BIND_DN = "" AUTH_LDAP_BIND_PASSWORD = "" AUTH_LDAP_USER_SEARCH = LDAPSearch("OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET", ldap.SCOPE_SUBTREE, "sAMAccountName=%(user)s") AUTH_LDAP_CONNECTION_OPTIONS = { ldap.OPT_REFERRALS: 0 } AUTH_LDAP_USER_ATTR_MAP = { "username": "sAMAccountName", "first_name": "givenName", "last_name": "sn", "email": "mail", } from django_auth_ldap.config import ActiveDirectoryGroupType AUTH_LDAP_GROUP_SEARCH = LDAPSearch( "DC=DEV,DC=TCORP,DC=NET", ldap.SCOPE_SUBTREE, "(objectCategory=Group)" ) AUTH_LDAP_GROUP_TYPE = ActiveDirectoryGroupType(name_attr="cn") AUTH_LDAP_USER_FLAGS_BY_GROUP = { "is_superuser": "cn=django-admins,cn=users,DC=DEV,DC=TCORP,DC=NET", } AUTH_LDAP_FIND_GROUP_PERMS = True AUTH_LDAP_CACHE_GROUPS = True AUTH_LDAP_GROUP_CACHE_TIMEOUT = 1 # 1 hour cache AUTHENTICATION_BACKENDS = [ "django.contrib.auth.backends.ModelBackend", "django_auth_ldap.backend.LDAPBackend", ] # ERROR message in the console: search_s('OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET', 2, 'sAMAccountName=jsmith') raised OPERATIONS_ERROR({'desc': 'Operations error', 'info': '000004DC: LdapErr: DSID-0C090A6C, comment: In order to per form this operation a successful bind must be completed on the connection., data 0, v3839'}) search_s('OU=Contractors,OU=DEV Users,DC=DEV,DC=TCORP,DC=NET', 2, 'sAMAccountName=%(user)s') returned 0 objects: Authentication failed for jsmith: failed to map the username to a DN. # -
Django ORM - updating specific instance with a user-ForeignKey
I have the following model setup: class Model1(models.Model): val1_1 = models.CharField(max_length=25, blank=True) val1_2 = models.CharField(max_length=25, blank=True) user = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='model1') class Model2(models.Model): val2_1 = models.BinaryField() model1_link = models.ForeignKey(Case, on_delete=models.CASCADE, related_name='model2') class Model3(models.Model): id = models.BigAutoField(primary_key=True) model2_link = models.ForeignKey(Model2, on_delete=models.CASCADE, related_name='model3') val3_1 = models.CharField(max_length=50) class Model4(models.Model): id = models.BigAutoField(primary_key=True) model3_link = models.ForeignKey(Model3, on_delete=models.CASCADE, related_name='model4', null=True, default=None) pred = models.CharField(max_length=50) # These fields are NOT FILLED IN during creation of an instance, and are instead updated later on with a separate query disputed_on = models.DateTimeField(blank=True, null=True) suggested_by = models.ForeignKey('users.User', on_delete=models.PROTECT, related_name='submitted_disputes', blank=True, null=True) At times, I will want to access Model4's specific instance, to actually fill in a value in fields disputed_on & suggested_by, by traversing all the way from Model1. I do that currently as such: query = Model1.objects.filter(id=some_chosen_id).get().model2.last().model3.filter(val3_1=some_chosen_value).get().model4.last() The output of that query is a single model instance, not a QuerySet. Next, I calculate new values I want to insert: dispute_date = datetime.now(tz.tzutc()) if request.user.is_authenticated: disputer = request.user else: # Assume admin (first entry) disputer = User.objects.get(pk=1) And I save new values by doing the following: query.disputed_on = dispute_date query.suggested_by = disputer query.save() Now, the strangest thing happens - my postgres DB gives me an error stating, the following: … -
Converting ndarray to Base64
A user uploads an image, if that user doesn't have another image to upload then that image is saved. We then take that image, slice it in two halves. The first half gets saved again. As for the second image, we need to convert it into a Base64 Image. However, for some reason I'm getting this error: ValueError: ndarray is not C-contiguous img = q.choice_set.all()[0].img reader = misc.imread(img) height, width, _ = reader.shape with_cutoff = width // 2 s1 = reader[:, :with_cutoff] s2 = reader[:, with_cutoff:] misc.imsave(settings.MEDIA_ROOT + "/" + img.name, s2) validated_data["choiceimage"] = base64.b64encode(s2) When I save this in the database, I get an error. What am I doing wrong? How can I decode the numpy array into base64? -
How make backend to work by java spring in python Django , Tensorflow with sql?
Create a back end, link the Java spring framework to the Python Django web project, add the Tensorflow framework, and ultimately link the sql database. عمل back end وربط اطار Java spring في مشروع الويب Python Django واضافة اطار Tensorflow وبالنهاية ربط قاعدة البيانات sql -
Ajax, not appending to table list and doesnt hide progress bar
I am trying to upload images using an Ajax request in Django with a status bar, however, after reaching 100% my status bar doesn't hide and images are not prepended tu the table. I was wondering what's the issue in my javascript code. my js code: $(document).ready(function(){ $(".js-upload-images").click(function () { $("#fileupload").click(); }); $("#fileupload").fileupload({ dataType: 'json', sequentialUploads: true, start: (e) => { $("#container-progress").show(); }, stop: (e) => { $("#container-progress").hide(); }, progressall: function (e, data) { var progress = parseInt(data.loaded / data.total * 100, 10); var strProgress = progress + "%"; $(".progress-bar").css({"width": strProgress}); $(".progress-bar").text(strProgress); }, done: function (e, data) { if (data.result.is_valid) { $("#image_list tbody").prepend( "<tr><td><a href='" + data.result.url + "'>" + data.result.name + "</a></td></tr>" ) } } }); }); my post_create html file: {% load crispy_forms_tags %} {% load static %} <script src="{% static 'js/image_upload.js' %}"></script> <script src="{% static 'js/jquery-file-upload/vendor/jquery.ui.widget.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.iframe-transport.js' %}"></script> <script src="{% static 'js/jquery-file-upload/jquery.fileupload.js' %}"></script> <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ form|crispy }} </div> <div class="my-3 mx-3"> <button type="button" class="btn btn-sm mr-auto btn-primary js-upload-images"> <span><i class="fas fa-camera"></i></span> </button> <input id="fileupload" type="file" name="file" … -
Unable to render plotly graph to template in django
I am trying to plot a plotly graph to my django template but unable to do so, getting a blank template. views.py #plotly libraries used import plotly.graph_objects as go import plotly.express as px import plotly.offline as py def home(request): df=index(request) #returns a dataframe #overall cases total_df = df.groupby(['Country'])['Total Cases'].sum() total_df = total_df.reset_index() fig0 = px.scatter_geo(total_df,locations="Country", locationmode='country names', color="Total Cases", size='Total Cases',hover_name="Country", projection="orthographic",color_continuous_scale=px.colors.sequential.deep, ) fig0 = go.Figure(data=fig0) plot_div0 = py.plot(fig0, include_plotlyjs=False, output_type='div',config={'displayModeBar': False}) return render(request, 'test/welcome.html', {'plot_div0':plot_div0}) welcome.html {{ plot_div0 | safe }} -
Accessing Djnago generic DetialView directly from CreateView
I'm trying to acomplish the following functionality: the user enters required information in the form created using generic CreateView, in this case it is length and width. After the form is submitted the app performs simple calculations and returns the result along with submitted data. I tried to follow this example: [https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Generic_views My models: from django.db import models class Building(models.Model): length = models.IntegerField(default=1) width = models.IntegerField(default=1) area = models.IntegerField(default=1) def __str__(self): return self.name def save(self, *args, **kwargs): self.area = self.length * self.width super().save(*args, **kwargs)re views: class BuildingDetailView(DetailView): model = Building context_object_name = 'building' class BuildingCreateView(CreateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building-detail') class BuildingListView(ListView): model = Building class BuildingUpdateView(UpdateView): model = Building form_class = BuildingForm success_url = reverse_lazy('building_detail') urls: path('', views.indexView, name='index'), path('add_temp/', views.BuildingCreateView.as_view(), name='building_add'), path('buildings/', views.BuildingListView.as_view(), name='building_changelist'), path('building/<int:pk>/', views.BuildingDetailView.as_view(), name='building-detail'), html: {% extends 'base.html' %} {% block content %} <h1>Title: </h1> {% for object in object_list %} <p><strong>Length:</strong> {{ object.length }}</p> <p><strong>Width:</strong> {{ object.width }}</p> <p><strong>Area:</strong> {{ object.area }}</p> {% endfor %} {% endblock %} This setup is giving me the following error. I assume the problem is in my template: File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\User\AppData\Local\Programs\Python\Python36\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, … -
How do you use ManyToManyFields between apps without producing circular imports?
I have two apps, users and posts, with the models CustomUser and Block in users, and a model Post in posts. I'd like to created a "bookmarked" ManyToMany field for the User, so that they can bookmark any posts they want. It would look something like: class CustomUser(AbstractUser): ... neighbors = models.ManyToManyField("CustomUser", blank=True) blocks = models.ManyToManyField("Block", blank=True) bookmarked = models.ManyToManyField("Post", blank=True) ... As you can see, I have quite a few ManyToMany fields already, but they were all for models from the same app users. As for my Post class: class Post(models.Model): ... author = models.ForeignKey(CustomUser, on_delete=models.CASCADE) block = models.ForeignKey(Block, null=True, on_delete=models.SET_NULL) ... I already imported two models from the users app, CustomUser and Block, into the posts app. I understand that by importing Post into users' models.py, it creates a circular import, at least, it gives me the following error: ImportError: cannot import name 'CustomUser' from partially initialized module 'users.models' (most likely due to a circular import) Is there a way to prevent this? I know an option is to just create the bookmarked attribute in the Post model instead of the User model, but I'm reluctant to do so simply because it's a little weird to me personally. … -
Django drop down list dependant on model?
I'm trying to make a drop down list dependent on a model. For example my app has a "store" model, when a user is created a store is set for them. Stores can have employees. When a logged in user accesses this drop down list, I want to list all the employees that are associated with the store that the user. What is the best way to do this? -
Como utilizar ManyToManyField no html para inserção de dados
forms.py from app_teste.models import Diario class FormDiario(forms.ModelForm): class Meta: model = Diario fields = '__all__' models.py from django.db import models class Diario(models.Model): nome = models.CharField('Nome', max_length=50) DiarioDescricao = models.ManyToManyField('Equipamento') class Equipamento(models.Model): descricao = models.CharField('Descrição', max_length=50) views.py from django.shortcuts import render, redirect # Create your views here. from app_teste.forms import FormDiario def index(request): if request.method == "POST": form = FormDiario(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = FormDiario() return render(request, 'index.html', locals()) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>INICIAL</title> </head> <body> <h1>Pagina Inicial</h1> <div> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Finalizar</button> </form> </div> </body> </html> No template index, quero inserir vários equipamentos, porem sou iniciante e não tenho ideia de como fazer isso, sem sair da pagina. Estou usando ManyToManyField pois na documentação o encontrei e pelo que entendi, da para adicionar vários objetos dentro da mesma tabela. Mas não sei como eu faria no template para poder realizar essa inserção. Me ajudem! Obs: NÃO É NENHUM ERRO, APENAS UMA DUVIDA E UM PEDIDO DE AJUDA!