Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I have a question about django models. I was creating a django model in visual studio code. It suggested me below code when I type charfield
class message(medels.Model): messageBody= models.CharField(_(""), max_length=1000) In this code what is _("") this? My IDE suggested me that. Please help me to understand it. -
Can I create an (Java/PHP) application that can connect to sqlite3 in django?
Can I create an application (Java/PHP) that can connect to sqlite3 in django? -
Remove anchor name from Django HttpResponseRedirect or redirect
I don't know if it's a bug or a feature, but when I'm on my home page with the contact form anchor (url = http://localhost:8000/#contact) After submitting the form, all of these will redirect including the #contact anchor name and I cannot get rid of it: from django.http import HttpResponseRedirect from django.urls import reverse from django.shortcuts import redirect # Following 3 lines all send back to http://localhost:8000/#contact return HttpResponseRedirect(reverse('homepage')) return redirect(reverse('homepage')) return redirect('/') # As a test, the following line redirects to http://localhost:8000/account/email/#contact return HttpResponseRedirect(reverse('account:email')) I found some people with the opposite issue, trying to add the anchor name, but can't find a related question with my issue -
How to add a Context `OrderItem` to appear in PDF file from Django Admin
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted Ordered on: {{order.ordered_date}} <----------Showing {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} I even tried removing the forloop but still nothing happened Ordered on: {{order.ordered_date}} <----------Showing {{ order_item.item.title }} <----------Not Showing -
How to multiply fields in Django ModelForm?
I am trying to multiply the price and quantity fields from my modelForm to create a total_value field. I would like the value to populate after the user inputs a value for price and quantity. I have tried creating functions in the model to carry out the multiplication, however, I do not understand how to post the data in the template. Sorry I am very new to programming. Below are the links to my code. forms.py models.py views.py template.html -
filtering relational models inside django forms
i have a model which has a foreign key relation with two oder models one of them is 'level'. the view knows in which level you are based on a session variable, and then filter the lessons this is the lesson model: class Lesson(models.Model): level = models.ForeignKey(Level,on_delete=models.CASCADE) subject = models.ForeignKey(Subject,on_delete=models.CASCADE) chapiter = models.CharField(max_length=200) lesson = models.CharField(max_length=200) skill = models.CharField(max_length=200) vacations = models.IntegerField() link = models.URLField(max_length=700,null=True,blank=True) remarques = models.TextField(null=True,blank=True) order = models.IntegerField() created = models.DateTimeField(auto_now_add=True, auto_now=False) updated = models.DateTimeField(auto_now=True) state = models.BooleanField(default=False) now this is my cbv to create a new lesson: class GlobalLessonView(CreateView): model = Lesson form_class = GlobalLessonForm success_url = reverse_lazy('globalform') and this is the form: class GlobalLessonForm(forms.ModelForm): class Meta: model = Lesson fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['subject'].queryset = Subject.objects.none() #change to .all() to see list of all subjects if 'level' in self.data: try: level_id = int(self.data.get('level')) self.fields['subject'].queryset = Subject.objects.extra(where=[db_name+'.scolarité_subject.id in( select subject_id from '+db_name+'.scolarité_levelsubject where level_id='+level_id+')']) except (ValueError, TypeError): pass # invalid input from the client; ignore and fallback to empty City queryset elif self.instance.pk: self.fields['subject'].queryset = self.instance.level.subject_set one of the main conditions is to filter level by a session variable but the form does not accept request.session so is there any way … -
Downloading PDF files from Django Admin returning UnboundLocalError at /admin/order/(48\d+)/pdf/
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that when I have click on the PDF link in the Admin it returns UnboundLocalError at /admin/order/(48\d+)/pdf/ local variable 'Order' referenced before assignment It is the first time to face this error and I am trying to figure out how to fix it, however know exactly where to look. Here is the views which is the reason for the error @staff_member_required def admin_order_pdf(request, order_id): Order = get_object_or_404(order, id=order_id)<-------------- the order model is showing error html = render_to_string('order/pdf.html', {'order': Order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response Here is the admin def order_pdf(obj): return mark_safe('<a href="{}">PDF</a>'.format(reverse('core:admin_order_pdf', args=[obj.id]))) order_pdf.short_description = 'Order PDF' class OrderAdmin(ImportExportActionModelAdmin): list_display = ['id', 'user', ........, order_pdf] Here is the urls.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Would really appreciate help in figuring this one out. -
Django : Several paths, one ListView, different templates?
Please help me. I want to have multiple path in urls.py (lets say a, and b). But I want to ONLY have one ListView, and this ListView need to channel me to different html file when I access the url (a.html when access 'a/', b.html when access 'b/'). Currently I use different ListView for each path (aListView and bListView), even though the model is the same. But it seems that it violate the Don't Repeat Yourself rule. And the code looks bad. So the question is how can I define several different templates in one ListView? Below is my current mind map. Thank you My mind route -
Sending .py -> .html value to .js (Django, Mapbox)
Below is my code in my main.html file: <body> <h1>mappymappy</h1> <div id='map'></div> <script> mapboxgl.accessToken = '{{ mapbox_access_token }}' var map = new mapboxgl.Map({ container: 'map', style: 'mapbox://styles/mapbox/streets-v11', center: [-73.9911, 40.7051], zoom: 9.5 }) </script> {% for center in drop_in_centers %} <script> new mapboxgl.Marker({ "color": 'red' }) .setLngLat([{{ center.longitude }}, {{ center.latitude }}]) .setPopup(new mapboxgl.Popup({ offset: 25 }) .setHTML("<h2>Drop-in Center</h2><h3>{{center.center_name}}</h3>")) .addTo(map) </script> {% endfor %} I want to move the scripts to a separate .js file. However, in order to do that I have to figure out a way to send the values mapbox_access_token and drop_in_centers to .js file and make the values able to be used in the .js file. How can I do this? +) both mapbox_access_token and drop_in_centers are from views.py file. -
Extending path name in urls.py
Supposed my views.py contain multiple views that are meant to go deeper in the url path. urlpatterns = [ path('<int:table_pk>/order/', views.menu_category_view, name='menu_category_view'), path('<str:menu_category>/', views.menu_item_view, name='menu_item_view'), ] The first view has the path generated as <int:table_pk>/order/. If I want the second view to have a path as following <int:table_pk>/order/<str:menu_category>/, how should i go about passing the variables (in the view and/or template) in DRY manner? What if I have more path levels that need to extend the path above it in this same manner? -
How can I return display values for all selected fields and field names in QuerySet?
I have a Django view that passes templated data to an html page as json. The issue I am having is that the actual database fields and fieldnames are passed instead of the human-readable name and result of get_FOO_display(), respectively. For clarity, here is what my model looks like: class FooBar(models.Model): name = models.CharField('Name', max_length=255) AWAITING_CLASSIFICATION_STATUS = 1 IN_PROGRESS_STATUS = 2 AWAITING_REVIEW_STATUS = 3 CLOSED_STATUS = 4 STATUS_CHOICES = [ (AWAITING_CLASSIFICATION_STATUS, 'Awaiting Classification'), (IN_PROGRESS_STATUS, 'In Progress'), (AWAITING_REVIEW_STATUS, 'Awaiting Review'), (CLOSED_STATUS, 'Closed') ] status = models.IntegerField('Status', choices=STATUS_CHOICES, default=AWAITING_CLASSIFICATION_STATUS) And my view currently: def IndexView(request): foo_list = FooBar.objects.all().values() json_list = json.dumps(list(foo_list)) context = {'foo_list': json_list} return render(request, 'foo-app/index.html', context) And what my data should look like: [ {'Name': "name1", "Status": "Awaiting Classification"}, {'Name': "name2", "Status": "In Progress"}, ] Some ideas I have explored: Iterating over the list and looking up each based on the model (sounds like a lot of extra processing server side). Sending the QuerySet in its entirety and processing it client side (I think this would include more data than I would like to reveal to the client). Storing the data in the database in human readable form (nope). What is the most Pythonic/Djangonic way of doing this? -
User authorization via login does not work
I try to log in, but I get the error: "'str' object is not callable". What can happen? from django.contrib.auth import login, authenticate login="eeiguomfug" pas="B6AFQJTK" user = authenticate(username=login, password=pas) login(request, user) -
Send a queryset from Django views to JQuery
I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side. This is my views file add_field_views.py : from django.http import JsonResponse def drop_down_requests(request): text = request.POST['text'] print("---->", text) from captiq.financing_settings.models import ChoiceGroup response = ChoiceGroup.objects.get(slug="Ja/Nein") output = JsonResponse(response,safe=False) print("output -", output) return output this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views : urlpatterns = [ path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'), ] then is my JQuery which is waiting for the queryset data or JSON data : window.addEventListener('load', function () { (function ($) { "use strict"; $(document).ready(function () { $("#id_depending_field").change(function (event) { console.log("am here man"); const valueSelected = this.value; $.ajax({ type: "POST", url: 'my-ajax-test/', data: { csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value, text: valueSelected }, success: function callback(response) { console.log("____________", response) } }); }) }); })(django.jQuery); }); With the code above am not able to get JSON data in JQuery. What am I doing wrong here ? -
Linking two models automatically in django
I would like when i create new order to be linked to this company. now, i have to choose it manually class Company(models.Model): name = models.CharField(max_length=64) address = models.TextField(max_length=250) class Order(models.Model): company = models.ForeignKey('Company', on_delete=models.CASCADE) order_date = models.CharField(max_length=64) order_notes = models.TextField(max_length=250) -
Is Celery still necessary in Django
I'm creating a web app with Django 3.1 and there's lots of DB interactions mostly between three tables. The queries mostly use results that are recent inputs. So query1 will run and update table1, query2 will use table1 to update2 table2 and query3 will use the column updated by query2 to update other columns of table2. All these run every time users input or update info. Perhaps a visual will be clearer. query1 = Model1.objects.filter(...).annotate(...) query2 = Model2.objects.filter(...).update(A=query1) query3 = Model2.objects.filter(...).update(B=A*C) I'm beginning to worry about speed between python and PostgreSQL and can lose data when multiple users start using it same time. I read about celery and Django Asynchronous support, but it's not clear if I need celery or not. Can someone help me out here please. -
Annotating a count of a superset of fields with Django
So the setup here is I have a Post table that contains a bunch of posts. Some of these rows are different versions of the same post, which are grouped together by post_version_group_id, so it looks like something like: pk | title | post_version_group_id 1 | a | 123 2 | b | 789 3 | c | 123 4 | d | 123 so there are two "groups" of posts, and 4 posts in total. Now each post has a foreign key pointing to a PostDownloads table that looks like post | user_downloaded 1 | user1 2 | user2 3 | user3 4 | user4 what I'd like to be able to do is annotate my Post queryset so that it looks like: pk | title | post_version_group_id | download_count 1 | a | 123 | 3 2 | b | 789 | 1 3 | c | 123 | 3 4 | d | 123 | 3 i.e have all the posts with the same post_version_group_id have the same count (being the sum of downloads across the different versions). At the moment, I'm currently doing: Post.objects.all().annotate(download_count=models.Count("downloads__user_downloaded, distinct=True)) which doesn't quite work, it annotates a download_count which looks like: … -
DRF add non model fields just to update or create model instance
I have this issue at the moment with DRF. I'm recieving extra fields that the model is not using. But those values will define the fields within the model. { "file_name": "test", "file_type": "jpg", "file": basex64 file, "url_img": null } And i got this model class imageModel(models.Model): id = models.AutoField(primary_key=True) url_img = models.textField(null=False) All I need is to parse file_name and file_type to upload img to create a url_img and upload it on cloud. Is there a way to do this via DRF? -
I am downloading a file from google drive and want to save to the django model with s3 configured, how should i save it?
i mean it didn't uploaded to s3. Note this is an automation task. -
Build completed, but View Docs links broken
I have installed a local ReadTheDocs server and think I am very close to having it working. However, while the build of my documentation project says that it is complete, and I can see the generated files under the readthedocs.org/media/html/cadd-faq/latest directory, the View Docs links from the build page generate a 404 page with the following debugging information. Using the URLconf defined in readthedocs.urls, Django tried these URL patterns, in this order: ^$ [name='homepage'] ^support/ [name='support'] ^security/ ^.well-known/security.txt$ ^search/$ [name='search'] ^dashboard/ ^profiles/ ^accounts/ ^accounts/ ^notifications/ ^accounts/gold/ ^builds/ ^500/$ ^projects/ ^api/v2/ ^api/v2/docsearch/$ [name='doc_search'] ^api/v2/search/$ [name='search_api'] ^api-auth/ ^api/v3/ ^wipe/(?P<project_slug>(?:[-\w]+))/(?P<version_slug>(?:[a-z0-9A-Z][-._a-z0-9A-Z]?))/$ [name='wipe_version'] ^i18n/ ^admin/ ^media/epub(?P.)$ ^media/htmlzip(?P.)$ ^media/json(?P.)$ ^media/pdf(?P.*)$ style-catalog/$ ^media/(?P.+)$ [name='media-redirect'] ^debug/ The current path, docs/cadd-faq/en/latest/, didn't match any of these. I can manually point my browser at the URL ".../media/html/cadd-faq/latest/index.html" which redirects to ".../static/html/cadd-faq/latest/index.html" and view the sphinx generated content, so the build appears to really have succeeded. But those pages do not have the ReadTheDocs wrapping content that I would expect the View Docs button to have sent me to, so those URLs are certainly not the right ones either. That all would seem to indicate that the problem is with something in my ReadTheDocs and/or Django configuration. Any pointers to how … -
Django/Python - How to show "task" ONLY if the user is author or responsable of this task
I'm new to python and django and I need some help, please. What I'm trying to do is to only show a certain "task" if the user is responsable or author of the "task" in question. I was trying to do that with a if statement in html template: {% for task in task_list %} <h2>title - {{task.title}}</h2> {% endfor %} {% endif %} But does not return what I expected since: {% for task in task_list %} <h2>author --- {{task.author}}</h2> <h2>responsable --- {{task.responsable}}</h2> {% endfor %} Returns me the same user... I think the problem is that when I refer user.username it goes to the db and returns a query, and when I user {{task.blablabla}} its a string, I'm right? How I can fix that? models.py: title = models.CharField(max_length=50) content = models.TextField(blank=True) date_created = models.DateTimeField(auto_now_add=True) due_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE, default=User) responsable = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=User) STATUS_CHOICES = [('D', 'Done'),('P','Doing'),('N','Not done')] Status = models.CharField(max_length=1,choices=STATUS_CHOICES, default='N') IMPORTANCE_CHOICES = [('H', 'High'),('M','Medium'),('L','Low')] importance = models.CharField(max_length=1,choices=IMPORTANCE_CHOICES, default='M') DEPARTAMENT_CHOICES = [('D', 'Dev'),('M','Marketing'),('H','Human Resources'),('L','Legal'),('F','Financial'),('O','Others')] departament = models.CharField(max_length=1,choices=DEPARTAMENT_CHOICES, default='M') def __str__(self): return self.title views.py def dashboard_taskapp(request): task = Task.objects.all() context = { "task_list": task, } return render(request, "task_app/task_dashboard.html", context) Thanks in advance and … -
Django Foreign Key Mismatch; Two FKs in one table, first FK works, second does not
I have a Model Form that is taking drop down inputs from 2 models for Car Make and Car Model. Car Make FK works fine but when I added the FK for Car Model it did not work, since they are essentially the same code I'm really puzzled. Below I will show the Car Make and Car Model Models, as well as a Model for Garage Inventory and it's related Model Form. Any help much appreciatted. Models.py class MotorMakes(models.Model): MotorMakeName = models.CharField(max_length=50, unique=True, default=False) def __str__(self): return self.MotorMakeName or '' def __unicode__(self): return u'%s' % (self.MotorMakeName) or '' class MotorModelsV2(models.Model): MotorMakeName = models.CharField(max_length=50, default=False,) MotorModelName = models.CharField(max_length=100, unique=True, default=False) Mkid = models.ForeignKey(MotorMakes,on_delete=models.CASCADE, default=False, null=True) Mlid = models.IntegerField(default=False, unique=True) MotorImage = models.ImageField(upload_to='Car_Pics', default='Car_Pics/default.png',blank=True) class GarageInventory(models.Model): MotorDetailRef = models.ForeignKey(MotorDetail, on_delete=models.CASCADE, null=True) GarageID = models.CharField(max_length=5, default='',) ListMake= models.ForeignKey(MotorMakes,on_delete=models.CASCADE, to_field='MotorMakeName', default=False, null=True) ListModel= models.ForeignKey(MotorModelsV2,on_delete=models.CASCADE, to_field='MotorModelName', default=False, null=True) ListSeries = models.CharField(max_length=50, default='', null=True) Title = models.CharField(max_length=100, default='', null=True) BodyType = models.CharField(max_length=25, default='', null=True) GaragePrice = models.DecimalField(max_digits=10, decimal_places=2, default='0') FuelType = models.CharField(max_length=15, default='') Colour = models.CharField(max_length=15, default='') CarEngine = models.CharField(max_length=10, default='', null=True) DoorType = models.CharField(max_length=10, default='', null=True) Year = models.CharField(max_length=10, default='', null=True) created_date = models.DateTimeField(default = timezone.now) Forms.py ##############Garage Car Input Forms############### class GarageCarForm(ModelForm): GarageID = … -
How to order queryset based on best match in django-rest-framework?
I am trying to order results of a query with parameters by number of matches. For example, let's say we have a Model: class Template(models.Model): headline = CharField(max_length=300) text = TextField() image_text = TextField(max_length=500, blank=True, null=True) tags = TaggableManager(through=TaggedItem) ... With a Serializer: class TemplateSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Template fields = (...) And a ViewSet: class TemplateViewSet(viewsets.ModelViewSet): """ API endpoint that allows Templates to be viewed or edited. """ queryset = Template.objects.all() serializer_class = TemplateSerializer def get_queryset(self): queryset = Template.objects.all() tags = self.request.query_params.getlist('tags', None) search_text = self.request.query_params.getlist('search_text', None) if tags is not None: queries = [Q(groost_tags__name__iexact=tag) for tag in tags] query = queries.pop() for item in queries: query |= item queryset = queryset.filter(query).distinct() if search_tags is not None: queries = [Q(image_text__icontains=string) | Q(text__icontains=string) | Q(headline__icontains=string) for string in search_tags] query = queries.pop() for item in queries: query |= item queryset = queryset.filter(query).distinct() What I need to do is count every match the filter finds and then order the queryset by that number of matches for each template. For example: I want to find all the templates that have "hello" and "world" strings in their text, image_text or headline. So I set the query parameter "search_text" to hello,world. Template with … -
AttributeError at /posts/create/ : 'str' object has no attribute 'set' when trying to parse hashtags from title field and save it in tags field
I am trying to parse hashtags from title field and save to tags field with a post_save signal in django. I am using django-taggit package for tags but getting this error while saving the form.save_m2m. Can someone help to solve this error? this is the link to the package: https://django-taggit.readthedocs.io/en/latest/getting_started.html signal.py def parse_hash_tags(sender, instance, created, **kwargs): post_save.disconnect(parse_hash_tags, sender=Post) instance.tags = ','.join(re.findall(r'(?:#(\w+))', instance.title)) instance.save() post_save.connect(parse_hash_tags, sender=Post) post_save.connect(parse_hash_tags, sender=Post) traceback Traceback: File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in view 71. return self.dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\mixins.py" in dispatch 52. return super().dispatch(request, *args, **kwargs) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\views\generic\base.py" in dispatch 97. return handler(request, *args, **kwargs) File "C:\danny\Study\test\posts\views.py" in post 231. form.save_m2m() File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py" in _save_m2m 441. f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\danny\AppData\Local\Programs\Python\Python38-32\lib\site-packages\taggit\managers.py" in save_form_data 517. getattr(instance, self.name).set(*value) Exception Type: AttributeError at /posts/create/ Exception Value: 'str' object has no attribute 'set' -
How to activate virtual envirooment for existing django project using pipenv in python 3.8
I developed a Django webapp project using Django 2.2.1 in python 3.7.2 in a pipenv version 2018.11.26 virtual environment in MacBook Air. After an unintentional update to python 3.8 using brew upgrade, there were problems to work on my webapp and launching it. I installed pipenv pip3 install pipenv, and copied and pasted project folder, and used it with an another name, deleted Pipfiles, and ran pipenv install, but there were error: ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: .... .... After several hours of trial and error, I found the problem is with the version of some packages in my requirements.txt. I have these packages in my project: backports.csv==1.0.7 certifi==2019.3.9 chardet==3.0.4 defusedxml==0.6.0 diff-match-patch==20181111 Django==2.2.1 django-allauth==0.39.1 django-ckeditor==5.6.1 django-crispy-forms==1.7.2 django-finalware==1.0.0 django-import-export==1.2.0 django-js-asset==1.2.2 django-recaptcha==2.0.5 et-xmlfile==1.0.1 gunicorn==19.9.0 html5lib==1.0.1 idna==2.8 jdcal==1.4 numpy==1.16.3 oauthlib==3.0.1 odfpy==1.4.0 openpyxl==2.6.1 pandas==0.24.1 Pillow==5.4.1 psycopg2==2.7.7 psycopg2-binary==2.7.7 pycparser==2.19 pyparsing==2.3.1 PyPDF2==1.26.0 Pyphen==0.9.5 python-dateutil==2.8.0 python3-openid==3.1.0 pytz==2019.1 PyYAML==3.13 reportlab==3.5.21 requests==2.21.0 requests-oauthlib==1.2.0 six==1.12.0 sqlparse==0.3.0 tablib==0.13.0 urllib3==1.24.3 webencodings==0.5.1 whitenoise==4.1.2 xhtml2pdf==0.2.3 xlrd==1.2.0 xlwt==1.3.0 The first problem was for pandas 0.24.1, and I removed its version number, then pipenv succeeded to lock but it failed to install two other packages Pipfile.lock not found, creating… Locking [dev-packages] dependencies… Locking [packages] dependencies… Building requirements... Resolving dependencies... ✔ Success! … -
How to limit add to a model in django
How to limit add to a model in django ? i would like to create only one company on this model, only one, so if user want to add more, it s not possible. class Company(models.Model): name = models.CharField(max_length=64) address = models.TextField(max_length=250)