Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Poetry install doesn't seem to install the packages in the right place
So I'm having a problem for quite some time which I cannot get solved. Basically I took over a project which uses Poetry for package managing (It is a Django project). Adding packages with 'poetry add' and then installing them via 'poetry install' all works fine locally (I use a Docker container). But when pushing the changes to my server and then running 'poetry install' it says the packages are already installed. But when running the Django application, I get an internal server error saying the package doesn't exist. An example is given with the 'openpyxl' package. pyproject.toml ... [tool.poetry.dependencies] openpyxl = "^3.0.10" ... poetry.lock ... [[package]] name = "openpyxl" version = "3.0.10" description = "A Python library to read/write Excel 2010 xlsx/xlsm files" category = "main" optional = false python-versions = ">=3.6" [package.dependencies] openpyxl = {version = ">=2.6.0", optional = true, markers = "extra == \"xlsx\""} [package.extras] all = ["markuppy", "odfpy", "openpyxl (>=2.6.0)", "pandas", "pyyaml", "tabulate", "xlrd", "xlwt"] cli = ["tabulate"] html = ["markuppy"] ods = ["odfpy"] pandas = ["pandas"] xls = ["xlrd", "xlwt"] xlsx = ["openpyxl (>=2.6.0)"] yaml = ["pyyaml"] openpyxl = [ {file = "openpyxl-3.0.10-py2.py3-none-any.whl", hash = "sha256:0ab6d25d01799f97a9464630abacbb34aafecdcaa0ef3cba6d6b3499867d0355"}, {file = "openpyxl-3.0.10.tar.gz", hash = "sha256:e47805627aebcf860edb4edf7987b1309c1b3632f3750538ed962bbcc3bd7449"}, ] ... error: … -
(1366, "Incorrect integer value: 'CargoEmpleado object (1)' for column 'cargo_empleado' at row 1")
I try to modify the cargo_empleado column of my empleado table with stored procedures, but I get an error: (1366, "Incorrect integer value: 'CargoEmpleado object (1)' for column 'cargo_empleado' at row 1") models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') views.py def asignarrol(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('cargo_empleado'): rolupdate= Empleado() rolupdate.rut=request.POST.get('rut') rolupdate.cargo_empleado=CargoEmpleado.objects.get(pk=(request.POST.get('cargo_empleado'))) cursor=connection.cursor() cursor.execute("call SP_asignar_rol('"+rolupdate.rut+"','"+str(rolupdate.cargo_empleado)+"')") messages.success(request, "Al empleado "+rolupdate.rut+" se le asigno un rol ") return render(request, 'app/asignarrol.html') else: return render(request, 'app/asignarrol.html') SP CREATE DEFINER=`root`@`localhost` PROCEDURE `SP_asignar_rol`(p_rut varchar(9),p_id_nuevo_cargo varchar(50)) BEGIN UPDATE Empleado SET cargo_empleado=p_id_nuevo_cargo WHERE rut=p_rut; END help me please!! -
Error when reverse url with multiple arguments - Django
I'm writing a test for an url, problem is it fails when I try to pass multiple arguments, here is some code: #test_urls.py from django.test import SimpleTestCase from django.urls import reverse, resolve from cardiotesting.views import * class TestUrls(SimpleTestCase): def test_new_cardio(id_patient, protocol): id_patient = '05' protocol = 'fox' url = reverse('new_cardio_testing', args=[id_patient, protocol]) print(resolve(url)) #urls.py from django.urls import path from . import views urlpatterns = [ path('new/<str:id_patient>', views.new_cardio_testing, name='new_cardio_testing'), ] #views.py def new_cardio_testing(id_patient, protocol): pass When I run the test it returns: .E ====================================================================== ERROR: test_new_cardio_testing (cardiotesting.tests.test_urls.TestUrls) ---------------------------------------------------------------------- TypeError: TestUrls.test_new_cardio_testing() missing 1 required positional argument: 'protocol' But when there is only one argument the test succeeds. Appreciate any help. -
How to import model from one app to another?
The issue I face: Error: ModuleNotFoundError: No module named 'CVBuilderApp.cvs' What I did: In my main app views file i.e, in the CVBuilderApp.views file views.py: from CVBuilderApp.cvs.models import PersonalInfo My project structure: CVBuilderApp - accounts - models, urls, views - cvs - models, urls, views - CVBuilderApp - settings.py - manage.py How do I import the model while the main application name and the project name are the same? Please help -
How to select related objects with only one query
Models: class Tag(BaseModel): tag_name = models.CharField(max_length=250) slug = models.SlugField() def save(self, *args, **kwargs): self.slug = slugify(self.tag_name) super(Tag, self).save(*args, **kwargs) def __str__(self): return str(self.tag_name) class Tags(BaseModel): filtertype = models.CharField(max_length=250) tags = models.ManyToManyField(Tag) My current solution: def get(self,request,version): filtertype = request.query_params.get('filtertype', '') filtertypes = filtertype.split(",") tagsList = Tags.objects.filter(filtertype__in=filtertypes).values_list('tags', flat=True).distinct() queryset = Tag.objects.filter(id__in=tagsList) context = {"request": request} serialized = TagListSerializers(queryset, many=True, context=context) return Response(serialized.data) Im trying to get all the relevant Tag base on Tags/filtertype. Im wondering how can I do it with only one query. -
Django foreign key query returns records that are not in the database
I have a strange situation where Django seems to be giving me records that do not actually exist in the database when queried via a related_name on a foreign key. Here's a simplified example: Let's say I have a Person model and a Pet model, where each Pet has an owner, which is a foreign key on Person: class Pet(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name =models.CharField(max_length=50, null=False, db_index=True) owner = models.ForeignKey("Person", null=False, related_name="pets", on_delete=models.CASCADE) relationship = models.IntegerField(null=False, choices=PetRelationship.choices(), db_index=True) Now, I have the below function that retrieves a person's pets: def pet_tester(person): for pet in person.pets.filter(relationship=PetRelationship.FRIENDLY): pet_id = pet.id LOGGER.info(f"*************** pet.id = {pet_id}") LOGGER.info(f"******* Pet exists? = {Pet.objects.filter(id=pet_id).exists()}") ... Note that this is NOT a "minimal reproducible example". I can only reproduce it in my much larger application. For some reason (in the real app), the "exists" query is coming back as False. The output is like this: *************** pet.id = 123e4567-e89b-12d3-a456-426614174000 ******* Pet exists? = False If I query the actual database (Postgresql) directly (outside of Django), that pet ID sure enough does NOT exist. However, the person.pets.filter query is returning it just the same. I do not understand how this is even possible. It JUST retrieved the … -
celery for separate django docker microservices
I have 2 django microservices main_ms and Oms1_ms. the project name of both is config and both have these installed redis==4.3.4 celery==5.2.7 celery[redis]==5.2.7 both have celery.py. main_ms's is like this import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() and for Oms1_ms, instead of proj I have oms1_oms1 in both __init__.pys I have from .celery import app as celery_app __all__ = ('celery_app',) in both settings I have provided CELERY_BROKER_URL='redis://redis:6379/0' CELERY_RESULT_BACKEND='redis://redis:6379/0' from one of views I have in main_ms which calls the other celery from config.celery import app from rest_framework import views from rest_framework import status from rest_framework.response import Response class Oms1_Oms1ListView(views.APIView): def get(self, request, *args, **kwargs): remoteResponse = app.send_task('oms1_oms1.fun') print(remoteResponse) return Response({}, status=status.HTTP_200_OK) and in Oms1 app in Oms1_ms container in tasks.py I have from config.celery import app @app.task() def fun(): return 'as always!!' so when I run celery -A oms1_oms1 worker -l DEBUG command in Oms1 container I get this error Error: Invalid value for '-A' / '--app': Unable to load celery application. The module oms1_oms1 was not found. so how to set celery with django docker microservices correctly? where I have gone wrong? I also know one of celery uses is primarily to … -
Display the data of User role in Django Template
I have a django model with User roles. I want to be able to get the first_name, last_name and other details of a user role displayed other a template when another user role or the same user role is logged in. This is my models class User(AbstractUser): is_customer = models.BooleanField(default=False) is_employee = models.BooleanField(default=False) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) #username = models.CharField(unique = False , max_length=100) #email = models.CharField(unique = True , max_length=100 ) nin = models.IntegerField(unique = False , null=True) avatar = models.ImageField(null= True, default="avatar.svg") is_landlord = models.BooleanField(default=False) objects = UserManager() REQUIRED_FIELDS= [] class Landlord(models.Model): user = models.OneToOneField(User,related_name="prop_owner", null= True, on_delete=models.CASCADE) bio = models.TextField(null=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS= [] objects = UserManager() def __str__(self): return str(self.user) This is my views def propertySingle( request, pk, is_landlord, ): user = User.objects.get(is_landlord=is_landlord) property = Property.objects.get(id=pk) properties = Property.objects.all() images = Image.objects.filter(property=property) context = { "property": property, "properties": properties, "images": images, 'user':user, } return render(request, "base/page-listing-single.html", context) Template <div class="sl_creator"> <h4 class="mb25">Property Owned By:</h4> <div class="media"> <img class="mr-3" style="width: 90px; height:90px;" src="{{request.user.avatar.url}}" alt="avatar"> <div class="media-body"> <h5 class="mt-0 mb0">{{user.last_name}} {{request.user.first_name}}</h5> <a class="text-thm" href="#">View other Listings by {{property.landlord.last_name}} {{property.user.is_landlord.first_name}} -
How to export "down" on Django admin?
I need to export the author and each of his books, but the author just export the author. I managed to make the "book" maintainer export the author, but for every book it appears the author in every line. I have the "tabular in line" that means if I pick and author it shows every book in the admin page, so I know it's possible to do it but I don't know why, help! I have Author, Country and Book, and looks like this, models.py: class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Country(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): name = models.CharField('Book name', max_length=100) author = models.ForeignKey(Author, blank=True, null=True) author_email = models.EmailField('Author email', max_length=75, blank=True) imported = models.BooleanField(default=False) published = models.DateField('Published', blank=True, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True) country = models.ForeignKey(Country, blank=True) The admin.py: admin.site.register(Book) admin.site.register(Country) class BookInline(admin.TabularInLine): model = Book max_num = 0 can_delete = False @admin.register(Author) class AdminAuthor(ImportExportActionModelAdmin): list_display = (name) inlines = [ BookInline, ] class Meta: model = Book It's not a many to many relationship, its one to many, so plis help me to make it look Something like this as a django admin action: +--- Author -----+ … -
Djnago-admin how to add extra Fields registrations in django-admin interface
In my web application, only the admin can register a user. I need to add extra fields to the registration form only in the djnago-admin interface, how can I do it, please? -
Django Image Cropping in inlineFormsetFactory using cropper
I'm trying to make inline formset which one field gets chopped image as one of parameters. I have already done cropping with help of some tutorials but it works only with single model, when I tried to transform it to inline formset, new image is being saved in raw form - cropping isn't getting applied. tut I used: https://blog.pyplane.com/blog/how-to-crop-images-in-django-with-javascript/ models look like that: class Product(models.Model): name = models.CharField(max_length=200) category = models.ForeignKey(Category, on_delete=models.CASCADE) availability = models.IntegerField() price = models.DecimalField(max_digits=5, decimal_places=2) class Photo(models.Model): file = models.ImageField(upload_to=getImageURL2, default="static/default.png") uploaded = models.DateTimeField(auto_now_add=True) product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True, blank=True) forms.py class ProductForm(forms.ModelForm): class Meta: model = Product fields='__all__' class PhotoForm(forms.ModelForm): class Meta: model = Photo fields = ('file',) ProductPhotoInlineFormset = inlineformset_factory( Product, Photo, fields=('file',), form=PhotoForm, extra=1, can_delete=False, ) view def ProductCreateView(request): context = {} created_product = None form = ProductForm() if request.method == 'POST': print(request.POST) form = ProductForm(request.POST) if form.is_valid(): created_product = form.save() print("Successfully created new product: {}".format(created_product)) else: print("form is not valid") print(form.errors) print(form.non_field_errors()) context['form'] = form formset = ProductPhotoInlineFormset() if request.method=='POST': formset = ProductPhotoInlineFormset(request.POST or None, request.FILES or None, instance=created_product) if formset.is_valid(): for f in formset: imageset_obj = f.save() print("Successfully created new imagest: {}".format(imageset_obj)) return JsonResponse({'message': 'works'}) else: print(formset.errors) print(formset.non_form_errors()) context['formset'] = formset … -
sitemap.xml works on development but 404 errors on production
I've been following the documentation to add a sitemap to my website, everything works perfectly on development, once I upload to production, I have 404 errors as in sitemap can't be found. I checked the database on production to make sure the SITE_ID is the same as the pk of the site registered in database. This is my installed app in settings.py """ Django settings for icerd project. Generated by 'django-admin startproject' using Django 4.0.6. For more information on this file, see https://docs.djangoproject.com/en/4.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/4.0/ref/settings/ """ import os from pathlib import Path from django.conf import global_settings # Add custom languages not provided by Django from django.conf import locale from django.utils.translation import gettext_lazy as _ from icerd.productions import production_debug, production_secret_key, allowed_host, production_caches_location # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = production_debug # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = production_secret_key ALLOWED_HOSTS = ["*"] if DEBUG else allowed_host AUTH_USER_MODEL = "registration.User" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', … -
Django template not displaying data from database
I am running into an issue where my database is information is displaying on one template, but I want certain parts to display on another page for a blog. When I click into physics-blog it will display my images and post title. For this, I have looped through the database. Works fine and perfectly. But when I click into one of them and want to show {{ physicsBlog.body }} it doesn't show anything. Which I can't wrap my head around because that works just fine in the other ListView template, but not in the DetailView template. Here is my code. models.py class physicsBlog(models.Model):title = models.CharField(max_length=250)blog_image = models.ImageField(null=True, blank=True)description = models.CharField(max_length=200)author = models.ForeignKey(User, on_delete=models.CASCADE)body = RichTextField(blank=True, null=True)date_created = models.DateField(auto_now_add=True)def __str__(self):return self.title + ' | ' + str(self.author) views.py class physicsBlogListView(ListView):model = physicsBlogtemplate_name = 'physics.html'ordering = ['-id']class physicsBlogDetailView(DetailView):model = physicsBlogtemplate_name = 'physics-blog-details.html' urls.py urlpatterns = [path('', views.home, name="home"),path('physics-blog', physicsBlogListView.as_view(), name="physics-blog"),path('physics-blog/<int:pk>', physicsBlogDetailView.as_view(), name="physics-blog-details"),path('crypto-blog', cryptoBlogListView.as_view(), name="crypto-blog"),path('crypto-blog/<int:pk>', cryptoBlogDetailView.as_view(), name="crypto-blog-details"),] -
Creating a basic Input Form in a Django
I am trying to create a simple form in Django but it is not showing the input form in HTML and there is not error appearing so that I can track the error. Here is the model: class Log(models.Model): log_weight = models.FloatField(validators=[MinValueValidator(0)],blank=True, null=True) log_repetitions = models.IntegerField(validators=[MinValueValidator(1)],blank=True, null=True) class LogForm(forms.Form): log_weight = forms.IntegerField() log_repetitions = forms.IntegerField() class Meta: model = Log fields = ['log_weight', 'log_repetitions'] Here is the views: class workout_details(DetailView): model = Workout template_name = 'my_gym/start_workout.html' context_object_name = 'workout' def get_context_data(self, **kwargs): exercises = Exercise.objects.filter(workout_id=self.object) context = super().get_context_data(**kwargs) context['exercises'] = exercises return context def addlog(request, id): url = request.META.get('HTTP_REFERER') # get last url # return HttpResponse(url) if request.method == 'POST': # check post form = LogForm(request.POST) if form.is_valid(): data = Log() # create relation with model data.log_repetitions = form.cleaned_data['log_repetitions'] data.log_weight = form.cleaned_data['log_weight'] data.workout_id = id data.save() # save data to table return HttpResponseRedirect(url) return HttpResponseRedirect(url) Here is the template: <form class="review-form" action="{% url 'my_gym:addlog' workout.id %}" method="post"> {% csrf_token %} {{ form }} </form> Here is the url: urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), path('workout/addlog/<int:pk>', addlog, name='addlog'), ] My question: What is the reason that the form is not showing in the details page? How can I … -
Best Django model field to store frequency (from Hz to 10 GHz)
What is the best model field to store a frequency, from 1 Hz to 10 GHz? IMHO could be a PositiveBigIntegerField but I'm not completely convinced... Thank you -
How to save a pop up form (modal form) (field) having many-to-many relationship in Django?
I have got two models as shown in models.py. How well can it be done so that when creating a new object in the parent model it allows the data entry user to create one or more objects in the child model and link it to the parent model object using one form? models.py class ChildModel(models.Model): field = models.CharField() class ParentModel(models.Model): child = ManyToManyField(ChildModel) Case Example Let's have a parent and Children belonging to a parent. That is when creating a new parent you can attach his or her children's details. What I have tried I have joined both models using the many-to-many Django relationship. To attach the children to a parent, the first thing you need to do is create the children first, in a separate form, then select them from a list while creating the parent. Complains Is tiresome and not good when handling large data, for example, if there are 1000 children and you need to attach them to their respective parents. Project Screenshots parent creation form child creation form My Expectations The following image illustrates how a pop-up is generated when the green plus sign is clicked, a pop-up window appears having a child creation form … -
Django NoReverseMatch Reverse for 'conversation' not found
Hi I am currently facing a problem in redirecting the user to my directs-app. The NewConversation in directs/views.py starts a new conversation. It can be clicked in the profile-page user-profile.html of the users-app. Now I wanna do the same in my single-project.html in my projects-app. But I am getting the error above. Thanks for your help! directs/views.py def NewConversation(request, username): from_user = request.user body = '' try: to_user = User.objects.get(username=username) except Exception as e: return redirect('search-users') if from_user != to_user: Message.sender_message(from_user, to_user, body) return redirect('message') directs/urls.py urlpatterns = [ path('new/<username>', views.NewConversation, name="conversation"), ] users/models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) username = models.CharField(max_length=200, blank=True) users/views.py def userProfile(request, pk): profile = Profile.objects.get(id=pk) context = {'profile':profile} return render(request, 'users/user-profile.html', context) users/user-profile.html <h2 class="dev__name">{{profile.name}}</h2> <img class="avatar avatar--xl dev__avatar" src="{{profile.profile_image.url}}" /> <a href="{% url 'conversation' profile.user %}" class="btn profile-edit-btn">Message</a> projects/views.py def project(request, pk): projectObj = Project.objects.get(id=pk) context = {'project':projectObj} return render(request, 'projects/single-project.html', context) projects/models.py class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) projects/single-project.html <div class="project__tags" style="margin-top: 20px;"> <a href="{% url 'conversation' project.owner.user %}">Send message</a> </div> -
How do I skip a test_utility file when running Python unittest?
I have a utilities package, and am including tests for some of the utilities. However, one of the directories has a bunch of django TestCase specific reusable classes, and it keeps running and failing when I run: python -m unittest The file's name is testutils.py and is for other Django apps to import and use, not to be tested itself. Is there a settings or skip file where I can tell my package not to look at that file when running tests? -
Django query (select, count where)
I'm trying to recreate the following sql query in the django ORM CASE WHEN (SELECT COUNT(id) FROM offer WHERE offer.product_id = p.id) < 1 THEN '[]'::JSONB ELSE ( SELECT JSON_AGG(JSON_BUILD_OBJECT('name', o_sub.name, 'status', o_sub.status)) FROM offer o_sub WHERE o_sub.product_id = p.id LIMIT 2 -- TWO IN PREVIEW LIST. )::JSONB END AS _offers But I haven't been hable to do it so far I had something like this: merchant_offers=Case( When( number_of_offers__lt=1 , then=JSONObject( offer_name="offers__name", offer_value="offers__merchant_group_fees__value" ) ), ) But i dont really know how to do the second query the one with the JSON_AGG -
django request.user always returns AnonymousUser despite a token being sent with the request
i have a class that beehives differently depending on if the user is authenticated or not: class SomeClass(APIView): authentication_classes = () permission_classes = () def get(self, request): if request.user.is_authenticated: # do something... else: # do something else... it used to work perfectly with django 3.2.5 and JSONWebTokenAuthentication. however i had to upgrade to django 4.x and TokenAuthentication... with: authentication_classes = (TokenAuthentication, ) the user is available but the request returns 401 to anonymous users... with: authentication_classes = () anonymous requests are accepted, but i can't see the data of authenticated users. -
Django Autocomplete Light not working with Django update from Django 3.1 to 4.1
The application I inherited was at Django 2.2. I have gradually updated to 4.1 and everything works except the Django Autocomplete Light fields. For some forms.ModelForm, I have a box with a correct list that can be selected but it does not have the ability to type the first few letters and select from that filtered list. Most of the autocomplete fields are on forms.Form and either display a dropdown box where the only choice is '-----', a scroll bar only with no list, or a box that is 2 x 47 pixels. I have gone through the DAL documentation but could not find a solution. I have searched here plus other Google searches but I have not found a solution. I do realize that parts of the code use the older URL pattern that includes ^, $, and ?P< items. I have tried to change these for one of the apps but it did not solve the issue. forms.py # Forms from django import forms from django.forms import ModelForm # Models from login.models import User from .models import Suggestion, SuggestionDecision, Implementation # Autocomplete from dal import autocomplete class ReviewForm(forms.ModelForm): class Meta: model = Suggestion fields = ['suggestion', 'supervisors', 'managers'] … -
Moving Django models between "apps" - easy and fast
In my company's Django project, our models are currently spread across about 20 "app" folders with little rhyme or reason. We'd like to consolidate them into a single new app (along with the rest of our code) so that in the future, we can refactor all parts of our system at-will without worrying about violating an "app" boundary. Due to how Django works, simply moving the model breaks everything. I've spent hours reading everything I can about the various proposed solutions to this problem, with the best article being: https://realpython.com/move-django-model/ So far, I'm not happy with any of the solutions I've come across. They're all just too onerous. If I do the following: Move all models to the new app. (Let's call it "newapp".) Update all references in the code to the previous locations. (Including migration files.) Take down the site for a minute. Run a script to rename all database tables from someprevapp_model to newapp_model. Run a script to update app_label for all rows in the django_content_type table. Deploy latest codebase version, with updated model locations and references. Turn site back on. Have I succeeded, or am I missing something? UPDATE Just remembered - I'd also have to: 5.5) … -
Annotating without using Exists or SubQuery
I have a client who is using Django 1.8. While they will be moved to the latest version, we need to run some queries before their migration, but obviously we can't use Exists or OuterRef. In our case we want to annotate a queryset. eg recordset = Question.objects.annotate( has_answers=Exists(Answers.objects.filter(question=OuterRef('pk'))) ) Is there a workaround to do the equivalent of the above annotation. What did people use in 'the olden days'? -
Errors only happen when running django server with pipenv
I have a django project which runs with no errors when run without any virtual enviroments. But when i run my server inside a after writing the command python -m pipenv shell then python manage.py runserver I encounter a few errors such as syntax errors when the syntax is perfectly normal and module import errors which would never occur without using pipenv errors: url = f"https://resources.premierleague.com/premierleague/photos/players/110x140/p{photo_id}.png" - invalid syntax ImportError: No module named 'PIL' (import worked outside of pipenv) -
set user foreign key default value as superuser or admin on on_delete=models.SET_DEFAULT
As I was using on_delete=models.CASCADE with currentOwner in the asset model, whenever I deleted any user, all the assets owned by that user were getting deleted. I want the asset to be transferred to the superuser/admin. So I tried # MY SOLUTION but it is throwing me an error: ValueError: Field 'id' expected a number but got 'admin'. I think deleting previous migrations and running makemigrations and migrate commands might help, but that will probably erase all the data in the database, which I do not want to happen. Here are my User and asset models: class User(PermissionsMixin, AbstractBaseUser): username = models.CharField(max_length=32, unique=True, ) email = models.EmailField(max_length=32) gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")] gender = models.CharField(choices=gender_choices, default="M", max_length=1) nickname = models.CharField(max_length=32, blank=True, null=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) REQUIRED_FIELDS = ["email", "gender"] USERNAME_FIELD = "username" objects = User_manager() def __str__(self): return self.username class asset(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, null=False) asset_type = models.ForeignKey('assetType', on_delete=models.CASCADE, null=True) asset_name = models.CharField(max_length=30, null=True) #unique=True location = models.CharField(max_length=30, null=True) brand = models.CharField(max_length=30, null=True) purchase_year = models.PositiveIntegerField(blank=True, null=True) isActive = models.BooleanField(default=True, null=True) currentOwner = models.ForeignKey(User, default=User.objects.get(is_superuser=True).id, null=False, on_delete=models.SET_DEFAULT) # MY SOLUTION Is there any way this can be solved?