Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Failing to lookup a field with a foreign key subfield in Django Rest Framework
I am using the django framework to serialize a django object. I have a profile model and the first field in the model is a foreignkey of the user object. I want to be able to pass a usename is the url patters for the profile. In the Views, I want to be able to take that username and go through the user foreignkey and find the profile with that username user. THis is what I have right now in my code: Views.py class ProfileListView(ListAPIView): query_set = Profile.objects.all() serializer_class = ProfileSerializer class ProfileDetailView(RetrieveAPIView): query_set = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'user__username' urls.py path('profile/', ProfileListView.as_view()), path('profile/<username>', ProfileDetailView.as_view()), serializers.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('user', 'gender', 'phone', 'ip_address', 'dob_month', 'dob_day', 'dob_year', 'address_street', 'address_city', 'address_state', 'address_postal', 'address_country', 'profile_pic', 'role') models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) gender = models.CharField(max_length=12, choices=GENDER_CHOICES) # entity type phone = models.CharField(max_length=22) ip_address = models.CharField(max_length=32) dob_month = models.CharField(max_length=22, choices=MONTH_CHOICES) dob_day = models.SmallIntegerField() dob_year = models.SmallIntegerField() address_street = models.CharField(max_length=140) address_city = models.CharField(max_length=22) address_state = USStateField() address_postal = models.IntegerField() address_country = models.CharField(max_length=22) profile_pic = models.ImageField(upload_to='profile_pics/') role = models.CharField(max_length=12, choices=ROLE_CHOICES) created_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.user.username + ' - ' + self.type -
wagtail pathoverflow on adding new child page
I have developed a wagtail site and that works just fine. It's just a simple blog. I was able to add a blog index page and blog posts under them. Hover recently when try to add a new page it gives the error PathOverflow at /admin/pages/add/blog/blogpage/8/ Bellow is the complete traceback. Environment: Request Method: POST Request URL: https://vikatakavi.info/admin/pages/add/blog/blogpage/8/ Django Version: 2.1.5 Python Version: 3.5.2 Installed Applications: ['home', 'search', 'wagtail.contrib.forms', 'wagtail.contrib.redirects', 'wagtail.embeds', 'wagtail.sites', 'wagtail.users', 'wagtail.snippets', 'wagtail.documents', 'wagtail.images', 'wagtail.search', 'wagtail.admin', 'wagtail.core', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sitemaps', 'blog'] Installed Middleware: ['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', 'django.middleware.security.SecurityMiddleware', 'wagtail.core.middleware.SiteMiddleware', 'wagtail.contrib.redirects.middleware.RedirectMiddleware'] Traceback: File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/django/views/decorators/cache.py" in _wrapped_view_func 44. response = view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/urls/__init__.py" in wrapper 102. return view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/decorators.py" in decorated_view 34. return view_func(request, *args, **kwargs) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/wagtail/admin/views/pages.py" in create 224. parent_page.add_child(instance=page) File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in add_child 1013. return MP_AddChildHandler(self, **kwargs).process() File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in process 387. newobj.path = self.node.get_last_child()._inc_path() File "/home/ubuntu/projects/blogger/env/lib/python3.5/site-packages/treebeard/mp_tree.py" in _inc_path 1114. raise PathOverflow(_("Path Overflow from: '%s'" % (self.path, ))) Exception Type: PathOverflow at /admin/pages/add/blog/blogpage/8/ Exception Value: Path Overflow … -
django library inline editing of records example from mozilla
MDN has this django tutorial of a library database webpage. I am attempting this section example and it worked. The goal here is when you see each author you can also see a list of their books in your library. This is their github page. I was able to make the author page list their respective books. Now I want to challenge myself a bit further by making the author page list all the book instances as well. So before, if I go to an author like JK Rowling, I would be able to see Harry Potter 1, 2, and 3 (these are the three that I have added to my database). Now, I want to make it so that not only will I see these 3 books, I will also see each instance of the 3 books. So if I have two copies of Harry Potter 1, I will see these 2 entries instead. Here is what I have done to attempt it. I have added the class BooksInstanceInLine similar to how I did the class BooksInline, and I need a key between books instance to author as well. In class AuthorAdmin in admin.py I have added the following: … -
How to migrate default user data to custom user model in Django
As I want to customize Django user model, I migrated from default user model to my own custom user model. Since my Django project has been working since a long time ago, I need to keep the existing user data. I was thinking to move them manually, but Django default user model's passwords are hidden. How can I safely move existing user data to my custom user model? -
Case insensitive username in Django signup form
Here is my signup form, class SignupForm(forms.ModelForm): class Meta: model = User fields = ['first_name', 'last_name','username', 'email', 'password'] def clean_username(self): username = self.cleaned_data.get('username') email = self.cleaned_data.get('email') if username and User.objects.filter(username=username).exclude(email=email).count(): raise forms.ValidationError('This username has already been taken!') return username This works well to check if there is same username presents or not. However it does not check for case insensitivity. If there is a username e.g. 'userone', then it also accepts a username with 'Userone'. Although it does not break any functionality, but looks very unprofessional. My question is how can I check for case insensitive right in the forms, and raise error? -
Django form is not workin properly
i am trying to save data by form into 'ModuleNames' table but it is updating 'ModuleType' column of foreign(instance) table. I created an instance of foreign table because it was giving different error about assigning value to foreign key column and i learned instance is needed from blogs but it seems, it is not correct way. Could you please help me what is wrong with my code? models.py class ModuleTypes(models.Model): ModuleType = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) Sort = models.SmallIntegerField() isActive = models.BooleanField() slug = models.SlugField(('Type'), max_length=50, blank=True) class Meta: app_label = 'zz' def save(self, *args, **kwargs): if not self.id: self.slug = slugify(self.Type) super(ModuleTypes, self).save(*args, **kwargs) class ModuleNames(models.Model): ModuleName = models.CharField(max_length = 50) ModuleDesc = models.CharField(max_length = 256) ModuleSort = models.SmallIntegerField() isActive = models.BooleanField() ModuleType = models.ForeignKey(ModuleTypes, on_delete=models.CASCADE, null = True) slug = models.SlugField(('ModuleName'), max_length=50, blank=True) class Meta: app_label = 'zz' def __unicode__(self): return self.status forms.py class ModuleForm(forms.ModelForm): moduleName = forms.CharField(label='Module Name', max_length=50) ModuleDesc = forms.CharField(max_length = 256) ModuleSort = forms.IntegerField() isActive = forms.BooleanField() ModuleType = forms.IntegerField() class Meta: model = ModuleNames fields = ('moduleName','ModuleDesc','ModuleSort','isActive','ModuleType') views.py def addmodule(request,moduletype): template_name = 'module.html' modules = ModuleNames.objects.all() listmodules = ModuleTypes.objects.get(ModuleType=moduletype) modules = ModuleNames.objects.filter(ModuleType_id=listmodules) if request.method == 'GET': args = {'modules': … -
No such table upon initial Django migration
Back story: I'm creating a quiz app. I started by wanting to use Django (v=2.1.4) with Mongo via the djongo package. Everything worked until it didn't so I decided to just drop djongo and mongo entirely and go back to sqlite. I only mention it in case it is related, but I don't think it is. I made a copy of the project then deleted the original. I then created a new project with the same name and all the same apps. This created a bunch of new folders with blank files. I moved the copies of the original over to these folders (except the migration files) and replaced the blank files with the same name. I changed the mysite/settings.py file back to default to read: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'hoquidb'), } } To my knowledge this creates a fresh project ready for it's initial migration and it will use sqlite3. The problem: So I tried to do the initial migration and got a cryptic error message: (base) C:[redacted]\testabode\Hoqui\hoqui>python manage.py migrate Traceback (most recent call last): File "C:[redacted]\lib\site-packages\django\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:[redacted]\lib\site-packages\django\db\backends\sqlite3\base.py", line 296, in execute return Database.Cursor.execute(self, query, params) … -
UpdateView not populating form with existing data
So I have my UpdateView set up to send a request object to the form so I can modify a queryset in the form (based on request.user) my views.py: class DataSourceUpdateView(UpdateView): model = DataSource form_class = DataSourceForm template_name = 'engine/datasource_update.html' def get(self, request, *args, **kwargs): obj = DataSource.objects.get(pk=kwargs['pk']) self.object = None form = DataSourceForm(request) return self.render_to_response( self.get_context_data(form=form, object=obj)) def post(self, request, *args, **kwargs): form = DataSourceForm(request, request.POST, request.FILES) if form.is_valid: return self.form_valid(form) else: return self.form_invalid(form) my forms.py: class DataSourceForm(forms.ModelForm): def __init__(self, request, *args, **kwargs): self.request = request super(DataSourceForm, self).__init__(*args, **kwargs) self.fields['dataset_request'].queryset = DatasetRequest.objects.filter( creator=self.request.user) class Meta: model = DataSource exclude = ('creator', 'vote_score', 'num_vote_up', 'num_vote_down', 'file_size', 'slug') My problem is, in the template, the form is not populated with existing values. How can I fix this? -
How to start django project downloaded from bitbucket??? Error installing requirements.txt
I am new to the Wagtail cms and am taking over a friend's project.I have downloaded his repo and am trying to get it to run locally. In the site's requirements.txt file, there are some dependencies that just are not installing and giving errors: I tried it with python 2 and 3. I tried deleting modules versions. I have an answer: django-oauth-toolkit 1.2.0 has requirement django>=2.0, but you'll have django 1.11.18 which is incompatible. Can someone please give me instructions what are the steps for starting django project with wagtail when downloaded from repo. -
Save resulting JSON into SQLite - Django
I have this code: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @require_http_methods(['GET', 'POST']) def index(request): rates = getExchangeRates() return render(request, 'index.html') The resulting json from data.fixer.io has a format, like, currency | rate_of_the_currency. Something like this: "rates": {"SAR": 4.394498, "INR": 49.836962, and so on..., so, I have created this model on Django: class Fixerio_rates(models.Model): currency = models.CharField(max_length=128) rate = models.FloatField() Now, how can I save the result from my code into this model? migrations have been made already, it shouldn't be something complex to do, but since this is a migration from Flask into Django it confuses me a bit. It's kind of a different approach, Django has it's own way to deal with these things. Any ideas? -
How to structure a django model for user input when not all fields are required in all cases
I'm expanding an existing django application with new functionality. The problem is essentially as follows. Sorry if the equivalent of this question has already been asked, I'm not sure what to search for to find the solution. I have a 'store' model that contains a ManyToMany relationship to a 'departments' model, not all stores have all the same departments. I need to track daily department volumes for each store, and I need a user form to enter all this information. I don't know if I should create one model with all possible departments, or if I should create one model with one department and weight, and then create as many objects as departments for each day. Scale ability in this application will be very important going forward, and I'd like to start right. Code Below. Store departments class Department(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, unique = True) short_name = models.CharField(max_length=32) description = models.CharField(max_length=255) def __str__(self): return self.name; Volume Data Options (Model In Question) Option 1, one model with everything: class VolumeData(models.Model): id = models.AutoField(primary_key=True) store = models.ForeignKey(stores.models.Store, on_delete=models.DO_NOTHING) date = models.DateField(auto_now_add=True,null=False,blank=False) produce = models.DecimalField(decimal_places=2,Null=True) dairy = models.DecimalField(decimal_places=2,Null=True) deli = models.DecimalField(decimal_places=2,Null=True) meat = models.DecimalField(decimal_places=2,Null=True) seafood = models.DecimalField(decimal_places=2,Null=True) coffee = models.DecimalField(decimal_places=2,Null=True) … -
Django DRF change serializer data with CreateListModelMixin
I have this class view, but I am unable to modify the serializer data to insert more data (which is needed and needs to be populated automatically). Because I am creating many instances at once, the serializer is based on kwargs['many'] = True. Any idea on how I can add another field to each serializer data? Thanks, : class ReservedServiceView(CreateListModelMixin, ModelViewSet): queryset = ReservedService.objects.all() serializer_class = ReservedServiceSerializer authentication_classes = (authentication.TokenAuthentication,) def perform_create(self, serializer): # Create an event that is a Reflection of the Reserved Service serializer_data = self.request.data for reserved_service in serializer_data: print("--------",reserved_service, flush=True) service_id = reserved_service['original_service'] original_service = Service.objects.get(pk=service_id) calendar_event = CalendarEvent() calendar_event.name = original_service.name calendar_event.description = original_service.description calendar_event.date = reserved_service['date'] calendar_event.type_id = 1 calendar_event.start_time = reserved_service['start_time'] calendar_event.end_time = reserved_service['end_time'] calendar_event.location_id = original_service.location.id calendar_event.save() reserved_service['associated_event'] = calendar_event.id print("**********1", serializer_data) print("**********2", self.request.data) serializer.save() Based in: class CreateListModelMixin(object): def get_serializer(self, *args, **kwargs): """ if an array is passed, set serializer to many """ if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True return super(CreateListModelMixin, self).get_serializer(*args, **kwargs) -
Change POST method from Flask to Django
I have this code from a Flask application: def getExchangeRates(): """ Here we have the function that will retrieve the latest rates from fixer.io """ rates = [] response = urlopen('http://data.fixer.io/api/latest?access_key=c2f5070ad78b0748111281f6475c0bdd') data = response.read() rdata = json.loads(data.decode(), parse_float=float) rates_from_rdata = rdata.get('rates', {}) for rate_symbol in ['USD', 'GBP', 'HKD', 'AUD', 'JPY', 'SEK', 'NOK']: try: rates.append(rates_from_rdata[rate_symbol]) except KeyError: logging.warning('rate for {} not found in rdata'.format(rate_symbol)) pass return rates @app.route("/" , methods=['GET', 'POST']) def index(): rates = getExchangeRates() return render_template('index.html',**locals()) For example, the @app.route decorator is substituted by the urls.py file, in which you specify the routes, but now, how can I adapt the methods=['GET', 'POST'] line to a Django way? I'm a little bit confused on that, any ideas? -
Django - Form not updating in Django admin
I’m creating a profile page in my web application & I have a form to when the user makes a form submission I need the data from the form to update in django admin from the current logged in user. My Problem: The data populates in the django admin after a form submisstion however I need the data updating only and not to keep repeating listings per form submission. How do I execute this correctly with my current code? The Custom User Model I’m using is located in from users.models import CustomUser if that helps. Any help i gladly appreciated, Cheers Screenshot user_profile/admin.py from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.auth.admin import UserAdmin from user_profile.forms import HomeForm from users.forms import CustomUserCreationForm, CustomUserChangeForm from user_profile.models import Listing from users.models import CustomUser # Register models here. class UserProfileAdmin(admin.ModelAdmin): list_display = ['name', 'address', 'zip_code', 'mobile_number', 'created', 'updated', 'user'] list_filter = ['name', 'zip_code', 'created', 'updated', 'user'] admin.site.register(Listing, UserProfileAdmin) user_profile/models from django.contrib import auth from django.db import models from django.urls import reverse from django.contrib.auth.models import AbstractUser, UserManager from django.contrib.auth.models import BaseUserManager from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.conf import settings from users.forms import CustomUserCreationForm, CustomUserChangeForm from … -
mongoengine isn't an available database backend for Django
I am trying to use mongoengine as my database I can't address the problem I downloaded mongoengine but it seems like django isn't accepting it. I get this error when I runserver django.core.exceptions.ImproperlyConfigured: 'django_mongodb_engine' isn't an available database backend. Try using 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3' I have seen some people upgrading or downgrading their version of django and it get solved like that I am using the latest version of django This as the DATABASE in the setting.py file DATABASES = { 'default': { 'ENGINE': 'django_mongodb_engine', 'NAME': 'mydatabase', } } -
How to filter django queryset for a current week
I am writing this customer admin filter that required to filter the queryset for this/current week only. How can I achieve this class WeekFilter(admin.SimpleListFilter): title = _("Week") parameter_name = "week" def lookups(self, request, model_admin): return ( ('1', 'This week'), ) def queryset(self, request, queryset): if self.value() == '1': return queryset.filter() # HERE I have tried this queryset.filter(created_at__week__gte=1, created-at__week__lte=7) but it doesnt work as expected -
related_name works the first time but not the second
I have a somewhat deep hierarchy of models: models.py: class Individual(models.Model): gedcom = models.ForeignKey(Gedcom, on_delete=models.CASCADE) pointer = models.CharField(max_length=22, default="") given = models.CharField(max_length=255, default="") surname = models.CharField(max_length=255, default="") birth_date = models.CharField(max_length=255, default="") birth_location = models.CharField(max_length=255, default="") death_date = models.CharField(max_length=255, default="") death_location = models.CharField(max_length=255, default="") class Fact(models.Model): individual = models.ForeignKey(Individual, on_delete=models.CASCADE, blank=True) tag = models.CharField(max_length=4, default="") value = models.CharField(max_length=255, default="") priority = models.IntegerField(default=0) class FactDetail(models.Model): fact = models.ForeignKey(Fact, on_delete=models.CASCADE, blank=True) tag = models.CharField(max_length=4, default="") value = models.CharField(max_length=255, default="") priority = models.IntegerField(default=0) In my code I start creating individuals, their associated facts, and the fact_details. The related_name "fact_set" gets created automatically and works, but why doesn't this automatically work for factdetails too? should there not be a factdetail_set related name created? curr_individual = self.individual_set.create( pointer = curr_pointer, given = given, surname = surname, ) elements = record.get_child_elements() for element in elements: fact_details = element.get_child_elements() fact_priority = 0 curr_fact_tag = element.get_tag() curr_individual.fact_set.create( tag = curr_fact_tag, value = element.get_value(), priority = fact_priority, ) fact_priority += 1 fact_detail_priority = 0 for fact_detail in fact_details: curr_fact_detail_tag = fact_detail.get_tag() curr_fact_detail_value = fact_detail.get_value() if not done_birth and curr_fact_tag == 'BIRT': done_birth = True if curr_fact_detail_tag == 'DATE': curr_individual.birth_date = curr_fact_detail_value if curr_fact_detail_tag == 'PLAC': curr_individual.birth_location = curr_fact_detail_value if not … -
What is the use of "psycopg2" in Django while connecting to PostgreSQL
What is the use of the "psycopg2" PostgreSQL database adapter; or what is the difference between using postgresql vs postgresql_psycopg2 while establishing connection in the settings.py file in a Django project? 'ENGINE': 'django.db.backends.postgresql', 'ENGINE': 'django.db.backends.postgresql_psycopg2', -
Apache config on a Synology DS for use with mod_wsgi / Django
I'm started developing a new site using Django. For realistic testing I wanted to run it on a Synology DS212J NAS. Following the official Synology guides I installed ipkg and with it the mod_wsgi package. As Next step: Following the standard tutorial I made a virtualenv and installed Django in it. Opening a new project and adjust the settings following to: https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-16-04 I'm able to reach the "Hello World" Site from Django by use of manage.py As suggested I want to exchange the manage.py through the apache server on the NAS. So I think I should go and edit the apache config files for e.g. define a virtual host... However I can't localize the files for it, as it seems they where moved at DSM6 (which I use) in comparison too other guides. Where need I to enter the values following the Tutorial on the Synology? As I'm quite new into the topic do I need to especially load the mod_wsgi module for Apache and if where? Is it a good idea to use the basic mode of wsgi instead of the daemon mode? I'm not sure which Django modules will be used later on in development... Thanks for the … -
Passing value and ID from Request.POST
I am trying to have a website with multiple input type ="text" fields which as a default have values from database in them. Goal is to have X input types where X=number of entries in database and one extra input type box to add a new entry. The problem is that if user edits a textfield and hits submit, Request.POST['event'] returns only the new value, not the id of the box that has been edited, This is my current code: <form method="post"> {% csrf_token %} {% for choice in event %} <form method ='POST'> {% csrf_token%} <input type="text" name = "event" id="event{{ forloop.counter }}" value="{{choice.txt}}"><br> <input type = 'submit' value = 'Zapisz'/> </form> {% endfor %} <form method ='POST'> {% csrf_token%} {{form.as_p}}<br> <input type = 'submit' value = 'Zapisz'/> </form> and views.py: def rpg_create(request): try: event = get_list_or_404(Event) except: event = "" if request.method == 'POST': try: Adjusted_event = request.POST['event'] print (Adjusted_event) except: pass form = RpgForm(request.POST or None) if form.is_valid(): print(form) form.save() context = { 'form': form, 'event': event } return redirect('/rpgmaker', context) else: form = RpgForm() context = { 'form': form, 'event': event } return render(request,"rpgmaker/rpg.html",context) -
Do I need to copy the templates for third party apps (specifically Django-schedule)?
I am a Django newbie trying to use a third party app (Django scheduler) to display a calendar for event scheduling. I followed the installation instructions on the github and have successfully installed the app into my environment. I know it is working because it migrated successfully and I was able to create test instances of the Event and Calendar models using the API shell (python manage.py shell). But I am really confused about how to use django-scheduler to augment my current app (i.e. how to make a calendar show up when users are inputting events). Specifically, my question is; do I need to copy all of the templates folders, or should they be automatically included during the installation and I just need to link to them somehow? There is an example project but it does not integrate the scheduler into an existing app so I could not glean the answer from this. -
Django: DoesNotExist at /admin
I've a view that receives an arugment to make a Query filter and show some results. The URL for this view is: views.ProdCatDetail urlpatterns = [ path('', views.allCat, name = 'allCat'), path('<slug:c_slug>', views.ProdCatDetail, name = 'ProdCatDetail'), ] the problem is that if I want to access the admin panel, through: http://127.0.0.1:8000/admin I cannot becuase the view: views.ProdCatDetail gets called, and since there is no Category "admin" I get an error. How can avoid this, without using another URL for the views.ProdCatDetail view??? -
how to filter queryset based on Datefield in django?
I need to filter queryset based on today/tommorows date and the field available is a date field not datetime field I am using custom manager for providing filtered result class CallbackReqManager(models.Manager): def get_queryset(self): return super().get_queryset().filter() def callbacktoday(self): today=date.today print(today) return self.filter(prefereddate=today) class CallbackReq(models.Model): name = models.CharField(max_length=50) email = models.EmailField(max_length=254) query = models.CharField(max_length=150) preferedtime = models.TimeField(auto_now=False, auto_now_add=False) prefereddate = models.DateField(auto_now=False, auto_now_add=False) requestedon = models.DateTimeField(auto_now_add=True) attended = models.BooleanField(default=False) # whether call back is met objects = CallbackReqManager() but I am getting TypeError: match = date_re.match(value) TypeError: expected string or bytes-like object -
Append to QuerySet Item
I have 2 models, Item which represents a product, and OnHand which represents each individual serialized product. They are bound by a ForeignKey of product_id. Item Model: class Item(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) manufacturer = models.ForeignKey('Manufacturer', blank=True, null=True, on_delete=models.SET_NULL) introduction = models.DateField(auto_now=True) is_retired = models.BooleanField(default=False) tags = models.ManyToManyField(Tag) def __str__(self): return self.name OnHand Model: class OnHand(models.Model): name = models.CharField(max_length=100) serial = models.CharField(max_length=80) asset = models.CharField(max_length=20) product = models.ForeignKey(Item, blank=True, null=True, on_delete=models.CASCADE) def __str__(self): return self.serial On my Index view, I have a table which shows these products and counts quanity. In order to do this, i need to count the amount of OnHand objects exist with a matching product_id. Index: def index(request): items = Item.objects.all() quanity = count_onhand(items) context = { 'items':items, } print(items) return render(request, 'index.html', context) count_onhand: def count_onhand(items): for item in items: count = OnHand.objects \ .filter(product_id=item.product_id) \ .count() Because these are going to the same view and need to maintain their order, I figured the best direction would be to append to the Item queryset then appending to a list I'll send back with the original Item, with the quanity appended. How do I do this in Django properly? I've seen some hacky ways, … -
How do I add a css property in a for loop only once?
I have a my table body in a for loop in my Django app and I want to add a CSS property only to the contacts of a specific company but now my code is applying the CSS properties to all contancts. table body {% for company in company_list %} <tr id="company-row"> <th id="company-name" scope="row">{{ company.name }}</th> <td>{{ company.order_count }}</td> <td id="order-sum">{{ company.order_sum|floatformat:2 }}</td> <td class="text-center"><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr id="contact-row"> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td id="contact-orders">Orders: {{ contact.order_count }}</td> <th>&nbsp;</th> <td></td> </tr> {% endfor %} {% endfor %} jquery $(document).ready(function(){ $("table tr#company-row").hover(function(){ sum = $(this).find("#order-sum").html() // get value of total sales if (sum > 50000) { $(this).addClass("company-row-over") // green $("tbody #contact-row").each(function(){ orders = $(this).find("#contact-orders").html() // get orders from each contact orders = orders.split(':') orders = orders[1] orders = parseInt(orders) if (orders > 3) { $(this).addClass("contacts") // yellow } }) } else { $(this).addClass("company-row-under") // orange } }, // clear highlighting on mouse out function() { $(this).removeClass() $("table tr#contact-row").removeClass() }) })