Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Autocomplete using django-extra-views
I'm using django-extra-views and I want to implement an autocomplete functionality to some fields of an InlineFormSetFactory. I tried with django-ajax-selects but it didn't work... Is there an easy way to do it? My models.py: class Index(models.Model): id_index = models.AutoField(primary_key=True) index_name = models.CharField(max_length=30) index_id_index_type = models.ForeignKey(IndexType, on_delete=models.CASCADE, db_column='id_index_type', verbose_name="Tipus d'índex") index_id_index_provider = models.ForeignKey(IndexProvider, on_delete=models.CASCADE, db_column='id_index_provider', verbose_name="Proveïdor d'índex") miseq = models.CharField(max_length=9) nextseq = models.CharField(max_length=9) class Meta: db_table = 'index' unique_together = (("index_name", "index_id_index_type", "index_id_index_provider", "miseq", "nextseq"),) def __str__(self): return self.index_name class GeneCandList(models.Model): id_gene_cand_list = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=150, verbose_name="Llista de gens candidats") class Meta: db_table = 'gene_cand_list' def __str__(self): return self.name class Pool(models.Model): id_pool = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=50, verbose_name="Pool") hibridation = models.BooleanField(verbose_name="Hibridació OK?") samples = models.ManyToManyField('Sample', through='SamplePoolIndexCand', blank=True, verbose_name="Mostres" class Meta: ordering = ['-id_pool'] db_table = 'pool' def __str__(self): return self.name class Sample(models.Model): id_sample = models.AutoField(primary_key=True) name = models.CharField(unique=True, max_length=20) sample_id_sex = models.ForeignKey(Sex, on_delete=models.CASCADE, db_column='id_sex', verbose_name='Sexe') indexes = models.ManyToManyField(Index, through='SamplePoolIndexCand', through_fields=('sample_id', 'index_id'), blank=True, verbose_name="Índexs") pools = models.ManyToManyField(Pool, through='SamplePoolIndexCand', through_fields=('sample_id', 'pool_id'), blank=True, verbose_name="Pools") gene_cand_lists = models.ManyToManyField(GeneCandList, through='SamplePoolIndexCand', through_fields=('sample_id', 'gene_cand_list_id'), blank=True, verbose_name="Llista de gens candidats") class Meta: db_table = 'sample' def __str__(self): return self.name class SamplePoolIndexCand(models.Model): sample_id = models.ForeignKey(Sample, null=True, blank=True, on_delete=models.CASCADE, db_column='id_sample', verbose_name='Mostra') pool_id = models.ForeignKey(Pool, null=True, blank=True, on_delete=models.CASCADE, … -
Pagination and slicing issue in Django 3.2
Can you explain how Queryset slicing works in django? Because for me it works kinda strange. Let me explain: I have a simple task to send email to students via AWS. AWS SES has a limited number of recipient per call. Pagination So my first idea was pretty straightforward -- to use django built-in Paginator. Code AWS_LIMIT = 45 students_queryset = Students.objects.filter(id__in=received_students).order_by('email') students_paginated = Paginator(students_queryset, AWS_LIMIT) print(students_queryset.count()) for page_number in students_paginated.page_range: student_page = students_paginated.get_page(page_number) print(f"{page_number}: {len(student_page.object_list)}") Output 150 1:45 2:45 3:0 4:0 I expected to see something like this: 150 1:45 2:45 3:45 4:15 I tried to find any solutions to solve this. But in the end I gave up and decided to use simple slicing. Slicing Code AWS_LIMIT = 45 def get_index_range(student_count): index = -(-student_count//AWS_LIMIT) return range(index) def get_slice(queryset, index): start_index = AWS_LIMIT * index end_index = start_index + AWS_LIMIT print(f'Slice: {start_index}:{end_index}') return queryset[start_index:end_index] students_queryset = Students.objects.filter(id__in=received_students).order_by('email') print(students_queryset.count()) for index in get_index_range(students.count()): students_slice = get_slice(students_queryset, index) print(f"{index+1}: {students_slice.count()}") Output But result was the same 150 Slice: 0:45 1:45 Slice: 45:90 2:45 Slice: 90:135 3:0 Slice: 135:180 4:0 Solution I went to Django 3.2 documentation: Generally, slicing a QuerySet returns a new QuerySet – it doesn’t evaluate the query. An … -
How to display recent posts in django
Here is the case, I need the last records of the model to be displayed on the page, for this I added a new pub_date record in the models to add to the queue of records, I also added this to views.py, and it kind of displays, but both records. views.py code def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) avaibilitys = Avaibility.objects.order_by('-pub_date') context['avaibilitys'] = avaibilitys return context models.py code class Avaibility(models.Model): name_text = models.CharField(max_length=200) apply_text = models.CharField(max_length=200) presence_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published', null=True) def __str__(self): return self.name_text def __str__(self): return self.apply_text def __str__(self): return self.presence_text this is what displays -
Django Tenants: django_conten_type tables are same in Public vs tenant schemas
I have a multi-tenant app using django_tenants. From what I understand, and this article seems to confirm it, the django_content_type table in the "public" schema should contain only apps/models specified in the SHARED_APPS setting (in settings.py), while that table in all tenant schemas should contain apps/models specified in the TENANT_APPS setting. That isn't the case in my app. So as not to clutter this post with a long list of app names that are (correctly) in both places, I'll point out two instances: I have an app/model: countries.country that only exists in "public". I have an app/model: tags.tag that only exists in tenant schemas. Comparing django_content_type table in "public" to the same table in a tenant schema named "demo", I find that: Both tables have 36 rows - all exactly the same countries.country exists in both (the table only exists in "public") tags.tag exists in both (the table only exists in tenant schemas) Even tenants.tenant and tenants.domain exists in both, even though the tables exist only in "public". Can someone explain why my tables are in this state, and why my app differs from what's described in the article I linked to above? -
I cant run the server in my project with django
I created a project in django normally, but when I try to run the server (python manager.py runserver) I get the following error: C:\Users\Fredy\AppData\Local\Programs\Python\Python39\python.exe: can't open file 'C:\Downloads\django_one\manager.py': [Errno 2] No such file or directory The strange thing is that the manager.py file is there. I went back to other projects that I had already created that were working and the same error occurred. Does anyone know how I fix this? -
CreateView django-role-permission
I use django-role-permission library for use roles and I have CreateView: class CreatePostView(CreateView): model = apps.blog.models.Post form_class = PostForm template_name = 'cabinet/post/create.html' success_url = "/cabinet/post" And I want this view can access only user with role: edit_posts -
How to integrate 1С with Django?
There is an online store built on Django. How do I set up an exchange of data on products between Django and 1C? I have checked some documentation on the CommerceML format, but it is still unclear how to set it up on the 1C side. As far as I understand, all uploads are configured quite simply. You just need to register the URL of the handler. And then everything happens automatically -
How to fix raise SMTPServerDisconnected('please run connect() first') in django 2
I have a next email-settings in settings.py: EMAIL_HOST = "smtp.gamil.com" EMAIL_HOST_USER = os.environ.get('email_host_user') EMAIL_HOST_PASSWORD = os.environ.get('email_host_password') EMAIL_PORT = 587 EMAIL_USE_TLS = True And i have a next function in views.py: def post_share(request, post_id): # get post from id post = get_object_or_404(Post, id=post_id, status='published') sent = False if request.method == "POST": # form was send to save form = EmailPostForm(request.POST) if form.is_valid(): # All field of the form have been checked cd = form.cleaned_data # Sending email post_url = request.build_absolute_uri(post.get_absolute_url()) subject = '{}, ({}) recommends you reading "{}"'.format(cd['name'], cd['email'], post.title) message = 'Read "{}" at {}\n\n{}\'s comments: {}'.format(post.title, post_url, cd['name'], cd['comments']) send_mail(subject, message, 'lilarro93@gmail.com', [cd['to']]) sent = True else: form = EmailPostForm() return render(request, 'blog/post/share.html', {'post': post, 'form': form, 'sent': sent}) And if functions "send_mail" is called, i have a following problem: terminal: >>> send_mail("Django mail", "This mail was sent from django", 'server@gmail.com', ['another@gmail.com'], fail_silently=False) ... raise SMTPServerDisconnected('please run connect() first') smtplib.SMTPServerDisconnected: please run connect() first How i can fix it? -
Use Traefik reverse-proxy to host WordPress and Django
I am new to deployment related tasks so what I'm asking may be very simple to implement but it is difficult for me nonetheless. In one domain, I need a WordPress-based public website (about 3-4 pages) as well as a link to log into the internal management Django v3.2 app. Both plus some extras (redis, postgres) will be served through docker-compose. I am using cookiecutter-django for my Django application. It uses Traefik by default as reverse-proxy for the production configuration. I looked at the docs for Traefik and I couldn't quite understand how I can implement the paths for my use case. I have the WP site and the Django app separately working currently so I just need to figure out how to deploy it together under the same domain, just different paths. As an example of what I need to achieve, let's assume my WordPress site has pages home, about, and contact so I would want the full URL to be example.com, example.com/about, and example.com/contact respectively. Any other links should be forwarded to Django. For those who have not used cookiecutter-django, the default file structure and configuration is to have a separate traefik.yml and Dockerfile for Traefik, and separate … -
APS Scheduler raising exception for no reason django
Even though the target function is receiving both the arguments it's still throwing an error for missing parameters ? wonder why check_device() missing 1 required positional argument: 'device_id' Job "check_device (trigger: interval[0:00:30], next run at: 2021-11-05 19:35:24 IST)" raised an exception Scheduler snip def job_add(application_id,device_id,count): scheduler.add_job( check_device, 'interval', args = (application_id,device_id,), seconds=7, jobstore = 'default', id=f'my_job_{count}', replace_existing=True, max_instances = 7, misfire_grace_time=None ) function i am calling def check_device(application_id,device_id): print('Mqtt connected ... calling on ',application_id,device_id) mqttc = mqtt.Client(clientId) -
AttributeError: module 'crontab' has no attribute 'CronSlices'
I am currently dev a website using Django. I want to program tasks so I am planing to use Celery and Redis. I've installed Celery (pip command). I've also installed Redis using brew and it works : redis-cli ping returns PONG. I had to install django-celery-result and django-celery-beat (I used pip command). After setting-up my Django code, I got this error message when I run the server. File "/usr/local/lib/python3.9/site-packages/django_celery_beat/validators.py", line 7, in <module> class _CronSlices(crontab.CronSlices): AttributeError: module 'crontab' has no attribute 'CronSlices' I didn't know how to fix this error. Do anyone has an idea of where the problem comes from ? Thx -
Query Django comparing two charfield fields
I have this two examples models class ExternalTransaction(): external_id = models.CharField(max_length=255) class Transaction(): transaction_id = models.CharField(max_length=255) I want to create query which returns ExternalTransaction queryset which contains only transactions which are not in Transaction.transaction_id. I've tried to write something like this: ExternalTransaction.objects.exclude(external_id__in=Transaction.objects.all().values_list('transaction_id')) but it does not work, returns empty queryset. -
Update Create Method in Django Rest Framework for two nested werializers
I've found many answers to similar questions but not to my specific one. I'm trying to update the Create Method for my serializer which has two nested serializers: class TaskSerializer(serializers.ModelSerializer): products = ProductSerializer() prep = PrepSerializer() class Meta: model = Task fields = '__all__' def create(self, validated_data): products_data = validated_data.pop('products') task = Task.objects.create(**validated_data) for products_data in products_data: Product.objects.create(task=task, **products_data) return task I want to add the "prep" nested serializer in as well to be updated at the same time but I can't seem get the syntax right. Any help, greatly appreciated. -
In Django models, how does the foreign key field know which field to match with in the other model?
I understand what Foreign Keys do but I'm having trouble understanding why this is working in Django. I have the Project model in 'app1/models.py' file. This model has a ForeignKey named 'owner' that links to the Profile model in my 'app2/models.py' file. How does the 'owner' field in the Project model know it should be linking to the 'user' field in the Profile model if I'm only passing the model name to the 'owner' field? I feel like I should be passing the Profile.field or something like this in the Project model: owner = models.ForeignKey(Profile.user, null=True, blank=True ... ) Full model code from Dennis Ivy's tutorial: class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) #null is default=False and is required description = models.TextField(null=True, blank=True) #for a bigger field, allows null(for db)/blank(for Django get/post) featured_image = models.ImageField(null=True, blank=True, default='default.jpg') demo_link = models.CharField(max_length=2000) source_link = models.CharField(max_length=2000, null=True, blank=True) #can be blank in db tags = models.ManyToManyField('Tag', blank=True) #quotes will ref other class after this one vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) #generate when model instance is created id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name … -
django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)'
I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items: when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error: NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$'] my code: Model.py file class Post(models.Model): #data fields title = models.CharField(max_length=64) textarea = models.TextField() #bid price = models.FloatField(default=0) currentBid = models.FloatField(blank=True, null=True) imageurl = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateTimeField(auto_now_add=True) # for activated the Category activate = models.BooleanField(default=True) buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator") ############################### this is the watchers watchers = models.ManyToManyField(User, blank=True, related_name='favorite') def __str__(self): return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}" urls.py urlpatterns =[ # Watchlist path('Post/<int:id>/watchlist_post/change/<str:reverse_method>', views.watchlist_post, name='watchlist_post'), path('watchlist/', views.watchlist_list, name='watchlist_list') ] views.py #start watchlist def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'Bidform': BidForm(), # IS_WATCHED method 'is_watched': is_watched } return render(request, 'auctions/item.html', context) @login_required def watchlist_post(requset, … -
Not migrated with Open edX migrate
I am trying to generate edX open-release / hawthorn and when migrations run the following output is what shows me I cut the code for a better reading Apply all migrations: ... Traceback (most recent call last): File "manage.py", line 123, in <module> execute_from_command_line([sys.argv[0]] + django_args) ... File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 98, in state_forwards state.models[app_label, self.model_name_lower].fields.append((self.name, field)) KeyError: ('enterprise', 'enterprisecustomer') Captured Task Output: --------------------- ---> pavelib.servers.update_db ---> pavelib.prereqs.install_prereqs ---> pavelib.prereqs.install_node_prereqs ---> pavelib.prereqs.install_python_prereqs ---> pavelib.prereqs.uninstall_python_packages pip install -q --disable-pip-version-check --exists-action w -r requirements/edx/development.txt pip freeze > /edx/app/edxapp/edx-platform/test_root/log/pip_freeze.log NO_EDXAPP_SUDO=1 EDX_PLATFORM_SETTINGS_OVERRIDE=devstack_docker /edx/bin/edxapp-migrate-lms --traceback --pythonpath=. Build failed running pavelib.servers.update_db: Subprocess return code: 1 make: *** [Makefile:257: dev.migrate.studio] Error 1 -
How to disable translations in tests (django, pytest)
That's not really a question but the proposition of solution to the problem. I tried to find an article to solve this issue I was facing but at the end of the day I actually came up with something which might help some ppl in the same situation as mine: Tech Stack: Django==2.2.x, pytest==6.0.0 Issue: I tried to test the simple form validation. Compare error messages returned from form validation with the expected ones, to check if the validation works as expected. class TestPassword: @pytest.mark.parametrize( 'password,error_message', [ ('#noDigitPassword', 'At least one digit is required.'), ('#nouppercasep4ssword', 'At least one capital letter is required.'), ('#NOLOWERC4SEPASSWORD', 'At least one lower case letter is required.'), ('NoSymbolP4ssword', 'At least one special char (!%&amp;@#$^*?_~.) is required.'), ('#WhitSpace P4ssword', 'Whitespaces are not allowed.'), ], ) def test_form_password_complexity_check(self, password: str, error_message: str) -> None: form = SignUpForm( dict( email="dummy@email.com", first_name="dummy first_name", last_name="dumy last_name", password=password, ) ) assert form.is_valid() is False assert error_message in str(form.errors['password']) class SignUpForm(forms.Form): email = forms.CharField(max_length=255) first_name = forms.CharField(max_length=255) last_name = forms.CharField(max_length=255) password = forms.CharField( max_length=255, validators=[ at_least_one_capital_case_validator, at_least_one_lower_case_validator, at_least_one_number_validator, at_least_one_special_char_validator, no_whitespaces_validator, ], ) Validation error messages use ugettext_lazy and the output strings are: _("At least one lower case letter is required.") _("At least one … -
How to configure two databases with different tables in same Django app?
settings.py DATABASE_ROUTERS = ["mysite.router.CheckerRouter"] DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "A", "USER": "user", "PASSWORD": "dummypassword", "HOST": "server", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, "marketing": { "ENGINE": "sql_server.pyodbc", "NAME": "B", "USER": "user", "PASSWORD": "dummypassword", "HOST": "server", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } models.py class table1(models.Model): ## Default database table ID = models.CharField( db_column="Identifier", max_length=200, blank=True, null=True, db_index=True ) var1 = models.CharField( db_column="Type", max_length=200, blank=True, null=True, db_index=True ) class Meta: db_table = "Table 1" class table2(models.Model): ## Marketing database table ID = models.CharField( db_column="Identifier", max_length=200, blank=True, null=True, db_index=True ) marketer = models.CharField( db_column="Type", max_length=200, blank=True, null=True, db_index=True ) class Meta: db_table = "Table 2" app_label = "marketing_label" router.py class CheckerRouter: def db_for_read(self, model, **hints): if model._meta.app_label == "marketing_label": return "marketing" return "default" def db_for_write(self, model, **hints): if model._meta.app_label == "marketing_label": return "marketing" return "default" def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == "marketing_label" or obj2._meta.app_label == "marketing_label": return True return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == "marketing_label": return db == "marketing" return None When making migrations, the app is not detecting the marketing database tables at all. Only the default database … -
Sending a file with json with requests and tastypie
I'm trying to send some zip files, and some json to my tastypie endpoint. I'm getting: The format indicated \'multipart/form-data\' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." On my client. This is my client code: def sendLogs(): url = "http://43.197.102.4:8000/api/ziprel/" payload = {"param_1": "value_1","param_2": "value_2"} files = { 'JSON': (None, json.dumps(payload), 'application/json'), 'Console': (os.path.basename('/home/pi/Desktop/Console.zip'), open('/home/pi/Desktop/Console.zip','rb'), 'application/zip') } r = requests.post(url,files=files) print(r.content) I get the error when I print, r.content. Here's my tastypie code: class MultipartResource(object): def deserialize(self, request, data, format=None): try: if not format: format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded') if format == 'application/x-www-form-urlencoded': return request.POST if 'multipart' in format: data = request.POST.copy() data.update(request.FILES) # Get the error here json.loads(request.body) zip = TestZipModel() zip.ADB = request.FILES['ADB'] zip.save() return data except Exception as e: print("Error {}".format(e)) return super(MultipartResource, self).deserialize(request, data, format) # overriding the save method to prevent the object getting saved twice def obj_create(self, bundle, request=None, **kwargs): pass The server is getting: Error 'utf-8' codec can't decode byte 0x95 in position 350: invalid start byte Am I able to send JSON with a multipart/form-data content type? Is there a better way to do this? Sending data along with the zips will be very helpful. -
Allauth/Microsoft Graph API - AADSTS900144: The request body must contain the following parameter: ‘resource’
I can't get contacts using Microsoft Graph API for some users as it raises: {“error”:“invalid_request”,“error_description”:“AADSTS900144: The request body must contain the following parameter: ‘resource’.} This error happens only with some users. Not all of them have problems. SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'SCOPE': ['Contacts.Read', 'Contacts.ReadWrite', 'offline_access', 'User.Read'], 'AUTH_PARAMS': {'prompt': 'select_account'}, }, The error URL is https://login.microsoftonline.com/error?code=900144 which just says it's an authentication issue. Do you know where the problem is and how to add the resource parameter? -
I could not point correctly the static image files
index.html <div class="carousel-inner" role="listbox"> {% for pizza in pizza_list %} {% if forloop.counter0 == 0 %} <div class="carousel-item active"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="..."> </div> {% else %} <div class="carousel-item"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="..."> </div> {% endif %} {% endfor %} </div> views.py def index(request): pizza_list = [] print(os.getcwd()) for item in os.listdir('static/Pizza'): pizza_list.append(item) ## print(pizza_list) context = {'pizza_list':pizza_list} return render(request,'index.html',context) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py under Main_Project folder from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('pizza.urls')), ] urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT) My project directory Main_Project (top) --Main_Project (top) --settings --urls --pizza --static --Pizza --(images) --templates --migrations --views.py --models.py --urls.py In this Django project, I have a confusion about where should the static images and files put under because I could not load the image in index.html that I saved in the static folder directory. Also, I am not sure whether my settings are correct in order to have the images shown on the templates … -
Django ListView Through Model Relationships
I have been reading through here and I can't seem to find the answer of the question I am looking for. Maybe I'm not asking the correct question. I have three models. Recruiter Office Recruit Recruiters are assigned to multiple offices and each office has multiple employees. What I need to be able to do is create a listview that lists all of the employees that are associated with a recruiter. So something like this: Recruiter 1 has Office 1 and 2 assigned to them. Office 1 has Employee 1,2,3. Office 2 has employee 3,4,5 The Listview should display all employees under Recruiter 1. My Models are: class Recruit(models.Model): id = models.CharField(max_length=25,primary_key=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile_phone = models.CharField(max_length=20,null=True) preferred_phone = models.CharField(max_length=20,null=True) email= models.CharField(max_length=100,null=True) officeid = models.ForeignKey(Office,on_delete=models.DO_NOTHING,related_name="recruit") class Office(models.Model): office_name = models.CharField(max_length=100) officeid = models.CharField(max_length=20,primary_key=True,unique=True) class Recruiter(models.Model): user = models.OneToOneField(User, related_name='recruiter',on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile,on_delete=models.CASCADE) Do I need a AssingedOffices table to join this all together? class AssignedOffice(models.Model): user = models.ForeignKey(UserProfile,on_delete=models.CASCADE) esa_office = models.ForeignKey(Office,on_delete=models.CASCADE) Just not sure how to connect them & display in the listview. -
Django admin site: how to change admin URL based on verbose_name
class Meta: verbose_name only changes its displayed name. But when its clicked. i want its url changed too based on verbose name Here's my code: Models: tables = [f.id for f in StockId.objects.raw( "SELECT TABLE_NAME AS id FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME LIKE 'my_project_auth_stockid%%'")] table_map = {} for tbl in tables: class Stocks(models.Model): user_id = models.IntegerField() product_name = models.CharField(max_length=100) mrp = models.IntegerField() selling_price = models.IntegerField() class Meta: db_table = tbl managed = False verbose_name = _(tbl) verbose_name_plural = _(tbl) table_map[tbl] = Stocks Admin.py from my_project_auth.models import * class AllStocksAdmin(AdminSite): site_header = 'All User Stocks' stockadmin = AllStocksAdmin(name="stockadmin") for tbl in tables: class StocksAdmin(ImportExportModelAdmin): resource_class = StocksAdminResource list_display = ["product_name"] stockadmin.register(table_map[tbl], StocksAdmin) What I am trying to do is in above to make multiple stock table out of single model. But Admin panel for each stocks is not working. All stocks table is pointing towards single table because of admin URL is based on model's class name. I'm trying to do something like this in Admin.py, please suggest changes: for tbl in tables: class StocksAdmin(ImportExportModelAdmin): resource_class = StocksAdminResource list_display = ["product_name"] def get_urls(self): # Not Working urls = super(StocksAdmin, self).get_urls() my_urls = path(f'stockadmin/{tbl}/', self.admin_view(stockadmin)) return my_urls + urls -
how to create a Pagination with if and for loop django
I tried to do Pagination using for and if and it didn't work So how do I do that this an image that can show u front page image page 2 image front page code {% for post in posts %} {% if forloop.counter <= 2 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty %} <div class="notification"> <p>No posts yet!</p> </div> {% endfor %} page 2 code {% for post in posts %} {% if forloop.counter2 <= 30 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty … -
Map integration not wokring
The following are the two lines I put in the head tag of my html <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyC_Ii8L8wy40S8pB-eUBg13MlIOGYHXx6Y"></script> <script src="{% static "js/mapscript.js" crossorigin="anonymous" %}"></script> The below is the script I use to load map into my html. In my html I have a div tag with ID equal to map_canvas. var map; function initialize() { console.log("Loading map"); var mapOptions = { zoom: 12, center: new google.maps.LatLng(55.85361568022353, -4.288761402220929) }; map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); The issue is that even if I added a API key and have a billing registered for google maps, map is not rendering after using the code above though this javascript code is hit. Can anybody give suggestions?