Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Finding latest date in Django Q object
Not 100% happy with the structure of this code, but unfortunately I can't change it at the moment. I'm searching a big database in Django, and because of technical limitations, I must store a list of Q objects, and use Django's reduce() function to merge the Q objects into a single Queryset. I currently have a model like such: class Obj(models.Model): id_number = models.CharField(max_length=128) modified = models.DateField('%Y-%m-%d', default='1900-01-01') I am currently using the following code to select rows that have an id_number present in a list, latest_ids: split_queries = [] for id_num in latest_ids: split_queries.append(Q(id_number=id_num)) result = Obj.objects.filter(reduce(operator.or_, split_queries)) This is working as I expected, but I would like to only keep the row where id_number=id_num and the date modified is the latest. I have seen solutions such as using Django's aggregate() function or the latest() function, but I can't figure out how to use these with Q objects. I was hoping for a Q object such as Q(id_number=id_num, Max('modified')) is behavior like this possible with Q objects in Django? -
Django / HTML Submit button redirecting to the wrong page
I am trying to make a registration form with Django & HTML and I am following this tutorial: Video 2:45:00 into the video, I do the exact same steps as him, even though the only difference in my code is related to my previous question: My previous thread This is my HTML code: <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Registration</title> </head> <body> <form action="register" method="post"> {% csrf_token %} <input type="text" name="first_name" placeholder="First Name"><br> <input type="text" name="last_name" placeholder="Last Name"><br> <input type="text" name="username" placeholder="Username"><br> <input type="email" name="email" placeholder="Email"><br> <input type="password" name="password1" placeholder="Password"><br> <input type="password" name="password2" placeholder="Confirm Password"><br> <input type="Submit"> </form> </body> </html> and this is my views.py: from django.shortcuts import render, redirect from django.contrib.auth.models import User, auth def register(request): if (request.method == 'post'): first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] password1 = request.POST['password1'] password2 = request.POST['password2'] email = request.POST['email'] user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() print('user created') return redirect('') else: return render(request, 'register.html') However, it seems that when I press "Submit", instead of the button actually reading the views.py code and check the IF statement, it just redirects me to localhost:8000/account/register/register, which is completely wrong, such as shown here: Imgur link … -
How should I divide up my project into applications?
I am using Django to create a small website and a small store to go along. I was wondering what are good conventions to split up my project, how do I decide I should create applications with more specific functionality. I heard alot of people write about either projects with 80(!?) apps or tell me each app should have it's own designated and independant functionality. The first makes me none the wiser and the latter indicates that I should create a single app for the entire store. Since payments would be useless without products, and without a shopping cart why even bother with payments... Before I started looking into how I should split it up I guessed that I should divide my shop in something along the lines of: Orders, Profiles, Products and Payments. Where an order is a collection of products, a profile and a payment. Where the payment can be uninitiated, in progress or completed. I believe this would be everything I need for a store. Do any of you have any advice on my implementation or any concrete suggestions on dividing a project into apps, espcecially when on a smaller and simpeler scale. Any articles or resources … -
django 'set' object has no attribute 'items' error
I am trying to deploy my django app on AWS. I create a web-crawler inside my app using bs4 adn requests.I used that to get data from e-commerce sites.it's works perfectly on amazon but it throw this(see at image1) when I try to scrape from newegg. but the same codes works on localhost. first I thought it's the user agent issue and I tried with other user agent but didn't works. I really can't figure out whats the issue so if you know what cause this error then please tell it will be very helpfull. the code and image below: image1 headers = {"User-agent":"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"} url = "https://www.newegg.com/p/pl?d="+query data = re.get(url,headers=headers) soup = bs4.BeautifulSoup(data.content, 'lxml') items_container = soup.find("div", {"class":"list-wrap"}) items = items_container.find("div", {"class":"items-view"}) prdList = [] for item in items.find_all("div", {"class":"item-container"}): header = item.find("a", {"class":"item-title"}) title = header.text link = header["href"] img = item.find("a", {"class":"item-img"}) imgsrc = img.find("img")["src"] price = item.find("li", {"class":"price-current"}) if price == None: price = '$--' else: price = price.find("strong").text prdList.append(Scraper.prdTmplt(imgsrc, title, price, link, site)) allProduct = prdList return allProduct -
Does boosting the number of dynos affect NewRelic APM throughput metrics?
Apologies if this is not the right venue/way to ask... I'm asking more out of curiosity than anything else. I've been working on a large application hosted on Heroku. We've implemented rolling deploy, but still try not to deploy during peak usage times. We recently increased the number of dynos by one, and a senior engineer claims that now it's "safe" to deploy at any time regardless of throughput as "the rpms is higher because we have more dynos to handle all the traffic." It looks like throughput is calculated based on the rate of successful request/response, and that requests that error may not be included in this metric. https://discuss.newrelic.com/t/how-is-throughput-calculated/62322 https://discuss.newrelic.com/t/what-is-the-definition-of-throughput/55856 I'm guessing that if there are a very large number of requests, the requests would queue so that more dynos would mean improvements in the request/response cycle. However, how would this affect throughput rates? And further, how would this affect deploy? If the throughput is 30k rpm wouldn't it still be better to wait until later in the day when usage has started to go back down? -
Django Rest Framework- can I allow pk id or full objects in a serializer's create method?
Lets say I have the following models: class Author(models.Model): first_name = models.CharField(max_length=32) last_name = models.CharField(max_length=32) class Book(models.Model): title = models.CharField(max_length=64) author = models.ForeignKeyField(Author, on_delete=models.CASCADE) And I have the following serializer: class BookSerializer(serializers.ModelSerializer): class Meta: model = Book fields = ('id', 'title', 'author') read_only_fields = ('id') If I then query my books, A book's data looks like: { "id": 1, "title": "Book Title", "author": 4 } Which is what I want, as I return both an array of books, as well as an array of authors, and allow the client to join everything up. This is because I have many authors that are repeated across books. However, I want to allow the client to either submit an existing author id to create a new book, or all of the data for a new author. E.g.: Payload for new book with existing author: { "title": "New Book!", "author": 7 } or, payload for a new book with a new author: { "title": "New Book!", "author": { "first_name": "New", "last_name": "Author" } } However the second version, will not pass the data validation step in my serializer. Is there a way to override the validation step, to allow either an author id, or … -
Django searching
I am trying to make app which user can look for few names of one category in the same time. F.e. There are 10 name like mexicola, red rasputin and black magic. And i wish that user can look for mexicola and red rasputin just with writing "mexicola red rasputin" or "red rasputin mexicola black magic" or just "black magic" and so on. But now it works only with one.. i can not find what is wrong. Here are my views from django.shortcuts import render from django.db.models import Q #new from .models import Recipe from .models import Ingredient def drink_list(request): template = "drinks/drink_list.html" return render(request, template) def search_results(besos): query = besos.GET.get('q') q = Q() for queries in query.split(): q = (Q(recipe_name__icontains=queries)) results = Recipe.objects.filter(q) template = "drinks/search_results.html" context = { 'results' : results, } return render(besos, template, context) model: from django.db import models class Ingredient(models.Model): ingredient_name = models.CharField(max_length=250) def __str__(self): return self.ingredient_name class Recipe(models.Model): recipe_name = models.CharField(max_length=250) preparation = models.CharField(max_length=1000) ingredients = models.ManyToManyField(Ingredient) def __str__(self): return self.recipe_name -
Trying to use natural_key in order to serialize objects
I'm trying to use natural_key methods in order to serialize my models. I have this method in my Monitor model with this inside print: def natural_key(self): print("INSIDEEEEEEEEE") fields = self._meta.fields + self._meta.many_to_many dict_result = {} for field in fields: attr_type = field.get_internal_type() if attr_type == 'ForeignKey': foreign_field = getattr(self, field.name) if foreign_field != None: dict_result[field.name] = foreign_field.natural_key() else: dict_result[field.name] = '' elif attr_type == 'ManyToManyField': foreign_field = getattr(self, field.name) ff_list=[ff.natural_key() for ff in foreign_field.all()] dict_result[field.name] = ff_list else: dict_result[field.field.name] = getattr(self, field.name) return dict_result And I'm calling serializer like this: queryset = serializers.serialize('json', monitors, use_natural_foreign_keys=True) The problem is that this serializer is not executing natural_key method. -
Django 403 Forbidden permission error on Linode even after assigning correct permission to all files.in Apache2
I was trying to host my Django website on Linode. This is how my project heirarchy is. Please access the website here. I haven't touched my etc/apache2/apache2.conf file. / -->root |-->Intranet(Project folder) |-->Intranet |-->wsgi.py Even after granting all the necessary permission I am getting a 403 permission error. The website can be accessed here http://172.105.36.26/. Where am I going wrong with the configuration files. My 000-default.conf file <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost #DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined # … -
django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
This has already been asked, but none of the answers have helped me. This is my configuration. I can connect normally to my local db with this exact configuration, only changing the host in settings.py to localhost. Dockerfile FROM python:3.7 RUN mkdir /app COPY requierments.txt /app/ WORKDIR /app RUN pip install -r requierments.txt COPY . /app/ docker-compose.yml version: '3' services: db: image: mariadb:10.2 expose: - 3306 ports: - "3306:3306" environment: MYSQL_DATABASE: 'django_backend' MYSQL_USER: 'django' MYSQL_PORT: '3306' MYSQL_PASSWORD: 'mysql1234pass' MYSQL_ROOT_PASSWORD: 'password' web: build: . image: backendblockchain_web volumes: - .:/app ports: - "8000:8000" depends_on: - db links: - db command: - /bin/bash - -c - | sleep 10 python3 manage.py migrate python3 manage.py runserver 0.0.0.0:8000 setting.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'django_backend', 'USER': 'django', 'PASSWORD': 'mysql1234pass', 'HOST': 'db', 'PORT': '3306' } } -
jinja2schema not retrieving set variables
I've just started using the json2schema package to retrieve a list of all the variables (both undefined and defined via set) used in a given template. It is working fine with the undefined variables, but it's not retrieving the set variables. Example: from jinja2schema import infer template_str = "<html> {% set foo = 'bar' %} {{ foo }} {{ fizz }} {{ buzz }} </html>" variables_inferred = infer(template_str) # returns {'buzz': <scalar>, 'fizz': <scalar>} # foo isn't retrieved What am I missing? How can I retrieve the set variables? -
Why do I get Page Not Found (404) when using path() instead of url()?
I am working a new Django app following a YouTube tutorial, and so far in my 'urls.py' I've used this code: urlpatterns = [ path('', views.index, name='index'),] and it just worked. However, now I've reached a point where I'm making subdomains (localhost:8000/accounts/register) and using the following code: urlpatterns = [ path('register', views.register, name='register'), ] gives me the following error: Page not found error image (imgur) However, when instead of using path() I use url(), like so: urlpatterns = [ url('register', views.register, name='register')] it works as expected. What is the difference between path() and url(), and which one should I use (in general or in any specific cases)? Thank you for your help guys, I really appreciate it. -
Update value of a template tag from views in django
I have a form in Django to provide information regarding various tasks on a particular day, and these tasks are saved as model objects. I render the tasks on the HTML page as shown as follows in a grid view. (Click Here for the Grid View) But now I want to be able to show the tasks only on that particular day. Using the arrows on the top right corner, I want to be able to filter the tasks and display them. I have already extracted the current date from the javascript of the calendar and send it via ajax call in my views.py. From there I filter the tasks according to the date, but when once I change the view (ie., the date from the left and right corner arrows) I am able to capture the updated date but not able to update the template tags on the JS side. views.py # The default view when the page loads for the first time # As it loads by default to the current date, so filtering tasks on the current date. def schedule(request): today = datetime.datetime.today() tasks = Tasks.objects.filter(schedule_date=today.strftime("%Y-%m-%d")) context = { "tasks": processes, } return render(request, r'dhtmlx_grid_view.html',context) . . … -
how can we post and get data with React hooks by using api (django)
I work with react hook in frontEnd and django in backEnd. SignIn.js export default function SignIn() { const [email, setEmail] = useState(""); const [Password, setPassword] = useState(""); const [customers, setCustomers] = useState([]); const handleSubmit = (evt) => { evt.preventDefault(); alert(`Submitting email ${email}`) alert(`Submitting Password ${Password}`) } return ( some code for UI ..... ); } My question is how can i post and get data from\to django by using api. in other word how can check if user have account or not (Log in function) and sign up in website Thank you. -
Use datetime picker from django admin
I have a DateTimeField on my model, and I would like to utilise the datetime picker from Django admin. This is my view: class TaskCreateView(LoginRequiredMixin, CreateView): model = Task form_class = CreateTaskForm This is my form: class CreateTaskForm(ModelForm): class Meta: model = Task fields = [ 'title', 'description', 'done', 'due_date', 'priority' ] widgets = { 'due_date': AdminDateWidget() } In my template I have included this: {% block js %} {{ form.media }} <script type="text/javascript" src="/admin/jsi18n/"></script> <script type="text/javascript" src="/static/admin/js/core.js"></script> <script type="text/javascript" src="/static/admin/js/admin/RelatedObjectLookups.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> <script type="text/javascript" src="/static/admin/js/actions.min.js"></script> <script type="text/javascript" src="/static/admin/js/calendar.js"></script> <script type="text/javascript" src="/static/admin/js/admin/DateTimeShortcuts.js"></script> {% endblock %} However, all I am seeing is an input type="text" with a 'Today' anchor next to it. What do I need to do in order to implement admin datetime picker for my model field? -
Django admin import-export csv with FK issues
I am bit new to Django admin. I have done "import" with django-import-export. And my models contains ForeignKey references. And I am getting error invalid literal for int() with base 10: ' Homewares & Giftware'. I can show the code, pasting error + relevant information that I think is needed. If something more required, I can provide. Kindly help !!! This is import_csv () #Importing csv file in djnago admin side def import_csv(self, request): context = dict( self.admin_site.each_context(request), form=self.import_form ) if request.method=='POST': csv_file=request.FILES['csv_file'] if not csv_file.name.endswith('.csv'): messages.error(request,'File is not CSV type') return HttpResponseRedirect("import") # if csv_file.multiple_chunks(): # messages.error(request,"Uploaded file is too big (%.2f MB)." % (csv_file.size/(1000*1000),)) # return HttpResponseRedirect("import") data_set = csv_file.read().decode('UTF-8') io_string=io.StringIO(data_set) next(io_string) for column in csv.reader(io_string,delimiter=',',quotechar='"'): if column: print("handle",column[1]) created=VendProduct.objects.get_or_create( handle=column[1], sku=column[2], composite_handle=column[3], composite_sku=column[4], composite_quantity=column[5], vend_product_name=column[6], description=column[7], variant_option_one_name=column[8], variant_option_one_value=column[9], variant_option_two_name=column[10], variant_option_two_value=column[11], variant_option_three_name=column[12], variant_option_three_value=column[13], tags=column[15], supply_price=column[16], retail_price=column[17], account_code=column[18], account_code_purchase=column[19], #brand=column[20], ### HERE IS THE ISSUE ) This is the error that I am getting: Request Method: POST Request URL: http://127.0.0.1:8000/admin/accounting/vendproduct/import/ Django Version: 2.2.6 Exception Type: ValueError Exception Value: invalid literal for int() with base 10: 'Homewares & Giftware' Exception Location: /home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/site-packages/django/db/models/fields/init.py in get_prep_value, line 968 Python Executable: /home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/bin/python Python Version: 3.7.5 Python Path: ['/home/roohi/work/24campus/campus_co_backend', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python37.zip', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/lib-dynload', '/usr/lib/python3.7', '/home/roohi/.local/share/virtualenvs/campus_co_backend-K2HrvuyD/lib/python3.7/site-packages', … -
Django + Nginx Unable to serve media files
I have two servers: the first for Nginx and the second for Django + media files. Nginx server IP: xxx.xx.xx.1 Django + media files server IP: xxx.xx.xx.2 In Django's settings.py file, my media path configurations: MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = "/media/" In the first server, my Nginx configurations: server { listen 80; server_name example.com; location /media/ { proxy_pass http://xxx.xx.xx.2/; } location / { include proxy_params; proxy_pass http://xxx.xx.xx.2:8000/; } } In the second server, where the media files are placed, my Nginx configurations: server { listen 80; server_name xxx.xx.xx.2; location /media/ { alias /home/sadm/Desktop/{project_name}/media; } However, when trying to access example.com/media/images/my_image.jpg, I get a 404 error. Any help is greatly appreciated! Thanks in advance! -
Django and JQuery - Iterate through object list
I have a table that looks like this: <table> {% for object in object_list %} <tr> <th id="hiddenth">{{ object.user }}</th> <th><button onclick="showTh()">Show Users</button></th> </tr> {% endfor %} </table> This returns a column with usernames and a column with buttons as expected. But, all buttons are mapped to the first row of the table and the other rows are not affected. How can I fix this? Thank you for any help -
How to use cycle in django with two columns?
I created one section divided into two columns. Each of the columns is to represent one blog entry. Unfortunately, two columns are currently assigned one and the same entry, and they will be two separate. I don't quite understand how to use the cycle tag correctly in this case. example http://imgbox.com/NWO7qA7S I use the bootstrap 4 and django 2.2 frameworks to create the page. I tried various combinations, but understanding the operation of the cycle tag is unclear to me. {% for post in posts %} <section class="bg-light py-5" id="aktualnosci"> <div class="container"> <h1>Informacje o zmianach w prawie podatkowym</h1> <div class="divider"></div> <p class="text-paragraph pt-3">Lorem ipsum dolor sit amet consectetur adipisicing elit. Ullam iure consectetur accusantium delectus, iusto culpa mollitia eum molestiae at? Ab!</p> <div class="row py-3"> <!-- FIRST POST --> <div class="col-lg-6"> <div class="news-card"> <div class="text-center text-white bg-blue d-flex align-items-center news-card-date"> <div class="mx-auto news-card-date-body w-75"> <i class="far fa-calendar-alt d-none d-block mx-auto"></i> <span class="d-block news-card-date-value mt-1">{{ post.published }}</span> </div> </div> <div class="news-card-body"> <div class="news-card-img"> <img class="img-fluid" src="{% static 'main/images/126.jpg' %}" alt=""> </div> <div class="news-card-content"> <div class="news-card-content-inner"> <h2>{{ post.title }}</h2> <p class="text-paragraph">{{ post.lead }}</p> <a class="pb-2" href="#">Czytaj więcej</a> </div> </div> </div> </div> </div> <!-- SECOND POST --> <div class="col-lg-6"> <div class="news-card"> <div class="text-center … -
How to generate dynamically image URL in Django?
I'm new in Django, and I don't use mainly Python for websites. But now one project require that. I want to create API, where you POST static image URL, and and script would generate with Django something like this: https://example.com/img?image=xXgGDd5GSjfsdaskDAdsKdkSD76454dfGdDfFs.png. This would be exactly same like gived static URL. I have no problem to create API, due about this is much guides when I google it, but this generating... This is my problem. -
How to display a page and start the file download from it in django?
I have a method in my views.py that I've constructed with a http response # # content-type of response response = HttpResponse(content_type='application/ms-excel') # #decide file name response['Content-Disposition'] = 'attachment; filename="ThePythonDjango.xls"' #adding new sheets and data new_wb = xlwt.Workbook(encoding='utf-8') new_wb.save(response) This works fine if I only have response in my return But I also want to return a render return render(request, 'uploadpage/upload.html', {"excel_data": seller_info, "message":message, "errormessage":errormessage}) I was wondering if there's a way to do that -
Uploading Image from django template occurs "MultiValueDictKeyError(repr(key))"
I have tried some of the solutions from previous posts, but nothing works. Everything works fine if I remove the image-upload input from the template. My Template: <form id="contact" action="#" method="post" enctype="multipart/form-data"> <input type="hidden" name="customer_id" value="{{ customer_id }}"> <fieldset> <input type="text" name="name" {% if name %} value="{{ name }}" {% else %} placeholder="Your Name" {% endif %} tabindex="1" required> </fieldset> <fieldset> <input type="text" name="phone" {% if phone %} value="{{ phone }}" {% else %} placeholder="Your Phone Number" {% endif %} minlength="11" maxlength="14" tabindex="3" required> </fieldset> <fieldset> <label>Complaint Image</label> <input type="file" name="complaint_image" accept="image/*" required> </fieldset> <fieldset> <button name="submit" type="submit" id="contact-submit">Submit Feedback</button> </fieldset> </form> views.py: if request.method == "POST": customer_id = request.POST.get("customer_id", None) name = request.POST.get("name", None) phone = request.POST.get("phone", None) image = request.FILES["complaint_image"] return redirect('/custom/success/') Error Message File "/home/raphael/alice_v2/custom/views.py", line 1926, in pureit_feedback image = request.FILES["complaint_image"] File "/home/raphael/alice_v2/venv/lib/python3.6/site-packages/django/utils/datastructures.py", line 85, in __getitem__ raise MultiValueDictKeyError(repr(key)) django.utils.datastructures.MultiValueDictKeyError: "'complaint_image' -
istalled gunicorn but it is not in venv/bin folder
I'm new to gunicorn and trying to deploy a django website on an ubuntu. I have used: pip3 install gunicorn sudo apt-get install gunicorn but when I want to fill this file: sudo nano /etc/systemd/system/gunicorn.service and I fill it with: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=sammy Group=www-data WorkingDirectory=/home/sammy/myprojectdir ExecStart=/home/sammy/myprojectdir/myprojectenv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myproject.wsgi:application [Install] WantedBy=multi-user.target but there is no gunicorn file in /bin what is the missing part? -
AttributeError 'Client' object has no attribute 'get'
Bonjour, j'ai un problème très probablement idiot mais que je n'arrive pas à résoudre, un Attribute error après l'exécution d'une fonction de views En mode degug de mon application Django j'obtiens: AttributeError Exception Value: 'Client' object has no attribute 'get' (...) Error during template rendering In template (...)Comptabo/templates/base.html, error at line 0 Lorsque que je clique sur le nom d'un client dans ma page index. J'ai déjà essayé beaucoup de chose et regardé les topics correspondant ainsi que la doc, je ne comprends pas d'où vient l'erreur. Ce n'est pas un problème liée au template, ni au fichier urls.. Si quelqu'un a une idée Ma fonction client dans views.py : def client(request, id = 0): if id: client = Client.objects.get(id = id) form = ClientForm(client) factures = Facture.objects.filter(client = client) devis = Devis.objects.filter(client = client) form_fact = FactureForm() form_dev = DevisForm() return render(request,'client.html',{'client' : client, 'form' : form, 'factures': factures, 'devis': devis, 'formf': form_fact,'formd': form_dev}) else: return redirect('/index') Ma class Client dans models.py : class Client(models.Model): nom = models.CharField(max_length = 30) adresse_voie = models.CharField(max_length = 30) adresse_code = models.IntegerField() adresse_ville = models.CharField(max_length = 30) adresse_pays = models.CharField(max_length = 30, default = "France") tel = models.CharField(max_length = 12) fax = models.CharField(max_length … -
Access Foreign key items for SQLAlchemy
I would need your support/advice again, as I am just a hobby programmer. I am storing data for a data analysis in mysql and access through django/phpmyadmin. I think it is better than just storing in a text file. For the real analysis I download the latest data then using SQLAlchemy to pandas. Here is the issue: To have the data structured, I use in django/mysql foreign keys, e.g. class Analyse(models.Model): company = models.ForeignKey('analysen.Company', on_delete=models.CASCADE, related_name='analyse') ... other fields class Company(models.Model): identification = models.CharField(max_length=100, primary_key=True) name = models.CharField(max_length=80) The table for the analysis is "Analyse", however, in my pandas aggregation I would like to use after "downloading" with SQLAlchemy also the company name, so a different field of class Company than the primary key. Which is the easiest solution without changing too much? I believe this is not too complicated, I just do not find the solution right now. Thanks in advance for your help! Kind regards!