Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create relationships between django models
I have the two models, One is the User model and the other is a Contact model. The Contact model is as follows: class Contact(models.Model): pass user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('User'), related_name="user") contact = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, null=True, on_delete=models.CASCADE, verbose_name=_('Contact'), related_name="contact") created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=True, auto_now_add=False) is_contact = models.BooleanField(default=False) Basically, what is does is create a contact for a user. Kind of a friend request and accept simple model. So the loggedIn user(request.user) could be either the contact.user or contact.contact. And the settings.AUTH_USER_MODEL is a CustomUser model: class CustomUser(AbstractUser): pass email = models.EmailField(unique=True) first_name = models.CharField(max_length=20, default="", blank=True) last_name = models.CharField(max_length=20, default="", blank=True) How can I create a relationship, where I can get a users contact by doing something like this: // get user contacts user=CustomUser.objects.get(pk=1) user.contacts.objects.all() -
Read data from cache in Django Admin Changelist View
I want to read data from cache in Django admin changelist view. But I notice that ChangeList is using QuerySet and read data from database. I was wondering if there is a way to custom Changlist view to make it read from cache? -
Django code not working for following scripts
following queries not working : data = replypost.objects.annotate( appreciate=Count(Case( When( review__userlikes='1', then='1' ), output_field=IntegerField() )), varygood=Count(Case( When( review__userlikes='2', then='1' ), output_field=IntegerField() )), good=Count(Case( When( review__userlikes='3', then='1' ), output_field=IntegerField() )) ) -
How to update two models using one serializer
I am facing one issue for updating models using django serializer. Here is my models: class User(models.Model): email = models.EmailField(unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class UserProfile(AuditFields): user = models.ForeignKey(User, on_delete=models.CASCADE) designation = models.CharField(max_length=200, blank=True) contact_number = models.CharField(max_length=20, blank=True) team = models.CharField(max_length=200, blank=True) manager = models.CharField(max_length=200, blank=True) joining_date = models.DateField(default=datetime.now) I need to create a serializer for editing profile details of the current user This is my serializer. But it is a modelserializer so only getting the detauls from the User Profile table only class ProfileSerializer(ModelSerializer): class Meta: model = UserProfile fields = '__all__' extra_kwargs = {'user': {'required': False}} How can I edit first_name , last_name from User table and using same serializer and save it. I am using UpdateAPIView for updating the details Here is my view for reference . class ProfileUpdateView(UpdateAPIView): def get_queryset(self, *args, **kwargs): queryset_list = UserProfile.objects.filter( user=self.request.user) return queryset_list serializer_class = ProfileSerializer -
[Django]How to display a message(correct or incorrect) after submitting the form, without refreshing the page?
I have a made a quiz page, which checks whether the answer of the user is correct or not using a "checkans" function. I want to return a "Correct" message if the answer is correct and an "Incorrect" message if the answer is not correct. Now I can "kind of" do it, but not exactly what I want. Now it returns the message after redirecting to a whole new page, with the Question Box and everything else totally disappeared, only with the message. I want the message to be shown on the same original question page, somewhere under the question box or within the question box, without redirecting to another page or refreshing the page, after submitting the answer. I don't know how to do it. Here is my view: class QuizView(generic.ListView): template_name = 'geniusdennis/quiz.html' queryset = Spanish.objects.all() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # grab the max id in the database max_id = Spanish.objects.order_by('-id')[0].id random_id = random.randint(1, max_id + 1) random_spanish_question = Spanish.objects.filter(id__gte=random_id)[0] context['random_spanish_question'] = random_spanish_question return context Here is my function for checking the answer: def checkans(request, spanish_id): random_spanish_question = get_object_or_404(Spanish, pk=spanish_id) query = request.GET.get('ans') coreng = random_spanish_question.english_set.get() if query == str(coreng): return render(request, 'geniusdennis/quiz.html',{ 'message': "Correct!", }) … -
Models not rendering in Django templates
I'm trying to pass an abstract model to an inclusion tag like via takes_context=True. The abstract model contains choices for a model field. I want to pass the abstract model instead of hardcoding the choices in the template to stay DRY. While debugging I realized that the template isn't receiving the model as expected. # urls.py ... urlpatterns = [ path('', IndexView.as_view(), name='index'), ] # views.py ... class IndexView(TemplateView): """Home Page""" template_name = 'index.html' def get_context_data(self, **kwargs): kwargs['model'] = MyModel return super(IndexView, self).get_context_data(**kwargs) ... # index.html {{model}} The above renders nothing in the browser. When I change the variable to a string, the context renders as expected. # views.py ... class IndexView(BaseSearchBarMixin, TemplateView): """Home Page""" template_name = 'index.html' def get_context_data(self, **kwargs): kwargs['model'] = 'testing 123' return super(IndexView, self).get_context_data(**kwargs) ... # index.html {{MyModel}} # browser testing 123 I have a feeling I'm doing something stupid but don't know what -
Directing url.py to correct HTML in Pythonanywhere Django
I have created my Django project locally, and used the following structure to store URLs: - main_project folder --app folder ---templates folder ----app folder -----results.html -----thanks.html Now, when I moved this project to PythonAnywhere, it's not picking any of the html files, or their URLs - and any URL is just directing to the main (index) page. My app - url.py file is: from django.conf.urls import url, include from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ url('', views.address_input, name='address_input'), url('results/', views.address_input, name='results'), url('outofrange/', views.handler500, name='outofrange'), url('thanks/', views.contactview, name='thanks'), ] handler404 = 'apps.views.handler404' handler500 = 'apps.views.handler500' My project - url.py file is: from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), url('app/', include('app.urls')), url('', include('app.urls')), ] Additionally, my settings.py file has following setting, and it is reading the .css file in static. # default static files settings for PythonAnywhere. # see https://help.pythonanywhere.com/pages/DjangoStaticFiles for more info MEDIA_ROOT = u'/home/user/project/media' MEDIA_URL = '/media/' STATIC_ROOT = u'/home/user/project/app/static' STATIC_URL = '/static/' Can someone help me point the urls in the right direction. PS: I was able to use PATH in urls.py in my development environment, but cannot use it in Python Anywhere. -
Block template tags and include html
I've got two html files. I want to include one in the other and then use a block statement in the second. message.html <div> Hi </div> {% block message1 %} {% endblock message1 %} main.html {% include "message.html" %} {% block message1 %} this is a message {% endblock message1 %} When main.html is rendered, the string "this is a message" doesn't show up. Do you know why? thanks! -
I am trying to assign a group to my users with a form on registration but getting this error
AttributeError at /register_user 'User' object has no attribute 'group' I already have the attribute group class register_form(UserCreationForm): group = forms.ModelChoiceField(queryset=Group.objects.all(), required=True) class Meta: model = User fields = ['username', 'first_name', 'last_name', 'email', 'group'] this is my view @user_passes_test(lambda u: u.groups.filter(name='system_administrator').exists()) def register_user(request): if request.method == 'POST': form = register_form(request.POST) if form.is_valid(): user = form.save() my_group = form.instance.group my_group.user_set(user) return redirect('index.html') else: form = register_form return render(request, 'register_user.html', {'form': form}) And this is what the post request looks like (it has other attributes as well obviously) first_name 'asdfadsf' last_name 'asdfasdf' email 'asdfasdf@asdfasdf.com' group '1' -
ModelAdmin related issues in Django
Below is my code within the admin.py file. class JobAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title', 'organization',)} save_as = True Issue #1: I'm trying to prepopulate my slug using 2 different fields. The title field is getting populated correctly, whereas the organization field is a foreign key field, which is also getting populated but with an integer value. I would like to have this field populated with its original value which is the name field within the Organization model. To achieve this, I did try changing the organization field as follows: class JobAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title', 'organization__name',)} But this is giving me an error. ERRORS: <class 'jobs.admin.JobAdmin'>: (admin.E030) The value of 'prepopulated_fields["slug"][0]' refers to 'organization__name', which is not an attribute of 'jobs.Job'. System check identified 1 issue (0 silenced). Issue #2: The save_as = True does not enable the “Save as new” button. I did refer to the Django Admin Document but I'm unable to comprehend what else needs to be done to enable this. I would be really thankful if anyone could help me in fixing these issues. Thanks for your time and help in advance! -
Django compare strings in template (for loop) and replace output
There is a forloop in a template file in django {% for tag in tags_list %} {{ tag }} {% endfor %} The output is all the contents in tags_list like the example below 1 2 3 4 5 I tried to replace number 3 with the string "Not available" like below {% for tag in tags_list %} {% if 3 == tag %} {% tag = "Not available" %} {{ tag }} {% else %} {{ tag }} {% endif %} {% endfor %} But it does not work. There are two problems: 1- {% if 3 == tag %} cannot compare. 2- {% tag == "Not available" %} cannot change the value of the variable. What is wrong with these codes? -
Django and aggregating grand-child records
I am new to Django but have been around RdB for a while. I am finally getting the hang of model-view-template. I am struggling a little on "aggregate" and "annotate" especially when my model has grand-child records and I want aggregate. I use Django 3 on Python 3. Here is my example setup, I need help straightening it out. I am all sorts of wrong. There are stores, each that served many pizzas, each pizza has many toppings, each topping used a different qty of items. I want to know the total topping qty for each pizza made and for total topping qty for each store. models.py class Parlor(models.Model): name = models.CharField(max_length=64) class Pizza(models.Model): name = models.CharField(max_length=64) store = models.ForeignKey(Store, on_delete=models.CASCADE) class Topping(models.Model): name = models.CharField(max_length=64) pizza = models.ForeignKey(Pizza, on_delete=models.CASCADE) qty = models.IntegerField(default=0) views.py class ParlorDetail(generic.DetailView): model = Pizza template_name = 'pizza/parlor_detail.html' context_object_name = 'parlor' def get_context_data(self, **kwargs): context = super(TunnelSiteDetail, self).get_context_data(**kwargs) id = self.kwargs['pk'] topping_qty = Pizza.objects.filter(store=id).annotate(sum=Sum('qty')).aggregate(sum=Sum('qty')) return context class PizzaDetail(generic.DetailView): model = Pizza template_name = 'pizza/pizza_detail.html' context_object_name = 'pizza' def get_context_data(self, **kwargs): context = super(TunnelSiteDetail, self).get_context_data(**kwargs) id = self.kwargs['pk'] topping_qty = Topping.objects.filter(piza=id).annotate(sum=Sum('qty')) return context parlor_detail.html {% extends "pizza/my_base.html" %} {% block content %} <div>Parlor: {{ name }}</div> <div>Pizzas … -
In BeautifulSoup, how do I search for an element within another element?
I'm using Django 2, Python 3.7, and BeautifulSoup 4. I have the below code, which is supposed to find an element within an element ... req = urllib2.Request(fullurl, headers=settings.HDR) html = urllib2.urlopen(req, timeout=settings.SOCKET_TIMEOUT_IN_SECONDS).read() bs = BeautifulSoup(html, features="lxml") pattern = re.compile(r'^submitted ') posted_elt = bs.find(text=pattern) author_elt = posted_elt.find("span", class_="author") if posted_elt is not None else None However the line author_elt = posted_elt.find("span", class_="author") if posted_elt is not None else None is throwing the error "TypeError: find() takes no keyword arguments". What's the correct way to search for an element within another element? -
How to access primary key of object from url to be used in a form?
I have a ListView which currently displays items from a model called 'Session'. Each session has a title in the ListView template which links to a CreateView (via its pk in the url) in which I want a form to be filled out for a user to make a Booking. The "Session" model is linked to an "IndividualSession" model via fk which has datetimes a session is available. I then have a "Booking" model which I want to use for the form in my CreateView which allows a user to make a booking for an IndividualSession. The issue I am having is I would like to have a ModelChoiceField that displays all the datetimes from the IndividualSession model but only for the Session that the user has clicked on. I currently have it setup so the choices in the form show all the datetimes in the IndividualSession model, I need it so only the datetimes related to session the user clicked on are shown. models.py class Session(models.Model): skill = models.CharField(max_length = 100) description = models.TextField() spaces = models.IntegerField() title = models.CharField(max_length = 100) company = models.CharField(max_length = 100) teacher = models.ForeignKey(User, models.SET_NULL, blank = True, null = True) def __str__(self): … -
Unapplied migrations django
I`ve got a Typeerror: expected string or bytes-like object that prevents me to apply my migrations. How can I find where this error comes from. The resulting errors are: - OperationalError at /admin/login/ no such table: django_session - OperationalError at /projects/ no such column: projects_project.chantier_id when using a ForeignKey. view that creates a new project: views.py def create_project(request): form = ProjectForm(request.POST or None, request.FILES or None) if form.is_valid(): project = form.save(commit=False) project.save() return render(request, 'projects/detail.html', {'project': project}) context = { "form": form, } return render(request, 'projects/create_project.html', context) My Model: class Project(models.Model): PROJECT_TYPE = ( (0, 'Service'), (1, 'Remedials'), (2, 'Project'), (3, 'Call Out'), (4, 'Breakdown'), (5, 'One Off'), (6, 'Others'), ) user = models.ForeignKey(User, default=1, on_delete=models.CASCADE) type = models.IntegerField(choices=PROJECT_TYPE,default=1) chantier = models.ForeignKey(Chantier, default=1, on_delete=models.CASCADE) Here is the error message. WARNINGS: ?: (2_0.W001) Your URL pattern '(?P<project_id>[0-9]+)/render/pdf/$' [name='Pdf'] has a route that contains '(?P<', begins with a '^', or ends with a '$'. This was likely an oversight when migrating to django.urls.path(). Operations to perform: Apply all migrations: projects Running migrations: Applying projects.0008_auto_20200223_0126...Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "C:\Users\servi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\servi\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\__init__.py", line … -
Celery 4 + Django + Redis, missing django settings section in documentation?
I am trying to setup celery 4 in my Django project which I want Redis as broker. But I cannot find Django specific settings for broker in the Celery 4 documentation? Also the settings documentation for version 4 does not mention about CELERY_BROKER_URL anymore, I am sure the version 3 documentation does mention these settings. I searched on the web and found these settings: CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' But I am not sure if it's for version 3 or version 4. I am utterly confused. -
Django Rest Framework. Create/Update multiple images and serialize
I'm pretty new to developing api's with django rest framework. I've been working on a task for about a week. I feel like I'm getting closer but still running into problems. I have a Listing model and an Image model. Each listing can have multiple images. My Image model has only two fields, photo which is the imagefield, and listing, which is a ForeignKey to a listing My serializers looks like class ImageSerializerForListingDetail(serializers.ModelSerializer): class Meta: model = Image fields = ('photo', ) def get_image_url(self, listing): return listing.photo.url ` class ListingSerializer(serializers.HyperlinkedModelSerializer): user = UsernameSerializer(read_only=True) image_set = ImageSerializerForListingDetail(many=True, required=False) class Meta: model = Listing exclude = ('url', ) depth = 1 def create(self, validated_data): images_data = self.context.get('view').request.FILES listing = Listing.objects.create(**validated_data) for image_data in images_data.values(): Image.objects.create(photo=image_data, listing=listing) return listing def update(self, instance, validated_data): images_data = validated_data.pop('image_set') images = instance.image_set.all() images = list(images) instance = validated_data.get(**validated_data) instance.save() for image_data in images_data: image = images.pop(0) image.photo = image_data.get('photo') image.listing = image_data.get('listing') image.save() return instance My ViewSet looks like this... class ListingViewSet(viewsets.ModelViewSet): queryset = Listing.objects.all().order_by('id') permission_classes = [IsOwnerOrReadOnly, ] serializer_classes = { 'list': ListingListSerializer, 'retrieve': ListingSerializer } default_serializer_class = ListingSerializer def get_serializer_class(self): return self.serializer_classes.get(self.action, self.default_serializer_class) I am testing a PATCH request in postman, but I am … -
Django add comment section on posts feed
I want to share a project that currently can create user and each user can create N posts The source its available on github and i has two models users and post and the template layers Currently the feed for each post has a button that send an commenting the post i want to change that to put the comments of the post and not send and email each user should be able to comment a post and the comment should remain % block container %} <div class="row"style= "align:center"> {% for post in posts %} <div class="col-sm-12 col-md-8 offset-md-4 mt-5 p-0 post-container,width:50%;"> <div class="card" style="width: 32rem;width:50%;"> <div class="card-body"> <div class="media pt-3 pl-3 pb-1"> <a href="{% url "users:detail" post.user.username%}"> <img class="mr-3 rounded-circle" height="35" src="{{ post.profile.picture.url }}" alt="{{ post.user.username }}"> </a> <h3 class="card-title">{{ post.title }}</h3> </div> <p class="card-text">{{ post.desc }}</p> </div> </div> <img style="width: 50%; heigth:60%" src="{{ post.photo.url }}" alt="{{ post.title }}"> <div class="media-body"> <b> <p style="margin-top: 5px;">@{{ post.user.username }} - <small>{{ post.created }}</small> &nbsp;&nbsp; <a href="" style="color: #000; font-size: 20px;"> <i class="far fa-heart"></i> </a> <br> </p></b> </div> <!-- COMENT SECTION THAT I WANT TO IMPLEMENT MY FEATURE--> <form action="{% url 'posts:comment_new' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input class="form-control {% if … -
Django, How to add two form in one page?
I am new to django, my question is simple. How can I add two form in the same page? I tried many things as making a class in views or add a second urls path but didn't find how. Thanks you for helping this is my code: forms.py class scrap_info(forms.Form): url = forms.CharField(label="Urls") website = forms.ChoiceField(label="Website", choices=ask_website) class sms_info(forms.Form): data = forms.ChoiceField(label="Data list", choices=ask_data) number = forms.CharField(label="Sms number") views.py def scrap_app(request): form1 = scrap_info(request.POST or None) return render(request, "sms/scrap_app.html", {'form1': form1}) def sms_app(request): form2 = sms_info(request.POST or None) return render(request, "sms/sms_app.html", {"form2": form2}) scrap_app.html <body> <div> <form method="POST"> {% csrf_token %} {{ form|crispy }} <button class="btn btn-outline-info" type="submit" value="Save">SCRAP</button> </form> </div> </body> urls.py urlpatterns = [ path("/scrap_app", views.scrap_app, name="scrap_app"), ] -
Is it possible to pass function returned value as form value from html to views?
I have JS function which returns array of items. I would like to pass it via form to views. At this moment this array is being passed as ajax request but it is not too much reliable. It works but sometimes sends the empty request. Below i put the code to show what I would like to obtain. The js function is kinda dummy because the code is quite long but the role of this function is just to return the array. Is the below logic correct to make it working ? <form method='post' action='/category/' class="form-inline"> {% csrf_token %} <li class="nav-item"> <button class="nav-link purple darken-4" type="submit" name="Array" value=test() style="background-color: grey;">Make order</button> </form> <script> function test(){ var array = [] return aray } </script> -
Add w3school autocomplete functionality to django form field
i want to add the w3school.com autocomplete functionality to one of my django form fields. At first I used a simple html form and it worked, but after implementing the django-way of working with forms and models, I can't get the autocomplete to work anymore. Here is the relevant part of my code: forms.py class PlantForm(forms.ModelForm): class Meta: model = Plant fields = ('plantname') widgets = { 'plantname': forms.TextInput(attrs={'placeholder': 'Trage hier den Namen des gelieferten Produkts ein.', 'class': 'autocomplete', 'autocomplete': 'off'}), models.py class Plant(models.Model): plantname = models.CharField(max_length=255) main.js const plants = ["Strauß", "Pepperoni", "Physalis", "Aster"]; window.onload = function () { autocomplete(document.getElementById("id_plantname"), plants); }; index.html <link rel="stylesheet" href= "{% static 'xyz/index.css' %}"> <script src="{% static 'xyz/main.js' %}"></script> <form autocomplete="off" method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Eintragen</button> </form> The css and js code is copy and paste from the w3schools tutorial. I guess it has something to do with the autocomplete class. Maybe it is assigned wrong in the forms.py? The id of the field in main.js should be right according to the django documentation and my tests. Hope you can help me, many thanks in advance. -
wsgi.py cannot be loaded as Python module
I ran a git pull and a **sudo apt-get update** the other day and managed to ruin my wsgi.py setup with Apache2 & Django. My discovieries 1) If I start apache2 I receive a "500 Internal Server Error", but it starts fine. 2) If I try to run python3 manage.py runserver the Django server starts just fine. 3) I took a look at the settings.py but couldn't find anything that should cause issues on my VPS, I have done git pulls before without any issues. 4) Except the sudo apt-get update I haven't installed anything, only the installations I made a few weeks ago. It has been working great until now. Error.log ModuleNotFoundError: No module named 'main' mod_wsgi (pid=14871): Target WSGI script '/var/www/main/subber/wsgi.py' cannot be loaded as Python module. mod_wsgi (pid=14871): Exception occurred processing WSGI script '/var/www/main/subber/wsgi.py'. File "/usr/local/lib/python3.6/dist-packages/django/core/wsgi.py", line 12, in get_wsgi_application [Mon Mar 02 21:24:09.979048 2020] [wsgi:error] django.setup(set_prefix=False) This is driving me crazy, any suggestions? Is it possible that a apt-get update destroys my server configuration? -
How to add permissions in a Django REST API based in django.contrib.auth group permission
I'm trying to add permissions in a Django API, based in the permissions of the Group of the User, classes who are provided by django.contrib.auth. I've tried to add permission_classes = [DjangoModelPermissions,] but it's not working. from django.contrib.auth.models import User, Group from rest_framework import viewsets from rest_framework.response import Response from rest_framework.views import APIView from django.core import serializers from siga.models import Layer, Categoria from siga.serializers import UserSerializer, GroupSerializer, LayerSerializer, CategoriaSerializer from rest_framework.permissions import DjangoModelPermissions class UserViewSet(viewsets.ModelViewSet): """ API endpoint that allows users to be viewed or edited. """ permission_classes = [DjangoModelPermissions,] queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): """ API endpoint that allows groups to be viewed or edited. """ permission_classes = [DjangoModelPermissions,] queryset = Group.objects.all() serializer_class = GroupSerializer class LayerViewSet(viewsets.ModelViewSet): permission_classes = [DjangoModelPermissions,] queryset = Layer.objects.all() serializer_class = LayerSerializer class CategoriaViewSet(viewsets.ModelViewSet): permission_classes = [DjangoModelPermissions,] queryset = Categoria.objects.all() serializer_class = CategoriaSerializer class CategoriaLayerList(APIView): permission_classes = [DjangoModelPermissions,] queryset = Layer.objects.all() def get(self, request): categorias_layers = [] categorias = Categoria.objects.all() for categoria in categorias: layers = Layer.objects.filter(categoria=categoria) categoria_layer = { "id": categoria.id, "nome": categoria.nome, "layers": layers.values() } categorias_layers.append(categoria_layer) return Response(categorias_layers) class CurrentUserView(APIView): permission_classes = [DjangoModelPermissions,] queryset = User.objects.all() def get(self, request): serializer_context = { 'request': request, } serializer = UserSerializer(request.user, context=serializer_context) return … -
How can I run tests from a live database in Django?
I've got a DRF project that integrates with Salesforce using the django-salesforce package for reading a couple of objects. No writes go to Salesforce - the connection is entirely read-only. That said, I want to write tests for my viewsets and other functional endpoints, but I can't just link the salesforce database config to those test cases since the Django test runner automatically tries to create an isolated testing database. I can't just use SimpleTestCase as far as I know - if Django sees any database transactions, it kills the test. Is there some way to run tests as part of the normal testing flow that just read from the live salesforce database connection without creating a testing database? Do I need to implement a separate custom testing suite with another library in order to do that? -
Cleaning Up Multiple Pipenv Environments
I have a Django project that I set up via PyCharm. Since it was set up, I've moved it and renamed it. In the process, I think I created multiple pipenv environments. The reason I think so is that there are two entries under preferences/Project:xyz/Project Interpreter. One is listed as: xyz/venv/bin/python. The other is: ~/.local/share/virtualenvs/xyz-1IjVbwgz/bin/phton. I replaced the real project name with xyz. The one local to the project has problems installing and uninstalling mysqlclient. Pycharm says it adds or deletes it, but it remains displayed. I just executed "pipenv shell" on the command line and got this response: Launching subshell in virtual environment… . /Users/curt/.local/share/virtualenvs/xyz-1IjVbwgz/bin/activate ➜ merrittsecurity . /Users/curt/.local/share/virtualenvs/xyz-1IjVbwgz/bin/activate It would appear the one in .local/share is the correct one. So a few questions. Is this the normal location for pipenv? I'm on MacOS Mojave. Can I safely delete the one local to the project? There is an option in PyCharm to do that. The project runs fine. I just want to clean it up before using Docker with it.