Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to make conditional sum for related items when use values() in Django?
I have two models class OrderItem(models.Model): name = models.CharField(max_length=64) price = models.FloatField() quantity = models.FloatField(default=0.0) class OrderModifier(models.Model): item = models.ForeignKey( 'order.OrderItem', related_name="modifiers", on_delete=models.CASCADE) name = models.CharField(max_length=64) price = models.FloatField() void_status = models.BooleanField(default=False) I need to make a sum of price per unique name of OrderItem it works like items = OrderItem.objects.all() qs = items.annotate().values('product__name'). \ annotate( amount=Sum('quantity'), total=Sum(F('quantity') * (F('price'))) ) But I need to add sum of all related Modifiers only when their void_status = False Tried like qs = items.annotate().values('product__name'). \ annotate( amount=Sum('quantity'), total=Sum(F('quantity') * (F('price'))) + Sum( F('quantity') * Case(When(modifiers__void_status=False, then='modifiers__price'), default=0)) ) But that changes my amount (adds to Item qty N of related modifiers) -
Django Trying to send (smtp) email but connection refused
I am using Mac Catalina 10.15.7 / django 3.1.2 / python 3.8.5. I am trying to send an email from django. First, I have defined these in settings.py EMAIL_BACKEND='django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS=True EMAIL_HOST='smtp.gmail.com' EMAIL_PORT=587 EMAIL_HOST_USER='MYID@gmail.com' EMAIL_HOST_PASSWORD='MYPASSWORD' SERVER_EMAIL='MYID@gmail.com' DEFAULT_FROM_EMAIL=EMAIL_HOST_USER and then, I went to the gmail setting and 1) enabled IMAP usage and 2) (in the account's security settings) enabled the usage of the low-security application (https://www.google.com/settings/security/lesssecureapps) So then, in my pycharms' python console, from django.core.mail import EmailMessage email = EmailMessage('subject text', 'body text', to=['RECEIVINGEMAILID@gmail.com']) but I get these errors: Traceback (most recent call last): File "<input>", line 1, in <module> File "/Users/capstone1/lib/python3.8/site-packages/django/core/mail/message.py", line 225, in __init__ self.from_email = from_email or settings.DEFAULT_FROM_EMAIL File "/Users/capstone1/lib/python3.8/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/Users/capstone1/lib/python3.8/site-packages/django/conf/__init__.py", line 64, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting DEFAULT_FROM_EMAIL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. so I can't do the next step email.send() According to the error description, I thought maybe I used write the DJANGO_SETTINGS_MODULE block in settings.py like - DJANGO_SETTINGS_MODULE = [ { 'EMAIL_BACKEND':'django.core.mail.backends.smtp.EmailBackend', 'EMAIL_USE_TLS':True, 'EMAIL_PORT':587, 'EMAIL_HOST':"smtp.gmail.com", 'EMAIL_HOST_USER':'MYID@gmail.com', 'EMAIL_HOST_PASSWORD':'MYPASSWORD', 'SERVER_EMAIL':'MYID@gmail.com', 'DEFAULT_FROM_EMAIL':"MYID@gmail.com" } ] but it's still giving me the same error. -- OR, if I do … -
How to generate a random product_id int to MySQL when adding a new product via Django Admin
I'm trying to add a "product_id" alongside new products to a MySQL database for use in an ecommerce website running Django. I then want to use these product_id values to be searchable from within the eCommerce site. For this reason they only need to be 5 characters long. The product class in models.py looks like this: from django.utils.crypto import get_random_string class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) category = models.ForeignKey(Category, related_name='products', on_delete=models.CASCADE) product_id = models.IntegerField(get_random_string(5, 1234567890)) # Max length 5, numerals only description = models.TextField(blank=True, null=True) price = models.FloatField() When trying to migrate the models to the MySQL server I get: File "C:\Users\user\Desktop\ecommerce\apps\store\models.py", line 18, in <module> class Product(models.Model): File "C:\Users\user\Desktop\ecommerce\apps\store\models.py", line 22, in Product product_id = models.IntegerField(get_random_string(5, 1234567890)) # Create a random numeric id for each product File "C:\Users\user\Desktop\ecommerce\venv\lib\site-packages\django\utils\crypto.py", line 74, in get_random_string return ''.join(secrets.choice(allowed_chars) for i in range(length)) File "C:\Users\user\Desktop\ecommerce\venv\lib\site-packages\django\utils\crypto.py", line 74, in <genexpr> return ''.join(secrets.choice(allowed_chars) for i in range(length)) File "C:\Users\user\AppData\Local\Programs\Python\Python38\lib\random.py", line 288, in choice i = self._randbelow(len(seq)) TypeError: object of type 'int' has no len() As I understand I should be able to set the length of an integer and set it as a numeric id to be stored each time a new product is … -
Save json data into my db using django and postgresql
I'm working with django and postgres, I've a large json data that i want to save into my db but idk how. My json data looks like this: { "Name": "some name", "Direction": "Street name", "City": "City", "Region": "Region", "DirectionGeo": "Street with geopy", "Category": "Category", "ExternalCode": "Code", "lat": latitude, "lon": longitude } That's all the data I want to save, can someone give me an advice on how I can save my data into the db using python please -
column "xx_xx" can only be updated to DEFAULT - DJANGO
Im trying to update some values (via django) at a table on Postgres that contains a Generated column. This is the error im getting: column "xx_xx" can only be updated to DEFAULT See complete error here -
How can i test this url in django
Hi friend i'm trying to test this urls but i don't how do that i have the following code # Method of the test def testViewDeleteUserIsResolved(self): url = reverse('inventory:viewDeleteUser', args={'idUser': tbUser.objects.first().id}) self.assertEquals(resolve(url).func,viewDeleteUser) # Url to try path('viewDeleteUser/?P<idUser>[0-9a-f-]+', views.viewDeleteUser, name='viewDeleteUser'), -
Update data into django database asynchronously
hope you all are doing well. I am trying to make a chat application that with read receipts, I have created the basic chat functionality but when implementing the status of a message, it doesn't update the database, the thing that I am trying to do is we trigger an event when a user visits the window and sends a json response via django channels with status in it we can fetch the data asynchronously but I am not able to update the status field in it. This is how my consumers.py looks like consumers.py async def websocket_receive(self,event): print("received",event) front_text = event.get('text', None) if front_text is not None: loaded_dict_data = json.loads(front_text) status = loaded_dict_data.get("status") message = eval(loaded_dict_data.get("msg"))["id"] self.get_message(message) @database_sync_to_async def get_message(self,message): to_mark=ChatMessage.objects.get(pk=message).update(status="Read") It doesn't throw out any error, but it doesn't update data in database Any help would be much appreciated. -
I can't add Many-To-Many relation in Django
I have 2 models: class Item(models.Model): name = models.CharField(max_length=100) price = models.FloatField(max_length=20) shelfLife = models.BooleanField() def __str__(self): return self.name @property def shL(self): temp = "Doesnt' have shelf life" if(self.shelfLife): temp = "Does have sehlf life" return temp class Order(models.Model): num = models.CharField(max_length=20) date = models.DateField() items = models.ManyToManyField(Item) def __str__(self): return self.num according to this doc I can do: elif request.method == "POST": list_items = request.POST.getlist('arr[]') # get list of items order_num = request.POST.getlist('o_n') # get order num order_date = request.POST.getlist('o_d') # get order date order = Order(num=order_num[0], date=order_date[0]) order.save() for i in range(len(list_items)): item_name = str(list_items[i]) item = Item.objects.filter(name=item_name) order.items.add(item) To fetch each item that I need, I loop through the list_items list of strings and filter each object request by this string and then just add the item to the many-to-many field of the order model. In addition, when I fetch item = Item.objects.filter(name="Salad") the returned QuerySet is not empty, however, if I pass a string variable to the name filter it returns an empty QuerySet. There is a trace of another id error bellow I would appreciate any help! Thanks Error: Internal Server Error: /api/order/item-list/ Traceback (most recent call last): File "/home/anton/miniconda3/envs/cw/lib/python3.8/site-packages/django/db/models/fields/__init__.py", line 1774, in get_prep_value return … -
Django folder without registering it as an app
RoR dev learning Django here. I've inherited a Django project, and I've learned that we can have apps, to encapsulate functionality. To do so I have to create an app like this: django-admin startapp my_app and then add the app to settings.py: INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'my_project.my_app', ) This works fine. However I have found some folders in this Django project for example named: /my_feature that has its own urls.py file and models and views files, just like an app. The my_feature functionalities work just fine. Requests are routed, views called, etc... However, they are NOT present in settings.py as an app. my_feature is nowhere to be found in INSTALLED_APPS or anywhere else (searched the entire project and nothing). So how is this working without it being registered as an app? If a folder with models and views and routes can just be placed in Django project root and will "just work", why are we taught it must be added to INSTALLED_APPS ? -
How do i include a url to display a user's input's result in my form?
using a client I created with certain methods to query Spotify's database. I want to create a form in which a user types something, I call these methods and the user is redirected to another URL where his processed data will show. I created another template to display the data but I do not know how to include the data in the template and also how to link the user to that template. forms.py class SpotifyForm(forms.Form): SpotifyForm = forms.CharField(label= "Spotify Form") urls.py from django.urls import path from .views import Search urlpatterns = [ path("home/" , Search.as_view()), ] views.py class Search(View): form = SpotifyForm template_name = "spotify_calls/homepage.html" context = {"form": form} def get(self, request): return render(self.request , self.template_name, self.context) def post(self, request, *args , **kwargs): form = self.form(request.POST) template_name= "spotify_calls/display.html" if form.is_valid(): data = form.cleaned_data["SpotifyForm":SpotifyForm] SpotifyAPI(client_id = "a79865c029b2469b8738db8cea4252bb" , client_secret = "e775fa3a745f4254a6b9734a5c25e719") SpotifyData = SpotifyAPI.search(self, query=data, search_type="artist") show_data = {"data" : SpotifyData} return render(self.request,template_name,show_data) else: form() Page I want the data to be shown on {% extends "spotify_calls/home.html" %} <h1>Your Spotify Data is</h1> {% block body %} <h2>{{ show_data }}</h2> {% endblock %} Spotify search method def base_search(self, query_params): headers= self.get_resource_header() endpoint = "https://api.spotify.com/v1/search" lookup_url = f"{endpoint}?{query_params}" r = requests.get(lookup_url, headers=headers) … -
how to use filter() queryset without use loop here
i want avoid using queryset inside loop cuz that hit database a lot i have to list Degreyid: [1, 3, 2, 3] companyid: [2, 2, 2, 1] i want use filtering in conjunction: -i want filter for object have Degreyid:1 and companyid:2 and seconde test should be Degreyid:3 and companyid:2.......... Degreyid:3 and companyid:1 . i dont want use loop like this : i=0 list=[] while i < len(listilam): ddegrycomp = DegreyCompany.objects.filter(withdegrey=Degreyid[i], company=companyid[i]) i+=1 there is any way to use filter with two list in parallel ?? note: using : .filter(withdegrey__in=Degreyid, company__in=companyid) dont help here -
django update form with materialize modal
I have this code in my django project and iam trying to edit records with a materialize modal but it always return url with id 1 "cpemodels/edit/1/" and so i can only edit record with id 1, I have a table with edit button in every row. (i dont have any issues when edit record with external page). urls.py path('cpemodel/edit/<int:pk>/', cpemodel_edit, name='cpemodel_edit') views.py def cpemodel_edit(request, pk=None): cmodel = get_object_or_404(CPEMODEL, pk=pk) if request.method == "POST": form = CPEMODELForm(request.POST, instance=cmodel) if form.is_valid(): form.save() return redirect('cpemodel') else: form = CPEMODELForm(instance=cmodel) return render(request,'provision/cpemodel/edit.html',{'form': form, 'cmodel': cmodel }) cpemodel.html <table class="responsive-table striped"> <thead> <tr> <th>Modelo</th> <th>Descripción</th> <th>Vendor</th> <th>Tipo</th> <th>ETHs</th> <th>POTs</th> <th>TV</th> <th>WIFI</th> <th></th> </tr> {% for cpemodel in object_list %} <tr> <td>{{cpemodel.model}}</td> <td>{{cpemodel.desc}}</td> <td>{{cpemodel.vendor}}</td> <td>{{cpemodel.type}}</td> <td>{{cpemodel.eth_ports}}</td> <td>{{cpemodel.pot_ports}}</td> <td>{{cpemodel.catv_port}}</td> <td>{{cpemodel.wifi}}</td> <td><a class="btn-floating waves-effect waves-light green light-3 hoverable" href="{% url 'cpemodel_edit' cpemodel.id %}"><i class="material-icons">edit</i></a></td> <td><a class="btn-floating waves-effect waves-light red light-3 hoverable" href="{% url 'cpemodel_delete' cpemodel.id %}"><i class="material-icons">delete</i></a></td> <td><button class="waves-effect waves-light btn modal-trigger" data-source="cpemodel/edit/{{cpemodel.id}}/" href="#modal1">Modal</button></td> <div id="modal1" class="modal"> <div class="modal-content"></div> </div> javascript code $(document).ready(function(){ $('.modal').modal(); $('.modal-trigger').click(function(){ var url = $('.modal-trigger').attr("data-source"); // use other ajax submission type for post, put ... $.get( url, function( data ) { // use this method you need to handle the response from the … -
Django : create chat with post author just with a submit button
I got a question I did not solved. I try to create a chat with the author of the post. But I got an issue when I tried to catch him directly with form instance: I've created a form with crispy form without field. All field are passed with form.instance. I really thank you in advance. #Post detail class PostDetail(generic.DetailView,FormMixin): model = Cuisine context_object_name = 'post' template_name = 'post_detail.html' form_class = CreateChannelForm def get_context_data(self, **kwargs): context = super(PostDetail, self).get_context_data(**kwargs) context['cuisine_user'] = Cuisine.objects.get(pk=user_id) context['form'] = self.get_form() return context def form_valid(self, form): if form.is_valid(): form.instance.post = self.object form.instance.usera = self.request.user form.instance.userb = cuisine_user #Here is the error form.save() return super(PostDetail, self).form_valid(form) else: return super(PostDetail, self).form_invalid(form) I got private space: class Channel(models.Model): usera = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_usera") userb = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_userb") post = models.ForeignKey(Cuisine,on_delete=models.CASCADE,related_name="channel_post") date_created = models.DateTimeField(auto_now_add=True, null=True) is_active = models.BooleanField('', default=False) slug = models.SlugField(editable=False,unique=True) Here is the model of the post: class Cuisine(models.Model): #Remplir manuellement title = models.CharField(max_length=90) user = models.ForeignKey(User,on_delete=models.CASCADE,related_name='cuisine_user') image = models.ImageField(upload_to='nutriscore/') description = models.TextField(max_length=1000, blank=True) -
Conditional pagination_by number in Django
I have a Django view with pagination: class MyListView(ListView): model = Model context_object_name = "Model" template_name = "template.html" paginate_by = 6 This template has a search bar that works fine: def get_queryset(self): if query: postresult = account_list.filter(name__contains=query) list = postresult return list The problem is, I want the pagination value for a page with a search query to be 20. How can I make the paginate_by value a conditional? -
Wagtail: Blog Pagination with Detailed Page Next and Previous Buttons
I have a pagination on my blog listing page. However, I would like it so that when you are in the Blog posts Details page there is still the option to loop through the posts with a next and previous post option. models.py Here is the repo I have been learning on Any help would be greatly appreciated. Original code from Kalob Taulien @CodingForEverybody -
Django custom auth Access Denied
I am writing a simple Django login page. Where I have an app that handles the authentication of the web page, which then redirect to a seperate app containing the home page. The login functionality is working, if i entered in a wrong password I will get the error Invalid username or password. Please try again.. When I log in and try to access the HomePageView however. I am getting a permission denied error. Am I missing something? Models.py class Users(AbstractUser): registration_id = models.CharField(max_length=100) last_active = models.DateTimeField(null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) REQUIRED_FIELDS = ['password'] USERNAME_FIELD = 'username' EXCLUDE_FIELDS = ["last_active"] forms.py class MyLoginForm(Form): username = forms.CharField(label='Username', max_length=100) password = forms.CharField( widget=forms.PasswordInput()) views.py (auth app) class LoginView(View): template_name = 'auth/login.html' def get(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect(request, reverse('homePage')) return render(request, self.template_name, {'form': MyLoginForm} ) def post(self, request, *args, **kwargs): is_first_login = False try: form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user_info = auth.authenticate(username = username, password = password) if not user_info: messages.error(request,'Invalid username or password. Please try again.') return render(request, self.template_name, {'form': MyLoginForm} ) user_profile = Users.objects.get(username = user_info) login(request, user_profile) messages.info(request, "login successful") return redirect("homePage") else: messages.error(request, "Failed to log in") return … -
How do I display a link from view in a Django template?
Where to find info how to throw links {%url 'name'%} in the template from the view? When creating an article in the admin panel, a link to a page with an identical theme should be added to the "a" tag. I understand that you need to write a model, but what if there are a lot of pages(you need a choice)? Who the faced? view` class BlogArticles(ListView): # model = BlogNewArticles template_name = "blog/blog.html" def get_context_data(self, **kwargs): context = super(BlogArticles, self).get_context_data(**kwargs) context['blockheader'] = BlogPromoHeader.objects.all() # context['blockcenter'] = BlogPromoCentre.objects.all() # context['blockfooter'] = BlogPromoFooter.objects.all() # html {% for post in object_list %} <div class="blog vertical-blog col-lg-4 col-md-4 col-sm-6 col-xs-12"> <div class="blog-foto"><a href="{{ post.get_absolute_url }}"><img src="/media/{{ post.article_image_field }}"></a></div> <div class="blog-date">{{ post.article_datetime }}</div> div class="blog-subtitle"><a href="">{{ post.article_razdel }}</a></div> <div class="blog-title"><a href="{{ post.get_absolute_url }}">{{ post.article_title }}</a></div> </div> {% endfor %} -
I am using django crispy forms how can I change this text to start from the top and get to the below line when the line is full
So guys my site looks like this right now. Here's the site! You will definitely understand my problem if you didn't from the title HTML {% load crispy_forms_tags %} <div class="row"> <div class="col-md-6 offset-md-3" id="ada"> <h3>Makale Ekle</h3> <hr> <form method = "post"> {% csrf_token %} {{form|crispy}} <br> <button type = "submit" class = "btn btn-danger">Ekle</button> </form> </div> </div> CSS body { background: rebeccapurple; font-family: Arial, Helvetica, sans-serif; } #ada { margin: auto; margin-top: 100px; padding-top: 5rem; padding-bottom: 5rem; border: 5px solid rgb(49, 2, 68); background-color: purple; border-radius: 5%; } h3 { font-size: 2rem; color: white; } label { color: white; } input { width: 800px; margin-bottom: 1.2rem; size: 2rem; border: 3px solid purple; text-align: justify; } input[name="context"] { height: 10rem; padding: 20px 10px; line-height: 28px; } So guys I think I am missing something easy. I tried to solve it by adding some code in CSS but it definitely didn't work. -
group items with same value with that value as header
I'm practicing my python and django by making a recipe site. I can add ingredients (class RecipeIngredient) per recipe using inlines, searching for ingredients i already have in my database (class Ingredient) (with nutrional facts etc). This results in one big list of ingredients per recipe. To order them I added a step and a stepnum attribute. I return a list ordered by the stepnum, but how can I div them apart? For instance. If you make a cake you would have ingredients for the cake, and for the icing. all the ingredients for the icing would get a step value of "icing", and a stepnum of 0. all the ingredients for the cake would get a step value of "cake" and a stepnum of 1. I would like all the ingredients with stepnum 1 to appear under one that has the value associated with the items that have a stepnum value of 1, in this case "cake". How? I have this code on my recipedetail.html: <div><h1> INGREDIENTS: </h1></div> <div> {% for ingredients in recipe.get_text %} <ul> {% for item in ingredients %} <li><em> {{item.1|safe}} {% if item.2 is not None %} {{item.2|safe}} {% endif %} {{ item.0|safe}} </em></li> {% … -
Django migrations wrongly applaying
Basic problem I'm working on a django project where I'm using multiple databases with a custom router. Therefore, django should know which database to use for which app. Now I came across some in my opinion weird behaviour and wanted to ask if anyone knew if that is the correct behaviour or not, especially because the github page doesn't seem to have an issues tracker. To make the point clear, I'm using an extreme example, which I nonetheless tried. For testing purposes, I set the allow_migrate function to just return False. I did create a custom router which overrides the allow_migrate function and I also registered it under the DATABASE_ROUTERS settings. The allow_migrate function is also called, as I checked it with some print statements. How I understand the router usage The way I understand the documentation for using multiple databases with a custom router, the allow_migration method specifies if a migration is to be applied for the current db, app_label and model_name. If it returns True, the migration is applied, if False, it is 'silently skipped' and therefore not applied. What I expected As I set the allow_migrate function to return False all the time, I expected that none … -
Django: Need to check POST request mime type before uploading it to S3
So, here's my basic problem. I have form in my frontend that posts a file to my Django backend. Django will then pass that file off to AWS S3 for storage. I need to verify the file is a PDF or DOC before uploading to S3. I thought to check it's mime type with python-magic like so, form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): mime_type = magic.from_buffer(request.FILES['file'].read(), mime=True) if mime_type in ALLOWED_MIMETYPES: upload(request.FILES['file'], file_name) where upload just basically wraps boto3's upload_fileobj method. However, according to this Stack, the .read() I use in magic.from_buffer() empties the file buffer, so that when I pass the file into the upload method, it no longer exists. I've tried using copy and deepcopy to duplicate the file before checking it's mime type and then passing the duplicate into the upload function, but copy and deepcopy don't seem to work with fileobjects, as the duplicate is also empty after calling .read() on the original. How can I copy the file passed through the POST request so that I can check its mime type before passing it to S3 for storage? Is there another way to check it's mime type that doesn't involve emptying the file buffer? -
How to approve all installed apps permission programmatically in Django
settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Local apps 'users.apps.UsersConfig', # Third party apps 'allauth', 'allauth.account', 'allauth.socialaccount', ] views.py @user_passes_test(lambda u: u.is_superuser) def create_group(request): groups = Group.objects.all() if request.method == 'POST': group_name = request.POST.get('group_name') group = Group.objects.create(name=group_name) return HttpResponse(group.name) else: ctx = {'groups': groups} return render(request, 'users/admin/create_group.html', ctx) Here, I've created a view for creating user group programmatically. Now I want to allow users to approve permission just like django-admin dashboard. Like select few permissions and then press submit button to add these permissions to selected group. There must be some way doing so, because django admin itself doing it this way. I'd like to get some ideas how can I get this done. -
How do I setup multiple Django sites in Ubuntu 18
I bought a virtual server. Now I want to design two or more sites on it. The server company also provided me with an IP. How do I program my settings so that I can set up and access multiple sites through this server? In addition; I program using Python and the Django framework and on this server I can use Ubuntu 18.04, CentOS 7.06 and Debian 9. -
Django - Serialize an object with an object whitin
guys, I can't figure out how to do the following: I need to serialize a post object. If I do: return JsonResponse([post.serialize() for post in posts], safe=False, status=200) I get but I need to include additional data from the user: I can do it by doing a list like: post_list = [] for post in posts: post = { 'author': { 'user': post.author.user.username, 'name': post.author.user.first_name, 'avatar': post.author.avatar.url, }, 'message': post.message, "created": post.created, 'likes': post.likes.count(), } post_list.append(post) But I think this is not the best way to do it. Is it posibble to nest the user object in the post object using serialize()? Thanks in advance!!!! -
Poor Django architecture leading to "django.db.utils.OperationalError: no such table: main.invTypes"?
I hope I can get some help with an issue I've been beating my head against for a while now. I like to think I'm an intermediate Python developer, I'm working a on a pet project to improve my Django whilst focussing on getting the structure right and understanding how to write more pythonic code. I'm focussing on getting the model definitions correct to begin with and haven't started to look at forms or views yet. Perhaps I'll end up using it as a glorified database interface.... The following code creates a Market Order item which is stored in a database containing all the users data, which is downloaded from a 3rd party API. type_id is referenced in a separate database as it's taken from the static data download available from a 3rd party. I think it makes sense to separate them like this as it'll make database admin easier and cleaner in the future. I've checked and debugged the database router and fairly confident it's setup correctly. class MarketOrder(models.Model): date = models.DateTimeField(auto_now = True) duration = models.PositiveSmallIntegerField(default = 90) is_buy_order = models.BooleanField(default = False) issued = models.DateTimeField(blank=True, null=True) # tzinfo = tzlocal(), location_id = models.PositiveIntegerField(blank=True, null=True) min_volume = models.PositiveIntegerField(default …