Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why my test_views works alone, but not when I run all of my tests?
I'm writing tests to ensure that my view is rendered and its context data is there when I access the link. All these tests are working, when I run them in their current dir, but when I run all my tests, these view tests give me an error in the context data. def cve_factory(): cve = Cve.objects.create( name='test', ) cve.save() return cve def vuln_to_test_context(): vuln = Vuln.objects.create( cve=cve, ) vuln.save() return vuln class PublicVulnViewTests(TestCase): def test_vulns_page_if_cvss_nonexistent(self): package = Package.objects.create(name='django') cve = cve_factory() vuln = vuln_to_test_context(cve=cve, package=package) response = self.client.get(f"/vulnerabilities/{cve.name}/{cve.id}/") self.assertEqual(response.status_code, 200) self.assertEqual(response.context_data['highlightedCVSS'], None) self.assertEqual(response.context_data['severity'], None) This is an example of one of my tests and it is working, because I am accessing its URL correctly, but when I run all tests, the context data is not accessed because it does not exist in my response. self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 update_date = response.context_data['severity'] AttributeError: 'HttpResponseNotFound' object has no attribute 'context_data' I do not have TestCase from other directories being imported from unnitest or anything different, my TestCase is always being imported from Django.tests. -
Is Azure Cache for Redis is fine for setting up dynamic spider in Django and Celery on Azure
I am trying to figure out how can set up a project where I will be scrapping data from multiple websites using multiple spiders. Each spider has different configuration and gets different type of data (depending on website). I am using playwright to get the data. My idea is to use Celery to create tasks and schedule them so it will scrape data at particular time and day. Then the data will be sent to database and user will be able to download the output file. The whole project will be deployed to Azure and from what I am reading I will need Azure Cache for Redis. I will be also using rotating proxy to access data from websites. My questions are: Is Azure Cache for Redis a good option for such project. If not then what else can I use? What is the most efficient way to store scraped data from pages? I am currently using MongoDB but it is quite expensive solution. The reason for using noSQL is that each spider is different and scrape different type of data and in relational database it would be inefficient to add columns every time I am scrapping data from new … -
M2M field doesn't get updated
I was trying to update an M2M field but it just doesn't get updated neither from admin panel nor the serializer! We have a "Book" model which has a "Category" field that is M2M to BookCategory Model this is my model: class Book(models.Model): #... category = models.ManyToManyField('BookCategory', related_name='bookCategory') def __str__(self): return self.name class BookCategory(models.Model): name = models.CharField(max_length=100) parent = models.ForeignKey('BookCategory', on_delete=models.PROTECT, null=True, blank=True) description = models.TextField() def __str__(self): return self.name and this is my view: class BookChange(RetrieveUpdateDestroyAPIView): serializer_class = BookSerializer lookup_field = 'pk' def get_queryset(self): return Book.objects.all() and the Model Serializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = '__all__' The funny thing is that when I remove the current category it works but it doesn't add the new ones I also tried Overriding the serializer.save() in def update Can you help me out? -
How do I query specific arguments using Django RESTQL?
I'm working on a project that displays data in a table with headers. For this purpose, I chose Django RESTQL because it allows me to use pagination, sorting, and filtering. I'm able to filter by column but I can't filter by specifics. Like, if I wanted to only see the results that contain 'hello' in the name. When I run the test query, it's as if I only queried for columns and not the specific attributes. What I've Tried: https://github.com/yezyilomo/django-restql-playground-backend/blob/master/api/views.py I've tried looking at the devs backend code and everything seems similar. I'm not sure what I'm doing wrong. It must be the way I'm setting up the query in Postman or something simple. I used the following docs for the syntax. Test query: {{baseUrl}}/series/?query=(name: 'hello'){id, name} Serializer: class SeriesSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = Series fields = ['id', 'name', 'removed', 'active'] views: class SeriesViewSet(QueryArgumentsMixin, viewsets.ModelViewSet): queryset = Series.objects.all().order_by('-id') serializer_class = SeriesSerializer filter_fields = { 'id': ['exact', 'lt', 'gt'], 'name': ['exact', 'contains'], } -
How to bulk_update queryset values
# Count mandate for each delegate, multiply it by score delegate_votes = PollVotingTypeRanking.objects.filter(author_delegate__poll=poll).values('pk').annotate( score=F('priority') * Count('author_delegate__created_by__groupuserdelegator', filter=~Q(author_delegate__created_by__groupuserdelegator__delegator__pollvoting__poll=poll) & Q(author_delegate__created_by__groupuserdelegator__tags__in=[poll.tag]))) # Set score to the same as priority for user votes user_votes = PollVotingTypeRanking.objects.filter(author__poll=poll ).values('pk').annotate(score=F('priority')) PollVotingTypeRanking.objects.bulk_update(delegate_votes | user_votes, fields=('score',)) Attempting to update the values for delegate_votes and user_votes, how do i do that? Currently im getting the error 'dict' object has no attribute pk -
I cannot import from one app to another . why cant I do it?
This is my directory : I want to import The groups class model in group directory from here : from django.db import models from django.utils.text import slugify from django.urls import reverse import misaka from django.contrib.auth import get_user_model User=get_user_model() from django import template register = template.Library() # GROUPS MODULES.PY. class Group(models.Model): name= models.CharField(max_length=255,unique=True) slug= models.SlugField(allow_unicode=True,unique=True) description = models.TextField(blank=True, default= 'NOT_PROVIDED') description_html = models.TextField(editable=False,default='', blank=True) members = models.ManyToManyField(User,through='GroupMember') def __str__(self): return self.name def save(self,*args,**kwargs): self.slug = slugify(self.name) self.description_html = misaka.html(self.description) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('groups:single',kwargs={'slug':self.slug}) class Meta: ordering = ['name'] and place it here in the posts/ models.py: from django.db import models from django.urls import reverse import misaka from groups import Groups #POST MODULES.PY from django.contrib.auth import get_user_model User = get_user_model() class Post(models.Model): user = models.ForeignKey(User,related_name='post', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=True) message= models.TextField() message_html = models.TextField(editable=False) group = models.ForeignKey(Group, related_name='posts', null=True , blank=True , on_delete=models.CASCADE) def __str__(self): return self.message def save(self,*args,**kwargs): self.message_html = misaka.html(self.message) super().save(*args,**kwargs) def get_absolute_url(self): return reverse('posts:single',kwargs={'username':self.user.username,'pk':self.pk}) class Meta: ordering = {'-created_at'} unique_together = ['user','message'] on Pycharm in the import 'from groups import Group' is underlined red. I have no idea why its not working. also this is the settings : -
How to set placeholder for django integerfield
I have a model form: class CaseForm(ModelForm): class Meta: model = Case fields = ["sex", "age"] With corresponding model: class Case(TimeStampedModel): id = models.UUIDField( primary_key=True, unique=True, default=uuid.uuid4, editable=False ) user = models.ForeignKey( get_user_model(), blank=False, null=True, on_delete=models.SET_NULL) age = models.IntegerField("Age") SEX_CHOICES = [ ("male", "Male"), ("female", "Female"), ('', "Sex") ] sex = models.CharField("Sex", max_length=20, choices=SEX_CHOICES, blank=False) This displays a placeholder of 'Sex' for one field and I would like to display the a similar placeholder for 'Age'. One method I have seen is: class CaseForm(ModelForm): age = IntegerField(label='Age', widget=TextInput(attrs={'placeholder': 'Age'})) class Meta: model = Case fields = ["sex", "age"] However when this is rendered, although 'Age' is there as a placeholder, the field no longer behaves like an integer field. Any advice on the correct method appreciated -
How do I sync a docker volume to update when my local files are updated? Django, nginx
Sorry, it seems like answered question, but I couldn't find not outdated solution or the one that could help me (especially with django). I have to manually re-make volume so my docker server will update. My php friend told me I should make a synchronized volume, but I just don't understand how compose.yml volumes services: back: volumes: - blog-django:/usr/src/app - blog-static:/usr/src/app/static nginx: volumes: - blog-static:/usr/src/app/static db: volumes: - pgdata:/var/lib/postgresql/data/ volumes: blog-django: blog-static: pgdata: Project copied in volume by COPY . . -
Page not found (404)The current path, {% url 'post_detail' post.pk % }, didn’t match any of these
[hi i am new to django and i am facing a problem when using primary keys.project name is blog project and app is blog this is my code.] this is the screenshot of the error when i click on a heading:1 please help me #blog/urls.py from django.urls import path from .views import BlogListView,BlogDetailView urlpatterns = [ path("post/<int:pk>/",BlogDetailView.as_view(),name = "post_detail"), path('', BlogListView.as_view(), name = "home"), ] #blog/templates/home.html {% extends 'base.html' %} <style> .post-entry{ color:antiquewhite; } </style> {% block content %} {% for post in object_list %} <div class = "post-entry"> <h2><a href = "{% url 'post_detail/' post.pk % }">{{post.title}}</a></h2> <p>{{post.body}}</p> </div> {% endfor %} {% endblock content %} -
Can we add add objects to django queryset like we do to python list. I have an empty django queryset, now I want to add objects to it
This is how I have initialized an Empty Queryset now I want to add objects to it. How can I do that. from django.db.models.query import EmptyQuerySet -
Get requests are regularly (every 2 s) sent on / when enabling SSL with a Django app
I have a dockerized Django application which is working well on port 80. nginx is running on my server with a basic rule, catching traffic on port 80 and redirecting it to the exposed port of my app container. Everything works fine. Now I enabled SSL, added a listen 443 default_server ssl; to my nginx server, but from now, my container logs are showing, every 2 seconds, requests like this: djangotutorial-app-1 | 2022-10-06T14:58:29.131231656Z Not Found: / djangotutorial-app-1 | 2022-10-06T14:58:29.133263459Z [06/Oct/2022 14:58:29] "GET / HTTP/1.0" 404 2167 ... so it's bloating the logs. This didn't happen without SSL. As I don't know where to search from here, because there is obviously no error message or whatever useful information, I would be glad if someone has an idea on how to debug that. -
no such table: main_uploadfile after uploading file
I have a django app. and I try to upload image. So I have this view.py: from .forms import ProfileForm from .models import UploadFile # Create your views here. """ def store_file(file): with open("temp/hello.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) """ class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/main") return render(request, "main/create_profile.html", { "form": submitted_form }) and this form.py: class ProfileForm(forms.Form): upload_file = forms.FileField() and this model.py: class UploadFile(models.Model): image = models.FileField(upload_to="images") and yes, I did this: python manage.py makemigrations and python manage.py migrate that created this file: class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='UploadFile', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('image', models.FileField(upload_to='images')), ], ), ] but still after uploading I get this error: OperationalError at / no such table: main_uploadfile Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.1.1 Exception Type: OperationalError Exception Value: no such table: main_uploadfile Exception Location: C:\Python310\lib\site-packages\django\db\backends\sqlite3\base.py, line 357, in execute Raised during: main.views.CreateProfileView Python Executable: C:\Python310\python.exe Python Version: 3.10.6 Python Path: ['C:\\Users\\engel\\Documents\\NVWA\\software\\blockchainfruit\\schoolfruitnvwa', 'C:\\Python310\\python310.zip', 'C:\\Python310\\DLLs', 'C:\\Python310\\lib', 'C:\\Python310', 'C:\\Python310\\lib\\site-packages'] Server time: Thu, 06 Oct 2022 … -
Django: How to use User ModelForm for log in?
I'm trying to use a modelForm for a login rather than a Form (to avoid repetition): class LoginForm(forms.ModelForm): class Meta: model = get_user_model() widgets = { "password": forms.PasswordInput(), } fields = ("email", "password") However, since the email field has a unique=True, and since forms can be used to create objects, when running is_valid() method on the form, I get an error: User with this E-mail already exists. What is the right way to handle this? Thanks. -
Docker on windows Vmmem grows with each rebuild of container
I have a Django + Gunicorn + Nginx website running in a docker container on windows 10 that's been working wonderfully. Every time that I update my source code I run the following command to rebuild the container: docker-compose up -d --build [servicename] This runs as expected, builds the container detached and then swaps them out when complete, Nginx stays running and looses connection for a second then boom, back up and running. Ill do this maybe 5-20 times a week depending on what I'm adding/fixing and pushing to production. the issue that I just came across was that the Vmmem process is growing by a factor of 1 each time, so when I run docker-compose up for the first time, memory usage will be about 3,000MB. When I run my rebuild, it will grow to 6,000 MB. and on and on.... Since the system I'm running on has 32GB of RAM, I didn't notice the mass amount of buildup until a few months in of running. Is this normal behavior from docker? and if so is there anything I can do to to alleviate the build up other than restarting the computer? -restarting docker does not solve the issue … -
django filter by fields that can change
I have this model : class Project(models.Model): state = models.CharField(max_length=7, default='#FFFF00') name = models.CharField(max_length=200, default="") price = models.FloatField(default=0) decision = models.TextField(blank=True, null=True) For example, if I want to filter all the projects named 'hello_project' with a price of 10, I can do this : projects = Project.objects.filter(Q(name='hello_project') & Q(price=10)) What I want to do is filter by lists that can change : fields = ["name", "price"] filters = ["hello_project", 10] Is there a way to do something like this that works ? (lists size can change) : projects = Project.objects.filter(Q({fields[0]}={filters[0]}) & Q({fields[1]}={filters[1]}) I've done this: def filter_projects(fields, filters): all_projects = Project.objects.all() filtered_projects = [] for i in range(len(fields)): for project in all_projects: if str(functions[fields[i]](project)) == str(filters[i])): filtered_projects.append(project) all_projects = filtered_projects filtered_projects = [] return all_projects It works but it's very long with a lot of projects so I want to know if I can do this in one line -
Annotating frequency of many to many objects in a query (Django)
I'm trying to annotate a product reports with the frequency at which a product appears on the report. I have the below so far which works, but it's counting the frequency products appear across all users reports, rather than the specific user. BarcodeScanProduct's are linked via m2m to barcodescanproduct and Products are linked by foreign key to BarcodeScanProduct's. user = request.user report, created = BarcodeScanReport.objects.get_or_create(user=user, complete=False) report_products = report.barcodescanproduct_set.all( ).annotate(instance_count=Count('product__barcodescanproduct__id') ).order_by('-product__status') Any ideas? -
Why do I get this TypeError in Django Cloudinary when running Debug=False?
So I have this Django project using django-cloudinary-storage for media files, deployed with Heroku. I know it's silly but I've been running the app with Debug=True. Everything was fine, all static and media files were served perfectly. But then I realized doing so is critical to the security of my app, so I re-deployed it with Debug=False. This is when I got this error message saying TypeError: expected str, bytes or os.PathLike object, not NoneType (Full traceback at the bottom) Let me show you my settings.py. I don't see what I've done wrong, but I keep getting the error. What do you think is the problem? (...) STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) STATICFILES_STORAGE = 'cloudinary_storage.storage.StaticHashedCloudinaryStorage' STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') CLOUDINARY_STORAGE = { 'CLOUD_NAME' : '', # some string 'API_KEY' : config("CLOUDINARY_API_KEY"), 'API_SECRET' : config("CLOUDINARY_API_SECRET"), } DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' And I also have this in my urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Full traceback. Traceback (most recent call last): File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 973, in _bootstrap_inner self.run() File "/opt/homebrew/Cellar/python@3.9/3.9.10/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "/Users/ryanoh/Projects/crysenv/lib/python3.9/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) … -
Django models - inherit from two classes: each with a custom Manager?
I've got an issue where I have a Model that is inheriting from two other AbstractModel classes. Both of the AbstractModel use a custom Manager to to point all queries to a particular database. Here is the first Model: # appA / models.py class AbstractA(models.Model): objects = managers.AManager() class Meta: abstract = True # appA / managers.py class AManager(models.Manager): def get_queryset(self): return super(AManager, self).get_queryset().using("database_a") This is the secondary Model that I utilize in order to do 'soft deletions' (from this article) # appA / models.py class ASoftDeletionModel(models.Model): deleted_at = models.DateTimeField(blank=True, null=True) objects = SoftDeletionManager() all_objects = SoftDeletionManager(alive_only=False) class Meta: abstract = True def delete(self): self.deleted_at = timezone.now() self.save() def hard_delete(self): super(ASoftDeletionModel, self).delete() # appA / managers.py class SoftDeletionManager(models.Manager): def __init__(self, *args, **kwargs): self.alive_only = kwargs.pop("alive_only", True) super(SoftDeletionManager, self).__init__(*args, **kwargs) def get_queryset(self): if self.alive_only: return ( SoftDeletionQuerySet(self.model) .using("database_a") .filter(deleted_at=None) ) return SoftDeletionQuerySet(self.model).using("database_a") def hard_delete(self): return self.get_queryset().using("database_a").hard_delete() class SoftDeletionQuerySet(models.QuerySet): def delete(self): return super(SoftDeletionQuerySet, self).update( deleted_at=timezone.now(), using="database_a", ) def hard_delete(self): return super(SoftDeletionQuerySet, self).delete(using="database_a") def alive(self): return self.using("database_a").filter(deleted_at=None) def dead(self): return self.using("database_a").exclude(deleted_at=None) I've created another simple model for making comments on a thing that inherits from both of those models like so: class Comment( ASoftDeletionModel, AbstractA ): thing = models.ForeignKey( Thing, on_delete=models.PROTECT, related_name="%(class)ss" ) … -
How can I get count of pages in LimitOffsetPagination django rest framework?
If my code looks like this: class SimpleLimitOffsetPagination(LimitOffsetPagination): offset_query_param = 'page' max_limit = 100 default_limit = 5 def get_paginated_response(self, data): return Response({ 'count': self.count, 'max_page': 'needs count of pages', 'results': data }) Is that possible to get count of pages? or do we have another solution? It's important to have an opportunity using limit filed. -
Problem with add and change instanse in django admin
I try from admin to add or change instance of model - CompletedWork. Error is: TypeError at /admin/ReportingTool/completedwork/68/change/ init() missing 1 required positional argument: 'user' my model: class CompletedWork(models.Model): period = models.ForeignKey(directory.Period, on_delete=models.SET('deleted date'), ) worker = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted worker'), related_name='worker_do', default=settings.AUTH_USER_MODEL ) work_done = models.ForeignKey(directory.WorksType, on_delete=models.SET('deleted works type')) work_scope = models.FloatField(blank=True, null=True) work_notes = models.CharField(_("Comments"), max_length=70, blank=True, null=True, ) record_author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET('deleted user'), related_name='record_author', auto_created=True, ) record_date = models.DateTimeField(auto_now=True) checked_by_head = models.BooleanField(default=False) active = models.BooleanField(default=True) def __repr__(self): return f'{self.period}, {self.worker}, {self.work_done}' def __str__(self): return self.__repr__() def is_active(self): if self.active: return True return False my form: class CompletedWorkForm(forms.ModelForm): class Meta: model = CompletedWork fields = ( 'period', 'worker', 'work_done', 'work_scope', 'work_notes', ) def __init__(self, user, *args, **kwargs): if kwargs.get('record_author'): self.user = kwargs.pop('record_author') super(CompletedWorkForm, self).__init__(*args, **kwargs) if user.struct_division: if user == user.struct_division.head: self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division= user.struct_division).order_by('last_name') | CustomUser.objects.filter(struct_division__management_unit= user.struct_division).order_by('last_name') ) elif StructuralDivisions.objects.filter(curator=user): sd_user_curator = StructuralDivisions.objects.filter(curator=user) self.fields['worker'] = forms.ModelChoiceField( queryset= CustomUser.objects.filter(struct_division__in=sd_user_curator) | CustomUser.objects.filter(id=user.pk) ) else: self.fields['worker'] = forms.ModelChoiceField( queryset=CustomUser.objects.filter(id=user.pk) ) self.fields['work_done'] = forms.ModelChoiceField( queryset=WorksType.objects.filter(available_to=user.struct_division) ) def save(self, commit=True): obj = super(CompletedWorkForm, self).save(commit=False) if commit: obj.user = self.instance.record_author obj.save() return obj my view: class EditCompletedWorkView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): model = CompletedWork form_class = CompletedWorkForm template_name = 'completed_work_edit.html' context_object_name = … -
Using the URLconf defined in , Django tried these URL patterns, in this order:
I have a django app. And some upload functionaliteit. The page with the upload function is loading correct. But after I do a submit. I get this errror: Page not found (404) Request Method: POST Request URL: http://127.0.0.1:8000/main/ Using the URLconf defined in schoolfruitnvwa.urls, Django tried these URL patterns, in this order: admin/ The current path, main/, didn’t match any of these. so this is the views.py from .forms import ProfileForm from .models import UploadFile # Create your views here. """ def store_file(file): with open("temp/hello.png", "wb+") as dest: for chunk in file.chunks(): dest.write(chunk) """ class CreateProfileView(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) uploadfile.save() return HttpResponseRedirect("/") return render(request, "main/create_profile.html", { "form": submitted_form }) urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.CreateProfileView.as_view()) ] forms.py: class ProfileForm(forms.Form): upload_file = forms.FileField() So my question is: what I have to change? -
Django to Postgres connection issues on AWS server
I'm setting up an Amazon AWS test server with Django on which I use Postgres as a database. This was my way here: $ sudo apt update $ sudo apt install python3-pip python3-dev libpq-dev postgresql postgresql-contrib I downloaded my files from Github and created a virtual environment for it and inside I installed psycopg2. $ pip install psycopg2 How I configured Postgres: $ sudo -i -u postgres $ psql $ createuser --interactive (super user); $ createdb Filme; Some other information that may be useful about Postgres: $ service postgresql status > postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; enabled; vendor preset:> Active: active (exited) since Wed 2022-10-05 17:08:25 UTC; 20h ago Main PID: 977 (code=exited, status=0/SUCCESS) CPU: 1ms Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Starting PostgreSQL RDBMS... Oct 05 17:08:25 ip-172-31-29-151 systemd[1]: Finished PostgreSQL RDBMS. $ pg_lsclusters > Ver Cluster Port Status Owner Data directory Log file 14 main 5432 online postgres /var/lib/postgresql/14/main /var/log/postgresql/postgresql-14-main.log In my settings.py file of my project: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'Filme', } } O erro ocorre quando eu tento rodar a migração para o novo banco de dados: $ (env) $ python3 manage.py migrate > Traceback (most recent call last): File "/home/ubuntu/Filmes/env/lib/python3.10/site-packages/django/db/backends/base/base.py", … -
Is it possible to use ImageFields from other models via inheritance? (django)
I have two models with imageFields, and want to have the same images there, to display them at the admin-page... My two models: class Produkt(models.Model): STATUS_CHOICES = ( ('draft', 'offline'), ('published', 'online'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') image = models.ImageField(upload_to='images', height_field=None, width_field=None, null=True) price = models.DecimalField(max_digits=10, decimal_places=2, default=0.00) publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='published') class Meta: ordering = ('-publish',) def __str__(self): return self.title objects = models.Manager() published = PublishedManager() def get_absolute_url(self): return reverse('app:produkt_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) tags = TaggableManager() class Bestellung(models.Model): def two_week_hence(): return timezone.now() + timezone.timedelta(weeks=2) produkt = models.ForeignKey(Produkt, on_delete=models.CASCADE, related_name='bestellung') def get_image(self): return self.produkt.image versand_bis = models.DateTimeField(default=two_week_hence) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=True) class Meta: ordering = ('created',) def __str__(self): return f'hat Produkt {self.produkt} bestellt' and my admin.py looks like this: @admin.register(Produkt) class ProduktAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.image.url)) image_tag.short_description = 'Image' list_display = ('title', 'image_tag', 'image', 'kategorie', 'price', 'publish', 'status') list_filter = ('created', 'publish', 'status', 'price',) search_fields = ('title',) prepopulated_fields = {'slug': ('title',)} date_hierarchy = 'publish' @admin.register(Bestellung) class BestellungAdmin(admin.ModelAdmin): def image_tag(self, obj): return format_html('<img height="100" src="{}" />'.format(obj.get_image.url)) image_tag.short_description = 'Image' list_display = ('produkt', 'image_tag', 'versand_bis', 'created', 'active') list_filter = … -
how can I import one model from one app to another?, been doing it the standard way but its not working [closed]
This is the directory layout/related files and settings: When I run migrations I get this error message : I just want to import the group class from the models.py in group directory to my post models.py. I have tried many changes to the structure of the import code with no success. I tried : from simplescoial.groups.models import Groups This seems to have no issue with Pycharm (no red underlines and picks up autocomplete at all stages) but on the terminal I get a NoModuleFoundError it cant find simplesocial.groups. -
Creating a single-column dataframe in Pandas from a Django queryset
I'm trying to create a dataframe containing the values from field_1 and field_2 in a single column. I haven't used pandas a whole lot before, so I'm sure this is naive. # Create a dataset in CSV format field_names = ["work_description", "comments"] writer = csv.writer(open("dataset.csv", "w"), quoting=csv.QUOTE_ALL, delimiter=",") writer.writerow(field_names) for instance in WorkOrder.objects.all(): writer.writerow([str(getattr(instance, f)) for f in field_names]) # Read CSV data_frame = pd.read_csv("dataset.csv", index_col=0) # Combine columns df2 = data_frame.apply(lambda x: ", ".join(x[x.notnull()]), axis=1) If I'm working with a fairly large dataset, is there a way I can make this more efficient? I would like to eliminate the step that creates the CSV entirely, if possible. If anybody can point me in the right direction, that'd be fantastic.