Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Importing Json into Django Database from url
I wrote a script which will basically import data from a json file and store it in the database of my Django Application. I'm simply pointing to a json file and i'm adding "facilities" if they don't exist or they get updated if the last modified date changes. It worked perfectly fine until i couldn't import the json file locally anymore and made some smaller changes to use an external json file. When i run the importer now it will only import the first two facilities and then tell me that all others are up to date even though they don't exist. I even modified and tested the json file manually to make sure it is not caused by a bug inside the json file. I will add the old code plus the modified code below. One of the main differences is that this part is now at the very bottom in the new version after the if statement: for key, data_object in data.items(): And also that i'm using "import requests" in the new version with the following code at the bottom of the file. My feeling is that i made a mistake right there: def handle(self, *args, **options): """ … -
How to use the django test's database with Selenium?
I am testing my django app with django TestCase class. For unit tests and integrations tests I encountered no problem with the database django create then destroy for the tests. But now i want to do some functional test using selenium. The problem is that selenium seem to not be able to access the db. Here is the test code of my test : class HostTest(LiveServerTestCase, TestCase): def setUp(self): self.driver = webdriver.Chrome(service=Service(ChromeDriverManager().install())) # Setting up temporary test database # Setting up products self.product1 = Product.objects.create( id=1, name="apple", url="apple_url", nutriscore="A", img_url="apple_img_url", kcal=101, fat=201, protein=301, sugar=401, ) def tearDown(self): self.driver.close() def test_new_user_reserach_and_add_favorite(self): driver = self.driver driver.get(self.live_server_url) self.assertIn("Accueil", driver.title) search_bar = driver.find_element_by_name("product_searched") search_bar.send_keys("apple") search_bar.send_keys(Keys.ENTER) self.assertIn("Recherche", driver.title) product = driver.find_element_by_class_name('product-presentation') For this I have an error at the last line, and the error is long but its basically tell me that selenium cant find the element. I tried to print product1 in the test and it work. That why I'm pretty sure that the problem is with Selenium. Here is the code of my view : def product_research(request): no_repetition_result = [] vectors = SearchVector('name', weight='A') + SearchVector('category__name', weight='B') query = SearchQuery(f'{request.GET.get("product_searched")}') research_result = Product.objects.annotate(rank=SearchRank(vectors, query)).order_by('-rank') for product in research_result: if product not in no_repetition_result: … -
retrieving the last instance of a model in another model's modelSerializer in django rest framework
I am creating rest APIs for a website in which users can purchase one of the provided subscriptions. In this website there is a user-info API which returns the information about the logged in user which can be used to show their info on the website. The problem is that, the mentioned API's serializer is a modelSerializer on the "User" model and the information that I want to return is the instance of "Subscription" model which the latest instance of "SubPurchase" model refers to. These are my serializers, models and views.And I need to somehow return the user's current subscription's ID and name along with the user's information. If you have any further questions, ask me in the comments and I'll answer them. # models.py class User(AbstractBaseUser, PermissionsMixin): userID = models.AutoField(primary_key=True) username = models.CharField(max_length=100, unique=True, validators=[RegexValidator(regex="^(?=[a-z0-9._]{5,20}$)(?!.*[_.]{2})[^_.].*[^_.]$")]) email= models.EmailField(max_length=100, unique=True, validators=[EmailValidator()]) name = models.CharField(max_length=100) isSuspended = models.BooleanField(default=False) isAdmin = models.BooleanField(default=False) emailActivation = models.BooleanField(default=False) balance = models.IntegerField(default=0) objects = UserManager() USERNAME_FIELD = 'username' class Subscription(models.Model): subID = models.AutoField(primary_key=True) nameOf = models.CharField(max_length=50) price = models.PositiveIntegerField() salePercentage = models.PositiveIntegerField(default=0) saleExpiration = models.DateTimeField(default=datetime.datetime.now, blank=True) def __str__(self): return f"{self.nameOf}" class SubPurchase(models.Model): price = models.PositiveIntegerField() dateOf = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(User, null=True, on_delete=models.SET_NULL) subscription = models.ForeignKey(Subscription, null=True, … -
Render multiple html files and views and show it in single html file Django
Below shown are my files index.html <!-- Modal --> <div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Create Contact</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form method='POST'> {% csrf_token %} <div class="modal-body"> {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button> <input type="submit" class="btn btn-primary save-btn"> </div> </form> </div> </div> </div> new_contact.html <!-- Modal --> <div class="modal fade modal{{link.id}}" id="createmodal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Create Contact</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form method='POST'> {% csrf_token %} <div class="modal-body"> {{form.as_p}} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="Submit" class="btn btn-primary btn-delete" data-sid="{{link.id}}" >Create Contact</button> <input type="submit" class="btn btn-primary save-btn"> </div> </form> </div> </div> </div> views.py def new_contact(request): data = Contact.objects.all() form = CreateContactForm() if request.method == 'POST': form = CreateContactForm(request.POST) if form.is_valid(): form.save() messages.success(request, 'Link edited successfully.') else: messages.error(request, form.errors) return render(request,'app/editModal.html', context={'form':form,'data':data}) def index(request): data = Contact.objects.all() return render(request,'app/editModal.html', context={'form':form}) I want to render new_contact.html file in index.html file. I have already used include tag but it doesn't work for my requirement. include tag includes that html file into the index file but does … -
How to login in django using desktop app? [closed]
I have a django app running on localhost, what i need to do is login on the django server using credentials provided on a desktop app that was made using pyside2. -
How to share one session between react and django?
I have frontend on React and backend on Django. They are running on two different ports. The Goal is to save data from frontend to Django session and having access to it on every request. But thing is it creates new session everytime I make a request This is how request looks like on React side const data = await axios.post( "http://127.0.0.1:8000/api/urls/", qs.stringify({ long: long_url, subpart: subpart, }) ); And this is how it processed by view in Django where i am trying to create list of urls and append it every time. @api_view(['POST']) def users_urls(request): if request.method == 'POST': long_url = request.POST.get('long') subpart_from_input = request.POST.get('subpart') if 'users_urls' in request.session: request.session['users_urls'].append(short_url) else: request.session['users_urls'] = [short_url] return Response(short_url) It works as it should work when i make requests from Postman. But there is some trouble with react. Help me please to figure this out -
Django 'python manage.py runserver' does not work. Is Python setup correct?
I downloaded Django via pip install djange django-admin startproject xyz is working fine. but when I do python manage.py runserver or similar .. the following error -
Django - Not being able to merge front end to backend
Im learning programming and im completely new in it..i was working on a project and i have used django for back-end. Now the problem im currenctly facing is that i got no idea how should i link frontend and backend ?.. first we created backend (where there is login/signup/and dashboard) using django and boostrap,js .. and the backend work perfectly so below the folder structure of the backend we are working on. so this is the structure of the backend .. to be more clear check 2nd image. Here you can see that, budgetwebsite folder which is just below the folder authentication. budgetwebsite is our main thing or a part of our system.. then we did django startapp for authentication(for username validation and email) then we did django startapp for userincome(here we worked on userincome like add/delete income) then we did django startapp for expenses(here we worked on expenses like add/delete/expense) and that userpreference is our admin panel. thats for the backend section Now lets move on the front end section aswell. then we created a different folder name front end and we started working on it. So now lets move to the problem... i just want to merge this … -
How to display changed fields in Django Admin?
I have a model Managers and a proxy model MyManagers. A am trying to display changed field in Admin panel for proxy model, but Admin/history display only user, date and action. How to fix it? My models.py from django.db import models from django.contrib import admin from simple_history.models import HistoricalRecords class Managers(models.Model): name = models.CharField(max_length=30, default='') lastname = models.CharField(max_length=30, default='') enduser_id = models.CharField(max_length=8, default='', help_text=u"Please enter the end user id, like ABC1WZ1") history = HistoricalRecords() class Meta: verbose_name = 'Manager' verbose_name_plural = 'Managers' def __str__(self): return self.name + self.lastname class ManagersAdmin(admin.ModelAdmin): list_display= ('name','lastname','enduser_id') class MyManagers(Managers): class Meta: proxy=True def __str__(self): return self.name.upper() +' '+self.lastname.upper() class MyManagersAdmin(admin.ModelAdmin): search_fields = ['name', 'lastname','enduser_id'] list_display = ('name', 'lastname','enduser_id') history_list_display = ['name','lastname','enduser_id','changed_fields'] def changed_fields(self, obj): if obj.prev_record: var = obj.diff_against(obj.prev_record) return var.changed_fields return None My admin.py: from django.contrib import admin from .models import * # Additional board for assigning a manager to a Department. admin.site.register(Managers, ManagersAdmin) admin.site.register(MyManagers, MyManagersAdmin) -
Django Multi table inheritance serializer display
I have extended my model like this. class Item(models.Model): name = models.CharField(max_length=50) class Category1(Item): code = models.CharField(max_length=50) class Category2(Item): status = models.IntegerField(default=1) class Order(models.Model): # fields class OrderItem(models.Model): order = models.ForeignKey("Order", on_delete=models.PROTECT, related_name="order_items") item = models.ForeignKey("Item", on_delete=models.PROTECT) Is there any way to access the child fields from the parent model? From the serializer, I have to display all the details from the Order model. Order -> OrderItem -> Item I was able to display up to the Item details, but I have to display the other fields from Category1 and Category2. Is there any way I can execute this? My serializer is like this class OrderItemSerializer(serializers.ModelSerializer): class Meta: model = OrderItem fields = "__all__" class OrderSerializer(serializers.ModelSerializer): order_items = OrderItemSerializer(many=True) class Meta: model = Order fields = "__all__" -
how to design blog commenting system with django orm?
im new to django and im wondering how can i design a nested commenting system for my blog project ? class Post(models.Model): title = models.CharField(max_length=20) paragraph = models.TextField() sources = models.CharField(max_length=100) author = models.CharField(max_length=50) likes = models.PositiveIntegerField(default=0) def __str__(self): return f'||{self.title}|| from -> {self.author}' class Comment(models.Model): name = models.CharField(max_length=20) mail = models.EmailField() content = models.CharField(max_length=250) post = models.ForeignKey(Post, on_delete=models.SET_NULL, null=True, blank=True) reply = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True) def __str__(self): return f'{self.name} said --> {self.content}' i tried this for models and, it doesnt seem to work for nested comments. -
Application error in heroku when django is deployed
I am trying to deploy a Django project to Heroku and for some reason it gives me an 'Application Error'. When I look at the logs, I get this: 2022-01-30T12:44:14.000000+00:00 app[api]: Build succeeded 2022-01-30T12:44:21.330403+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=lms-mkc.herokuapp.com request_id=44f703bc-3648-49a3-a440-d421a3e8d742 fwd="196.189.238.73" dyno= connect= service= status=503 bytes= protocol=https 2022-01-30T12:44:21.808170+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=lms-mkc.herokuapp.com request_id=a2c0669b-650d-4188-84b3-92d3ba425942 fwd="196.189.238.73" dyno= connect= service= status=503 bytes= protocol=http -
i facing kernel issue in my jupyter notebook from anacoda
Traceback (most recent call last): File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\web.py", line 1704, in _execute result = await result File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\handlers.py", line 74, in post model = yield maybe_future( File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 98, in create_session kernel_id = yield self.start_kernel_for_session(session_id, path, name, type, kernel_name) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 769, in run yielded = self.gen.throw(*exc_info) # type: ignore File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\sessions\sessionmanager.py", line 110, in start_kernel_for_session kernel_id = yield maybe_future( File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\tornado\gen.py", line 762, in run value = future.result() File "C:\ProgramData\Anaconda3\lib\site-packages\notebook\services\kernels\kernelmanager.py", line 176, in start_kernel kernel_id = await maybe_future(self.pinned_superclass.start_kernel(self, **kwargs)) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\multikernelmanager.py", line 186, in start_kernel km.start_kernel(**kwargs) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\manager.py", line 337, in start_kernel kernel_cmd, kw = self.pre_start_kernel(**kw) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\manager.py", line 286, in pre_start_kernel self.write_connection_file() File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\connect.py", line 466, in write_connection_file self.connection_file, cfg = write_connection_file(self.connection_file, File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_client\connect.py", line 136, in write_connection_file with secure_write(fname) as f: File "C:\ProgramData\Anaconda3\lib\contextlib.py", line 119, in enter return next(self.gen) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_core\paths.py", line 461, in secure_write win32_restrict_file_to_user(fname) File "C:\Users\HP\AppData\Roaming\Python\Python39\site-packages\jupyter_core\paths.py", line 387, in win32_restrict_file_to_user import win32api ImportError: DLL load failed while importing win32api: The specified procedure … -
model only shows up in admin if foreign key to superuser
In the django admin I have a model "profile" that has a foreign key to user. If I make a new instance of the profile model it shows up in the admin only if the user it's attached to a user who has superuser status. I would like to have them all show up in the admin. Where would I start looking to find the permissions for "profile"'s admin page. To my knowledge my query set is set to Profile.objects.all() So what else should I be looking for? views.py is as follows class ProfileViewSet( RetrieveModelMixin, ListModelMixin, CreateModelMixin, UpdateModelMixin, GenericViewSet, ): """ API endpoint that allows users to be viewed or edited. """ queryset = Profile.objects.all() serializer_class = ProfileSerializer permission_classes = [permissions.IsAuthenticated] lookup_field = "user__username" admin.py just has fieldsets definitions. serializer.py has fields definitions. -
How to create a django model with static image file
enter code here class EncryptedMessage(models.Model): image = models.ImageField(upload_to="images", blank=True) def __str__(self): return 'image: {}'.format(self.image) This is my django model, I need to create an object with static image file. class EncryptedMessage(models.Model): image = models.ImageField(upload_to="images", blank=True) def __str__(self): return 'image: {}'.format(self.image) -
How to specify that class C would be used inherited by classes that also inherit from class A
I'm trying to create a utility class UploadFile that would be used by subclasses of ModelAdmin. I can just create a vanilla class and it would be all fine and dandy. However, is there a way to tell static analyzers and code completion tools that this utility class will have access to properties of ModelAdmin, without UploadFile inheriting from ModelAdmin? Inheriting from ModelAdmin gives the error: TypeError: Cannot create a consistent method resolution order (MRO) for bases ModelAdmin, UploadFile Example code: class ModelAdmin(...): def send_message(...): pass class UploadFile: def upload(self): self.send_message() class MyModelAdmin(ModelAdmin, UploadFile): pass Moving ModelAdmin inheritance from MyModelAdmin to FileUpload would prevent MyModelAdmin from creating other utility classes that would also access ModelAdmin properties and methods. -
Django - Different behavior between DEV and PROD
I'm finalizing my first own Django app and I have some strange issues, as the behavior on my server is different than in my local Dev environment. My main issue is about a page displaying 2 multiple select boxes, and buttons dedicated to move items from one to the other thanks to Javascript functions: it works in DEV but not in Prod. On top of that, the display is also different, and looks weird on the Prod server. The page is dedicated to list users and add them to a group. The icons intend to move one / all user(s) from the list to the group, and vice versa. It works perfectly in DEV but not at all in PROD. I start with the JS code related to the buttons (I also consider a double click on a single item to move it from one group to the other and it doesn't work either, so it's included hereafter): // Add all (from source to destination) $('#add_all').on("click", function(e) { e.preventDefault(); $('#id_users').find('option').removeAttr('selected'); $('#id_all_users option').each(function() { add_option('#id_all_users', '#id_users', $(this)); $('#id_users_in_group').val($('#id_users_in_group').val() + "-" + String($(this).val())) }) }) // Add selected (from source to destination) $('#add_selected').on("click", function(e) { e.preventDefault(); $('#id_users').find('option').removeAttr('selected'); let values = $('#id_all_users').val(); $('#id_all_users … -
Django request.session not working properly
i am creating a web app and i'm using ajax to send the data from frontend to backend so i can process the forms and save them to the database. I send the data from ajax to a get-data method and from there i save it to the session, and when i access the /success page and try to get the same data from session, it tells me that the key doesn't exist. How is that possible? Here is the code down below. $.ajax({ type: "POST", url: "/get-data/", data: JSON.stringify(obj), dataType: "text", headers: { "X-CSRFToken": getCookie("csrftoken") }, success: function (response) { console.log("success"); // i get this, so i it means that the ajax works properly. }, error: function (response, err, err2) { console.log(err2); }, }); def get_data(request): if request.method == "POST": if is_ajax(request): rec_data = json.loads(request.body) print("the request came") request.session["data_check_form"] = rec_data print("everything set") print(request.session["data_check_form"]) # i print this and i get the json file properly return JsonResponse({"success": "200"}) def success_view(request): print("test") data = request.session.get("data_check_form", False) print(data) # i get false ... -
django.db.utils.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: django aws
When trying to get data from the database I receive the below error: 2022-01-30 11:47:05,004 ERROR Exception inside application: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Traceback (most recent call last): File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 219, in ensure_connection self.connect() File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/base/base.py", line 200, in connect self.connection = self.get_new_connection(conn_params) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/utils/asyncio.py", line 33, in inner return func(*args, **kwargs) File "/var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/postgresql/base.py", line 187, in get_new_connection connection = Database.connect(**conn_params) File "/var/app/venv/staging-LQM1lest/lib64/python3.8/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? The above error occurs only in production. I have an external database in RDS (amazonAWS) and I am not sure why it's still trying to make a connection to "/var/run/postgresql/.s.PGSQL.5432". Here is my database settings in settings.py: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': os.getenv('RDS_USER'), 'PASSWORD': os.getenv('RDS_PASSWORD'), 'HOST': os.getenv('RDS_HOST'), 'PORT': '5432' } I am using the below snippet which authenticates users using token authentication in channels: from urllib.parse import parse_qs from channels.auth … -
Why does docker build constantly fail?
I'm trying to use Docker for the first time for my Django project using the book "Django For Professionals", but I am keep on getting build errors when I type "Docker build ." for a few days. I have looked at other stack overflow posts(An error, "failed to solve with frontend dockerfile.v0") but it still does not work. Here is the error code that I get. yoonjaeseo@Yoons-MacBook-Pro hello % docker build . [+] Building 0.1s (2/2) FINISHED => [internal] load build definition from Dockerfile 0.0s => => transferring dockerfile: 419B 0.0s => [internal] load .dockerignore 0.0s => => transferring context: 2B 0.0s failed to solve with frontend dockerfile.v0: failed to create LLB definition: file with no instructions yoonjaeseo@Yoons-MacBook-Pro hello % export DOCKER_BUILDKIT=0 export COMPOSE_DOCKER_CLI_BUILD=0 yoonjaeseo@Yoons-MacBook-Pro hello % docker build . Sending build context to Docker daemon 179.2kB Error response from daemon: failed to parse Dockerfile: file with no instructions I have my Dockerfile within my Django project and it is as follows: FROM python:3.8 ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 WORKDIR /code COPY Pipfile Pipfile.lock /code/ RUN pip install pipenv && pipenv install --system COPY . /code/ Please let me know if any additional information is needed. Thank you! -
A question app that the user must give coins to ask a question and the answerer will get the coins
enter code hereI am creating a kind of a question and answer web application. I want the user asking the question to compulsorily give coins. The choices are already there. Then the user that answers the question gets the coins given by the other user. I am using Django signals, but the user that ask the question got hienter image description heres coins deducted but the answerer didn't get any coin it is given me an error. This is the model for the question and answer . I already have the user model with the user default coin as 5000 class Question(models.Model): COINS_CHOICES = ( (10, 10), (20, 20), (30, 30), (40, 40), (50, 50), (60, 60), (70, 70), (80, 80), (90, 90), (100, 100), ) label = models.CharField(max_length=5000) image = models.ImageField() #slug = models.SlugField() timestamp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now_add=True) subject = models.ForeignKey(Subject, on_delete=models.CASCADE) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) coins_given = models.PositiveSmallIntegerField(choices=COINS_CHOICES, blank=False, null=True) def __str__(self): return self.label class Answer(models.Model): label = models.CharField(max_length=5000) image = models.ImageField() timestamp = models.DateTimeField(auto_now_add=True) updated_on = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) question = models.ForeignKey(Question, on_delete=models.CASCADE) clap = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="answers") def __str__(self): return self.label def number_of_clap(self): return self.clap.count() class Comment(models.Model): text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) … -
Running a for loop inside html file for specific time in django
I want a for loop to run 2/3 times for this specific model. Lets assume I have 10 data, I want the first 3 one to be shown inside html file through a for loop. Can anyone help me with this one? This is the models.py class CompanyInformation(models.Model): name = models.CharField(max_length=50) details = models.TextField(max_length=50) website = models.CharField(max_length=50, null=True, blank=True) social_fb = models.CharField(max_length=50, null=True, blank=True) social_ig = models.CharField(max_length=50, null=True, blank=True) social_twitter = models.CharField(max_length=50, null=True, blank=True) social_youtube = models.CharField(max_length=50, null=True, blank=True) def __str__(self): return self.name views.py file from django.shortcuts import render from .models import * # Create your views here. def aboutpage(request): aboutinfo = CompanyInformation.objects.all()[0] context={ 'aboutinfo' : aboutinfo, } return render(request, 'aboutpage.html', context) inside the html file {% block body_block %} <p class="redtext">{{ aboutinfo.name }}</p> <p class="redtext">{{ aboutinfo.details }}</p> <p class="redtext">{{ aboutinfo.website }}</p> {% endblock body_block %} -
Django ; How i can migrate a project done with the sqlite3 to postgresql
From days my friend has worked in the OS:windows and he did a part of the django application using the database :sqlite3 , he give me a backup of his work to complete my part , on the backup i have found a database named databaseproject.db, My question here that am using Linux as an OS and postgresql , How I can migrate this database databaseproject.db(it's an sqlite3 database ) to postgresql. Ps: when i have tried do the command below on the directory(after copied the project in a virtual environement on my linux): python manage.py dumpdata --natural-foreign \ --exclude=auth.permission --exclude=contenttypes \ --indent=4 > data.json ----> command go without errors, Here i have found the data.json contain an empty list.. So i want to know , How i can correctly migrate from sqlite3 to postgresql.? Thanks in advance. -
Django models not being saved to database when updated using Celery and when deployed to Heroku
So the title is a bit long winded but i think explains my issue pretty well. I have a Django project that updates models every 60 seconds by scraping currency data from another website using Celery and RabbitMQ. When i run the celery worker locally it works perfectly, however when i deploy to Heroku the models do not update. When i check the logs (heroku logs --tail) It shows that the tasks are running but they aren't updating the database models. I beleive this must be due to some configuration error in my settings.py file but i have tried numerous solutions and nothing has worked. I have also tried changing to use Redis instead and have experienced the same problem (it runs fine in the logs but does not actually update the database). Here is what i believe to be the relevant code that could be causing the problem. Settings.py (when using rabbitMQ): CELERY_BROKER_URL = 'rabbitMQ_url_given_from_heroku' BROKER_URL = os.environ.get("CELERY_BROKER_URL", "django://") BROKER_POOL_LIMIT = 1 BROKER_CONNECTION_MAX_RETRIES = None CELERY_TASK_SERIALIZER = "json" CELERY_ACCEPT_CONTENT = ["json", "msgpack"] Settings.py (when using Redis): CELERY_BROKER_URL = 'Redis_url_given_from_heroku' CELERRY_RESULT_BACKEND = 'django-db' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'UTC' celery.py import os from celery … -
I'm trying to read CVS file in Django
I'm new to Django trying to read data from CSV file and display data in form of a table using Django templates. Please help me with how I can do it.