Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to edit content after website goes live in digital ocean?
I hosted a Django website in digitalocean.com, Now it is live I don't know how to edit it.. I tried this approach, but didn't work: edited the content of website pushed it to GitHub Pull it from digitalocean root user I saw all changes took effect in GitHub and my files in digitalocean but it doesn't work. I resarted nginx, still nothing works as expected. Can you please help me with this? -
Convert join SQL query into django
I am new to django and trying out stuff with it. How do I display selected fields from the joined table. For example: I have two models, X and Y. I am merging these two models based on the foreign key of model Y. How do I write this query as a django code? SELECT col1, col2, col3... FROM X, Y WHERE X.col2 = Y.col1; -
How do I create multiple tables from one single API Call using django?
I am an FE dev that is trying to venture into the world of Python & Django. To learn this, I am creating a sort of mock trading app. I have 2 models. User and UserPortfolio. Currently, I can create both tables independently through 2 different API Calls. However, I would love to be able to create UserPortfolio when User is created. I have established a OneToOne relationship between the tables. Using python, what is the best way to achieve this efficiently? Extra quick question, is it good practice in Django to split models inside a project into their own files? Thanks in advance for your help! :) Inside a folder called models, my user.py looks like this: from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \ PermissionsMixin from .user_portfolio import UserPortfolio class UserManager(BaseUserManager): def create_user(self, email, password=None, **extra_fields): """Creates and saves new user""" if not email: raise ValueError('Email address is required') user = self.model(email=self.normalize_email(email), **extra_fields) user.set_password(password) user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """Custom user model that supports using email instead of username""" email = models.EmailField(max_length=255, unique=True) first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) date_of_birth = models.CharField(max_length=255) phone_number = models.IntegerField(null=True) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now_add=True) created_on = models.DateTimeField(auto_now_add=True) objects … -
django checkbox get checkbox value from html
html file <form method="post"> {% csrf_token %} <table border="2" bordercolor="black" width="500" height="100" cellspacing="0" cellpadding="5"> <thead> <tr> <th>selection</th> <th>student name</th> <th>e-mail</th> <th>CV</th> </tr> </thead> <tbody> {% for ta in tas %} <tr> <td><input type="checkbox" name="checkbox_list" value="{{ ta.id }}"></td> <td>{{ ta.user.first_name }}&nbsp;{{ ta.user.last_name }}</td> <td>{{ ta.user.email }}</td> <td><a href="{{ ta.cv.url }}">view cv</a></td> </tr> {% endfor %} </tbody> </table> <button type="submit">next</button> </form> views.py def ta_ranking(request, id): print('hello word!') check_box_list = request.POST.getlist('checkbox_list') if check_box_list: print(check_box_list) potential_ta = TA.objects.filter(id__in=check_box_list) return render(request, 'ta_ranking.html', {'potential_ta': potential_ta, 'course_id': id}) return redirect('ta_list', id=id) my question is that the ta_ranking class in views.py didn't be called when I click the submit button in html. How can I fix this problem? Thanks for any help! -
'No module named django_cleanup.apps' in production
In development I added django-cleanup to my project. After deploying I'm getting ImportError: No module named django_cleanup.apps in my error logs. My INSTALLED_APPS looks like this: INSTALLED_APPS = [ ... 'main', 'django_cleanup.apps.CleanupConfig', ] I also ran pip3 install django-cleanup -
I have a question about Django's permission management using native sql
My Django program uses native mysql to do the query. There is no ORM. The back-end management system has sales staff and management staff. They see different interfaces. The administrator can see all the interfaces, while the sales staff can only see some of the interfaces What should I do? I am a newbie to python and have not been exposed to such problems. I need help very much, thanks! -
Comparing values from two models within Django DetailView
So I'm attempting to create an automated "tick sheet" as a proof of concept for a proposal to automate a process at my workplace. At work we receive orders from various Suppliers and need to manually tick off the orders that are received against a list of what is expected on a paper sheet each day. I'm using the generic DetailView in order to have a separate page for each Retailer and have a model representing the Retailer with a ManyToMany relationship with the Suppliers. I also have an Order model to 'simulate' a connection to the actual WMS database (with the intention of modifying it after getting actual db read access if/when this is put into production.) I need the expected orders (in the Suppliers ManyToMany relationship) to match against those in the 'real' Order model data, and return an answer as to whether it exists in the db (in a way that I can display it on a template). After a few frantic attempts to solve it myself I'm a little stumped as to how to achieve this within the context of the DetailView, so I fear I am misunderstanding something... My models.py: from django.db import models from … -
Django user access control
For example, I have one model Post. class Post(models.Model): task = models.ForeignKey("User") I want users can only access posts created by themselves but have too many views which list some posts to rewrite queryset in each view. So is there any graceful way to control user access? Save and get current user in thread and implement a new Manager class to Post is a way, but I don't know why this is not recommended. -
Django display Foreign Key reference in Template
I'm trying to develop an application in django. I have a general Publication table that may or may be not linked to a Project model. Here is some code : Project class Project(models.Model): title = models.CharField(max_length=254) abstract = models.CharField(max_length=254) link = models.URLField() def __str__(self): return self.title Publication class Publication(models.Model): id = models.IntegerField(primary_key=True) title = models.CharField(max_length=254) authors_string = models.CharField(max_length=254, default='') project = models.ForeignKey(Project, on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.title Now the problem is that I'm trying to display this reference in the template. How can I do that? publication.project.title seems not to work. In general publication seems not to have a project field Template {% for p in projects %} <option value="">{{ p.title }}</option> {% if p.projects.id %} <option>{{ o.title }}</option> {% endif %} {% endfor %} What am I missing? -
Django Python Template Nested List using For Loop
i'm really new to python programming. Please help me how to show the following result to my template: The Result That I Would like to have in my Django Template is the following example below in a table view: Up Devices Down Devices Server-01 Server-02 Server-03 Total 2 Total 1 I am connecting to a server with API. Here is an example of the API result via GET: { "treesize": 10, "devices": [ { "objid": 3222, "objid_raw": 3222, "device": "Server-01", "status": "Up", }, { "objid": 3291, "objid_raw": 3291, "device": "Server-02", "status": "Down", }, { "objid": 3357, "objid_raw": 3357, "device": "Server-03", "status": "Up", }, ] } Here is my views.py. Please correct me if this is the best way to get the info that I wanted. response = requests.get('http://<ipaddress>/api/table.json?username=user&passhash=123456&content=devices&columns=objid,device,status&id=2223') data = response.json() up_devices = dict() for device in data['devices']: if device['status'] == "Up": device_info = { "objid" : device['objid'], "device" : device['device'], "status" : device['status'], } objid = device['objid'] up_devices[objid] = device_info else: device_info = { "objid" : device['objid'], "device" : device['device'], "status" : device['status'], } objid = device['objid'] down_devices[objid] = device_info context = { 'treesize': data['treesize'], "up_devices": up_devices, } return render(request, 'monitoring/dashboard.html', context) My List results is { 3222: {'objid': … -
Django DRF rename field in serializer but unique_together validation fails
In the serializer used to create a model I want to rename my model field to (field_name)_id so it's clearer for API consumers that this field is an ID field. The model also has a unique_together constraint on some fields. However when validation runs in the serializer, it fails with a KeyError that the field does not exist: ...rest_framework/utils/serializer_helpers.py", line 148, in __getitem__ return self.fields[key] KeyError: 'question' Is there a simple way to get this to work? Minimal example code below. Model class MyModel(Model): question = ForeignKey('uppley.Question', null=False, on_delete=PROTECT) user = ForeignKey('catalystlab.User', null=False, on_delete=PROTECT) class Meta: unique_together = ('question', 'user',) Serializer class MyCreateSerializer(ModelSerializer): question_id = PrimaryKeyRelatedField( write_only=True, source='question', queryset=Question.objects.all(), ) user_id = PrimaryKeyRelatedField( write_only=True, source='user', queryset=User.objects.all(), ) class Meta: model = MyModel fields = ('question_id', 'user_id',) test.py - test for demonstration purposes question = QuestionFactory() user = UserFactory() data = { 'question_id': question.id, 'user_id': user.id, } serializer = MyCreateSerializer(data=data, write_only=True) is_valid = serializer.is_valid(raise_exception=True) #KeyError exception raised here. Previously with DRF 3.10.3 this all worked fine, however with 3.11.0 this now throws a KeyError as mentioned above. What I have tried Removing the source field on PrimaryKeyRelatedField for user_id and question_id in the Serializer actually results in bypassing the unique_together validation … -
Page Not Found when attempting to access a login_required view django
I'm new to django and am having an issue. I have set up a project with simple registration, login, and logout functions. I was experimenting with what would happen if I logged out and attempted to access a login_required page such as the following: @login_required() def index(request): context = { 'server_time': timezone.now(), } return render(request, 'market/index.html', context) When I visit the above function when logged out via the path path('', views.index, name='index'), I get redirected to localhost:8000/accounts/login/?next=/market/ and an error saying: Page not found (404) Using the URLconf defined in app.urls, Django tried these URL patterns, in this order: [name='login_user'] register/ [name='register'] verify/ [name='verify'] admin/ market/ I'm not sure why this error is happening because app.urls has path('', include('core.urls')), in it, so when django tries to find login_user it should go to core.urls and find path('', views.login_user, name='login_user'),, shouldn't it? Let me know if anything in the question is unclear. I'm new to django and stackoverflow. -
Django, how to trigger functions at a specific time?
I have a Django Model which has a published_at field. I want to execute a function every 24 hrs after the published_at everyday. So if, publish_at = '5 Feb 2020 12AM' At 6 Feb 2020 12AM , a set of methods will be implemented At 7 Feb 2020 12AM , a set of methods will be implemented for x days -
Running "/usr/local/bin/gunicorn" in a docker build says " stat /usr/local/bin/gunicorn: no such file or directory"
From the toplevel maps directory, I'm able to install the gunicorn extension ... (venv) localhost:maps davea$ pip3 install gunicorn Collecting gunicorn Downloading gunicorn-20.0.4-py2.py3-none-any.whl (77 kB) |████████████████████████████████| 77 kB 1.2 MB/s Requirement already satisfied: setuptools>=3.0 in ./web/venv/lib/python3.7/site-packages (from gunicorn) (45.1.0) Installing collected packages: gunicorn Successfully installed gunicorn-20.0.4 Below is my docker-compose.yml file version: '3' services: web: restart: always build: ./web ports: # to access the container from outside - "8000:8000" environment: DEBUG: 'true' command: /usr/local/bin/gunicorn maps.wsgi:application -w 2 -b :8000 apache: restart: always build: ./apache/ ports: - "80:80" #volumes: # - web-static:/www/static links: - web:web mysql: restart: always image: mysql:5.7 environment: MYSQL_DATABASE: 'maps_data' # So you don't have to use root, but you can if you like MYSQL_USER: 'chicommons' # You can use whatever password you like MYSQL_PASSWORD: 'password' # Password for root access MYSQL_ROOT_PASSWORD: 'password' ports: - "3406:3406" volumes: - my-db:/var/lib/mysql volumes: my-db: And then I have web/Dockerfile as follows ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ RUN pip3 freeze > requirements.txt COPY requirements.txt … -
How to send images in django api?
I'm trying to send my image from django server to app.There are two appoaches for above problem: 1)send url of the image 2)send encoded image I'm not sure which one to use due to following:- If i choose the first way. Json resoponse will be quicker but if a user returns a page twice, it will make two request on server. Moreever it would be impossible to cache the image. In case of second approach, i can cache the image at client app, but does encoding increase overall response time from the server? Which is the recommended approach for sending image from api. Currently i'm sending image by following:- return JsonResponse({'image':model.image.url}) -
Will taking a snapshot of my RabbitMq instance on AWS harm my app prod?
I have a django webapp using Celery, Supervisord and connected to a t2.micro rabbitmq instance. I wanted to upgrade to a t2.large but was wondering if taking a snapshot will affect anything. Orginally I had not built this set up and so I am trying to learn. Will proceeding with the upgrade only require me to switch the RabbitMQ ip address? What precautions should I take? -
DatabaseWrapper objects created in a thread can only be used in that same thread." when trying to insert into database using celery
I am using celery to read data from a csv and upload it to Postgres. The celery task is working(I think), but django is throwing an error. I am getting a file,converting it to pandas, deleting 2 columns, and converting to numpy and passing to celery. #tasks.py @shared_task def a(data): for x in data: date=x[0] date=datetime.datetime.strptime(date,"%m/%d/%Y") date=str(date.date()) desc=x[1] amount=x[3] account=x[6] cat=x[5] account_type=x[4] #changing account type if account_type=="debit": account_type=False else: account_type=True #creating account if needed and assigning the the object to account try: account=t102_accounts.objects.get(c102_acc_name=account,c102_is_credit_fl=account_type) except: account=t102_accounts.objects.create(c102_acc_name=account,c102_is_credit_fl=account_type) #creating cat if needed and assigning the object try: cat=t100_code_lookup.objects.get(c100_code_name=cat) except: cat=t100_code_lookup.objects.create(c100_code_name=cat,c100_for_exp_fl=True,c100_for_income_fl=True) #creating the transaction if it is not existing already try: t106_transactions.objects.get(c106_trans_amount=amount, c106_trans_date=date,c102_trans_card_num=account, c100_trans_cat=cat,c106_trans_name=desc) continue except: t106_transactions.objects.create(c106_trans_amount=amount, c106_trans_date=date,c102_trans_card_num=account, c100_trans_cat=cat,c106_trans_name=desc) return 'done' #calling the function in views def upload(request): if request.method=="POST": form=UploadFile(request.POST,request.FILES) if form.is_valid(): data=request.FILES["file"] data=pd.read_csv(data) del data["Notes"] del data["Labels"] data = data.dropna(axis=0) data=data.to_numpy() data=data.tolist() a.delay(data) return redirect(dashboard) -
Django modify or reset migrations
I wanted to edit my Models who was working fine(Data was stored with no problem). So I edited the models class, and I runned the manage.py makemigrations command and I think it bugged my project. Even If I delete what I added on my models, it not working like before. Thanks for helping. ps: I dont care about losing the current data that I have saved on my DATABASE models.py (BEFORE modifying) from django.db import models class Post(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) number = models.CharField(max_length=100) def __str__(self): return self.name models.py (AFTER the edit) from django.db import models class Post(models.Model): THE_GENDER = [ ("Monsieur", "Monsieur"), ("Madame", "Madame") ] name = models.CharField(max_length=100) email = models.CharField(max_length=100) gender = models.CharField(max_length=8, choices=THE_GENDER) number = models.CharField(max_length=100) def __str__(self): return self.name forms.py from django import forms from .models import Post from crispy_forms.helper import FormHelper class post_form(forms.ModelForm): def __init__(self, *args, **kwargs): super(post_form, self).__init__(*args, **kwargs) self.helper = FormHelper(self) class Meta: model = Post fields = ["name", "email", "gender" "number"] -
How can I use a Django custom tag from within a PostgreSQL table field? (for citations)
In short, I am trying to call a Django custom tag from within a PostgreSQL database field. I am using a DetailView to load information from a model 'Disorder.' The 'Disorder' model contains a free text field called 'diagnostic_criteria'. I would like to be able to reference citations stored in a PolymorphicModel 'Reference' with the 'diagnostic_criteria' field using a custom tag (of the form {%cite 'reference_slug'%}). I have the custom tag working when it is called directly from a template (disorders_detail.html) but tags within the database field (loaded as {{disorder.diagnostic criteria}}) are not detected. This code and screenshot below illustrates the problem. The reference (identified by {% 'reference1' %} is displayed correctly when called from the template but fails when it is imported from the database. See below the screenshot. #pages/templates/disorders/disorders_detail.html {% extends 'base.html' %} {% load citation_tags %} {% block content %} <h1>{{ disorder.disorder_name }}</h1> <p>Let's have a look at the evidence.{% cite 'reference1' %}</p> <h2>Diagnostic criteria</h2> {{ disorder.diagnostic_criteria | safe }} {% show_references reference_list %} {% endblock content %} The contexts of disorder.diagnostic_criteria are shown in the following screenshot: A screenshot from the page (slightly different source code but the important stuff is the same): #Sample code from … -
Adding to a Many to Many relationship given primary keys
Given primary keys to two different objects with a many to many relationship, what is the most effective way to add the relationship that results in the least amount of database hits? I'm thinking something like the below, but it results in hitting the database twice. ob = A.objects.get(pk=pk_a) ob.B.add(pk_b) Is it possible to only hit the database once? -
Is there a way I can get my docker-compose build command to auto-generate my Django requirements.txt?
I'm using Django 2 and Python 3.7. I have the following directory structure. web - Dockerfile - manage.py + maps - requirements.txt + static + tests + venv "requirements.txt" is just a file I generated by running "pip3 freeze > requirements.txt". I have the below Dockerfile for my Django container ... FROM python:3.7-slim RUN apt-get update && apt-get install RUN apt-get install -y libmariadb-dev-compat libmariadb-dev RUN apt-get update \ && apt-get install -y --no-install-recommends gcc \ && rm -rf /var/lib/apt/lists/* RUN python -m pip install --upgrade pip RUN mkdir -p /app/ WORKDIR /app/ pip3 freeze > requirements.txt COPY requirements.txt requirements.txt RUN python -m pip install -r requirements.txt COPY . /app/ I was wondering if there is a way to build my container such that it auto-generates and copies the correct requirements.txt file. As you might guess, the line pip3 freeze > requirements.txt I have attempted to include above causes the whole thing to die when running "docker-compose build" with the error ERROR: Dockerfile parse error line 15: unknown instruction: PIP3 -
Django performant way to get a queryset of a massive (I'm talking huge) list of ids in order
Pretty much the same flavor as: Django get a QuerySet from array of id's in specific order. I tried https://stackoverflow.com/a/37648265/4810639 But my list of ids is huge (> 50000) and both qs = Foo.objects.filter(id__in=id_list) and qs = qs.order_by(preserved) buckle under the strain. Note: I need a queryset due to the specific django method I'm overriding so anything returning a list won't work. -
Removing '\n' from scraped data in Python
Im scraping repo's names from Github like: *imports* repositorys = [] for ulr in user_repo_url: //in this list I have url like ('https://github.com/USER/?tab=repositories) source = urllib.request.urlopen(url).read() soup = bs.BeautifulSoup(source,'lxml') repos = [repo.text for repo in soup.find_all('div',class_='d-inline-block mb-1')] repositorys.append(repos) return render(request,'file.html',{'repositorys':repositorys}) Im using Django and everything works, but insted of getting clear text I get name and '\n' symbols. I was trying using strip and map function but they didn't work. Do you have any other suggestions why doesn't it work? -
How can create model forms that are subclasses of the model form in django
I want to create a modelForm which depends on a model which name is Project, and this model has two types of fields. The first part of fields are described project features, and the other part must be taken from a catalogue which name is riskCatalogue. I have some issues about to create project modelForm. 1- The fields of riskCatalogue must have private key or id. 2- Every fields of riskCatalogue have some fields which are in fieldSet. So, my question is how can i create Project modelForm. When I want to create a project, I can edit the all project feature fields except project's riskCatalogue fields, and i can't give the id for riskCatalogue fields. models.py class fieldSet(models.Model): riskEvent = models.CharField(max_length=100,verbose_name='Risk Event') impact = models.IntegerField(editable=True,verbose_name='Impact') probability = models.IntegerField(editable=True,verbose_name='Probability') effect = models.IntegerField(editable=True,verbose_name='Risk Effect') description = models.CharField(max_length=200,editable=True,verbose_name='Description') responcive = models.CharField(max_length=100, choices=payType,verbose_name='Responcible') class riskCatalogue(models.Model): # risk catalogue and risks' id War = models.OneToOneField(War,editable=True,on_delete=models.CASCADE,verbose_name='War') Revolution = models.OneToOneField(Revolution,editable=True,on_delete=models.CASCADE, verbose_name='Revolution') CivilDisorders = models.OneToOneField(CivilDisorders,editable=True,on_delete=models.CASCADE, verbose_name='Civil Disorders') ... class Project(models.Model): projectName = models.CharField(max_length=120,verbose_name='Project Name') summary = models.TextField(verbose_name='Summary') crtDate = models.DateTimeField('Creating Date',auto_now_add=True) # project features prjType = models.CharField(max_length=50, choices=types,verbose_name='Project Type') prjCountry = models.CharField(max_length=100, choices=countries,verbose_name='Country') ... prjRisks = models.OneToOneField(riskCatalogue,on_delete=models.CASCADE) forms.py class featureForm(forms.ModelForm): class Meta: model = Project fields = … -
Repeated values in django serializer response with nasted bjects
I working with DRF and i need retrieve data from many fields with many foreign keys. My models are: class ModelFormulario(models.Model): descricao = models.CharField( max_length = 100, unique = False ) class ModelSessao(models.Model): formulario_id = models.ForeignKey('ModelFormulario', on_delete=models.DO_NOTHING, related_name = 'formularioid_sessao' ) tiposessao_id = models.ForeignKey('ModelTipoSessao', on_delete=models.DO_NOTHING, related_name = 'tiposessaoid_sessao' ) comentario = models.CharField( max_length = 100, unique = False ) class ModelTipoSessao(models.Model): perspectiva = models.ForeignKey('models.ModelPerspectiva', on_delete=models.DO_NOTHING, related_name = 'perspectivasidtiposessao' ) descricao = models.CharField( max_length = 100, unique = False, ) observacao = models.CharField( max_length = 100, unique = False ) class ModelFormularioCapa(): formulario_id = models.OneToOneField(ModelFormulario, related_name='formularioid_formulariocapa', on_delete=models.DO_NOTHING, primary_key=True ) descricao = models.CharField( max_length = 100, unique = False ) I'm doing it in serializers like this: #Serializers class QuestaoSerializer(serializers.ModelSerializer): class Meta: Model = ModelQuestao fields = ['id', 'sessao_id', 'tiporesposta_id', 'descricao', 'escala'] class SessaoSerializer(serializers.ModelSerializer): tiposessaoid_sessao = serializers.PrimaryKeyRelatedField(many=True, queryset=ModelTipoSessao.objects.all()) class Meta: Model = ModelSessao fields = ['id', 'formulario_id', 'cometario', 'tiposessao_id', 'tiposessaoid_sessao'] depth = 1 class FormularioSerializer(serializers.ModelSerializer): class Meta: formularioid_formulariocapa = serializers.PrimaryKeyRelatedField(many=True, queryset=ModelFormularioCapa.objects.all()) formularioid_sessao = serializers.SerializerMethodField() model = ModelFormulario fields = [ 'id', 'descricao', 'formularioid_formulariocapa', 'formularioid_sessao', ] depth = 3 My goal is run the FormularioSerializer endpoint, to retrieve a lot of datas, when i do it i receive this JSON: [ { "id": …