Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Class 'Item' has no 'Objects' memberpylint(no-member)
I'm trying to import the model into my views but somehow it's giving me an error "Class 'Item' has no 'Objects' memberpylint(no-member)". I don't understand why? views.py from django.shortcuts import render from .models import Item # def products(request): # context = { # 'items': Item.objects.all() # } # return render(request, "products.html", context) def item_list(request): context = { 'items': Item.Objects.all() } return render(request, "home-page.html", context) def checkout(request): return render(request, "checkout.html") here's my model for that from django.conf import settings from django.db import models CATEGORY_CHOICES = ( ('S', 'Shirt'), ('SW', 'Sportswear'), ('OW', 'Outwear') ) LABEL_CHOICES = ( ('P', 'primary'), ('S', 'secondary'), ('D', 'danger') ) class Item(models.Model): title = models.CharField(max_length = 100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES, max_length=2) label = models.CharField(choices=LABEL_CHOICES, max_length=1) def _str_(self): return self.title class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) title = models.CharField(max_length = 100) def _str_(self): return self.title class Order(models.Model): title = models.CharField(max_length = 100) items = models.ManyToManyField(OrderItem) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField() ordered = models.BooleanField(default=False) def _str_(self): return self.title Can anyone tell me what's it I'm doing wrong? Same with the product function when I try to call the Item it's giving me the same error. That's why I commented out. -
Overriding Django admin inlines formset will not save more than 1 row
I have a straight forward admin.ModelAdmin class with an inlines, of which I am overriding the form and formsets with a forms.Model and BaseInlineFormset to add a custom field. I have a custom jQuery script that gets loaded in and whenever a machine is picked from the select2 drop-down it runs an AJAX query to the REST API and grabs the items based on a foreign key value and populates the CleaningEntryInline with information. However, upon saving it is only posting a single record to the database. class CleaningEntryInline(admin.TabularInline): model = CleaningEntry form = CleaningEntryForm formset = CleaningEntryFormSet extra = 0 raw_id_fields = ['cleaning_item'] fieldsets = [ (None,{'fields':[('cleaning_item','cleaning_action', 'checked', 'na', 'notes')]}) ] template = 'admin/quality/cleaningentry/edit_inline/tabular_actions.html' class CleaningLogAdmin(admin.ModelAdmin): ####Save model function override to make and save QC Lab user and make uneditable. def save_model(self, request, obj, form, change): obj.lab_user = request.user.username obj.save() list_display = ['machine_used','get_product_info','lot_num','start_time','lab_user'] list_filter = ['machine_used'] readonly_fields = ['lab_user', 'cleaning_users'] search_fields = ['machine_cleaned', 'lot_num', 'recipe_cleaned__recipe_name__item_code', 'lab_user'] autocomplete_fields = ['machine_used','recipe_cleaned'] fieldsets = [ ('Cleaning Info',{'fields':[('machine_used', 'recipe_cleaned', 'lot_num')]}), (None,{'fields':[('start_time')]}), (None,{'fields':[('clean_time', 'lab_user')]}) ] inlines = [CleaningUserInline, CleaningEntryInline] change_list_template = 'admin/quality/cleaninglog/change_list.html' list_per_page = 25 form = CleaningEntryForm class Media: js = ( 'admin/js/vendor/jquery/jquery.min.js', 'admin/js/jquery.init.js', 'admin/js/list_filter_collaspe.js', 'admin/js/equipaction_filter.js', ) css = {'all':( 'admin/css/vendor/select2/select2.css', ) } … -
ImportError: No module named. Worker failed to boot
I am trying to get gunicorn working with my Nginx but it just can't seem to see the WSGI.py file. I tried different combinations of my project name and with different paths. This is how my wsgi.py file looks like: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'voopglobal.settings') application = get_wsgi_application() It should ideally say "Booting worker with PID and a PID number" but it gives me an error instead. ubuntu@ip-172-31-25-61:~/voop-global-it-project/voopglobal$ gunicorn voopglobal.wsgi [2019-09-10 12:01:01 +0000] [27716] [INFO] Starting gunicorn 19.7.1 [2019-09-10 12:01:01 +0000] [27716] [INFO] Listening at: http://127.0.0.1:8000 (27716) [2019-09-10 12:01:01 +0000] [27716] [INFO] Using worker: sync [2019-09-10 12:01:01 +0000] [27720] [INFO] Booting worker with pid: 27720 [2019-09-10 12:01:01 +0000] [27720] [ERROR] Exception in worker process Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 578, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 126, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 135, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 377, in import_app __import__(module) File "/home/ubuntu/voop-global-it-project/voopglobal/voopglobal/wsgi.py", line 12, in <module> from django.core.wsgi import get_wsgi_application ImportError: No module named django.core.wsgi [2019-09-10 12:01:01 +0000] [27720] [INFO] Worker exiting (pid: … -
Using foreign keys on the same model, but on two different fields
If this question is stupid I'm sorry, but I couldn't really find anything useful on Google. So I have a model made up of two fields. I want to create a model with some other fields, but two of them should be the ones from the previous one. Is there any way to obtain this? Code: from django.db import models from django.contrib.auth.models import User from datetime import date # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE) meserie = models.ForeignKey(CORMeserii, max_length=50, to_field='MeserieCor', on_delete=models.CASCADE) dataSolicitare = models.DateField(default=date.today) denumireMeserie = models.CharField(max_length=50) locuri = models.IntegerField() agentEconomic = models.CharField(max_length=50) adresa = models.CharField(max_length=150) dataExpirare = models.DateField() experientaSolicitata = models.CharField(max_length=200) studiiSolicitate = models.CharField(max_length=200) judet = models.CharField(max_length=20) localitate = models.CharField(max_length=25) telefon = models.CharField(max_length=12) emailContact = models.EmailField(max_length=40) rezolvata = models.BooleanField(default=False) def __str__(self): return self.cor I thought this might work, but I get these errors: from django.db import models from django.contrib.auth.models import User from datetime import date from .validators import validate_file_size # Create your models here. class CORMeserii(models.Model): CodCOR = models.CharField(max_length=25, primary_key=True, unique=True) MeserieCor = models.CharField(max_length=50, unique=True) class Oferta(models.Model): solicitant = models.ForeignKey(User, on_delete=models.CASCADE) cor = models.ForeignKey(CORMeserii, max_length=25, on_delete=models.CASCADE) meserie = models.ForeignKey(CORMeserii, … -
Not Found: /media/media/photos/e.jpg in django
I've deployed one project In web server. our project everything fine but i unable print image on profile page .in our local system working fine but in server error getting Not Found: /media/media/photos/e.jpg in django. models.py class Matr(models.Model): photo = models.ImageField(upload_to='media/photos/', null=True, blank=True) settings.py MIDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) profile.html {% if user.matr.photo %} <img src="{{ user.matr.photo.url }}" width="330"> {% endif %} -
Is there a better way to write output of background tasks to the database?
first of all thx for reading. In my project, I have azure-function / azure webjob to do the parsing,analysis of the raw data when it comes to the storage account. The output will be update to database with direct sql command like: sql_update = """UPDATE "PrototypeOne" SET files_amount =%s, used_time = %s where "User_Name" =%s;""" cursor.execute(sql_update,vars) My questions are: 1, is there a smarter way to update the database? can my backend play some role in between? 2, Is there a pub/sub library for such 'script level' application? Background: My backend is django 2.0+, with postgresql as database on azure. -
connect assets uploaded in anonymous mode post login
I am building a web app where user can upload a file in logged out mode but expects the file to be associated with him post login in the same session. The way I have implemented is to attach both a session_key and a User to the model as follows class Asset(Model): id = BigAutoField(primary_key=True) file = FileField(upload_to=get_file_path) submission_time = DateTimeField(auto_now_add=True, blank=False) expiration_time = DateTimeField(default=some_method) session = CharField(max_length=1024) user = ForeignKey( User, on_delete=CASCADE, related_name="%(app_label)s_%(class)s_related", related_query_name="%(app_label)s_%(class)ss", blank=True, null=True) def __str__(self): return self.file.name When the user first uploads the Asset, I capture the same and store it in backend with session_key. Once users confirms his willingness to post this Asset to share with community by doing signup/login, I match the Asset's session key with current session key and updates the user field in the Asset model. Is this the best approach? Does this approach have any security loopholes here? -
Upload an html file to a Google disk using api
There's a view that forms the body of an html document and and gives it to the new page of the site (url like - http://localhost/cv/4/html/) view.py class CvView(AuthorizedMixin, View): def get(self, request, employee_id, format_): """Returns employee's CV in format which is equal to `format_` parameter.""" employee = get_object_or_404(Employee, pk=employee_id) user = request.user content_type, data = Cv(employee, format_, user).get() if isinstance(data, BytesIO): return FileResponse( data, as_attachment=True, filename=f'cv.{format_}', content_type=content_type) return HttpResponse(data, content_type=content_type) urls.py path('cv/<int:employee_id>/<str:format_>/', CvView.as_view(), name='cv'), variable data passed to HttpResponse contains a complete html document <!DOCTYPE html> <html lang="en"> <head> ..... </head> <body> ..... </body> I need to pass this document to the google drive for opening.To do that, I'm using Google API Client. The function for creating a document opening is as follows def file_to_drive(import_file=None): SCOPES = 'https://www.googleapis.com/auth/drive' creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first # time. ..... ..... # GET PERMISSIONS ..... ..... service = build('drive', 'v3', credentials=creds) # Call the Drive v3 API file_metadata = {'name': 'test.html'} media = MediaFileUpload(import_file, mimetype='text/html') file = service.files().create(body=file_metadata, media_body=media, fields='id') response = None while response is None: status, response = file.next_chunk() … -
Is it safe to use auth_user for regular website users?
I want to create a website where people can post things using accounts. It should also be possible to login with google (or other) OAuth, where I would basicly create an auth_user for them using googles tokens. So is it safe to use djangos preexisting user and group system for regular everyday users of my website by just denoting them without staff or superuser priviledges? Also can I just link the google token to an auth_user and start a session for him that way? Or should I implement my own user and group system? -
Django Prepopulate Class Based CreateView Form Attribute with currently logged in username
I Need to Restrict the Options in a Select Field of a Django Form for not staff users. So theses are my models.py: #!/usr/bin/python3 from django.db import models from django.urls import reverse class Extension(models.Model): username = models.CharField(primary_key=True, max_length=200, help_text='') callerid = models.CharField(max_length=200, help_text='') extension = models.CharField(max_length=3, help_text='') firstname = models.CharField(max_length=200, help_text='') lastname = models.CharField(max_length=200, help_text='') password = models.CharField(max_length=200, help_text='') context = models.ForeignKey('Context', on_delete=models.SET_NULL, null=True) def get_absolute_url(self): return reverse('extension-detail', args=[str(self.username)]) def my_get_absolute_url(self): return reverse('my-extension-detail', args=[str(self.username)]) def __str__(self): return self.username class Context(models.Model): name = models.CharField(primary_key=True, max_length=200, help_text='') countryprefix = models.CharField(max_length=200, help_text='') cityprefix = models.CharField(max_length=200, help_text='') number = models.CharField(max_length=200, help_text='') extensionsfrom = models.CharField(max_length=200, help_text='') extensionstill = models.CharField(max_length=200, help_text='') portscount = models.CharField(max_length=200, help_text='') def get_absolute_url(self): return reverse('context-detail', args=[str(self.name)]) def my_get_absolute_url(self): return reverse('my-context-detail', args=[str(self.name)]) def __str__(self): return self.name views.py: #!/usr/bin/python3 from django.contrib.auth.mixins import LoginRequiredMixin, PermissionRequiredMixin from django.contrib.auth.models import Permission from catalog.models import Extension, Context from django.shortcuts import render from django.urls import reverse_lazy from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView from django.views.generic.list import ListView class ExtensionCreate(LoginRequiredMixin, PermissionRequiredMixin, CreateView): model = Extension fields = '__all__' permission_required = 'catalog.add_extension' class ExtensionUpdate(LoginRequiredMixin, PermissionRequiredMixin, UpdateView): model = Extension fields = '__all__' permission_required = 'catalog.change_extension' class ExtensionDelete(LoginRequiredMixin, PermissionRequiredMixin, DeleteView): model = Extension success_url = reverse_lazy('extensions') permission_required = 'catalog.delete_extension' … -
How to increment django DB using cookies
I am trying to increment my DB by 1 if a user has not visited that unique item.pk before. At the moment it will only increment by 1 for all items in my DB, id like to to increment by 1 for each item.pk in the DB. def bug_detail(request, pk): """ Create a view that returns a single bug object based on the bug ID (pk) and render it to the bug_detail.html template or return 404 error if object is not found Also handles commenting on the bug as well as regulating the amount of views attributed to the bug. """ bug = get_object_or_404(Bug, pk=pk) if request.method == "POST": form = BugCommentForm(request.POST) if form.is_valid(): bugComment = form.save(commit=False) bugComment.bug = bug bugComment.author = request.user bug.comment_number += 1 bug.save() bugComment.save() return redirect(reverse('bug_detail', kwargs={'pk': pk})) else: messages.error( request, "Looks like your comment is empty!", extra_tags="alert-danger") form = BugCommentForm(instance=bug) return redirect(reverse('bug_detail', kwargs={'pk': pk})) else: form = BugCommentForm() comments = BugComment.objects.filter(bug__pk=bug.pk) comments_total = len(comments) response = render(request, 'bug_detail.html', {'bug': bug, 'comments': comments, 'comments_total': comments_total, 'form': form}) if 'last_visit' in request.COOKIES and 'bugg' in request.COOKIES: last_visit = request.COOKIES['last_visit'] # the cookie is a string - convert back to a datetime type last_visit_time = datetime.strptime( last_visit[:-7], "%Y-%m-%d … -
Error:Not Found: /media/media/photos/e.jpg in django
I've deployed one project In web server. our project everything fine but i unable print image on profile page .in our local system working fine but in server error getting Not Found: /media/media/photos/e.jpg in django. models.py photo = models.ImageField(upload_to='media/photos/', null=True, blank=True) settings.py MIDIA_ROOT=os.path.join(BASE_DIR,'media') MEDIA_URL='/media/' urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) profile.html {% if user.matr.photo %} <img src="{{ user.matr.photo.url }}" width="330"> {% endif %} -
Django admin login error - Exception Value: no such table: auth_user
Steps: -Pycharm: Django template. python manage.py createsuperuser # succesful python manage.py makemigrations python manage.py migrate python manage.py runserver server is working, I am going to http://127.0.0.1:8000/admin/login putting credentials(doesn't matter correct or not), clicking Log in getting error: OperationalError at /admin/login/ no such table: auth_user User is created correctly because when I am trying to create another one with same credential db returns warning that superuser already exist. Also database is working, I can get into it through python manage.py shell here's some more logs if it's gonna help: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 2.2.5 Python Version: 3.7.4 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed 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'] -
Dynamic log filename based on logged in username
I would like to maintain independent user logs in django based on logged in username. Any assistance on configuring django logging callback filter will be appreciated I followed instructions from this link but could not get it to work Dynamic filepath & filename for FileHandler in logger config file in python def write_dynamic_log(record): def write_dynamic_log(record): now = datetime.datetime.now().strftime("%Y%m%d%H%M%S") dynamic_log_name = '/var/logs/django/test_%s.log' %now log_file = open(dynamic_log_name, "a") log_file.write(record.msg) log_file.close(); return True 'write_error_logs': { '()': 'django.utils.log.CallbackFilter', 'callback': write_dynamic_log, }, -
Django Rest Framework: Get singular object using the root API
I am trying to set up an API endpoint that returns a singular object. Right now I have: class ShoppingCartViewSet(viewsets.GenericViewSet, mixins.ListModelMixin): """ API endpoint that allows users to be viewed or edited. """ serializer_class = ShoppingCartSerializer authentication_classes = (TokenAuthentication,) permission_classes = (IsAuthenticated,) def get_paginated_response(self, data): return Response(data) def get_queryset(self): return ShoppingCart.objects.filter(user=self.request.user) Which uses the ListModelMixin and a filter to return one item, becasue each user has 1 shopping cart. The issue is the filter function returns a queryset, but I only want a single item. I attempted to use the RetrieveModelMixin but that doesn't run on the endpoint that I want. Retrieve runs on .../api/shopping-cart/id but I want to retrieve on .../api/shopping-cart because the filtering is done via the person who is logged in. Any solutions? -
django orm use inner jsoin use two table unique columns
I need to select from DB this data: Event e inner join FireMonitor f on e.event_id = f.event_id; Models in django: class Event(BaseModel): id = models.AutoField(primary_key=True) event_id = models.CharField(max_length=128, unique=True) receiver = models.CharField(db_column='Freceiver', db_index=True, max_length=512) class FireMonitor(BaseModel): id = models.AutoField(primary_key=True) event_id = models.CharField(max_length=128, unique=True) -
Update HTML text based on backend respond
I need to update html tag text, based on respond from backend. I am using Django server to run the app. In the backend, I am running a timer, measuring the amount of time, the process had taken. I need to get this amount of time to frontend, and display it. class Timer(): def __init__(self): self._start_time = datetime.datetime.now().replace(microsecond=0) print(self._start_time) def elapsed_time(self): return (datetime.datetime.now().replace(microsecond=0) - self._start_time).seconds urls.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.home, name='home'), url(r'^$', views.output, name='output') ] views.py: urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^$', views.home, name='home'), url(r'^$', views.output, name='output') ] And my html looks this so far: <td class="value" id="elapsed-time">00:00</td> <script> var urlMappings = { url_elapsed_time : "{% url 'output' %}" } $.ajax({ type: "POST", url: urlMappings.url_elapsed_time }).done(function(data){ console.log("Done"); }).fail(function(data){ console.log("Fail"); }); </script> So far, I am only getting 403 error message. Any help? -
butttons of copy excel pdf do not shown in views?
hello my friends i'm new in datatables and django i try to make tables with buttons of save export excel csv and pdf and field for search and paginations filters but tables is show and other things is hidden with no errors i download all datatables packages i put it in static folder and i will show you my code thank you for help {% extends 'base.html' %} {% load static %} {% block content%} <caption>listes des Immobilisations</caption> <table id ="table_id" class = "table table-bordered"> <head class = "alert-success"> <tr> <td>Code immob</td> <td>Designation</td> <td>Quantite</td> <td>Date mes</td> <td>Compte immob</td> <td>Duree de vie</td> <td>Num aut</td> <td>Origine</td> <td>fournisseur</td> <td>N° facture</td> <td>Date Facture</td> <td>Valeur HT</td> <td>Monaie</td> <td>Taux cvt</td> <td>Taux contre valeur</td> <td>Frais d'approche</td> <td>Cout d'acquisition</td> <td>Reference commande</td> <td>Date commande</td> <td>Journee</td> <td>Compte analytique</td> <td>Local</td> <td>Mode_amort</td> <td>Code_r</td> <td>Val_amort</td> <td>Status</td> <td>Code_bar</td> <td>Service</td> <td>Cni</td> </tr> </thead> <tbody> {% for immob in all_immobs %} <tr> <td>{{ immob.immo_code}}</td> <td>{{ immob.immo_desig}}</td> <td>{{ immob.immo_qte}}</td> <td>{{ immob.immo_datemes}}</td> <td>{{ immob.immo_cptimmob}}</td> <td>{{ immob.immo_dureevie}}</td> <td>{{ immob.immo_numaut}}</td> <td>{{ immob.immo_origine}}</td> <td>{{ immob.immo_origine}}</td> <td>{{ immob.immo_fournisseur}}</td> <td>{{ immob.immo_nufact}}</td> <td>{{ immob.immo_datefact}}</td> <td>{{ immob.immo_valht}}</td> <td>{{ immob.immo_monaie}}</td> <td>{{ immob.immo_tauxcvt}}</td> <td>{{ immob.immo_tauxctrval}}</td> <td>{{ immob.immo_frais}}</td> <td>{{ immob.immo_coutacq}}</td> <td>{{ immob.immo_refcmde}}</td> <td>{{ immob.immo_datecmde}}</td> <td>{{ immob.immo_journee}}</td> <td>{{ immob.immo_cptanal}}</td> <td>{{ immob.immo_local}}</td> <td>{{ immob.immo_mode_amort}}</td> <td>{{ immob.immo_code_r}}</td> <td>{{ immob.immo_val_amort}}</td> <td>{{ immob.immo_status}}</td> … -
Celery: Getting unexpected run_command() takes 1 positional argument but 318 were given error
I am attempting to run an async task and am getting an unexpected error: run_command() takes 1 positional argument but 318 were given. I have a list of commands that I want to run from a celery task. run_command.chunks(iter(commands), 10).group().apply_async() @task def run_command(commands): for command in commands: print("RUNNING, ", command) print("Pid: ", os.getpid()) os.system(command) As shown above, I am attempting to break down my command into batches that will be executed in parallel. Thanks for the help -
how to display foreign key related info in template
I have two model called organization and staff.Staff model have onetoone relation with user and Foreignkey relation to the organization.The problem what i got is to filter the staffs by their related organization.I have tried liked this but didn't worked out. models.py class Staff(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='user') name = models.CharField(max_length=255, blank=True, null=True) organization = models.ForeignKey(Organization, on_delete=models.SET_NULL, blank=True, null=True, related_name='organization') .....other fields..... views.py def view_staff_users(request): staff_users = User.objects.filter(is_staff=True) organizations = Organization.objects.all() staffs_by_org = Staff.objects.select_related('organization') # tried this also: # staffs_by_org = [] # print('staffff',staffs_by_org) # for organization in organizations: # staffs = Staff.objects.filter(organization=organization) # staffs_by_org.extend(staffs) # print('staaa',staffs_by_org) template {% for user in staffs_by_org %} # tried this also: {% for u in user.organization_set.all %} {{user.user.name}} {{user.username}} {{user.email}} {{user.user.organization}} {% endfor %} -
Django :- Very Important Question about creating Queryset and add data on it
Models: class MyTeam(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) match = models.ForeignKey(Match, on_delete=models.SET_NULL, null=True, related_name='match_set') mega_league = models.ForeignKey(MegaLeague, on_delete=models.SET_NULL, null=True, blank=True, related_name='mega_league_set') captain_first_team = models.ForeignKey(FirstTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_second_team_set") captain_second_team = models.ForeignKey(SecondTeamPlayer, on_delete=models.SET_NULL, null=True, blank=True, related_name="captain_second_team_set") team_player_first_team = models.ManyToManyField(FirstTeamPlayer, blank=True, related_name="team_player_first_team_set") team_player_second_team = models.ManyToManyField(SecondTeamPlayer, blank=True, related_name="team_player_second_team_set") First of all I need to add these captain_first_team & captain_second_team in one field (like add FirstTeamPlayer and SecondTeamPlayer in one field) . How? Views: def add_to_my_team_from_team_create(request, match_id): match = get_object_or_404(Match, pk=match_id) my_team = MyTeam.objects.create(match=match, user=request.user) return redirect('team_create', match.pk, my_team.pk) def team_create(request, match_id, team_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam, pk=team_id) first_team_player = match.first_team.first_team_player.all() second_team_player = match.second_team.second_team_player.all() context = { 'match': match, 'my_team': my_team, 'first_team_player': first_team_player, 'second_team_player': second_team_player, } return render(request, 'main/team_create.html', context=context) def add_first_team_player(request, match_id, team_id, player_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam.objects.filter(user=request.user, match=match.pk), pk=team_id) first_team_player = get_object_or_404(match.first_team.first_team_player, pk=player_id) my_team.team_player_first_team.add(first_team_player) return redirect('team_create', match.pk, my_team.pk) def remove_first_team_player(request, match_id, team_id, player_id): match = get_object_or_404(Match, pk=match_id) my_team = get_object_or_404(MyTeam.objects.filter(user=request.user, match=match.pk), pk=team_id) first_team_player = get_object_or_404(match.first_team.first_team_player, pk=player_id) my_team.team_player_first_team.remove(first_team_player) return redirect('team_create', match.pk, my_team.pk) In views, 1st I create a MyTeam using add_to_my_team_from_team_create function and then add data on the fields using add_first_team_player and also I can remove data from fields using remove_first_team_player. But I need the opposite one. … -
I want to store 8 digit random number in ID column of "auth_user" table in Django framework
Please help me, I don't want to create another column for that -
Using CheckboxSelectMultiple inside a form that uses input from DB related to User using ForeignKey. [See explaination]
I have a model called Level1 which is related to User model using ForeignKey class Level1(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) IT takes input from user and saves it in DB. I can get all the inputs that are given by the specific user by using user=request.user level1_answers=user.level1_set.all() (IF there is another method, please do share) Now what I want to do is to use these answers from level1 (level1_answers) and use them as an input for the Level2. Where Level 2 is a model same as Level1 with ForeignKey as User and ans except the fact that Instead of taking new answers as input, It uses the answers from level1 and presents the user with Checkboxes from those. class Level2(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) ans = models.CharField(max_length=1024) #I want ans to be presented as CheckboxSelectMultiple using Level1 answers. If user has answered 1,2,3,4,5,6,7 for Level1, I want to show Checkboxes to select from these and save this in DB in table Level2. -
Django application integration with Open edx LMS
We have a web application, Django https://sourceforge.net/p/schoolquiz/proctoringAPI/ci/master/tree/ I want to integrate that with the LMS of open edx https://sourceforge.net/p/schoolquiz/openedx/ci/master/tree/ I want to know how it can be done. -
How to use Global python environment instead of virtual on Azure App Service
I have a Django web app deployed on Azure App Service. I have integrated a bash script in it which is required for running some python notebooks for DataBricks. Problem is that when bash script is installing python packages in the virtual environment as expected but DataBricks notebook which it is calling is finding those packages in the global environment. I have tried deactivating the virtual inside bash script but that doesn't work. Is there any way to instruct azure app service to use global python environment instead of creating a virtual environment. Thanks