Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django formset get all parameter value issue
I have a listview that show data in table, I have create a form that filter the data and show in table (working), but I want to make a formset, add filter condition and get all values without any success. views.py class CmsView(ListView): queryset = Cmsexport.objects.all().values() model = Cmsexport form_class = CmsFilterForm template_name = 'table.html' context_object_name = 'table' paginate_by = 10 def get_queryset(self): queryset = super(CmsView, self).get_queryset() field = self.request.GET.get('field') lookup = self.request.GET.get('lookup') value = self.request.GET.get('value') reset = self.request.GET.get('btn-reset') if (field and lookup and value) is not None: query = field.lower().replace(" ", "_") + '__' + lookup queryset = Cmsexport.objects.filter(**{ query: value }).values() if reset: queryset = Cmsexport.objects.filter().values() return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = CmsFilterForm() context['formset'] = CmsFormSet(queryset=Cmsexport.objects.none()) return context forms.py class CmsFilterForm(ModelForm): class Meta: model = Cmsexport #fields = ['name', 'state_text'] fields = '__all__' CmsFormSet = modelformset_factory( Cmsexport, fields = '__all__', extra=1 ) Any idea? -
Django:UNIQUE constraint failed: users_profile.user_id
I am using a Form to create a registration feature for my website. However, when I try to register, I encounter the following issue. Strangely, in the admin database, a user and profile have been successfully created. Can anyone please help me identify what might be causing this problem django.db.utils.IntegrityError: UNIQUE constraint failed: users_profile.user_id model from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. from django.db.models.signals import post_save, post_delete from django.dispatch import receiver class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True , blank=True) name = models.CharField(max_length=200, blank=True, null=True) email = models.EmailField(max_length=500, blank=True, null=True) username = models.CharField(max_length=200, blank=True, null=True) location = models.CharField(max_length=200, blank=True, null=True) short_intro = models.CharField(max_length=200, blank=True , null=True) bio = models.TextField(blank=True, null=True) profile_image = models.ImageField( null=True, blank=True, upload_to='profiles/', default='profiles/user-default.png') social_github = models.CharField(max_length=200, blank=True, null=True) social_twitter = models.CharField(max_length=200, blank=True, null=True) social_linkedin = models.CharField(max_length=200, blank=True, null=True) social_youtube = models.CharField(max_length=200, blank=True, null=True) social_website = models.CharField(max_length=200, blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__(self): return str(self.username) class Meta: ordering = ['created'] class Skill(models.Model): owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True, blank=True) name = models.CharField(max_length=200, blank=True, null=True) description = models.TextField(blank=True, null=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) def __str__ (self): return str(self.name) #@receiver(post_save, … -
TypeError: data.map is not a function in react and django
I'm using Axios to retrieve data from the backend. When I log the data to the console, it appears as an object. However, I need the data to be in an array format. When I try to use the map function on the data, it gives me an error stating that data.map is not a function. I am using django in backend function Search() { const [data,setData] = useState([]) // setting data as array i had also used null here useEffect(()=>{ axios.get("http://127.0.0.1:8000/api/listing") //using axios api .then(response =>{ setData(response.data) console.log(response.data) //data is appears as object when do console.log }) .catch(error =>{ console.log("Error fetching data:",error) }); },[]); return ( <div> <h1>Fetched Data</h1> {/* <ul> //data.map is not a function {data.map(item =>( <li key={item.id}>{item.title}</li> ))} </ul> */} </div> ) } export default Search I have checked wheather data from backend is in form of array or object and i got that the data is not in form of array if (Array.isArray(response.data)) { setData(response.data); } else { console.error('Data is not an array:', response.data); } after that i tried to convert data to array in two ways .then((response) => { //if data is not in array convert it into array const dataArray = Array.isArray(response.data) ? … -
why is django import export not working for me
I have the following model for a website category class Category(models.Model): name = models.CharField(max_length=50) description = models.TextField(max_length=500, blank=True, null=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, blank=True, null=True ,related_name='sub_categories') created_at = models.DateTimeField(auto_now_add=True, verbose_name="created at") updated_at = models.DateTimeField(auto_now=True, verbose_name="updated at") class Meta: verbose_name = "category" verbose_name_plural = "categories" db_table = "website_categories" unique_together = ('name', 'parent',) def __str__(self): return self.name I have installed django-import-export model and have the following set up for the admin from .models import * from import_export import resources from import_export.admin import ImportExportModelAdmin from django.contrib.auth import get_user_model User = get_user_model() class WebsiteAdmin(admin.ModelAdmin): list_display = ("url", "category", "user") search_fields = ["url", "category", "user"] class ServiceCategoryAdmin(admin.ModelAdmin): list_display = ("name",) search_fields = ["name"] class ProductCategoryAdmin(admin.ModelAdmin): list_display = ("name",) search_fields = ["name"] class CategoryResource(resources.ModelResource): class Meta: model = Category fields = ('id', 'name', 'description',) class CategoryAdmin(ImportExportModelAdmin): list_display = ("name",) search_fields = ["name"] resource_classes = [CategoryResource] admin.site.register(Website, WebsiteAdmin) admin.site.register(ServiceCategory, ServiceCategoryAdmin) admin.site.register(ProductCategory, ProductCategoryAdmin) admin.site.register(Category, CategoryAdmin) On the admin side I see the import and export buttons and I am able to import a file but the data is not getting correctly imported and the only thing getting generated is the id. So for every line in the csv doc the id is generated bu not the name nor … -
Atomic Transactions not working in Django
I have a Django function which does a very basic create/update operation and I was trying to implement atomic block for transactions but it doesn't seem to work. The implementation is very straight forward but I am still unable to do the rollback so I am wondering if I am doing something wrong or missed some config. with transaction.atomic(): try: auth_user_data['email'] = email auth_user_data['first_name'] = first_name auth_user_data['last_name'] = last_name user = User.objects.using('xyz').create(**auth_user_data) auth_user_data['id'] = user.id user_securities_data['zipcode'] = address_info['zipcode'] user_securities_data['address'] = address_info['address'] user_securities_data['country'] = address_info['country'] user_securities_data['user_id'] = user.id user_securities_data['abc'] = user.id user = Profile.objects.using('xyz').create(**user_securities_data) except Exception as e: print("ERROR___________", e) What I am trying to achieve here is the first create to the DB should be success and the second create DB should be a failure and that would revert both the operations. -
Django pytest in docker-compose django.db.utils.OperationalError
I've docker-compose configuration for django and postgres, it works fine. However, when I'm trying to run pytest inside a django container it fails with an error: pytest apps/service/tests/test_api.py::TestCreate::test_new ====================================================================== test session starts ======================================================================= platform linux -- Python 3.8.18, pytest-7.4.1, pluggy-1.3.0 django: settings: project.settings.local (from env) rootdir: /app/code configfile: pytest.ini plugins: mock-3.11.1, django-4.5.2, Faker-19.6.1, celery-4.4.2 collected 1 item apps/service/tests/test_api.py E [100%] ============================================================================= ERRORS ============================================================================= __________________________________________________ ERROR at setup of TestCreate.test_new __________________________________________________ self = <django.db.backends.postgresql.base.DatabaseWrapper object at 0xffff71cedf70> @async_unsafe def ensure_connection(self): """Guarantee that a connection to the database is established.""" if self.connection is None: with self.wrap_database_errors: > self.connect() /usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py:219: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ /usr/local/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) /usr/local/lib/python3.8/site-packages/django/db/backends/base/base.py:200: in connect self.connection = self.get_new_connection(conn_params) /usr/local/lib/python3.8/site-packages/django/utils/asyncio.py:33: in inner return func(*args, **kwargs) /usr/local/lib/python3.8/site-packages/django/db/backends/postgresql/base.py:187: in get_new_connection connection … -
Poll Django DB regularly from within app - permissions error
I would like to keep record of some "check-in" events in my Django app database. If a client/user hasn't posted a check-in (done via HTTP request to my app) for over X minutes, then I would like to emit a socketIO message to the client. The client can post a check-in as frequently as they like. I am running this app from a Kubernetes pod, with database username and password being exported as environment variables on pod deployment. My solution is to kick off a thread at app startup, and have this thread poll the Django database every 10 minutes. If a check-in record is not found in the database in the last 10 minutes, then call my socket emission function. Otherwise, go back to sleep for 10 minutes. Unfortunately, when I try to poll the database from within my thread, I'm met with: django.db.utils.ProgrammingError: permission denied for table check_in_table Some simplified code snippets: # WatchCheckIn().start() is called from my apps.py file within my `AppConfig`'s `ready()` class WatchCheckIn(threading.Thread): def run(self) -> None: logging.info('Querying database for check-ins.') try: latest_record = models.CheckIn.objects.last() check_in_period = datetime.datetime.now( tz=datetime.timezone.utc) - datetime.timedelta(minutes=10) if latest_record.check_in_time < check_in_period: socket_views.notify_need_check_in() except IndexError: logging.warning('No previous check-ins found.') finally: time.sleep(600) In … -
Uncaught TypeError: Cannot read properties of undefined (reading 'connect'). Twilio SDK Javascript with Django
Im developing a Dialer web app with Django and to make calls trought the browser im user Twilio SDK and Im reciving this error Complete error: ContentDispatcherService: no listeners for an event TAB_STATE__GET_NAVIGATION_METHOD caller:1 Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist. caller.js:20 Requesting Access Token... caller.js:87 Uncaught TypeError: Cannot read properties of undefined (reading 'connect') at start_device (caller.js:87:12) at HTMLButtonElement.onclick (caller:75:86) caller.js:52 Device registered So im trying to make a call trhoug connect(); method but it doesnt stablish the conection, the device is register and idk what means on it. script / async function start_device() { console.log("Requesting Access Token..."); /*Document ready*/ $.get('token', { forPage: window.location.pathname }) .then(function (data) { device = new Twilio.Device(data.token, { codecPreferences: ["opus", "pcmu"], fakeLocalDTMF: true, enableRingingState: true }); device.on("ready", function (device) { console.log("Twilio.Ready"); updateCallStatus("Ready"); }); device.on('registered',function(reg){ console.log('Device registered'); updateCallStatus('Registered'); }); device.on("error", function (error) { console.log("Twilio.Device Error: " + error.message); updateCallStatus("ERROR: " + error.message); }); device.on("connect", function (conn) { // Enable the hang up button and disable the call buttons hangUpButton.prop("disabled", false); updateCallStatus("Calling"); }); device.on("disconnect", function (conn) { // Disable the hangup button and enable the call buttons hangUpButton.prop("disabled", true); updateCallStatus("Ready"); }); device.register(); startDevice.prop('disabled', true) }) .catch(function (err) { console.log(err); console.log("Could … -
je rencontre un probleme d'importation de mon fichier json dans la base de donnee postgresql [closed]
je n'arrive pas a importer mes donnee du json pour postgresql django svp aidez moi a resoudre ce problemme cela fait une semaine que je n'y arrive pas. voici l'erreur que cela genere l'orsque jexecute ma commande python manage.py loadata fixtures/file_backup.json django.core.serializers.base.DeserializationError: Problem installing fixture 'G:\Opera + 1.9 tmp\fixtures\file_backup.json': -
Is there an elegant way to send repeating data in RESTful requests [closed]
The frontend of an app I'm building makes various api calls to the backend which follows restful principles. There is some data the user inputs when they first visit the website that gets sent to the backend in every ensuing backend request. At the moment, I am just throwing that data along with other relevant data in the JSON payload every time. For some reason I'm convinced there has to be a more elegant way to package data that gets sent in every single GET request. -
Master template for airium
I am using airium as a replacement for the default Django templates system. In the default Django system the concept of master template is used to give a common frame and look to all the pages of a site. I believe the same notion of a "master html" providing a frame is also worth when using Airium, no? Is there a way to use such a "master html" with Airium? Is it a concept existing within Airium? How could this possibly work? -
cannot import available functions in views or models in django
i started a simple django app called 'some_app' and added some code to the models.py and views.py. now i made a new file in the same directory called 'tmp_01.py' and wanted to import the functions and classes i wrote in views.py and models.py respectively. i'am facing a "moduleNotFoundError". models.py contains: from django.db import models class C1(models.Model): title=models.CharField(max_length=250,default='full of empty') and views.py : from django.shortcuts import render from django.db import transaction from .models import C1 john='doe' def finished(): print('DONE') def create_obj(): with transaction.atomic(): transaction.on_commit(finished) votes = C1.objects.create(title=john) votes.save() and finally tmp_01.py: from some_app.views import create_obj() from some_app.models import C1 create_obj() so when i run tmp_01.py i face ModuleNotFoundError: no module named "some_app" -
How to create a Djano ModelForm and a view that handles a Foreign key relationship
I have a model which consists of fk's to other models. class ParkingSpace(models.Model): name = models.CharField(max_length=50, blank=False) description = models.TextField(blank=False) image = models.ImageField(null=True, upload_to="images/parking_spaces") price = models.ForeignKey('Price', on_delete=models.CASCADE, null=True, blank=False) opening_hours = models.ForeignKey('OpeningHours', on_delete=models.CASCADE, null=True, blank=False) location = models.OneToOneField('Location', on_delete=models.CASCADE, null=True, blank=False) size = models.ForeignKey('Size', on_delete=models.CASCADE, null=True, blank=False) type = models.ForeignKey('Type', on_delete=models.CASCADE, null=True, blank=False) features = models.ManyToManyField('Features', blank=False, db_table='ParkingSpaceFeatures') reviews = models.ManyToManyField('Review', blank=False, db_table='ParkingSpaceReviews') contact_information = models.ForeignKey('ContactInformation', on_delete=models.CASCADE, null=True, blank=False) seller_account = models.ForeignKey('Account', on_delete=models.CASCADE, null=True, blank=False) Let me use the opening hours as an example: class OpeningHours(models.Model): # Opening and closing times of every day in the week monday_open = models.TimeField(null=True,blank=False) monday_close = models.TimeField(null=True,blank=False) tuesday_open = models.TimeField(null=True,blank=False) tuesday_close = models.TimeField(null=True,blank=False) wednesday_open = models.TimeField(null=True,blank=False) wednesday_close = models.TimeField(null=True,blank=False) thursday_open = models.TimeField(null=True,blank=False) thursday_close = models.TimeField(null=True,blank=False) friday_open = models.TimeField(null=True,blank=False) friday_close = models.TimeField(null=True,blank=False) saturday_open = models.TimeField(null=True,blank=False) saturday_close = models.TimeField(null=True,blank=False) sunday_open = models.TimeField(null=True,blank=False) sunday_close = models.TimeField(null=True,blank=False) Now I want to create a form where the user will be able to enter the information to create a parking space. For fields in parking space like price,opening_hours, location and contact_information these models have multiple fields that data needs to be inputted in a form. Is there a way that Django has that can handle all the database saving … -
ModuleNotFoundError: No module named 'pandas' in Django
I've followed the cookiecutter instructions to create a django project using Docker. I'm trying to use pandas inside my project but whatever I do, I get: (yt_venv) jan@Jans-MacBook-Pro summarizing % docker compose -f local.yml up [+] Running 3/0 ⠿ Container summarizing_local_postgres Running 0.0s ⠿ Container summarizing_local_docs Running 0.0s ⠿ Container summarizing_local_django Created 0.0s Attaching to summarizing_local_django, summarizing_local_docs, summarizing_local_postgres summarizing_local_django | PostgreSQL is available summarizing_local_django | Traceback (most recent call last): summarizing_local_django | File "/app/manage.py", line 31, in <module> summarizing_local_django | execute_from_command_line(sys.argv) summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 442, in execute_from_command_line summarizing_local_django | utility.execute() summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/core/management/__init__.py", line 416, in execute summarizing_local_django | django.setup() summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/__init__.py", line 24, in setup summarizing_local_django | apps.populate(settings.INSTALLED_APPS) summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/apps/registry.py", line 91, in populate summarizing_local_django | app_config = AppConfig.create(entry) summarizing_local_django | ^^^^^^^^^^^^^^^^^^^^^^^ summarizing_local_django | File "/usr/local/lib/python3.11/site-packages/django/apps/config.py", line 193, in create summarizing_local_django | import_module(entry) summarizing_local_django | File "/usr/local/lib/python3.11/importlib/__init__.py", line 126, in import_module summarizing_local_django | return _bootstrap._gcd_import(name[level:], package, level) summarizing_local_django | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ summarizing_local_django | File "<frozen importlib._bootstrap>", line 1204, in _gcd_import summarizing_local_django | File "<frozen importlib._bootstrap>", line 1176, in _find_and_load summarizing_local_django | File "<frozen importlib._bootstrap>", line 1140, in _find_and_load_unlocked summarizing_local_django | ModuleNotFoundError: No module named 'pandas' summarizing_local_django exited with code 1 In the same … -
Add Class To All Fields Django Forms
How do you add a class to all fields at one time using Django Forms? I know you can define it per field using field = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control-sm'})) But thats a lot of boiler plate to add to every field on a model form. And theres even by looping through the fields in the constructor, but that seems more of a hack than would be neccessarry. Is there a more generic/ built-in way of doing this? -
Is it possible to modify widget attributes for each instance of model form in django?
I have a model and a form based on that model. The form will be reused in several templates. Is there a way to tweak the widget attributes of the form field in views before sending it to the template. Shortest example: class Price(models.Model): ProductID = models.ForeignKey(Product, on_delete = models.CASCADE) amount = models.DecimalField(max_digits=12, decimal_places=2) class NewPriceForm(forms.ModelForm): class Meta: model = Price fields = ('ProductID','amount',) widgets = {'amount': forms.NumberInput(attrs={'autocomplete':'off', 'min':'0.01' }), } def set_price(request, ProductID): price_form = NewPriceForm(prefix = 'price') I want to set price_form minimum value to something other than in the widget attributes, based on variables that I have available in the view before sending it off to the template. Something like this: price_form.fields["amount"].widget.min = calculated_min_price -
How do I check if a date in the database is past due in my template
I'm new to Django so I apologize if this is something simple. I'm trying to check if a date stored in the database is past due. I have a "due_date" in my "Update" model and would like to check in my html if the date is past due in order to display a HTML output. I've been looking online for hours but none of the answers seems to work. models.py class Update(models.Model): date_created = models.DateField(blank=True, null=True) due_date = models.DateField(blank=True, null=True) index.html {% if update.due_date <= today %} <td class="py-2 px-4 text-center"> <span class="p-1 text-xs border rounded-md bg-red-100 border-red-400 text-red-600">Overdue</span> </td> {% else %} <td class="py-2 px-4 text-center"> <span class="p-1 text-xs border rounded-md bg-green-100 border-green-400 text-green-600">Current</span> </td> {% endif %} -
Django rest framework foreign key is null
I am a newbie in Django, and I had implemented an many to many relationship, however one field which is is null. When I post profile it is null. Below is how I add it: "profile": { "id": 1, "profile_pic": "/media/images/default.jpg", "story": null, "user": 1, "post": [] } Then, below is my models file : class Post(models.Model): profile = models.ForeignKey('Profile', on_delete=models.PROTECT, related_name='profile', null=True, blank=True) Then, my serializers file : class PostSerializer(serializers.ModelSerializer): class Meta: model = Post depth = 1 fields = '__all__' Then finally my views file : @permission_classes([IsAuthenticated]) @api_view(['POST']) def create_user(request): serializer = UserSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response() What I want is to post all the data and comes back in response. Also I am using react axios with ```multipart/form-data`` but my main goal for now is just be able to add it with rest framework and I don't care if it applcation/json or something other. -
there is a problem with embedding an HTML template in which there is a loop. Django
Good afternoon to all! I'm new to Python and Django. There is a page on it I am trying to attach a template of another page via include, but the loop that should display the data does not start. help me figure out the problem. {% extends "base.html" %} {% block title %} {% endblock %} {% block content %} <div class="container"> <h1>График замен ФН</h1> <style> { font-size: 12px; /* Adjust the font size as needed */ } </style> <div class="col-md-2"> <div class="form-group"> <label>&nbsp;</label> <button type="submit" class="btn btn-primary btn-block">Применить фильтры</button> </div> </div> </div> </form> {% include "includes/fn_base_template.html" with fn_replacements_page=fn_replacements_page %} {% include "includes/paginator.html" with fn_replacements_page=fn_replacements_page %} {% endblock %} includes/fn_base_template.html <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th class="col-md-2">Название объекта</th> <th class="col-md-1">SAP</th> <th class="col-md-2">Юридическое лицо</th> <th class="col-md-2">Адрес объекта</th> <th class="col-md-1">Номер позиции</th> <th class="col-md-1">Модель ФР</th> <th class="col-md-1">Серийный номер ФР</th> <th class="col-md-1">Серийный номер ФН</th> <th class="col-md-1">Дата первичной регистрации</th> <th class="col-md-1">Дата замены</th> </tr> </thead> <tbody id="table-body"> {% for fn_replacement in fn_replacements_page %} <tr> <td class="table-body-cell">{{ fn_replacement.name_object }}</td> <td class="table-body-cell">{{ fn_replacement.sap }}</td> <td class="table-body-cell">{{ fn_replacement.legal_entity }}</td> <td class="table-body-cell">{{ fn_replacement.addres_object }}</td> <td class="table-body-cell">{{ fn_replacement.nomer_pos }}</td> <td class="table-body-cell">{{ fn_replacement.model_fr }}</td> <td class="table-body-cell">{{ fn_replacement.sn_fr }}</td> <td class="table-body-cell">{{ fn_replacement.sn_fn }}</td> <td class="table-body-cell">{{ fn_replacement.date_fp }}</td> <td class="table-body-cell">{{ fn_replacement.replacement_date }}</td> … -
React axios object returns null with django rest framework
I am using axios to create a new instance in django rest framework. I do it with multipart/form-data but it returns null instead of the actual object. I also use the FormData const formData = new FormData() formData.append("image", selectedFile); formData.append('profile', currentUser[0]?.profile) formData.append('test','1') axios.post('http://127.0.0.1:8000/create_post/', formData, { headers: { "Content-Type": "multipart/form-data", }, }).then(res=>console.log(res)).catch(err=>console.log(err)) } -
Element could not be scrolled into view error
I have been working on a simple recipe app in django and want to be able to sort the recipes by country of origin. I am trying to get the hang of Test Driven Development, so I am using Selenium. Unfortunately, I get this error. I'm confused because there should only be one recipe in the database, and yet a call for a second recipe is made when the recipe doesn't exist. When I run python manage.py runserver, I can interact with the recipe card exactly the way I would imagine, but I get an error when trying to test it. How should I fix this error? ElementNotInteractableException: Message: Element '<a class="recipe-card" href="/recipes/2/">' could not be scrolled into view (edit) I have tried adding a second recipe to test with, but am then told that /recipes/3/ could not be scrolled into view. The Selenium test code class RecipesTest(LiveServerTestCase): def setUp(self): self.browser = WebDriver() self.browser.implicitly_wait(5) self.continent = Continent.objects.create(name='test_continent') self.country_1 = Country.objects.create(name='test country 1', continent = self.continent) self.country_2 = Country.objects.create(name='test country 2', continent = self.continent) self.recipe_1 = Recipe.objects.create(name='test recipe 1', country = self.country_1) def tearDown(self): self.browser.quit() def test_recipes(self): self.browser.get('%s%s' % (self.live_server_url, '/countries/1/')) recipe = self.browser.find_element(by=By.CLASS_NAME, value="recipe-card") recipe.click() The html file recipe_list.html {% … -
Accessing static content from css file with Google App Engine/Google Cloud Storage
I have a Google Cloud Storage bucket from which my Google App Engine django application retrieves its static content. This works swimmingly as long as the content is being accessed through staticfiles, but becomes a problem when I try to link src urls through my css (e.g. background image, font). In my bucket logs I can see this is because no authentication info is being passed in the request for these assets being linked via css, whereas those grabbed through the static system (e.g. staticfiles or {% static '' %} ) I'm wondering what the correct solution is to this RATHER than just using inline css within the html to invoke the staticfile system as doing so is bad practice. This is my current approach, I can see it requesting the correct bucket resource, it just isn't authenticating: @font-face { font-family: "syne":; src: url("path/to/font.ttf") format("truetype") } -
How can I create a shared portal for tenant
I have a question about django-tenent-scheme library. How may I create a tenant management portal, that is not shared with other tenants? I want to display a main page where a new customer can create his account and after that new tenant will be created. For instance, myapp.net/Portal is for creating new customers and for managing accounts, buying licenses, etc. And after creating a client he gets his own URL client.myapp.net. Is there any way to create a management portal in the project or should I create another project, deploy it with another server, and manage it by DNS like myapp.com A --> portal IP *.myapp.com A --> app ip I can create a tenant for the portal with the domain myapp.net but the portal is available in all tenants like client.myapp.net/portal -
Problem with Stripe Checkout (Nextjs and Django)
I am trying to make a payment page in nextjs using stripe. if i guendo the guide it works correctly, but i don't want to use the form to call the /create-checkout-session endpoint but i want to use an onClick function on a div to make a call with axios. Frontend Code 'use client'; import React, {useEffect, useState} from 'react'; import Container from "@/components/Container"; import axios from "axios"; const PagamentiPage = () => { const data = { product_id: 1, price: 599, name: "Test", description: "lorem ipsum dolor sit amet consectetur adipisicing elit.", } return ( <Container> <div className="product"> <img src="https://i.imgur.com/EHyR2nP.png" alt="The cover of Stubborn Attachments" /> <div className="description"> <h3>{data.name}</h3> <h5>Price: {data.price/100} €</h5> </div> </div> <form action="http://127.0.0.1:8000/pagamenti/create-checkout-session" method="POST" > <input type="hidden" name="product_id" value={1}/> <input type="hidden" name="price" value={70000}/> <input type="hidden" name="name" value={"Test"}/> <input type="hidden" name="description" value={"Frf"}/> <input type="hidden" name="username" value={"Federiko98"} /> <button type={"submit"} className={"bg-red-300 p-2 rounded"}> Checkout </button> </form> </Container> ); }; export default PagamentiPage; Backend Code class StripeCheckoutView(APIView): def post(self, request, *args, **kwargs): data = request.data try: checkout_session = stripe.checkout.Session.create( line_items=[{ 'price_data': { 'currency': 'eur', 'unit_amount': data.get("price"), # centesimi 'product_data': { 'name': data.get("name"), 'description': data.get("description"), }, }, 'quantity': 1, }], metadata={ 'username': data.get("username"), 'product_id': data.get("product_id"), }, mode='payment', success_url=f'{YOUR_DOMAIN}?success=true', cancel_url=f'{YOUR_DOMAIN}?canceled=true', ) … -
Pass token from frontend to backend and access claims that can be used to filter data from database, React Django MySQL project
The map function in the Schools.js file shows all schools in the database. I want it to only fetch and display the shools where the dist_office_id = place_id and the school_name is not empty. the place_id is a claim in the token. I want to pass the token from the School.js file (frontend) to the views.py file (backend) where i need to access the place_id claim from the token. When i hardcode the place_id = 3 it works fine as expected but there are many district offices and it should only show schools under any district that the user may belong to. import { useEffect, useState } from 'react'; import jwt_decode from "jwt-decode"; import {Table, Button, ButtonToolbar} from 'react-bootstrap'; import {FaEdit} from 'react-icons/fa'; import {RiDeleteBin5Line} from 'react-icons/ri'; import {getSchools, deleteSchool} from '../services/SchoolService'; import AddSchoolModal from '../components/modals/api_modals/AddSchoolModal'; import UpdateSchoolModal from '../components/modals/api_modals/UpdateSchoolModal'; const Schools = () => { const [schools, setSchools] = useState([]); const [addModalShow, setAddModalShow] = useState(false); const [editModalShow, setEditModalShow] = useState(false); const [editSchool, setEditSchool] = useState([]); const [isUpdated, setIsUpdated] = useState(false); const token = localStorage.getItem("authTokens") if (token){ const decoded = jwt_decode(token) var place_id = decoded.place_id } useEffect(() => { let mounted = true; if(schools.length && !isUpdated) { return; } getSchools() …