Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create a mysql database in Django on the first run?
I'd like my application to be "plug-and-play", so I need to automatically create the database on the first run. I use docker with docker-compose My attempt is to connect without specifying the database name and run a custom command before running the server: command: sh -c "python manage.py create_db && python manage.py runserver 0.0.0.0:8000" And the command itself: class Command(BaseCommand): """Django command to create DB""" def handle(self, *args, **options): con = connections['default'] db_name = os.environ.get('DB_NAME') db_up = False while not db_up: try: cursor = con.cursor() cursor.execute(f'CREATE DATABASE IF NOT EXISTS {db_name}') cursor.execute(f'USE {db_name}') db_up = True except Exception as err: self.stdout.write('Database unavailable, waiting 1 second...') self.stdout.write(str(err)) time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) If this is the right way, then now I just need to update the connection to use the newly created database, but I don't know how. The line cursor.execute(f'USE {db_name}') of course doesn't work. Is it the right way to create the database? If so, how to update the connection? If not, how to do it? Thanks! -
How do I route my databases in Django based on which user is logged in?
I am making a django website and I want each user to have their own database, for example now I have 2 databases hosted on azure, and in my settings.py file I have this: DATABASES = { 'default' :{}, 'user1': { 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'temp monitoring', 'USER' : 'maxwhitehead@maxiot', 'PASSWORD' : '#######', 'PORT' : 3306, 'HOST' : 'maxiot.mysql.database.azure.com', }, 'user2':{ 'ENGINE': 'django.db.backends.mysql', 'NAME' : 'temp monitoring', 'USER' : 'maxwhitehead@maxiot2', 'PASSWORD' : '#######', 'PORT' : 3306, 'HOST' : 'maxiot2.mysql.database.azure.com', } } I have a folder called users, and within that I have a file called Fields that includes this: from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ['username','email','password1','password2'] So I want people to login and see the posts from their associated database. I know I have to do something with database routing but I am not sure what, any help would be appreciated, thanks. -
Django Like Function With viewsets
Hey guys I try make blog app I take "detail": "Method "POST" not allowed." whwn I send get request to "/blog/like/1,2..." I take response but i cant send Post request That is The Models class Like(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) post = models.ForeignKey(Post, on_delete=models.CASCADE) def __str__(self): return self.created_by.username That is serializers class LikeSerializer(serializers.ModelSerializer): created_by = serializers.StringRelatedField() post = serializers.StringRelatedField() class Meta: model = Like fields = ( 'created_by', 'post', 'post_id' ) That is views class LikeView(viewsets.ModelViewSet): queryset = Like.objects.all() serializer_class = LikeSerializer def perform_create(self, serializer): serializer.save(created_by=self.request.user) def post(self, post_id): post = Post.objects.get(id=post_id) if Like.objects.filter(post=post, created_by=self.request.user).exists(): Like.objects.filter( post=post, created_by=self.request.user).delete() else: Like.objects.create(post=post, created_by=self.request.user) that is Urls from django.urls import path from .views import ( PostView, PostView_View, LikeView, CommentView ) from rest_framework import routers router = routers.DefaultRouter() router.register('', PostView) router.register('like', LikeView) urlpatterns = [ ] + router.urls -
Accessing the attribute of a model through a shared foreign key in another model
I am a complete newbie to the world of Django and I'm confused as to how I can access the list of values from a table that has access to another table through a foreign key. Here is the Request model: class Request(models.Model): """ Carry requests """ sender = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="requests") offers = models.ManyToManyField("Offer", blank=True) code = models.UUIDField(max_length=64, default=uuid.uuid4, editable=False) weight = MeasurementField( measurement=Weight, validators=[MinValueValidator(Weight(g=1))], verbose_name=gettext_lazy("Weight") ) description = models.TextField(blank=False) origin_country = models.ForeignKey( Country, on_delete=models.PROTECT, related_name="origin_requests", verbose_name=gettext_lazy("Origin Country") ) origin_city = models.ForeignKey( City, on_delete=models.PROTECT, related_name="origin_requests", verbose_name=gettext_lazy("Origin City") ) destination_country = models.ForeignKey( Country, on_delete=models.PROTECT, related_name="destination_requests", verbose_name=gettext_lazy("Destination Country"), ) destination_city = models.ForeignKey( City, on_delete=models.PROTECT, related_name="destination_requests", verbose_name=gettext_lazy("Destination City"), ) status = models.CharField(max_length=40, choices=Status.choices, default=Status.AVAILABLE) reward = MoneyField( max_digits=1000, decimal_places=2, default_currency="PHP", validators=[MinMoneyValidator(defaultdict(lambda: 0.01))], verbose_name=gettext_lazy("My Initial Offer Fee"), ) photo = models.ImageField(upload_to="requests/", verbose_name=gettext_lazy("Photo of Item")) accepted_offer = models.ForeignKey( "Offer", on_delete=models.SET_NULL, blank=True, null=True, related_name="accepted_requests" ) add_insurance = models.BooleanField(default=False, verbose_name=gettext_lazy("I WANT 100% INSURANCE FOR MY ITEMS")) declared_amount = MoneyField( max_digits=1000, decimal_places=2, default_currency="PHP", validators=[MinMoneyValidator(defaultdict(lambda: 0.01))], verbose_name=gettext_lazy("Declared Amount"), blank=True, null=True, ) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) history = HistoricalRecords(excluded_fields=["sender", "code", "created", "modified"]) @property def short_code(self) -> str: return str(self.code)[:8] def __str__(self) -> str: return f"({str(self.code)[:8]}) @{self.sender.username}: {self.origin_country} -> {self.destination_country}" Here is the Negotiation model: class Negotiation(models.Model): request … -
Using VCR mechanics to record and play queries to SQL database [closed]
Are there any libraries for python that would allow recording SQL queries to a file and later loading these queries from the file to memory and playing queries by monkey patching the db driver? I had employed this method in the past for recording http queries to external services with library vcrpy. I don't see any obstacles in implementation. The question is, does it even make sense in terms of test speed improvement? Also, what inconsistencies or pitfalls in usage of such an approach might this cause? -
Why the ListView not showing data in the template?
I'm working on my first Django project (the final project for codecademy's Django class) and I'm making webpages to show the inventory and menu that a restaurant has. I made the model, view, template, etc. for inventory and it displays the ListView perfectly. I did the same thing for my menu and it doesn't work. The page loads but the table that's supposed to output data is empty. Any insight on what might be going wrong? PS I'm new to programming and this is my first stackoverflow post so forgive any formatting errors or other faux pas ## views.py from django.http import HttpResponse from django.shortcuts import render from .models import Inventory, MenuItem, RecipeRequirement, Purchase from django.views.generic.edit import CreateView, DeleteView, UpdateView from django.views.generic import ListView # Create your views here. def index(request): return render(request, "index.html") class InventoryList(ListView): template_name = "inventory.html" model = Inventory class MenuList(ListView): template_name = "menu.html" model = MenuItem Inventory (below) works fine! :) {% extends './base.html' %} {% block content %} <h2>Inventory</h2> <table id="inventory"> <tr> <th>Ingredient</th> <th>Price</th> <th>Units Available</th> </tr> {% for ingredient in inventory_list %} <tr> <tr> <td>{{ ingredient.ingredient_name }}</td> <td>{{ ingredient.price }}</td> <td>{{ ingredient.units_avail }}</td> </tr> {% endfor %} </table> {% endblock %} This one (Menu) … -
How to print multiple values from two lists in django template
I am trying to figure out a way to print values from two different context variables in a single loop. I have tried the zip() method but it does not seem to work and does not print variables on the template. This is how I tried index.html <tbody> {% for item1, item2 in mylist %} <tr> <td><a href="/{{ url.short_url }}">/{{ item1.short_url }}</a></td> <td>{{ item1.original_url }}</td> <td>{{ item1.created_at }}</td> <td>{{ item1.clicks|intcomma }}</td> <td>{{ item2.browser }}</td> <td>{{ item2.platform }}</td> <td><a href="#"> <svg class="octicon octicon-graph" viewBox="0 0 16 16" version="1.1" width="16" height="16" aria-hidden="true"> <path fill-rule="evenodd" d="M16 14v1H0V0h1v14h15zM5 13H3V8h2v5zm4 0H7V3h2v10zm4 0h-2V6h2v7z"> </path> </svg> </a></td> </tr> {% endfor %} </tbody> views.py def index(request): urls = Url.objects.order_by('-created_at') clicks = Click.objects.order_by('-created_at') # context = {'urls': urls, 'clicks': clicks} mylist = zip(urls, clicks) context = { 'mylist': mylist, } return render(request, 'heyurl/index.html', context) But on running the local server I don't see anything on the table view. What am I doing wrong here? Are there any alternatives ? Here's my current version of code. models.py from django.db import models class Url(models.Model): short_url = models.CharField(max_length=255) original_url = models.CharField(max_length=255) clicks = models.IntegerField(default=0) created_at = models.DateTimeField('date created', auto_now_add=True) updated_at = models.DateTimeField('date updated', auto_now=True) class Click(models.Model): url = models.ForeignKey(Url, on_delete=models.CASCADE, related_name='related_clicks') browser … -
Invalid default value for 'id' - Django project
When I try to migrate I get this error Invalid default value for 'id' And in my dictionary I have no 'id' fields models.py from django.db import models class Product(models.Model): code=models.SlugField(max_length=70,unique=True) designation=models.CharField(max_length=255) def __str__(self): return self.article.code views.py from .models import Product def viewproduct(request): products={'message':'passe','my_product':[{'code':'mlkk','designation':'toto'}, {'code':'molo','designation':'patate'},...]} all_products=products['my_product'] for product in all_products: object_product=Product(code=product['code'],designation=product['designation']) object_product.save() Noted that my dictionary contains several products -
django 404 error The current path, didn’t match any of these
i have such error, when i try edit or delete: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/edit/ Using the URLconf defined in lab4new.urls, Django tried these URL patterns, in this order: create/ edit/<int:id>/ delete/<int:id>/ The current path, edit/, didn’t match any of these. but i can't get what's wrong with path: that's my urls.py: from django.urls import path from lab4 import views urlpatterns = [ path("", views.index), path("create/", views.create), path("edit/<int:id>/", views.edit), path("delete/<int:id>/", views.delete), ] Create works fine by the way, but what's the problem with edit and delete? -
Django Queryset not working after tranformation to Abstract class child
For more than a year, I construct many of my query using a Django Model where I have simple relation between none abstract model objects and everything was working perfectly : class Taxon(models.Model): parent = models.ForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name='children') rank = models.CharField(max_length=200, unique=False, default="NA") name = models.CharField(max_length=200, unique=False, default="NA") class Sequence(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() Exemple of queryset using my Model : taxon.sequence_set.filter(stuff_filtering) But recently I had to apply some modifications on my database and my Sequence objects are now derivated from an Abstract class called Observation, becoming this class Observation(models.Model): taxon = models.ForeignKey(Taxon, null=True, blank=True, on_delete=models.CASCADE) class Meta: abstract = True class Sequence(Observation): amplicon = models.CharField(max_length=1000, unique=False) sequence = models.CharField(max_length=1000, unique=False) score = models.FloatField() def __str__(self): return str((self.amplicon, self.sequence, self.score, self.taxon)) I didn't changed anything in my queryset because django documentation about abstract class (https://docs.djangoproject.com/en/3.2/topics/db/models/) say you can still use your chlid_set in a query. However i'm facing this error and I couldn't understand why. AttributeError: 'QuerySet' object has no attribute 'sequence_set' Knowing that in case of Abstract base classes, a table should be created in db for each child with parent attribute... So i … -
Serializing Array Field to String
I have an array field in my model i need to serialize and return the first 10 tags from the query getting error while serialising the data. referred - DRF serialize ArrayField as string serializers.py class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(self, obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class TagsSearchSerializer(serializers.ModelSerializer): tags = StringArrayField() class Meta: model = Mymodel fields = ('id', 'tags') models.py class Mymodel(models.Model): tags = ArrayField(models.CharField(max_length=64, blank=True),default=list, blank=True) views.py class TagsSearchAPIView(APIView): """ Used on dropdown menus to dynamically fetch Tags data """ def get(self, request): queryset = Mymodel.objects.all() tags = queryset.order_by('tags')[:10] serialized_tags = TagsSearchSerializer(tags, many=True, context={'request': request}) results = serialized_tags.data return Response({'results': results}) error to_representation() takes 1 positional argument but 2 were given -
User passes test in django to check subscription
I have a django application where I need to check if a user has a valid subscription, otherwise it redirects the user to his/her dashboard. I was thinking to use the django decorator user_passes_test but I couldn't find a proper way to create the function to check the user. My models for user and subscription are: class CustomUser(AbstractUser): user_type_data = ( ('admin', 'admin'), ('school_admin', 'school_admin'), ('student', 'student'), ) user_type = models.CharField( max_length=20, choices=user_type_data, default='student') address = models.CharField(max_length=500, null=True, blank=True) city = models.CharField(max_length=200, null=True, blank=True) zip_code = models.CharField(max_length=100, null=True, blank=True) country = CountryField(null=True, blank=True) phone = models.CharField(max_length=200, null=True, blank=True) selected_course = models.ForeignKey(QuizTheoryCourse, on_delete=models.CASCADE, null=True, blank=True) class Subscription(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE) issue_date = models.DateTimeField(null=True, blank=True) duration = models.IntegerField(choices=DURATION_CHOICES) expiration_date = models.DateTimeField() def __str__(self): return f'{self.user} - {str(self.expiration_date)}' def get_expiration(self): if self.expiration_date: if self.expiration_date > timezone.now(): expiration_date = self.expiration_date + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) else: expiration_date = dt.now() + timedelta(days=int(self.duration)) return expiration_date def is_subscription_valid(self): today = timezone.now() return today < self.expiration_date The function I am using to pass in the decorator is: def subscription_valid(user): try: superuser = user.is_superuser user_valid = user.subscription.is_subscription_valid return superuser or user_valid except user.DoesNotExist: return False My problem is that, anytime the user doesn't have any … -
ImportError: cannot import name 'fromshare' from 'socket'
im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare ` im facing this error ImportError: cannot import name 'fromshare' from 'socket' (/app/.heroku/python/lib/python3.10/socket.py) File "/app/coreapp/forms.py", line 1, in <module>from socket import fromshare` #i was trying to run Heroku run python manage.py migrate #my forms file : from django import forms from django.contrib.auth.models import User from coreapp.models import Restaurant from django.db import models class UserForm(forms.ModelForm): email = forms.CharField(max_length=100, required=True) password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User fields = ("username", "password", "first_name", "last_name", "email") class RestaurantForm(forms.ModelForm): class Meta: model = Restaurant fields = ("name", "phone", "address", "logo") ``` ` File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/app/.heroku/python/lib/python3.10/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() … -
Value: "" must be an instance of <class 'dict'> in django, djongo
I am using Django and connecting with a mongodb database using djongo. My database requirements are such that I need to use an embedded field in one of the collections. On adding any entry on Django Admin I am getting a preview error - I have 2 models, City containing 3 fields, and the Address containing 2 fields a city object and a pincode. Hence the city is an embedded field in model Address. On adding this entry through django-admin an error message pops up, and the entry doesn't get saved in the database. Please correct the error below -> Value: gwalior-MP-India must be an instance of <class 'dict'> An entry in address table looks like - { "city": { "city":"gwalior", "state":"MP", "country":"India" }, "pincode":"9999" } P.S. - I was not able to attach the screenshot of django-admin panel, as I was getting an error while posting this question -> Failed to upload image; an error occurred on the server. Here are the code snippets and the versions of the installed packages. models.py class City(models.Model): _id = models.ObjectIdField() city = models.CharField(db_column='city', max_length=255, null=True, blank=True) state = models.CharField(db_column='state', max_length=255, null=True, blank=True) country = models.CharField(db_column='country', max_length=255, null=True, blank=True) def __str__(self): return self.city … -
How to extracting long views code block in a smaller method?
I have a Django application. And I have a long method where a user can upload a file and the content of the file will be shown in textarea. Because of the S.O.L.I.D principle. The code that is responsible for extracting the data from the file has to be in a seperate method. So this is the views.py: class ReadingFile(View): def get(self, request): form = ProfileForm() return render(request, "main/create_profile.html", { "form": form }) def extractingtextfromimage(): pass def post(self, request): submitted_form = ProfileForm(request.POST, request.FILES) content = '' if submitted_form.is_valid(): uploadfile = UploadFile(image=request.FILES["upload_file"]) name_of_file = str(request.FILES['upload_file']) uploadfile.save() print('path of the file is:::', uploadfile.image.name) with open(os.path.join(settings.MEDIA_ROOT, f"{uploadfile.image}"), 'r') as f: print("Now its type is ", type(name_of_file)) print(uploadfile.image.path) # reading PDF file if name_of_file.endswith('.pdf'): pdfFile = wi(filename= uploadfile.image.path , resolution=300) text_factuur_verdi = [] image = pdfFile.convert('jpeg') imageBlobs = [] for img in image.sequence: imgPage = wi(image=img) imageBlobs.append(imgPage.make_blob('jpeg')) for imgBlob in imageBlobs: image = Image.open(io.BytesIO(imgBlob)) text = pytesseract.image_to_string(image, lang='eng') text_factuur_verdi.append(text) content = text_factuur_verdi print(text_factuur_verdi) # ENDING Reading pdf file else: content = f.read() print(content) return render(request, "main/create_profile.html", { 'form': ProfileForm(), "content": content }) return render(request, "main/create_profile.html", { "form": submitted_form, }) And it is about the comment: reading PDF file till: # ENDING Reading pdf file … -
How change fields helptext style django?
I want change text color etc of help_text in fields models. I see in html that there is helptext class: <span class="helptext">Sentenses</span> so I try in my css file: .helptext { color: #bd512f; } and it dont do changes. Is there collision with bootstrap? -
context must be a dict rather than type
I've been working on a project for a while, and I have a resource called Item. The item detail view can only be viewed, if the item is from the same company as the user. If not, it should be a 404. This is the code that I have: def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) # To only show items in your company if (context['item'].company != getCompany(self.request.user)): return HttpResponseNotFound return context getCompany is a function I wrote to check the users company. The company is in a custom Profile model. This function works, I already used it multiple times for other things Now i expected to have a 404 when going to a item from another company, but instead this error appears: Internal Server Error: /fr/items/5/ Traceback (most recent call last): File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/core/handlers/base.py", line 220, in _get_response response = response.render() File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 114, in render self.content = self.rendered_content File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/response.py", line 92, in rendered_content return template.render(context, self._request) File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/backends/django.py", line 58, in render context = make_context( File "/Users/username/Documents/Work/Inventory/inventory-env/lib/python3.9/site-packages/django/template/context.py", line 278, in make_context raise TypeError( TypeError: context must be a dict rather than type. Edited: What did I miss? -
Django, check django.db.Model subclass implementation
I am creating a subclass of Django's Model class, and require the user to implement some attributes and methods. I did it by inheriting from ABC from django.db.models.base import ModelBase class AbstractFooMeta(ModelBase, ABCMeta): """To avoid metaclass conflicts""" class AbstractFoo(ABC, models.Model, metaclass=AbstractUploadMeta): my_num: int magic_string: str name = models.CharField(max_length=250) class Meta: abstract = True @abstractmethod def do_thing(self): pass @classmethod @abstractmethod def do_class_thing(cls): pass class AbstractMagicFoo(AbstractFoo): magic_str = "answer is 42" class Foo(AbstractMagicFoo): my_num = 7 def do_thing(self) -> str: print('did the thing') @classmethod def do_class_thing(cls) -> str: print('did the class thing') I can create the migration, but when I try to run the migration I get: File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 362, in reload_model self._reload(related_models) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 395, in _reload self.apps.render_multiple(states_to_be_rendered) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 597, in render_multiple model.render(self) File "/home/michael/.venv/project/lib/python3.9/site-packages/django/db/migrations/state.py", line 872, in render return type(self.name, bases, body) TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases I am guessing Django is not using the meta class I defined. I tried setting the metaclass on all child classes but did not help. How can I attach some logic to AbstractFoo that when a concrete class (i.e. not AbstractMagicFoo, but only … -
DRF: How can I show all fields of a m2m field instead of just the name
I'm building a simple Lead Generator using Django Rest Framework. I'm trying to show a list of "assigned facilities" inside a lead using django's many to many fields. But all it will show inside the API is the id of each of the facilities associated to the many to many field. How do I access more than just the name using DRF? I basically need to show the name, a description and a picture of the facility from each facility record. serializers.py class LeadUpdateSerializer(serializers.ModelSerializer): is_owner = serializers.SerializerMethodField() class Meta: model = Lead fields = ( "id", "first_name", "last_name", "PrimaryAddress", "assigned_facilities", ) read_only_fields = ("id", "is_owner") def get_is_owner(self, obj): user = self.context["request"].user return obj.agent == user models.py class Facility(models.Model): UUID = models.CharField(max_length=150, null=True, blank=True) Name = models.CharField(max_length=150, null=True, blank=False) mainimage = models.ImageField(null=True, blank=True) FacilityDescription = models.TextField(max_length=1000, null=True, blank=True) def __str__(self): return self.Name class Lead(models.Model): assigned_facilities = models.ManyToManyField(Facility, related_name='assigned_facilities') created_at = models.DateTimeField(auto_now_add=True) first_name = models.CharField(max_length=40, null=True, blank=True) last_name = models.CharField(max_length=40, null=True, blank=True) def __str__(self): return f"{self.first_name} {self.last_name}" -
How to run Django rest api and react build together
I'm running django rest api and react in 2 different ports (using nginx and gunicorn), I want to only run the django server that will take charge of showing react build (react pages), so both react and django will run in the same port. -
issue with connecting to PostrgreSQL on localhost in Django application [duplicate]
I am using Docker to run my Django app and I have multiple images in it: PostgreSQL, celery_worker, celery_beat, and django_app. All of them except celery_beat is working fine. I am using this command to build docker: docker-compose -f docker-compose.yml up -d --build When I open Docker Desktop I see that it restarts all images, everything is working fine for few seconds, then it exits celery-beat and returns in celery-beat image with the following error: [2022-10-13 15:34:59,440: WARNING/MainProcess] could not connect to server: Connection refused Is the server running on host "127.0.0.1" and accepting TCP/IP connections on port 5432? I tried many solutions that I found on StackOverflow and other pages but with no success. 4 out of 5 images are working fine. When clicking on postgreSQL image I see the following status: 2022-10-13 13:27:04.195 UTC [1] LOG: database system is ready to accept connections docker-compose.yml version: '3.8' services: db: image: postgres:14.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ environment: - POSTGRES_USER=postgres - POSTGRES_PASSWORD=PF23_admin - POSTGRES_DB=postgres container_name: docerized_app_db_postgresql_dev app: build: context: ./backend dockerfile: Dockerfile restart: always command: python manage.py runserver 0.0.0.0:8000 volumes: - ./backend/:/usr/src/backend/ ports: - 8000:8000 env_file: - ./.env depends_on: - db container_name: docerized_app_django_app_dev redis: image: redis:7-alpine ports: - "6379:6379" container_name: docerized_app_redis_dev celery_worker: … -
Code works without errors in vs code, but not from command promt
I am learning django and to run a server i should do python manage.py runserver. I have installed django, but when i try to run a command through a command prompt i always get an error Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "D:\projects\django-proj\password_generator\manage.py", line 22, in <module> main() File "D:\projects\django-proj\password_generator\manage.py", line 13, in main raise ImportError( ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? if i call django-admin in command prompt, it works well. it also works if i just run a code in vs code. what can be the problem? -
Using HTMX/Javascript in Django Template : not defined
I decided to try HTMX with Django and implementing a Django form in a modal box. I found this tutorial and was following it. I got to the part where it uses an HTMX function htmx:afterSwap to open the modal but when I put that in a script tag in the template, I run into an error. It is Step 4 where the error occurs. My template looks (mostly) like this. I've tried to trim it down to the essentials. {% for thing in things %} {% if forloop.first %} <ul id="myThingList" class="things"> {% endif %} <button id="thing{{ thing.id }}Button" type="button" class="btn btn-primary" hx-get="{% url 'myapp:things-create' %}" hx-target="#thingSection"> Upload Thing</button> <li id="thingItem" class="thing" hx-target="this" hx-swap="outerHTML"> {{ thing.name }} </li> <div id="thingModal" class="modal fade" role="dialog" tabindex="-1" aria-labelledby="thingModal" aria-hidden="true"> <div id="thingSection" class="modal-dialog modal-dialog-centered" hx-target="this" role="document"></div> </div> {% if forloop.last %} </ul> {% endif %} {% empty %} <p class="no-things">No things have been added yet.</p> {% endfor %} <script> const modal = new bootstrap.Modal(document.getElementById("thingModal")) htmx.on("htmx:afterSwap", (e) => { // Response targeting #thingSection => show the modal if (e.detail.target.id == "thingSection") { modal.show() } }) </script> I am getting Uncaught ReferenceError: bootstrap is not defined Additional information: HTMX works (I use it in other … -
(urls.E004). Your URL Pattern is invalid in project level urls.py file
I am newbie to Django. I am getting the below error in-spite of rightly mapping the app level urls.py file to project level urls.py. Please help. urlpatterns = [ path('admin/', admin.site.urls), path('app_space/', include ('app_space.urls')) ] Response in terminal: SystemCheckError: System check identified some issues: ERRORS: ?: (urls.E004) Your URL pattern <contextlib._GeneratorContextManager object at 0x000001C33030C7C8> is invalid. Ensure that urlpatterns is a list of path() and/or re_path() instances. -
has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request
I'm trying to do get-request from react to django-server let projects = await axios.get('http://127.0.0.1:8000/api/project', {headers}).catch(error => console.log(error)) And i get 'Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/project' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.'