Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Deploying Django, Django REST Framework backend & VueJS + webpack frontend on GCP App Engine (standard)
I have following setup: Django==3.1.4 djangorestframework==3.12.2 django-webpack-loader==0.7.0 (I am not convinced to use this - but this is separate story - just doing some learning for fun) On local dev setup everything works fine. Webpack-loader finds and deploys VueJS application. But when deployed to GAE following error is thrown: Error reading /workspace/frontend/webpack-stats.json. Are you sure webpack has generated the file and the path is correct? it comes from: /layers/google.python.pip/pip/lib/python3.9/site-packages/webpack_loader/loader.py, line 28, in load_assets I read tones of tutorials. All is clear when running on local dev - starting both django and VueJS. Of course, the problem is that webpack-stats.json are not created, as VueJS server is not started. I tried to find proper solution for this, but failed. I tried as well having VueJS on just domain with statics - but failed as well. What is best solution to have basic VueJS app talking to REST CRUDS and run it on GAE? -
Django timezone won't record user's timezone
So I just deployed a django web app but to my surprise, it records all time objects with UTC +0. ALL OF THEM! no matter the user's timezone. I have USE_TZ = True in settings. Here are the places I'm inserting time. Model.py class Timesheet(models.Model): .... start_date = models.DateTimeField(default=timezone.now) .... def save(self, *args, **kwargs): entry = Timesheet.objects.filter(id=self.request.user) if entry.exists(): Timesheet.objects.filter(id=self.request.user).update(end_date=timezone.now()) ... super().save(*args, **kwargs) How do I make it use the timezone of the user all across U.S.? -
saving data into a two table tables at the same time with a single form
I would like to save data in two tables at the same time using a single form in Django. Any help would be appreciated. class Category(models.Model): name = models.CharField(max_length=100, blank=True, null=True) def __str__(self): return self.name class Stock(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) class StockHistory(models.Model): id = models.AutoField(primary_key=True) category = models.ForeignKey(Category, on_delete=models.CASCADE,blank=True) item_name = models.CharField(max_length=100, blank=True, null=True) quantity = models.IntegerField(default='0',blank=True, null=True) -
Issues saving multiple database objects when iteration over a dictionary
I have an issues that has been making me tear my hair out for a while now. I have a simple Django app built with Django Rest Framework that interfaces with a Cassandra backend using django-cassandra-engine. I have set up a rest endpoint that accepts JSON data that is formatted like so: { "id": "47819417-d305-49b4-9e47-5fc554228438", "device": "TestDevice", "readings": [ { "id": "92e448d2-fd89-4eb3-ab1a-cdaf2056963a", "name": "testValue1", "value": "35" }, { "id": "6d79924a-1221-46c2-a3a6-4b667d85a7b6", "name": "testValue2", "value": "64" } ] } The format of this JSON is fixed, the only variable is the amount of readings that it contains. In my database, I am storing one reading per line - so one record would have device_id (which is obtained from elsewhere in the system), device, name, value, origin and id. This means that the above example should produce two records in the database. When I receive it, I do the following processing: @api_view(['POST']) def import(request): if request.method == 'POST': event_data = JSONParser().parse(request) # Check to see if the device exists in the metadata and retrieve the ID try: device = DeviceMetadataByID.objects.filter(device_name=event_data["device"]) device_id = getattr(device[0], 'device_id') except IndexError: # If not, retrieve the device description and ID from the Edge database url = "http://192.168.1.131:48081/api/v1/device/name/" + … -
What is the best way to optimize the performance of those Django QuerySet?
I have this function that generate data for a HighChart chart. But it is very very very slow. It take 2.3 seconds to generate only 1 device for 24 hours even if there is no data at all in the Database. I normally have between 10 and 100 device to chart! Is there anyway to optimize those querySet ? def getVacChart(self, fromDate, toDate): if((toDate - fromDate).days <= 1): avgMinutes = 15 elif((toDate - fromDate).days <= 2): avgMinutes = 30 elif((toDate - fromDate).days <= 3): avgMinutes = 45 else: avgMinutes = 60 totalReadings = int(((toDate - fromDate).total_seconds() / 60) / avgMinutes) readings = self.vacReading.filter(timeStamp__gte = fromDate).filter(timeStamp__lte = toDate).order_by('timeStamp') i = 0 _from = fromDate + datetime.timedelta(minutes = (i * avgMinutes)) _middle = int(round((_from + datetime.timedelta(minutes = (avgMinutes / 2)) - datetime.datetime.fromtimestamp(0)).total_seconds())) * 1000 _to = _from + datetime.timedelta(minutes = avgMinutes) data = [] if(toDate > datetime.datetime.now()): stop = datetime.datetime.now() else: stop = toDate lastAvgRdg = None while _from <= stop: avgRdg = readings.filter(timeStamp__gte = _from).filter(timeStamp__lte = _to).aggregate(Avg('vacuum'))["vacuum__avg"] if(avgRdg is not None): avgRdg = round(avgRdg, 1) lastAvgRdg = avgRdg else: if(lastAvgRdg is not None): avgRdg = lastAvgRdg data.append([_middle, avgRdg]) i += 1 _from = fromDate + datetime.timedelta(minutes = (i * avgMinutes)) _middle … -
How to add groups listbox to user update from?
I've created a ModelForm in Django to update users. I would like to also use this form to change which groups the user is a member of. However, I cannot work out how to add groups field to my form. I think this is because of how the M2M relationship between user and groups is setup in Django, that I cannot access the widget from the user side. This seems like it should be quite a common problem. Is there an obvious solution that I am missing? My form currently looks like this: class UserUpdateForm(forms.ModelForm): username = forms.CharField(error_messages={'invalid': '150 characters or fewer. Letters, digits and ./+/-/_ only.'}) id_role = forms.ModelMultipleChoiceField(queryset=Roles.objects.all(), widget=forms.CheckboxSelectMultiple()) class Meta(): model = User fields = ('__all__') -
How to use Django shell to interact with running server?
In the apps.py of one of my apps I set some class variables for models that can't be set at initialization because they depend on other apps and the models in them. This works fine and the class variables are set, but what I want to do is then test these classes to see if they'll work as intended. My problem is the class variables are set when I run the development server, but I want to also be able to create new instances of these models for testing. I realize that this can be accomplished by building the front-end that will interact with the models in production, but this seems to be excessive for simple testing. Is there a way to use Django's shell on a currently running server, or do I have to go through importing and running all the things that manage.py usually takes care of on its own? In case what I have written isn't clear, here's an example of the files in question: # example.models.py from django.db.models import * class ExampleModel(Model): class_var = None . . . # apps.py from django.apps import AppConfig class ExampleConfig(AppConfig): name = 'example' def ready(self): from example.models import ExampleModel ExampleModel.class_var … -
Django Database - create a table that has three foreign keys from two other separate tables
I'm creating a database that has the following criteria: Table 1: each restaurant has a unique restaurant id Table 2: each restaurant id has many serving times (9 am-11 am) Table 3: a unique restaurant id that has its unique serving time has many food categories Table 4: a unique restaurant id that has its unique serving time and its unique food category have many food items Table 5: a unique restaurant id that has its unique serving time, unique food category, and its unique food item have one food item details I tried to include and exclude the foreign keys in the serializers.py, but the program does not work in both scenarios. I also tried different related_name in model.py (with and without %class). My whole database did not have any error, except a programming error occurs when I go to the Django admin site and click table 3. model.py class Restaurant_ID(models.Model): restaurant_id = models.CharField(unique=True, max_length=20) class Meta: verbose_name_plural = '1 Restaurant IDs' def __str__(self): return str(self.restaurant_id) class Restaurant_serving_times(models.Model): restaurant_id = models.ForeignKey(Restaurant_ID, on_delete=models.CASCADE) serving_time_hour = models.CharField(max_length=2, choices=Hours,default='8') serving_time_minutes = models.CharField(max_length=2, choices=Minutes,default='00') class Meta: verbose_name_plural = '3-1 Restaurant ID Serving Times' def __str__(self): return str(self.restaurant_id) class Serving_time_categories(models.Model): restaurant_id = models.ForeignKey(Restaurant_ID, on_delete=models.CASCADE) … -
How can i Show active in current page in pagination in django
Accually, i am facing all active in the list of page number on the buttom. But i want that only current page should be shown as active. i query the database as pagination and measure how much page needed. And then i make a list of pages. the list is called in template file make as a loop. views.py def index(request): Product_Details_all = Product_Details.objects.all().order_by('-id') # pagination p = Paginator(Product_Details_all, 15) # print(p.num_pages) number_of_pages = p.num_pages #show list of pages number_of_pages_1 = p.num_pages+1 list = [] for i in range(1, number_of_pages_1): list.append(i) page_num = request.GET.get('page', 1) try: page = p.page(page_num) except EmptyPage: page = p.page(1) context2 = {'Product_Details_all':page, 'list':list} return render(request, 'index.html', context2) template.html [![enter image description here][1]][1]{% if list %} <li> {% if Product_Details_all.has_previous %} <a href="{% url 'index' %}?page={{Product_Details_all.previous_page_number}}" class="prev" title="previous page">&#10094;</a> {% endif %} </li> {% for i in list %} <li> <a href="{% url 'index' %}?page={{i}}" class="active">{{i}}</a> </li> {% endfor %} <li> {% if Product_Details_all.has_next %} <a href="{% url 'index' %}?page={{Product_Details_all.next_page_number}}" class="next" title="next page">&#10095;</a> {% endif %} </li> {% endif %}``` -
Django URL shows previous and current page but I want only current page name in URL
Suppose currently I'm on the "http://127.0.0.1:8000/message/detailmessage/5" page and I want to go to "login" page by clicking on login hyperlink from base.html(nav-bar), I want it to show "http://127.0.0.1:8000/login" but it showing "http://127.0.0.1:8000/message/detailmessage/login" what should I do? base.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous" /> <style> {% block css %}{% endblock %} </style> <title>{% block title %}{% endblock %}</title> </head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <a class="navbar-brand" href="#">Home</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation" > <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavDropdown"> {% for id in doctor %} {{id.doctor_id}} {% endfor %} <ul class="navbar-nav ml-auto"> {% for id in doctor %} {{id.doctor_id}} <li class="nav-item"> <a class="nav-link" href=message/{{id.doctor_id}}>Message</a> </li> {% endfor %} <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" > LogIn/LogOut </a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="login">Login</a> <a class="dropdown-item" href="/">Log Out</a> </div> </li> </ul> </div> </nav> {% block body %} {% endblock %} <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous" ></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous" ></script> … -
Stripe IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId
I've got a Django website and I'm trying to integrate Stripe using Django the Stripe API on the backend and Vue.js on the frontend. However, when I try to run the checkout link that's supposed to redirect me to the payment processing page, I get the following error: Error: IntegrationError: stripe.redirectToCheckout: You must provide one of lineItems, items, or sessionId. at new r (https://js.stripe.com/v3/:1:6143) at Js (https://js.stripe.com/v3/:1:165350) at $s (https://js.stripe.com/v3/:1:165646) at https://js.stripe.com/v3/:1:166758 at Qs (https://js.stripe.com/v3/:1:166769) at nc (https://js.stripe.com/v3/:1:167275) at Ec.redirectToCheckout (https://js.stripe.com/v3/:1:188030) at http://localhost:8000/dashboard/myaccount/teams/plans/:342:39 Here's the Vue.js method responsible for this: <script src="https://js.stripe.com/v3/"></script> <script> const PlansApp = { data() { return { } }, delimiters: ['[[', ']]'], methods: { subscribe(plan) { console.log('Subscribe:', plan); const stripe = Stripe('{{ stripe_pub_key }}'); fetch('/dashboard/myaccount/teams/api/create_checkout_session/', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-CSRFToken': '{{ csrf_token }}' }, body: JSON.stringify({ 'plan': plan }) }) .then(function(response) { return response.json() }) .then(function(session) { console.log(session) return stripe.redirectToCheckout({ sessionId: session.sessionId }) }) .then(function(result) { if (result.error) { console.log('Error:', result.error.message) } }) .catch(function(error) { console.log('Error:', error); }); } } } Vue.createApp(PlansApp).mount('#plans-app') </script> And here's the Django code that creates the session on the backend: @login_required def create_checkout_session(request): stripe.api_key = settings.STRIPE_SECRET_KEY data = json.loads(request.body) plan = data['plan'] if plan == 'basic': price_id = … -
problem with multiple user dependent on each other in Django
I am working with some custom-made user models in Django. They are the following: myCustomeUser responsible for the primary identity of a user Industry is a user that will inherit the myCustomeUser Employee is another user account, which will inherit the myCustomeUser and Industry both my models.py: class myCustomeUser(AbstractUser): id = models.AutoField(primary_key=True) username = models.CharField(max_length=20, unique="True", blank=False) password = models.CharField(max_length=20, blank=False) is_Employee = models.BooleanField(default=False) is_Industry = models.BooleanField(default=False) class Industry(models.Model): user = models.OneToOneField(myCustomeUser, on_delete=models.CASCADE, primary_key=True, related_name='industry_releted_user') name = models.CharField(max_length=200, blank=True) owner = models.CharField(max_length=200, blank=True) license = models.IntegerField(null=True, unique=True) industry_extrafield = models.TextField(blank=True) Now I need to write the model of Employee. There are some conditions also: It should contain name, National ID, gmail, rank, employee_varified, named fields This will inherit the myCustomeUser and Industry both The Industry account user will primarily entry all the data of Employee in the database, except username and password(which are inherited from myCustomeUser) Later on, the Employee will search his National ID given by the Industry and finish the registration process by creating his username and password. I have tried the Employee model like this: class Employee(models.Model): user = models.ForeignKey(myCustomeUser,primary_key=True, null=True, on_delete=models.CASCADE) industry = models.ForeignKey(Industry, on_delete=models.CASCADE) National_ID = models.IntegerField(null=True, blank=False, unique=True) name = models.CharField(max_length=200, blank=False, null=True) gmail … -
POST image to django rest API always returns 'No file was submitted'
I am trying to get this working now for days -.- Using a simple NodeJS express server, I want to upload an image to a Django instance through Post request, but I just can't figure out, how to prepare the request and embed the file. Later I would like to post the image, created from a canvas on the client side, but for testing I was trying to just upload an existing image from the nodeJS server. app.post('/images', function(req, res) { const filename = "Download.png"; // existing local file on server // using formData to create a multipart/form-data content-type let formData = new FormData(); let buffer = fs.readFileSync(filename); formData.append("file", buffer); // appending the file a buffer, alternatively could read as utf-8 string and append as text formData.append('name', 'var name here'); // someone told me, I need to specify a name const config = { headers: { 'content-type': 'multipart/form-data' } } axios.post("http://django:8000/images/", formData, config) .then(response => { console.log("success!"); }) .catch(error => { console.log(error.response.data); // no file was submitted }); }); What am I doing wrong or did I miss something? -
how to do unit tests using Zeep on Django
i trying to using zeep on django to make test to a SOAP service, but always need to be running a runserver, but need to be executed without runserver because need to using a test database not a default database. i using like like this: def test_obtenerListaAcciones(self): # get actions # this server need to be up to work, but need to be execute test without work this. wsdl = 'http://127.0.0.1:8000/soap/getactions/' client = zeep.Client(wsdl=wsdl) headerArr = {} settings = Settings(strict=False, xml_huge_tree=True, extra_http_headers=headerArr, raw_response=True) client = Client(wsdl, settings=settings) action = self.test_create_actions() requestData = { } res = client.service.obtenerListaAcciones(**requestData) -
Django - rendering templates and passing them via AJAX
Ok, so this a more of a conceptual question. Basically i just found out i can do the following: Use ajax to start a function that returns a rendered HTML template, send that as a response to ajax, then apply that HTML code to a host div. This feel so much more versatile and powerfull than using include tags. I can render, and re-render forms (or any little snippet of HTML) in a flash with minimal JS, and, most importantly without refreshing the page. I understand that passing whole html blocks via AJAX might not be optimal, so i am avoiding abusing this. However this feels "hacky" to me, so my question is, Why should i NOT do this? if you want some example code: {% load crispy_forms_tags %} {% load static %} <div id="formdiv1"> </div> <script> function getform_rec() { $.ajax({ type: "GET", url: "/backoffice/ajax/rec_form/", success: function(data) { $("#formdiv1").html(data); } }); } getform_rec() </script> and my view def ajax_rec_form(request): if request.method == "GET": rec_id = request.GET.get("id", None) if not rec_id: form = Rec_form() else: form = Rec_form(instance=Rec.objects.get(id=rec_id)) return render(request, "rec-form.html", {"rec_id": rec_id, "form": form}) rec-form.html is just a html file with no extends or includes, and it just renders the … -
Is there a way i can join two tables and get the sum of duplicated field in Django
I have a model WarehouseTrade Account and WarehouseStorage Account it look like this:------- class WarehouseStorageAccount(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE, null=True) grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES) bags = models.IntegerField(default=0) gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) updated = models.DateTimeField(auto_now=True) class WarehouseTradeAccount(models.Model): warehouse = models.ForeignKey(Warehouse, on_delete=models.CASCADE, null=True) item = models.ForeignKey(Item, on_delete=models.CASCADE) grade = models.CharField(max_length=5, choices=ITEM_GRADE_CHOICES) bags = models.IntegerField(default=0) gross_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) net_weight = models.DecimalField(max_digits=20, decimal_places=3, default=0) updated = models.DateTimeField(auto_now=True) I am trying to get All the data in both accounts, but it should sum it up if there is a duplicate between the two. I have been able to achieve this with SQL using below code: SELECT data.warehouse_id AS Warehouse, data.item_id AS Item, data.grade AS Grade, SUM((data.net_weight)) AS Net_WEIGHT, SUM((data.gross_weight)) AS Gross_WEIGHT, SUM((data.bags)) AS Bags FROM (SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags FROM public.inventory_warehousestorageaccount UNION ALL SELECT warehouse_id, item_id, net_weight, grade, gross_weight, bags FROM public.inventory_warehousetradeaccount ) data GROUP BY data.warehouse_id, data.item_id, data.grade I tried using union to join the two tables, then get the aggregate the result, but I keep getting an error wt = WarehouseTradeAccount.objects.all() ws = WarehouseStorageAccount.objects.all() w=wt.union(ws) w.aggreate(new_net_weight=Sum('net_weight') How do I replicate this in Django? -
Write in database on exception
I have the following code, if the try catch statement executed successfully then I write in my database model success = True and if the code Excepts then I want to write success = False. In purpose I raise the exception in order to test my except statement. The code goes successfully in the except statement because I get the print, but it does not write in my database. try: ...do some work... models.SyncRun(success=True).save() raise Exception except Exception as e: print("in") models.SuncRun(success=False).save() raise Exception -
Django: access model instances
I have a model called OrderItems class OrderItem(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) product = models.ForeignKey( Product, on_delete=models.SET_NULL, blank=True, null=True) order = models.ForeignKey( Order, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) date_added = models.DateTimeField(auto_now_add=True) and a model called Order class Order(models.Model): customer = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) date_ordered = models.DateTimeField(auto_now_add=True) complete = models.BooleanField(default=False, null=True, blank=False) transaction_id = models.CharField(max_length=200, null=True) Now in my views.py i have an OrderItem model order instance. And in my Order model i need to set its order instance to complete. Im trying something as follows. orderID=OrderItem.objects.values('order').filter(order_id=4) #lets say there are more than one order_id with the value of 4 for order in orderID: order = Order.objects.get(id=orderID) order.complete=True order.save() this code gives me ValueError: The QuerySet value for an exact lookup must be limited to one result using slicing. How to fix this? Thanks in advance -
Is it an antipattern to make queries from models?
Django says the Models should be used as an Active Record and include persistence and business logic. What to do when the business logic requires access to unrelated models? Is it an antipattern to make queries from model instances? I see the queries are made from views and it is assumed that all dependencies of a model are covered by its database fields. -
Django static files works when site is accessed vai `appname.heroku.com` but not found when site is accessed via custom domain (www.exmple.com)
here are important debug values on settings.py site is hosted on heroku.com and DNS from namecheap STATIC_URL = '/static/' STATICFILES_DIRS = [os.path.join(BASE_DIR, 'staticfiles')] VENV_PATH = os.path.dirname(BASE_DIR) STATIC_ROOT = os.path.join(VENV_PATH, 'static_root') STATIC_URL = '/static/' 'whitenoise.middleware.WhiteNoiseMiddleware', STATICFILES_STORAGE = 'whitenoise.storage.CompressedStaticFilesStorage' -
Django + HTML: Why does my if condition in my template fail even thought I havent submitted interest?
Django + HTML: Why does my if condition in my template fail even thought I havent submitted interest? As you can see from my views.py i have already indicated that if you have submitted interest, you will get the message that you have submitted the interest, otherwise the button 'submit interest' will be shown. Why does it not work then? views.py def detail_blog_view(request, slug): context = {} #need to import a package get_object_or_404. return object or throw 404 blog_post = get_object_or_404(BlogPost, slug=slug) total_likes = blog_post.total_likes() liked = False if blog_post.likes.filter(id=request.user.id).exists(): liked = True context['liked'] = liked context['blog_post'] = blog_post context['total_likes'] = total_likes account = Account.objects.all() context['account'] = account #when post does not belong to me if blog_post.author != request.user: submittedinterest = False if blog_post.author.interestsender.filter(id=request.user.id).exists(): submittedinterest = True context['submittedinterest'] = submittedinterest #when the post belongs to me else: pass return render(request, 'HomeFeed/detail_blog.html', context) template {% if submittedinterest %} <a href="{% url 'HomeFeed:submitinterest' blog_post.slug %}"><button type="button" class="btn btn-warning">Collaborate!</button></a> {% else %} <div class="alert alert-success" role="alert"> <p class="text-center">You have submitted your interest.</p> </div> {% endif %} models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) body = models.TextField(max_length=5000, null=False, blank=False) likes = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name='blog_posts', blank=True) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) slug = models.SlugField(blank=True, unique=True) class … -
how to display fields from other table that has onetoone relation using serializers in django
I have two models class Rule(models.Model): pmdruleid = models.BigIntegerField(primary_key=True) effectivedate = models.DateTimeField(blank=True, null=True) retireddate = models.DateTimeField(blank=True, null=True) createdby = models.CharField(max_length=255, blank=True, null=True) class Meta: managed = False db_table = 'rule' class Ruledefinitions(models.Model): ruleactivestatus = models.CharField(max_length=14) rulename = models.CharField(max_length=255, blank=True, null=True) pmdclinicalruleid = models.OneToOneField(Rule, models.DO_NOTHING, db_column='pmdclinicalruleid', primary_key=True) pmdclinicalvariableid = models.IntegerField() class Meta: managed = False db_table = 'ruledefinitions' unique_together = (('pmdclinicalruleid', 'pmdclinicalvariableid'),) Corresponding serializers for the above models class RuleSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Rule fields = ['pmdruleid', 'effectivedate', 'retireddate', 'createdby'] class RuledefinitionsSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Ruledefinitions fields = ['ruleactivestatus', 'rulename', 'pmdclinicalruleid', 'direction', 'pmdclinicalvariableid'] Views for Rules model class ActiveclientViewSet(viewsets.ModelViewSet): queryset = Rule.objects.select_related('ruledefinitions').all() serializer_class = RuleSerializer When i call this view class, i am getting fields of only rule model in api response. I would also need to add the fields of ruledefinitions model fields (since both are connected by onetoone relationship) in the api response. Help me in snippet for displaying the ruledefinitions model fields in api response. I am new to django -
Django looking for wrong path on url() in css files
I am trying to set up a personal blog that uses Django and is hosted in Heroku. You can check it here: https://generic-blog.herokuapp.com/ All my static files were loading as intended on my local machine until I decided to store the static files on AWS S3. I configured my settings.py to use S3 and did python manage.py collectstatic to collect the static files to my s3 bucket. The static files are loading as intended, but on my css files there are url() with relative paths as this one: url("../fonts/blog.woff") format("woff") Which is not loading, as the path is incorrect. My browser's console gives me the following error: downloadable font: download failed (font-family: "blog" style:normal weight:400 stretch:100 src index:1): status=2147746065 source: https://personal-django-blogs.s3.amazonaws.com/fonts/blog.woff The path that Django tries to search for the font is wrong https://personal-django-blogs.s3.amazonaws.com/fonts/blog.woff would have to be https://personal-django-blogs.s3-sa-east-1.amazonaws.com/static_root/vendor/font-awesome/fonts/fontawesome-webfont.woff I could just replace each relative path with the absolute path of the file in s3 bucket, but this feels wrong. I think the problem lies in settings.py, but I couldn't manage to understand why when working on s3 the relative paths don't work anymore. Here's my settings.py relevant configurations: STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / 'static', ] # … -
how to split a for loop in django
I want have a simple model for images. there is a option to upload unlimited images. but I want don't want them to be shown under each other. for instance just show the first 5 images then some text and then again another 5. right now my code is like this: {% for img in images %} <img src="{{ img.images.url }}" class="img-fluid" alt=""> {% endfor %} I want the Structure to be like this: for loop for img0 to 5, then everything elese, then another for loop for img6 to 10, Thanks for the solutions and apologies for my bad English -
Creating automatic datetime in django
I would like to create a field with a predefined datetime. Something like this: class MyExample(models.Model): expiration = timezone.now() + timedelta(days=1) expiration_date = models.DateTimeField(verbose_name="Expirate in", default=expiration) ... I don't know if it's the best way, because when there are new migrations there is an update of the table with the expiration. Does anyone have any tips?