Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Add Field Update
With the help of a button, I developed a code that allows the area I want to be added as the button is pressed, and this code works without any problems. When I reopen the form to update it, the data comes in as I added and I save it again, then when I enter the updated form, the data is lost. So I'm giving an example, I pressed the button 3 times and 3 fields came to enter, I filled in 3 of them and saved, then when I enter to update, it appears in 3 data. When I exit the update screen and enter that form again, only the most recently added data appears from the 3 data. models.py class Records(models.Model): username = models.CharField(max_length=1000, verbose_name='Ad Soyad',null=True,blank=True) date = models.CharField(max_length=1000,null=True,blank=True) hours = models.CharField(max_length=1000,blank=True,null=True) tel = models.CharField(max_length=1000,verbose_name='Telefon Numarası',null=True,blank=True) tcNo = models.CharField(max_length=1000, verbose_name='TC Numarası',null=True,blank=True) adress = models.CharField(max_length = 1000,verbose_name='Adres/Köy',null=True,blank=True) kurum = models.CharField(max_length=1000,verbose_name='Kurum',null=True,blank=True) diagnosis = models.CharField(max_length=1000, verbose_name='Tanı',null=True,blank=True) intervention = models.CharField(max_length=1000, verbose_name='Müdahale', null=True,blank=True) # medications = models.CharField(max_length=1000, verbose_name='İlaçlar', null=True,blank=True) conclusion = models.CharField(max_length = 1000,verbose_name='Sonuç',null=True,blank=True) doctor = models.CharField(max_length=1000, verbose_name='Doktor',null=True,blank=True) record_one_measurement = models.CharField(max_length=1000, verbose_name='1.Ölçüm',null=True,blank=True) record_one_blood_pressure = models.CharField(max_length=1000, verbose_name='1.Tansiyon',null=True,blank=True) record_one_pulse = models.CharField(max_length=1000, verbose_name='1.Nabız',null=True,blank=True) record_one_spo2 = models.CharField(max_length=1000, verbose_name='1.SPO2',null=True,blank=True) record_one_respirations_min = models.CharField(max_length=1000, verbose_name='1.Solunum/DK',null=True,blank=True) record_one_fire = models.CharField(max_length=1000, verbose_name='1.Ateş',null=True,blank=True) record_second_measurement … -
Auto list fields from many-to-many model
I've created a model of analysis types and then i created a table that groups several analysis to one group: class AnalysisType(models.Model): a_name = models.CharField(max_length=16,primary_key=True) a_measur = models.CharField(max_length=16) a_ref_min = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) a_ref_max = models.DecimalField(max_digits=5, decimal_places=2, null=True, blank=True) # analysis_group = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) def __str__(self): return f"{self.a_name} - {self.a_measur}" class AnalysysGroup(models.Model): group_name = models.CharField(max_length=32) analysis = models.ManyToManyField(AnalysisType, blank=True) def __str__(self): return f"{self.group_name}" I want to have an option to multiple add values via admin panel (I.E. i chose Analysis type then below appear fields to fill) class PatientGroupAnalysis(models.Model): patient = models.ForeignKey(Patient, on_delete=models.CASCADE) analysis_date = models.DateTimeField() analysis_type = models.ForeignKey(AnalysysGroup, on_delete=models.CASCADE, default=1) # amalysis_data = ??? def __str__(self): return f"{self.patient}: {self.analysis_date} - {self.analysis_type} - {self.analysis_data}" enter image description here Tried to use amalysis_data = analysis.type.objects.all() and etc. but that's the wrong way i guess .. :( -
Automatically Move data to archive table if date is older
I have a gallery model in my models.py. I want to automatically move the data to another table called as Archive if created date is more than 30 days. This is my models.py class Gallery(models.Model): id= models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') video = models.FileField(upload_to='videos/', validators=[FileExtensionValidator( ['mp4', 'mov', 'mkv'] )]) tag = models.CharField(max_length=100) classes = models.ForeignKey(Classes, null=True, blank=True, on_delete=models.CASCADE) level = models.ForeignKey(Level, null=True, blank=True, on_delete=models.CASCADE) uploded_date = models.DateTimeField(auto_now_add=True) class Archive(models.Model): id= models.AutoField(primary_key=True) name = models.CharField(max_length=100) image = models.ImageField(upload_to='images/') video = models.FileField(upload_to='videos/', validators=[FileExtensionValidator( ['mp4', 'mov', 'mkv'] )]) tag = models.CharField(max_length=100) classes = models.ForeignKey(Classes, null=True, blank=True, on_delete=models.CASCADE) level = models.ForeignKey(Level, null=True, blank=True, on_delete=models.CASCADE) uploded_date = models.DateTimeField(auto_now_add=True) I have thought of creating signals and sending signals to Archive like this. I have already defined the signal. def date_is_old(self): if self.uploded_date > (datetime.datetime.now()-timedelta(days=15)): date_is_old.send(self.__class__) But this method seems to be ineffective as it only sends signal at time of creation of new record. I need the function to always check and If creation is past 30 days automatically move data to Archive. Is there some way to handle this? I am really out of option tried modifying create method and save methods on table "Gallery". -
Django app not being served via nginx on ubuntu 22.04
I have attempted twice to deploy a django app on ubuntu 22.04 and serve it using nginx but it doesn't work. The guide I am using has worked on previous versions of ubuntu. Upon completion of the guide, I get an 502 gateway error. While inspecting the log errors, I get this error. 4286#4286: using inherited sockets from "6;7;" The closest I have come to answer is this this question but the developer is working with php. -
Django image storing in db
there is a question how best to store images in Django? On stackoverflow, I read that it is better to store them in the file system and serve them Apache, how true is this? And also there is a question, is it possible to hide the path to the image so that it is not visible in the element expect? How i can hide this? -
How to access a specific user's model data as admin?
I'm creating a simple model form that is only available to staff. It has a user selection dropdown list populated by models.py user = models.ForeignKey(User, on_delete=models.CASCADE). On submit I need my view to look up the selected user from the form and return the data in the models for that user (from the built-in Django database). How would I go about doing this? I have searched here and the recommended articles, but they all appear to be for accessing a model as the logged-in user. Here is a screenshot of the form and my code: models.py class GetData(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) forms.py class DataRequestForm(forms.ModelForm): class Meta: model = GetData fields = ['user'] Views.py @login_required def data_form(request): if request.user.is_staff == True: if request.method == 'POST': form = DataRequestForm(request.POST) if form.is_valid(): user = request.POST["user"] print("Form is Valid") print(user) # How to access that user's model data here? -
Django project doesn't allow to work with personal modules
I created a django project and a folder with some helpers to handle firestore stuff. When I try to import the helpers it says that the 'helpers' is not a module. Am I missing something about django ? ANy tip? I'd like to import my helpers in some personalized mixins which will be used in certains views. -
NoReverseMatch at /invoicing/search/
In my localhost i have this error when i search something, for exemple number of invoicing, and at Web site server i have "Server Error (500)", for the same problem, can you help me to fixed this . enter image description here We have the supplier and the invoice, each supplier have 1 and more invoice, whem i go search the supplier for invoicing, i have this error "NoReverseMatch at /invoicing/search/ Reverse for 'profilePage' with keyword arguments '{'pk': ''}' not found. 1 pattern(s) tried: ['accounts/profile/(?P[0-9]+)$']" -
Unable to get current user inside django rest serializer
I'm unable to get current user inside serializer. I have passed context but still i get error like "user": [ "This field is required." ] #Serializer.py class AddressSerializer(ModelSerializer): class Meta: model = Address fields = "__all__" def create(self, validated_data): request = self.context["request"] validated_data["user"] = request.user return super().create(validated_data) #Views.py class AddAddress(APIView): permission_classes = [IsAuthenticated] def post(self, request): print(request.user) serializer = AddressSerializer(data=request.data, context={"request":request}) if serializer.is_valid(): serializer.save() return Response(serializer.data, 200) return Response(serializer.errors) #Models.py class Address(models.Model): user = models.ForeignKey(Account, on_delete=models.CASCADE) full_name = models.CharField(max_length=35) email = models.EmailField(max_length=100) phone = models.BigIntegerField() address_line_1 = models.TextField(max_length=500) address_line_2 = models.TextField(max_length=500) zip_code = models.IntegerField() city = models.CharField(max_length=20) state = models.CharField(max_length=15) country = models.CharField(max_length=15) class Meta: verbose_name_plural = "Address" def __str__(self): return self.full_name I exactly don't know the problem behind this -
Django - set timezone in a django-admin command
I have a django-admin command which is handling message sending to different users in different countries. Each user should get the message at the same date - according to their local timezone. For example: a user in Paris should get a message every Monday at 10 am (Paris time), and a user in NY should get a message every Monday at 10 am (NY time). What happens is that they both get the message at Monday 10 am GMT. I can't use the user's browser local timezone, because its a script running independently in my server. Instead, I want to send the message according to a TZ stored in my DB for each users preferences. How can I send the message according to each user's TZ in my "handle" function? I was trying to use the "django.utils.timezone.activate" but I am not really sure how to make it work -
Chained task or dependent task using celery and django
I am using celery for scheduled task management in my django app. using "app.conf.beat_schedule" i can schedule task successfully. But one of my task depends on another scheduled task and accepts params returend from it. In that case I am facing problem, seracing through internet I became confused and nothing found workable for me. I tried the following and it shows: " Scheduler: Sending due task chained (celery_task_1)" Inside celery.py import os from celery import Celery, group os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') app = Celery('config') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.beat_schedule = { 'chained': { 'task': 'celery_task_1', 'schedule': 5.0, 'args': (), 'options': { 'queue': 'default', 'link': signature( 'celery_task_2', args=(), kwargs={}, queue='default' ) } } } -
Add minimal parameters to logs including user ip address, user ID and time(in django)
Can anyone guide me in this? Add minimal parameters to logs including user ip address, user ID and time (in Django) -
Permission Denied for nginx django deployement on aws nginx (13: Permission denied)
I have the same issue. When i run the (sudo -u www-data stat /home) it gives error. you don`t have permission to execute this command. Although i have given the admin privileges from root user. -
How can i validate django field with either of two validators?
Here is the code, I want ip_address to satisfy either of validate_fqdn or validate_ipv4_address. import re def validate_fqdn(value): pattern = re.compile(r'^[a-zA-Z0-9-_]+\.?[a-zA-Z0-9-_]+\.[a-zA-Z0-9-_]+$') if not pattern.match(value): raise ValidationError('Provided fqdn is not valid') return value class KSerializer(serializers.HyperlinkedModelSerializer): ip_address = serializers.CharField(max_length = 100, validators = [validate_fqdn, validate_ipv4_address]) How can i achieve this? Thanks, -
Independent SQLAlchemy and Django projects integration
I have a project that implemets SQLAlchemy ORM for sending some information (stores in postgres database) to Telegram Bot. It takes randomly reports from DB and sends automatically on schedule. However, there are no explicit accesses to database and no indirect interfaces for interation with data there. Whenever I need change something or add, I'm using CLI. Now I want to develop website with Django (for studying purposes) and implement some features as adding and edititing information in database in order to send to Telegram Bot some fresh data. Are there any opportunities to keep Django web application separate from scheduled SQLAlchemy application? If I make some code changes in SQLAlchemy project DB, will they automatically migrate to Django ORM? Or after each changes in sqlalchemy I need to do python manage.py inspectdb > models.py? Do you know some solutions? I found several answers on the same issue: https://djangostars.com/blog/merging-django-orm-with-sqlalchemy-for-easier-data-analysis/ Configuring Django to use SQLAlchemy However, my main purpose is to use Django ORM for web application and SQLAlchemy for scheduled process. Solutions above can't help me -
How to connect Big Query with python using pyreportjasper
i am using the configuration as follow { 'driver': 'generic', 'jdbc_url': 'jdbc:bigquery://https://www.googleapis.com/bigquery/v2:443;ProjectId={project_id};OAuthType=0;OAuthServiceAcctEmail={email};OAuthPvtKeyPath={path_to_p12_file};', 'jdbc_driver': 'com.simba.googlebigquery.jdbc.Driver', 'jdbc_dir': path_to_all_jdbc_jar_dir, } All the required jar files are in the path_to_all_jdbc_jar_dir I can successfully connect to Jasper studio using similar configuration and it works However i ended up getting this error `NameError: Error fill report: Erro fill internal: java.lang.ClassNotFoundException: com.simba.googlebigquery.jdbc.Driver Anyone know what could possibly wrong here. Thanks alot I am using the jdbc driver below from https://cloud.google.com/bigquery/docs/reference/odbc-jdbc-drivers SimbaJDBCDriverforGoogleBigQuery42_1.2.21.1025 -
Debugging Dockerized Django Project on local machine
I am fairly new in using Docker containers, I had been using Pycharm debugging mode for inspecting views behaviour on local machine, using virtual environments. Can someone guide me, about the standard procedure of adding a breakpoint and step by step inspection, of a Python Django project run inside docker containers(with different services like mongodb, redis and project's container itself. What I did: Run the project locally using Docker, looked into its logs. I am expecting to add breakpoints and check the code state at each step. I am trying to avoid replicating whole codebase in another directory and run it using virtual environment. -
DRF multi fields base match filter queryset
I'm creating a search functionality where we can search based of first_name, last_name, username.it should filter all matches( if at least anyone fields match it should consider ) users except login users. this is what I have done but I'm searching for an efficient Django queryset. if search_name is not None and len(search_name) >= 3: search_obj_1 = User.objects.filter(first_name__iexact=search_name).exists() search_obj_2 = User.objects.filter(last_name__iexact=search_name).exists() if search_obj_1: search_obj_1 = User.objects.filter(Q(first_name__iexact=search_name)) &User.objects.filter(~Q(id=logged_user_id)) search_obj_2 = User.objects.filter(Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = [] search_obj = list(chain(search_obj_1, search_obj_2, search_obj_3)) elif search_obj_2: search_obj_1 = [] search_obj_2 = User.objects.filter( Q(last_name__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_2, search_obj_3, search_obj_1)) else: search_obj_1 = [] search_obj_2 = [] search_obj_3 = User.objects.filter( Q(username__iexact=search_name)) & User.objects.filter(~Q(id=logged_user_id)) search_obj = list( chain(search_obj_3, search_obj_1, search_obj_2)) so is there any better way do the same thing. -
Foreign key filter in a child object
I have the models: Boss - Shop - Employee - WorkSpace class Boss(models.Model): fullname = models.TextField() class Shop(models.Model): name = models.TextField() address = models.TextField() phone = models.TextField() boss = models.ForeignKey( Boss, on_delete=models.CASCADE, related_name="shops" ) class Employee(models.Model): name = models.TextField() phone = models.TextField() shop = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name="employees" ) class WorkSpace(models.Model): name = models.TextField() employee = models.ForeignKey( Shop, on_delete=models.CASCADE, related_name="work_spaces" ) I filtered with Boss.objects.filter(shops__employees__work_spaces__type=C1) and got: { "shops": [ { "id": 32, "name": "Garden flowers", "address": "5 st. Hool-Maa", "phone": "879124851861598", "employees": [ { "id": 150, "name": "Mike", "phone": "8154451246", "work_spaces": [ { "id": 497, "type": "B12" }, { "id": 15, "type": "Z5" }, { "id": 33, "type": "C1" } ] } ] } ] } But I only need C1 from work_spaces: [{ "id": 33, "type": "C1" }] How can I exclude other work_spaces from the queryset or do I need to convert the result to a list and then filter using a for loop? There can be many workspaces, and I don't need to show them all to the user, I need information about the Boss, the Shop, the Employee.. -
Django objects.all() can't work in aaPanel
If objects.all()[:1000000] it can work,but objects.all() it can not work,just retutn Nothing,no error I don't know what happen,it works fine on my computer Everyone can help me? it's my code def get_data(request): units=ErpWater168ShopCardset.objects.all() return render(request,"listall.html",locals()) I try use objects.filter() and objects.exclude(),they work normally,just objects.all() can't work -
Gather all logs from entire flow of celery's task
@shared_task() def run_scraper_task(): ImportDataTaskInfo = apps.get_model("data", "TaskInfo") logger = get_task_logger("A") logger.info("XXXXXXX") task = TaskInfo.objects.create(status=DataTaskStatuses.IN_PROGRESS) try: logger.info("XXXX") crawler_settings = Settings() crawler_settings.setmodule(setting1) crawler = CrawlerProcess(settings=crawler_settings) logger.info("XXXX") crawler.crawl(Spider) reactor.run() logger.info("XXXX") task.status = TaskStatuses.SUCCESS logger.info("XXXX") except Exception as error: logger.error("XXXXX") task.info += str(error) + "\n" task.status = TaskStatuses.ERROR finally: import_task.save() So i have scrapy connected to celery task, and scrapy execute spider.py and pipeline.py where i have for instance def process_item(self, item, spider): logger = get_task_logger("A") logger.info("Pipeline activated.") # i want this message to go into task.info. I want to inject all my logs into object task.info attribute. How i can catch it in spider and in pipeline? I have tried to catch proper task object for every step, but this seems not to be optimal option. -
Django admin: How can I put my logo on the page instead of the site title?
I created django project. It works fine and I can login to admin section of the site. At the top of every page, django shows the "django administration". I know how to change it. Now, I want to know how can I put my logo on the page instead of that title? I read about block branding but I am confused and some solutions I tried did not work. Of course maybe it was my fault and they detailed too advanced. I am newbie , so will be glad to receive more detailed solution. Thanks in advance. -
How to save image to model in wagtail?
When I try to do this I get the following error "'BoundField' object has no attribute 'width'". def serve(self, request): post_data = request.POST or None ... new_image = Image.objects.create( file=review_form['file'], title="Image title" ) new_review.image = new_image if new_review.is_valid(): new_review.save() My form class ReviewForm(TemplateForm): file = forms.ImageField() I used part of code of this answer from wagtail.images.models import Image def save(self, commit=False): if not commit: raise Exception("This form doesn't support save(commit=False)") # build the instance for this form, but don't save it to the db yet instance = super(MyForm, self).save(commit=False) # create the Image object avatar = Image.objects.create( file=self.cleaned_data['avatar_image'], title="Image title" # you may need to add more fields such as collection to make it a valid image... ) # attach the image to your final model, and save instance.avatar = avatar instance.save() return instance -
Data transfer for Jinja2 from Updateviev
I have such a template on every html page into which I want to transfer data from my url processors: {% block title %} {{ title }} {% endblock %} {% block username %} <b>{{username}}</b> {% endblock %} When using regular def functions, I pass them like this: data_ = { 'form': form, 'data': data, 'username': user_name, 'title': 'Add campaign page' } return render(request, 'dashboard/add_campaign.html', data_) But when I use a class based on UpdateView: class CampaignEditor(UpdateView): model = Campaigns template_name = 'dashboard/add_campaign.html' form_class = CampaignsForm There is a slightly different data structure, could you tell me how to pass the required date through the class? -
ValueError: could not convert string to float: '$2,464.34'
I am trying to convert the data to float in order make it as numerical format in excel to sort the data i am getting error.wherever the float in mentioned i did it now but previously there was no float . def get_output_value(self, key, value, neutral=None): display = value if value is None and not neutral.person.is_active: return '-', '-' if value is None: return float(f"${Decimal('.00')}"), float(f"${Decimal('.00')}") if isinstance(value, Decimal): return float(f"${intcomma(value.quantize(Decimal('.00')))}"), float(f"${intcomma(display.quantize(Decimal('.00')))}") return float(value), display