Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating a new model with a one-to-one relationship with an existing model Django
I want to add a Profile model relationship through a one-to-one field to the existing User model. However I already have a couple of users in the database. How can I migrate the new model while creating these default relationships at the same time? So for example I have two users Foo and Bar already created in the database and after migrating the Profile model both users should have an associated Profile with them. Models class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) first_name = models.CharField(max_length=255) surname = models.CharField(max_length=255) is_active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["first_name", "surname"] def get_full_name(self): return f"{self.first_name} {self.surname}" def __str__(self): return self.email def is_staff(self): return self.staff def is_admin(self): return self.admin ### New model I want to create class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default="gravatar.jpg", upload_to="avatars/") username = models.CharField(max_length=255, blank=True) phone = models.CharField(max_length=15, blank=True) def __str__(self): return f"{self.user.first_name}'s profile" -
Adding custom title to django form fields
I would like to add custom title to one of my form fields. I made some modifications but it still not working. My forms.py file ` from django.forms import ModelForm from django import forms from .models import bug from phonenumber_field.modelfields import PhoneNumberField status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class UploadForm(ModelForm): name = forms.CharField(max_length=200) info = forms.TextInput() status = forms.ChoiceField(choices = status_choice, widget= forms.RadioSelect()) fixed_by = forms.CharField(max_length=30) phn_number = PhoneNumberField() #created_by = forms.CharField(max_length=30) #created_at = forms.DateTimeField() #updated_at = forms.DateTimeField() screeenshot = forms.ImageField() class Meta: model = bug fields = ['name', 'info', 'status', 'fixed_by', 'phn_number', 'screeenshot'] labels = {'fixed_by' : 'Fixed by/Assigned to'} ` my models.py file ` from django.db import models from phonenumber_field.modelfields import PhoneNumberField, formfields from django.utils import timezone from django.contrib.auth.models import User # Create your models here. status_choice = [("Pending","Pending"),("Fixed","Fixed"),("Not Fixed","Not Fixed")] class bug(models.Model): name = models.CharField(max_length=200, blank= False, null= False) info = models.TextField() status = models.CharField(max_length=25, choices=status_choice, default="Pending") fixed_by = models.CharField(verbose_name="Fixed by/Assigned to", max_length=30) phn_number = PhoneNumberField() user = models.ForeignKey(User, on_delete= models.CASCADE) created_at = models.DateTimeField(auto_now_add= True) updated_at = models.DateTimeField(auto_now= True) screeenshot = models.ImageField(upload_to='pics') ` Need to change the form field title "Fixed by" to "Fixed by/Assigned to" -
django django.db.models.query_utils.DeferredAttribute object at 0x000
I'm trying to create a custom id for my project def get_default_id(): last_cl_itemid = ClearanceItem.objects.all().order_by('cl_itemid').last() if not last_cl_itemid: return str(ClearanceItem.sem)+ '00' class ClearanceItem(models.Model): cl_itemid = models.CharField(primary_key=True, max_length=255, default=get_default_id) office = models.ForeignKey('Office', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) class Meta: managed = False db_table = 'clearance_item' When I try to post something like this { "sem": "1", } It's should look like this 1-00 but When I check the rows in the ClearanceItem <django.db.models.query_utils.DeferredAttribute object at 0x0000024D625844C0>00 How can I do this or any alternative solution -
Removing items from a list in a request.session is not working I do not understand why
I try to create a basic Q&A game. In the request.session['questions'] I am saving the questions I want to render . The flow should be : Question 1 as son the form is loaded --> once the user click next question 2 shoul be rendered an so on until the request.session['questions'] is empty. whit the following code I Only could show the 2 first options and I don`t know why is not working as expected. def game(request): if request.method == 'GET': request.session['questions'] = ['question1','question2','question3','question4'] print(request.session['questions']) q = request.session['questions'].pop(0) form = QForm({'question':q}) print(request.session['questions']) return render(request, 'game.html', {'form':form}) else: if request.method == 'POST' and len(request.session['questions']) >0: q= request.session['questions'].pop(0) print(name) form = QForm({'question':q}) return render(request, 'game.html', {'form':form}) else: return redirect('home') -
Time gap between message.errors in django
I created a Django app with a form. when the form is submitted and found error, messages.error(request, e) is called, where e is the error text. the real code for field, errors in form.errors.items(): print('Field: {} Errors: {}'.format(field, ','.join(errors))) e = 'Field: {} Errors: {}'.format(field, ','.join(errors)) messages.error(request, e) if I have multiple errors, multiple error boxes pops up at same time, but I want to make a time difference of .5seconds between each error popup. I saw time.sleep(0.5) but the issue is it just takes timegap inside forloop not in gap between the popup. There might be a JS fix, I would like to know how here's my html code {% if messages %} {% for message in messages %} {% if message.tags == 'alert-success' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="success" data-toast-duration="2000" class="noty-tost d-none rounded shadow bg-success"></div> {% endif %} {% if message.tags == 'alert-danger' %} <!-- Toast --> <div data-toast data-toast-text="{{ message }}" data-toast-gravity="top" data-toast-position="right" data-toast-className="danger" data-toast-duration="5000" class="noty-tost d-none rounded shadow bg-danger"></div> {% endif %} {% endfor %} {% endif %} $(document).ready(function () { $('.noti-toast').click() }); // used to trigger it(using toastify.js from a template, i don't really know much about it, but … -
How to manullay generate a new drf-simplejwt access token post the expiry of old access token using the pre-genrated refresh token for specific user?
I am using django restframework's simplejwt library to manually create tokens for user using the below function. from rest_framework_simplejwt.tokens import RefreshToken def get_tokens_for_user(user): refresh = RefreshToken.for_user(user) return { 'refresh': str(refresh), 'access': str(refresh.access_token), } The above function get_tokens_for_user will return the serialized representations of new refresh and access tokens for the given user. This function is called while user registration and login. However, after the access token is expired, a new access taken needs to be generated using the refresh token. I am unable to figure out the way/method/function for generating new access token with the refresh token. -
I want to change UTC time zone to Pakistan time zone in Django 4..1.2, can anybody help me?
This is my code below and it is not working LANGUAGE_CODE = 'en-us' TIME_ZONE = 'Asia/Pakistan' USE_I18N = True USE_L10N = True USE_TZ = True it is giving me this error A server error occurred. Please contact the administrator. -
Django - Data is not posting to DB
I am currently working on a note/comment system. It is intended to work as adding notes to each individual projects. For example, you set up a "Project" and there is a note or comment sections intended for adding updates to the project. Here is my view.py for updating the project. The top portion is for updating the project itself, the bottom portion is for adding the notes. @login_required(login_url="/login") def update_project(request, pk): queryset = DevProjects.objects.get(id=pk) form = UpdateProject(instance=queryset) if request.method == 'POST': form = UpdateProject(request.POST, instance=queryset) if form.is_valid(): form.save() return redirect('/') project = get_object_or_404(DevProjects, id=pk) notes = project.notes.filter(id=pk) new_note = None if request.method == 'POST': notes_form = AddProjectNotes(request.POST, instance=project) if notes_form.is_valid(): new_note = notes_form.save(commit=False) new_note.project = project new_note.save() else: notes_form = AddProjectNotes() return render(request, 'projects/updateprojects.html', {"form": form, "queryset": queryset, 'project': project, 'notes': notes, 'new_note': new_note, 'notes_form': notes_form}) Whenever I try and submit the notes, it shows that is successfully posted to DB but in DB there is no entries. Here is my template. <div class="container"> {% if new_note %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment</h2> <form action="." method="post"> {{ notes_form.notes|as_crispy_field }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} </div> <div class="container"> … -
Adding multiple authentication classes in API using Django Rest Framework
I have multiple internal services communicating with a django server using DRF, I have implemented token authentication on django server to authenticate requests coming from different services. I want to develop an API which can be accessed by more than 1 external service. So in my API I declared authentication_classes = [ServiceAuthClass1, ServiceAuthClass2] and permission_classes=[] Following what DRF documentation says for custom authentication the overridden authenticate method in ServiceAuthClass1 and ServiceAuthClass2 should return None if you dont want to attempt authentication using that authentication class and you want DRF to check with another authentication class(ref). Agreed and Done! In case authentication does not happen with any mentioned class DRF is not raising any error/exception. How am I suppose to handle this case? -
Dockerfile is not working correctly in ARM Ubuntu 20
I am trying to build an image that works fine on mac on a ubuntu 20 virtual machine. on my host computer I run docker-compose --debug -f local.yml build and it works fine. docker-compose --debug -f local.yml build when I type the same command into ubuntu i get: DEBU[0000] using default config store "/Users/lancemeister/.docker/buildx" [+] Building 3.9s (20/42) => [meister_affiliate_shop_local_docs internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.85kB 0.0s => [meister_affiliate_shop_local_django internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 1.90kB 0.0s => [meister_affiliate_shop_production_postgres internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 32B 0.0s => [meister_affiliate_shop_local_docs internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_production_postgres internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_local_django internal] load .dockerignore 0.0s => => transferring context: 34B 0.0s => [meister_affiliate_shop_local_docs internal] load metadata for docker.io/library/python:3.10-slim-bu 2.9s => [meister_affiliate_shop_production_postgres internal] load metadata for docker.io/library/postgres:1 3.0s => [auth] library/python:pull token for registry-1.docker.io 0.0s => [auth] library/postgres:pull token for registry-1.docker.io 0.0s => [meister_affiliate_shop_local_docs internal] load build context 0.0s => => transferring context: 935B 0.0s => CACHED [meister_affiliate_shop_local_docs python 1/1] FROM docker.io/library/python:3.10-slim-bullse 0.0s => [meister_affiliate_shop_local_django internal] load build context 0.5s => => transferring … -
How to access list items in django jinja template dynamically using variable indexing
Django jinja template error - TemplateSyntaxError I was trying to create sample show users page where I am want to show username, password and role of the users. I will be storing role as numbers and later I am trying to get the role name from a list. I have hard coded this role names to a list roles = ['admin', 'teacher', 'student'] this roles has been passed to html page as context value. Also, I am passing a num variable for accessing the list items(atm its value is also hard coded, I will be changing this in future) views.py def index(request): roles = ['admin', 'teacher', 'student'] num=1 return render(request=request, template_name='show_all.html', context={'roles': roles, 'num': num}) and inside my html page I am trying to access this list using num variable as given below show_all.html {{roles[num]}} but it is throwing an error TemplateSyntaxError at /show_all Could not parse the remainder: '[num]' from 'roles[num]' there are few solutions that saying roles.0 will get you the first result and roles.1 will give next, But I don't want to hard-code the index there. requirements.txt asgiref==3.5.2 Django==4.1.3 sqlparse==0.4.3 tzdata==2022.6 I have tried {{roles.num}} {{roles.get(num)}} {{roles[num]}} nothing is giving me desired result. -
Django - 'object is not iterable' error but there are no iterations on my object
I have a Model called Request with a Many-To-One model relationship where a User can have multiple Request objects. A Request is a custom made painting Model with many fields. I am just trying to isolate the specific Request object the User clicked on and show it on a separate template called 'requestcarousel'. I am not running any for loops on the object so I am not sure why I am getting an 'object is not iterable' error. I've tried to use filter instead of get which doesn't give an error but none of the objects are being shown Here is my view: def requestcarousel(request, pk=None): if request.method == 'GET': allRequests = Request.objects.filter(requested_user=request.user.pk) requestedPaintings = allRequests.get(pk=pk) context = { 'requestedPaintings': requestedPaintings, } return render(request, "requestcarousel.html", context) Here is requestcarousel.html: {% extends "index.html" %} {% load i18n %} {% load static %} {% static "images" as baseUrl %} {% block request_carousel_content %} {% get_current_language as LANGUAGE_CODE %} <!-- START CAROUSEL --> <div class="card"> <!-- Title --> <div class="container p-2"> {% if requestedPaintings %} {% if LANGUAGE_CODE == 'ja' %} <div class="card-title p-3"> <h4>{{requestedPaintings.name}} </h4> </div> {% else %} <div class="card-title p-3"> <h4>{{requestedPaintings.english_name}} </h4> </div> {% endif %} {% endif %} </div> … -
Django - How to prevent form reload if entered incorrectly
I have the following login form: <input type="text" placeholder="Username" name = "username" /> <input type="password" placeholder="Password" name = "password" /> <button type = "submit" name = "submit" value = "sign_in" >Log In</button> {% for message in messages %} <p id = "messages" style = "color:red; font-weight: bold;" class = "errormessage">{{message}}</p> {% endfor %} In the event that the user incorrectly enters their username/password, I display an error, working with the following view: if (request.POST.get('submit') == 'sign_in'): #-----------SIGN IN FUNCTION---------- context = {} if request.user.is_authenticated: return HttpResponseRedirect("/levels/1") # redirect 2 dashboard else: if request.method == 'POST': # if user isnt already logged in username = request.POST.get('username') password = request.POST.get('password') user = authenticate(username=username, password=password) #authenticate user if user is not None: # if user exists login(request, user) return HttpResponseRedirect("/levels/1") # redirect to dashboard else: # if user entered username/password wrong context = {'ALERT':"Username OR password is incorrect"} messages.error(request, 'Username OR password is incorrect') However, the form doesn't work as expected. When the user incorrectly enters the form, the page refreshes and the user has to click back on the Log In button to view the error (the login form is a small modal that comes up) I want to make it so … -
django how to create custom id
I'm trying to create an custom id for my project the id should contain the course,schoolyear,semester then incrementing number that start with 00 When I post something like this in ex. Postman { "sem": "1", "sy": "2022-2023", "studentid": "2019-0478" "course": "ENGG" } it will create something like this ENGG2022-20231-00 but the error is saying django.db.utils.DataError: value too long for type character varying(20) for now this is what I got def get_default_id(): last_CI_id = CourseItem.objects.all().order_by('CI_id').last() if not last_CI_id: return str(CourseItem.office) + str(CourseItem.sy) + str(CourseItem.sem) + '00' Even if I remove the others like return str(CourseItem.sy) + '00' it still will return the same error class CourseItem(models.Model): CI_id = models.CharField(primary_key=True, max_length=20, default=get_default_id) studentid = models.CharField(max_length=9, blank=True, null=True) course = models.ForeignKey('Course', models.DO_NOTHING, blank=True, null=True) sem = models.CharField(max_length=1, blank=True, null=True) sy = models.CharField(max_length=9, blank=True, null=True) Hope someone can help and if this is not gonna work atleast can I have some alternative solution to this problem -
how to add a text box to django forms.MultipleChoiceField?
when use "widget=forms.Select" there is text box automatically added, but when use "widget=forms.CheckboxSelectMultiple" there are no text box around the choices. How to add the text box please? in the forms.py SEGMENTATION = ( (HIGH, 'High'), (MEDIUM, 'Medium'), (LOW,'Low') ) segmentation = forms.MultipleChoiceField( # widget=forms.Select, widget=forms.CheckboxSelectMultiple, choices=SEGMENTATION ) in html <div class="col-xs-5"> {% bootstrap_field offer_form.segmentation %} </div> [![now it looks like this][1]][1] [1]: https://i.stack.imgur.com/sbc6y.png -
Am trying to create a user request from an existing model object but If statement on 2 instances of object is not working for me
Here's my model class Users_Balanc(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) Amount = models.FloatField(max_length=4, default=0.0) Profit = models.FloatField(max_length=30, default=0.0) Bonus = models.FloatField(max_length=30, default=10.0) Referral_Bonus = models.FloatField(max_length=30, default=0.00) Deposit = models.FloatField(max_length=30, default=0.00) Withdrawals = models.FloatField(max_length=30, default=0.00) def __str__(self): return f'{self.user.username} Users_Balanc' And my view def withdrawal_request(request): if request.method == 'POST': Amount = request.POST['Amount'] username = request.GET.get['username'] total = Users_Balanc.objects.all() if (total.Amount <= Amount): New_Request = Request.objects.create(value=Amount, user=username) New_Request.save messages.info(request, 'Successful') return HttpResponse('Request sent sucessful') else: return HttpResponse('Insufficient funds') For more clarification, am using ajax post request method on the html page to return the response For more clarification, am using ajax post request method on the html page to return the response -
Why is My Ordered List with Template Variable is Showing the Numeral One for Each Entry?
I'd appreciate your help figuring out why my ordered list with template variables shows the numeral one for each entry. I'd also like to know how to correct this and present an ascending list. Here's what's happening: I am trying to show the top three selling items. One of the top items has a three-way tie, so I should show five items. I see five items, but each is labeled as number one. Here's what it looks like: Here's my code: views.py class ReportView(LoginRequiredMixin, TemplateView): template_name = "inventory/reports.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context["purchases"] = Purchase.objects.all() revenue = Purchase.objects.aggregate( revenue=Sum("menu_item__price"))["revenue"] total_cost = 0 for purchase in Purchase.objects.all(): for recipe_requirement in purchase.menu_item.reciperequirement_set.all(): total_cost += recipe_requirement.ingredient.unit_price * \ recipe_requirement.quantity purchases = Purchase.objects.values( 'timestamp', item_name=F('menu_item__name'), item_price=F('menu_item__price'), item_desc=F('menu_item__description')) df = read_frame(purchases) grouped_purchases = df.groupby('item_name')[ 'timestamp'].count().reset_index() sort_purchases = grouped_purchases.sort_values("timestamp", axis=0, ascending=False, ignore_index=True) top_3 = sort_purchases.nlargest(3, 'timestamp', keep='all') list_of_top_3_purchases = top_3['item_name'].to_list() context["revenue"] = revenue context["total_cost"] = total_cost context["profit"] = revenue - total_cost context["gross_profit"] = (revenue - total_cost) / total_cost * 100 context["gross_margin_ratio"] = (revenue - total_cost) / revenue * 100 context["list_of_purchases"] = list_of_top_3_purchases return context reports.html ... <section style="color: black;"><h2>Top 3 Purchases</h2> {% for item in list_of_purchases %} <ol> <li>{{ item }}</li> </ol> {% endfor … -
how can I store more objects from another class in other classes Field
I've been looking for my problem in Django documentation and couldn't find solution. My problem is that in Api Pannel I cannot insert more objects from "ActorsAndDirectors" class into "cast" Field in "Movie" class. I can only insert one. How to transfrom cast field so I could insert multiple objects from "ActorsAndDirectors" class into "Movie" class this is the code ` class ActorsAndDirectors(models.Model): name = models.CharField(max_length=32, blank=False, null=False) surname = models.CharField(max_length=32, blank=False, null=False) role = models.CharField(max_length=11, blank=False, null=False) def __str__(self): return f"{self.name} {self.surname}" class Movie(models.Model): title = models.CharField(max_length=50, blank=False, null=False, unique=True) description = models.TextField(max_length=400) cast = models.ForeignKey(ActorsAndDirectors, on_delete=models.CASCADE) premiere = models.DateField() updated = models.DateTimeField() slug = models.SlugField() def number_of_ratings(self): return Rating.objects.filter(movie=self).count() def avg_rating(self): score = 0 ratings = Rating.objects.filter(movie=self) for rating in ratings: score +=rating.stars if len(ratings) > 0: return score/len(ratings) else: return 0 def __str__(self): return f"{self.title}, ({self.premiere})" ` I looked through Django documentation for some kind of list Field but with no good results. Im looking for help how to transform the field or maybe some other explanation of my problem -
How to catch scrapy response from spider to pipeline?
I need all the scrapy response with settings, pipelines, urls and everything in pipeline where i create model objects? Is there any way of catching it? pipeline.py class ScraperPipeline(object): def process_item(self, item, spider): logger = get_task_logger("logs") logger.info("Pipeline activated.") id = item['id'][0] user= item['user'][0] text = item['text'][0] Mail.objects.create(user=User.objects.get_or_create( id=id, user=user), text=text, date=today) logger.info(f"Pipeline disacvtivated") spider.py class Spider(CrawlSpider): name = 'spider' allowed_domains = ['xxx.com'] def start_requests(self): urls = [ 'xxx.com', ] for url in urls: yield scrapy.Request(url=url, callback=self.parse, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ' 'like Gecko) Chrome/107.0.0.0 Safari/537.36'}) def parse(self, response): item = MailItem() for row in response.xpath('xpath thins'): ip['id'] = row.xpath('td[1]//text()').extract_first(), ip['user'] = row.xpath('td[2]//text()').extract_first(), ip['text'] = row.xpath('td[3]//text()').extract_first(), yield item I've tried to call response from pipeline, but i have only item. Also the things from created object are not enough from me. Any ideas? -
What is a proper way to write Django model mixin?
I am writing Django project that has a bunch of similar models, so i decided to write some mixins to structure them. What is a best implementation? -
Add custom command to existing django app
I have installed a thirdpartyapp. After installing my ./manage.py --help has an entry like this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... Now I have created thirdparty_cmd1_extra by extending thirdparty_cmd1. I have put it in my application directory. So it looks like $ ./manage.py --help ... [myapp] thirdparty_cmd1_extra [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd2 ... What I want is this, $ ./manage.py --help ... [thirdpartyapp] thirdparty_cmd1 thirdparty_cmd1_extra thirdparty_cmd2 ... -
Query Django ORM three tables with totals
I have three tables CATEGORIES, TIPODESPESA and EXPENSE. I would like to perform a simpler and faster query to return the total expenses grouped by TYPODESPESA and by CATEGORY. The expected result is the one below: enter image description here What I would like is a result in which the totals are grouped first by CATEGORY, then by TYPE EXPENSE and then show the EXPENSES. However, for me to be able to do this, I perform the following queries below and I'm trying to simplify and make it faster, but I'm still learning a few things. If you can help with the query. registros = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, ) \ .order_by('description') categorias_valores = CategoriaDespesa.objects.filter( tipodespesas__tipodespesa_movimentodespesa__data__lte=data_final, tipodespesas__tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesas__tipodespesa_movimentodespesa__company=company.company) \ .values('id').annotate(total=Coalesce(Sum( F("tipodespesas__tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) tipos_valores = TipoDespesa.objects.filter( tipodespesa_movimentodespesa__data__lte=data_final, tipodespesa_movimentodespesa__data__gte=data_inicio, tipodespesa_movimentodespesa__company=company.company).values('id') \ .annotate(total=Coalesce(Sum(F("tipodespesa_movimentodespesa__valor"), output_field=FloatField()), 0.00)) The classes I'm using are: class CategoriaDespesa(models.Model): description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class TipoDespesa(models.Model): category = models.ForeignKey( CategoriaDespesa, on_delete=models.CASCADE, related_name="tipodespesas") description = models.CharField(max_length=200, help_text='Insira a descrição') active = models.BooleanField(default=True, help_text='Esta ativo?', choices=CHOICES) user_created = models.ForeignKey(User, on_delete=models.PROTECT) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Despesa(models.Model): company = models.ForeignKey( Company, on_delete=models.CASCADE, related_name="companies_movimentodespesa") tipodespesa … -
Django project - where to put the script?
I am new to python. I am learning django. I made a script that finds certain words on different sites. I give a list of words and a list of sites. As a result, after crawling sites through selenium, I get the result using pandas in the form of a csv file. I want to visualize my project, make a simple web page that will have two windows. In the first window, the user enters a list of words. In the second window - enters a list of sites. Task: check if these words are on these sites. Display the result during the calculation in the form of a table, each time updating it. In the format - link -- found words What should be the structure of my django project? If I understand correctly, then you first need to write the forms in forms.py. What to do next? Where should I put my original script? Thanks this is an example of what I want to see on my page Sorry for the primitive drawing:) -
database viewer for server?
We have a few proprietary tools that store data in rather standard database, using those tools is a pain in the ass. (A common example is a part number database - with some details, and for example a link to a PDF manufactuer data sheet) Getting access to that tool is an issue. For me - 99% of the time - If I could open a giant txt dump of the database and search it using EMACS or VI - I can find what I need. What I'm looking for is a simple (Apache or IIS server) application that I can do that with HTML against the database. Needs to be able to: (A django thing would be great, we already have a django instance) a) Key point - Display and SEARCH only - no data entry. b) Existing well known database with a standard connector. c) Few canned SQL statements would generate the tables to display d) Dimensions are not small full database is 10K (rows) 200+ columns(attributes) e) A KEYWORD search is required - per line: Example Goal find a 0602 resistor that is 220 ohms. I would type "resistor" "film" "0602" and "220" - and click search. … -
Django save child from parent
I have this code: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model2s" ordering = ('sioticket',) def save(self, *args, **kwargs): vartype = self.name.type cpm = vartype return super(Model2, self).save(*args, **kwargs) I need to ejecute save() of Model2 from save() of Model 1. Or, from save() of Model1, do: tipo = self.name.type cpm = tipo But the problem is that, in parents I don't know if is it possible to access to save() of its childs classes or how to change values of its childs classes from save's parents. Also I have to say, that, if I create a new Model1 and Model2 works fine, but if I update type from Model1, it don't replicate to "cmp" of Model2. I've tried this: class Model1(models.Model): name = models.CharField(max_length=50) type = models.CharField(max_length=50) class Meta: verbose_name_plural = "Model1s" ordering = ('sioticket',) def def save(self, *args, **kwargs): super(Model1, self).save(*args, **kwargs) children = self.objects.all() for child in children: if child._meta.verbose_name_plural=="Model2s": child.save() class Model2(models.Model): name = models.ForeignKey(Model1, on_delete=models.CASCADE, null=True, blank=True) cpm = models.CharField(max_length=50) class Meta: verbose_name_plural …