Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cant find static(css) folder
My Django template cant seem to find my css file in my static folder which is structured at the root dir. Here is my settings.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-j@g&qm&20_oct_3f*sn-7n117si&1x4+m9cjao%g_&88gtmk9&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'maintenance', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'nitrofleet.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [BASE_DIR/'templates'], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'nitrofleet.wsgi.application' # Database # https://docs.djangoproject.com/en/3.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # … -
django-treebeard Materialized Path tree depth ended up being zero
I found a problematic node with id 633. tree.find_problems() ([], [], [], [633], [35, 9, 50, 291, 464]) After running tree.fix_tree() It does not find any problems. tree.find_problems() ([], [], [], [], []) But actually 633 is still in some wierd state. >>> node633.depth 0 >>> node633.path '' Problem: node633.depth is 0 which means its not root but it does not have parent as well. Path is empty too. This means my code will try to find parent from a node that does not have a parent. Running fix_tree again does not fix it. Moving node633 is not an option too because: treebeard.exceptions.InvalidMoveToDescendant: Can't move node to a descendant. Question: How can i fix this broken node66? -
Mat-icon display based on condition in for loop
I have an angular-django app which makes an aPI call to a third-party application and returns json response. I am looping through the response and displaying the data in a table. <tr *ngFor="let item of job_list"> <td style="text-align:center">{{item?.ReleaseName}}</td> <td style="text-align:center">{{item?.Source}}</td> <td style="text-align:center"><mat-icon *ngIf="Successful" style="color:green;">check circle icon</mat-icon> <mat-icon *ngIf="Faulted" style="color: red;">error icon</mat-icon> <mat-icon *ngIf="Stopped" style="color: grey;">cancel icon</mat-icon> {{item?.State}} </td> <td style="text-align:center">{{item?.StartTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> <td style="text-align:center">{{item?.EndTime | date:'dd-MM-yyyy HH:mm:ss'}}</td> </tr> Here, I want to display mat-icon based on {{item?.State}} value. For example if the value is Successful, I want to display the "check circle icon", if it's "Faulted", I want to display "error icon" etc. Is this possible? Thank you -
How to show that the lesson is done from related model?
I have list of lessons and i need to highlight the done ones by current person. I tried my version below, but it's showing only done lessons. I have 2 models: lessons and donelessons related with user and lessons with foreignkey. models class Lessons(models.Model): theory = models.TextField(blank=True) words = models.TextField(blank=True) question1 = models.CharField(max_length=255) answer1 = models.CharField(max_length=255) class DoneLessonsModel(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) lessons = models.ForeignKey(Lessons, on_delete=models.CASCADE, null=True, related_name="releases") done = models.BooleanField(default=False) views class News(ListView): model = Lessons template_name = 'static/news.html' context_object_name = 'posts' def get_queryset(self): return Lessons.objects.all().prefetch_related( Prefetch('releases', queryset=DoneLessonsModel.objects.filter(user=self.request.user))).all() html ... {% for p in posts %} {% for release in p.releases.all %} <div class="col-md-3 mt-3"> <div class="card mb-4 box-shadow {% if release.done == True %} bg-success text-white btn-outline-light {% else %} border-dark {% endif %} "> <div class="card-body"> <p class="card-text">Lesson №{{ p.pk }}</p> <div class="d-flex justify-content-between align-items-center"> <div class="btn-group"> <a href="{% url 'theory' p.pk %}" > <button type="button" class="btn btn-sm {% if release.done == True %} btn-outline-light {% else %} btn-outline-dark {% endif %} ">Start</button> </a> </div> </div> </div> </div> </div> {% endfor %} {% endfor %} ... -
Cannot resolve file 'signup'
I am newbie to Django and i need help to solve this problem. It states that cannot resolve file'signup'. <h3>Create your account!</h3> <form method="post" action="/signup"> {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" class="form-control" id="username" name="username" placeholder="Create A Username (use only letters and numbers)" Required> </div> -
Django: How to log user in right after they had registered with somewhat default UserCreationForm?
I'm trying to log the user in right after they had registered with the app, so that they don't have to manually log in right after. I have created RegisterForm from django's UserCreationForm and it works as it should - it creates an User object if the form is valid, but I don't know how to access that created User object to log it it using the login function, which requires, aside from request, also an user object. Note: I have edited the default User in models.py. This is my code: class RegisterForm(UserCreationForm): def __init__(self, *args, **kwargs): super().__init__(*args,**kwargs) self.fields['username'].widget.attrs.update({'class':'form-control','id':'username', 'aria-describedby':'usernameHelp'}) self.fields['password1'].widget.attrs.update({'class':'form-control','id':'password1', 'aria-describedby':'password1Help'}) self.fields['password2'].widget.attrs.update({'class':'form-control','id':'password2','aria-describedby':'password2Help'}) class Meta: model = User fields = ['username', 'password1', 'password2', 'email', 'first_name', 'last_name', 'photo', 'amazon', 'twitter', 'facebook', 'instagram', 'youtube'] widgets = { 'email':EmailInput(attrs={'class':'form-control', 'id':'email', 'aria-describedby':'emailHelp'}), 'first_name':TextInput(attrs={'class':'form-control', 'id':'first_name',}), 'last_name':TextInput(attrs={'class':'form-control','id':'last_name', 'aria-describedby':'nameHelp'}), 'photo':ClearableFileInput(attrs={'class':'form-control','id':'photo', 'aria-describedby':'photoHelp'}), 'amazon':URLInput(attrs={'class':'form-control', 'id':'amazon', 'aria-describedby':'amazonHelp'}), 'twitter':URLInput(attrs={'class':'form-control', 'id':'twitter', 'aria-describedby':'twitterHelp'}), 'facebook':URLInput(attrs={'class':'form-control', 'id':'facebook', 'aria-describedby':'facebookHelp'}), 'instagram':URLInput(attrs={'class':'form-control', 'id':'instagram', 'aria-describedby':'instagramHelp'}), 'youtube':URLInput(attrs={'class':'form-control', 'id':'youtube', 'aria-describedby':'youtubeHelp'}) } And here is the view: def register(request): # POST if request.method == "POST": # In addition to our form we must make sure to get the files too, if photo is uploaded form = RegisterForm(request.POST, request.FILES or None) if form.is_valid(): form.save() #user = User.objects.get() ??? #login(request, user) return HttpResponseRedirect(reverse('index')) else: … -
Can't mock a third party api call
I have a view that perform a third party API call: from .atoca_api_calls import atoca_api_call def atoca_api_call_view(request): # some code data = atoca_api_call(**params) # the actual API call happens in this func # some code My intention is to mock just the atoca_api_call() func and not the whole view. class AtocaTestCase(TestCase): def setUp(self): # some code @patch('crm.atoca_api_calls.atoca_api_call') def test_atoca_call(self, mock_atoca_api_call): mock_atoca_api_call.return_value = MagicMock( status_code=200, response=some_json # just returns some json ) url = reverse('crm:atoca-api-call') # url related to `atoca_api_call_view` response = self.client.post(url, some_others_params) # various asserts The test works fine but atoca_api_call() is not mocked. I'm aware of where to patch: @patch('crm.views.atoca_api_call', autospec=True) Raises a ValueError: ValueError: Failed to insert expression "<MagicMock name='mock.__getitem__().__getitem__().__getitem__()().resolve_expression()' id='140048216397424'>" on crm.Company.atoca_id. F() expressions can only be used to update, not to insert. It's probably a simple issue I don't catch for inexperience, any help is really appreciated. -
Use npm library for django on runserver environment
I made static folder in my root project. in settins.py STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), ) Install npm library under static directory. myproject/static$ npm -i js-cookie then There comes the files like this myproject/static/node_modules/js.cookie/dist/js.cookie.min.js then run server myproject$ python manage.py runserver then use in template.html However this shows the error GET http://localhost:8000/static/node_modules/js.cookie/dist/js.cookie.min.js net::ERR_ABORTED 404 (Not Found) I have two quesitons. Is it good practice to use npm library under django project?? Maybe runserver doesn't use mypoject/static? -
Django ORM for loop to get queryset
I am trying to use for loop to get list of author with the number of books writing and author with the title of book wrote. Here is my models.py class Author(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) def __str__(self): return self.title I have tried to loop through like this: for a in Author.all(): books = a.book_set.order_by('author') print(books) I get the authors as they are in DB. Also, for book in book_set.iterator(): ... print(book.title) I got the list of all books. I use author_list = Author.objects.order_by("book").count() which gave the number of author. How can I loop through the DB and get the Author with number of books, and Authors with book title wrote. -
Image and CSS pre loading in Django
I am developping a website with Django, hosted on Heroku, and still fairly new to it. I published my application, and notice a problem when navigating on the hosted website : Whenever you load a new page, it looks like images and css are reloading completely. For a short time (less than 1 second), It creates some king of glith on my menu bar because buttons are moving (because the image is missing) and changing color (because css is missing). What would be a proper way to handle this ? Is it possible to store those image and css in somme kind of cookie on the user browser ? Also, when i run the website on my localhost, i don't experiment the problem. Thanks for your help !! -
Django Drf: generate an 8 digit unique number in the user serializer
I have a field in my users model that will only be utilized for a Certain type of user student_id = models.CharField(_("student id"), validators=[ MinValueValidator(10_000_000_000), MaxValueValidator(99_999_999_999) ],unique=True, max_length=8, blank=True, null=True) when creating a user in the serializers.py file i tried the below code but didn't work def create(self, validated_data): def create_new_ref_number(): not_unique = True while not_unique: unique_id = randint(10000000, 99999999) if not User.objects.filter(student_id=unique_id): not_unique = False instance = User.objects.create( student_id=create_new_ref_number, firstname=validated_data['firstname'], middlename=validated_data['middlename'], lastname=validated_data['lastname'], age=validated_data['age'], phone=validated_data['phone'], ) after saving the user the student_id field is populated with the following string <function RegisterSerializerStudent.create.<locals>.create_new_ref_number at 0x000001E4C463A950> -
Django gives Secret key must not be empty error
I am having this issue when I try to run the server in Pycharm. I am new to Django and downloaded this project as a backend for my react application. I have generated a Secret Key using: from django.core.management.utils import get_random_secret_key print(get_random_secret_key()) exit() I added this Secret key to settings.py file as well. Error Log which I get: Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner self.run() File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run self._target(*self._args, **self._kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\core\management\__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\apps\registry.py", line 122, in populate app_config.ready() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\apps.py", line 27, in ready self.module.autodiscover() File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\contrib\admin\__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "W:\Playlistify-main\Playlistify-main\server\venv\lib\site-packages\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\zabim\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
How to block rows on read and write operations?
I have a model that counts how many operations were done by a user. (It's simplified for an example) User = get_user_model() class UserOperationCounter(models.Model): count = models.IntegerField(default=0) user = models.OneToOne(User) I have a context manager that is fetching a counter object for a user and increments the counter param after the exit @atomic() class IncrementCounterContextManager: def __init__(user_id): self.operation_counter = UserOperationCounter.objects.filter(user_id=user_id).select_for_update().get() def __enter__(): print(f"Fetch counter={operation_counter.counter} for user={operation_counter.user.id}") return self.operation_counter def __exit__(): self.operation_counter.count = F("count") + 1 self.operation_counter.save(update_fields=["count"]) self.operation_counter.refresh_from_db() print(f"Set counter={operation_counter.counter} for user={operation_counter.user.id}") Let's assume I want to use the context manager each time the user does some specific action on a platform and then I want to send him a notification with the message: "You have done <counter> hidden actions on our platform". select_for_update() works perfectly in scenarios when I want to update a Counter object at the same time, but the row is not locked for reading. Here is an example: def send_notification(counter, user_id): print(f"Send notification with counter={counter} to user={user_id}") user_id = 1 with atomic(): with IncrementCounterContextManager(user_id=1) as usr_counter1: send_notification(usr_counter1.counter, usr_counter1.user.id) with IncrementCounterContextManager(user_id=1) as usr_counter2: send_notification(usr_counter2.counter, usr_counter2.user.id) When I check logs I will see something like: Fetch counter=0 for user=1 Fetch counter=0 for user=1 Send notification with counter=0 to user=1 … -
Pivot table in django admin
good day There is a user and a task model, combined with a ForeignKey The task model has a type field - the type of the task, in which several variants of types are written, let it be 1, 2, 3 And actually further the question, I need to create a table with the number of tasks, that is, how many tasks of type 1, type 2 and type 3, filters are also needed by the start and end time of the task, and then export to Excel Here's how best to solve this problem, create a new model, or is it better to do something differently? With the creation of the model, there are questions about the constant updating of the database, it seems to me that this is not very good, now it is done so that there is a model field of the model Type 1, Type 2, Type 3 and then with the help of filters, tasks are obtained through the user and filtered, and then count () is calculated, but it can be done more correctly, so to speak, without unnecessary database operations. I use django, django-jet for the admin area -
Saving dictionary data to django model problem, error message = AttributeError("'dict' object has no attribute '_meta'")
I have a problem, saving a dictionary data to django model. Did I need to input sqlite3 query somewhere? Please teach me how can I solution this problem. received dictionary data {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Error message {"id":20,"title":"random data","temp":43.70915909663141,"humidity":10.40750545208753,"created_date":"2021-12-15T16:25:12.946427","author":1} Unexpected e=AttributeError("'dict' object has no attribute '_meta'"), type(e)=<class 'AttributeError'> modles.py class Data(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, on_delete=models.CASCADE) title = models.CharField(max_length=200) temp = models.FloatField(default=0.0) humidity = models.FloatField(default=0.0) created_date = models.DateTimeField(default=timezone.now) def __str__(self): return self.title class DataSerializer(serializers.ModelSerializer): id = serializers.IntegerField(write_only=False) class Meta: model = Data fields = '__all__' snd_clienet.py data = Data( id = 20, author = User.objects.get(username='labovming'), title = 'random data', temp = random.random()*300, humidity = random.random()*12, created_date = timezone.now() ) serializer = DataSerializer(data) msg = JSONRenderer().render(serializer.data) rcv_server.py while msg: stream = io.BytesIO(msg) data = JSONParser().parse(stream) serializer = DataSerializer(data=data) # create new instance serializer = DataSerializer(data, data=data) # update 'data' # serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True) # Update `comment` with partial data serializer.is_valid() **<<< Validation fail ** serializer.errors serializer.validated_data **<<< Empty ** try: serializer.save() **<<< Error occur here ** print(f'data added : {serializer}') if self.DBman.messageHandler(Name, msg.decode()) == -1: self.request.close() break msg = self.request.recv(1024) except Exception as e: print(f"Unexpected {e=}, {type(e)=}") break -
metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I am trying to implement multiple inheritance with Partitioned model and Aggregate Model class AdAgencyLocationPurposeAggregate(PostgresAggregateModel,PostgresPartitionedModel): PostgresAggregateModel: class PostgresAggregateModel(PostgresModel,metaclass=PostgresAggregateModelMeta ): PostgresPartitionedModel class PostgresPartitionedModel( PostgresModel,metaclass=PostgresPartitionedModelMeta ): -
Celery Scheduler not starting
I'm trying to setup scheduler but I got the following error "Unrecoverable error" from __future__ import absolute_import import os from celery import Celery from django.conf import settings os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings.prod') app = Celery('core') app.config_from_object("django.conf:settings") app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print("Request: {0!r}".format(self.request)) # CELERY STUFF BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Chicago' I was guided by https://realpython.com/asynchronous-tasks-with-django-and-celery/ Here are two photos of my errors -
Django static files deployed from AWS S3
My sidebar navbar doesn't get the right styles user/main.css ul.no-bullets { list-style-type: none; margin: 0; padding: 0; } home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} <div class="container"> <div class='row'> <div class="col-xs-12 col-md-3"> {% block sidebar %} {% include 'sidebar.html' %} {% endblock %} </div> <div class="col-xs-12 col-md-9"> Some page </div> </div> </div> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} sidebar.html {% block content %} <nav id="sidebar"> Hi {{ user.username }}! <img class="profile-pic" src="{{request.user.profile_pic.url}}" > <ul> <li><a href="/">Dashboard</a></li> <li><a href="/">Messages</a></li> <li><a href="/">Documents</a></li> <li><a href="{% url 'logout' %}">Log Out</a></li> </ul> </nav> {% endblock %} base.html <!DOCTYPE html> {% load static %} <html> <head lang="en"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!--Css Style --> <link rel="stylesheet" href="{% static 'user/main.css' %}" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> <!--Font Link--> <title>{% block title %}Base{% endblock %}</title> </head> <body> <main> {% block content %} {% endblock %} </main> </body> </html> -
How to serialize class into json (class is not in model)
I have simple class class City: def __init__(self, key): self.key = key def distance(self): distance = Distance.objects.get(id=self.key).distance return distance def __repr__(self): return "(" + self.key + ")" And in my view class as API def get_route(request): res = {} res['cities'] = [City(1),City(2),City(3)] return Response(res) it returns the list of class City However this shows the error Object of type City is not JSON serializable __repr__ could be used for representing class. However, it's not work for json. How can I solve it ?? -
Django Custom Admin Users
So I want 3 types of users: Admins, Doctors, and Patients They should possess the following attributes and only admins shall access the /admin routing so they should possess is_staff, is_superuser to determine if it's a patient or doctor. name, pw, email, phone, profile_pic, and date_created are other attributes they should possess. So I need to add parameters to the existing auth in admin.py from django.contrib.auth.models import User class Patient(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=200, null=True) phone = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, null=True) profile_pic = models.ImageField(default="", null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.name -
username with `james i. adams` not accepted with django routers
I have registered routers for user model, which has viewset that has lookup_url as username. The username james adams is accepted by the router, but getting below error for james i. adams django.urls.exceptions.NoReverseMatch: Reverse for 'user-detail' with keyword arguments '{'username': 'james i. adam', 'version': 'v1'}' not found. 4 pattern(s) tried: ['(?P<version>(v4))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v4))/users/(?P<username>[^/.]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?\\.(?P<format>[a-z0-9]+)/?$', '(?P<version>(v1))/users/(?P<username>[^/.]+)/?$'] Can someone guide me, how can I allow such username for url patterns with routers registered? Thanks in Advance -
How to Filter foreign key related models using datetime range
I'm trying to create a reservation system and I want to query all available tables. So, what I did is as follows, ... date_time = request.data.get('date_time') date_time = datetime.strptime(date_time, '%b %d %Y %I:%M%p') num_of_attendees = request.data.get('num_of_attendees') tables = Table.objects.filter(~Q( tablereservation__date_time__range=[date_time, date_time + timedelta(hours=2)]), num_of_chairs__gte=num_of_attendees ) ... But it returns all the table objects. My models, class Table(models.Model): """ Holds table details """ num_of_chairs = models.PositiveSmallIntegerField(default=1) def __str__(self): return str(self.id) class TableReservation(models.Model): """ Holds table reservation details """ date_time = models.DateTimeField() table = models.ForeignKey(Table, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return '{}-{}'.format(self.table, self.user) But I want is to get only the table objects that aren't reserved in the given date-time range. Any help is greatly appreciated. -
Django-Import-Export assign Field to specific column
I have a working form which exports all data to xls using Resource and Fields from the django-import-export package. But now I need to go a bit further and make it a bit more advanced. I need to export all data to an existing Excel template, assigning each field to a specific column, as in, for instance: Field 1 needs to be filled in B3, Field 2 in C4 etc. etc. I'm thinking after_export() can be used here but the docs dont go into detail how to use this method. Does anyone have some experience with this package? I'm not using the admin integration. -
ListCreateAPIView is not letting post data
I'm trying to create an API where I will upload image throw API end point, My Model has only one imageField. Please checkout the code below Model: class Image(models.Model): image = models.ImageField(upload_to="media", default="default.png", blank=True, null=True) def __str__(self): id = self.id return f'image-{id}' Serializer: class ImageSerializer(serializers.ModelSerializer): class Meta: model = Image fields = ['image'] Views: from rest_framework.generics import CreateAPIView, ListCreateAPIView from home.models import Image from .serializers import ImageSerializer class ImageListCreateView(ListCreateAPIView): queryset = Image.objects.all() serializer_class = ImageSerializer Urls: from django.urls import path from .views import ImageListCreateView urlpatterns = [ path('image/', ImageListCreateView.as_view(), name='image'), ] But if I visit the url '127.0.0.1:8000/api/image/' It only shows the data. not letting me post new data. -
How to integrate django to Elastic App Search
I have doing a project of e-commerce and I need to integrate Django and Elastic App Search. How to integrate