Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dash app in django-plotly-dash breaking migrate, how to stop it executing in a migrate?
I am using django-plotly-dash so have a Django template that hosts a Dash app. (The Dash app is using raw SQL queries over psycopg2) When I do a django migrate, this dash raw SQL fails because the tables have not yet been created. Thus halting the migrate. aka Catch22. Anyone know if there's a way to stop the Dash apps being executed during a migrate ? -
django-ninja endpoint for post
I am a beginner in programming, I use Django + Django ninja in my project. Now stuck on the moment of creating endpoints I'm trying to make a filter to add tags to an article and check if the tag exists. Here is the piece of code I'm currently working on: @router.post('/article', response={200: schema.ArticleOut, 500: schema.Error}) def create_article(request, tags_id: List[int], payload: schema.ArticleIn): try: for tag in tags_id: if tag > 0: qs = models.Article.objects.create(**payload.dict()) qs.save() current_article = get_object_or_404(models.Article, pk=qs.id) e = models.Tag.objects.get(pk=tag) current_article.tags.add(e) return 200, qs else: return 500, {'msg': 'No Tags'} except: return 500, {'msg': 'Not'} Tell me, does it make sense to do this in the request, if so, how best to implement it? Maybe there are other approaches? -
Dockerize exists Django Postgres project:on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432?
I have a django project using postgresql run in local host without any problem. And then I started to dockerize it: original settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'mydb', 'USER': 'myuser', 'PASSWORD': 'mypass', 'HOST': 'localhost', 'PORT': ' ', } } Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED 1 WORKDIR /app ADD . /app COPY ./requirements.txt /app/requirements.txt RUN pip install -r requirements.txt COPY . /app docker-compose.yml version: '3' services: web: build: . command: python manage.py runserver 0.0.0.0:8000 ports: - 8000:8000 Then I run: docker-compose build Image build successfully. Then I run : docker-compose up Error: conn = _connect(dsn, connection_factory=connection_factory, **kwasync) web_1 | django.db.utils.OperationalError: could not connect to server: Connection refused web_1 | Is the server running on host "localhost" (127.0.0.1) and accepting web_1 | TCP/IP connections on port 5432? web_1 | could not connect to server: Cannot assign requested address web_1 | Is the server running on host "localhost" (::1) and accepting web_1 | TCP/IP connections on port 5432? I know it is because container not able to connect with my local Postgresql db.What should I do,any friend can help? -
GitHub Actions with encrypted SECRET_KEY as environmental variable do not work
I don't have much experience in coding. I am currently writing a small Django application. Following all the rules, I do not want to place the SECRET_KEY in the repository, so I created the SECRET_KEY environment variable in the .bashrс file. And in the settings.py file I wrote: SECRET_KEY = os.environ.get ('SECRET_KEY') When I execute pylint --load-plugins pylint_django my_application in the terminal on my computer everything works. I get a response Your code has been rated at 9.88 / 10 Also I have workflow pylint.yaml to accomplish pylint-django tests on push trigger, when I send my files to my GitHub repo: name: Pylint on: [push] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - name: Set up Python 3.8 uses: actions/setup-python@v2 with: python-version: 3.8 - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Analysing the code with pylint run: | pylint --load-plugins pylint_django rm When I am pushing my files to GitHub, I reseive this: Run pylint --load-plugins pylint_django rm Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/pylint_django/checkers/foreign_key_strings.py", line 90, in open django.setup() File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/__init__.py", line 19, in setup configure_logging(settings.LOGGING_CONFIG, settings.LOGGING) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/conf/__init__.py", line 82, in __getattr__ self._setup(name) File "/opt/hostedtoolcache/Python/3.8.12/x64/lib/python3.8/site-packages/django/conf/__init__.py", line 63, … -
Could't Import Django: Are you sure it's installed and activated in your PYTHONPATH
I am trying to run django in python 3.6.8. When using pip freeze in my activated venv i get this list: asgiref==3.2.3 backports.entry-points-selectable==1.1.1 distlib==0.3.3 Django==3.0.8 django-bootstrap-datepicker-plus==3.0.5 django-crispy-forms==1.9.1 filelock==3.3.2 importlib-metadata==4.8.2 importlib-resources==5.4.0 mysqlclient @ file:///D:/Downloads/mysqlclient-1.4.6-cp36-cp36m-win32.whl Pillow==7.2.0 platformdirs==2.4.0 pytz==2020.1 six==1.16.0 sqlparse==0.3.1 typing-extensions==3.10.0.2 virtualenv==20.10.0 zipp==3.6.0 When i try to run my migrate.py file the following error: Traceback (most recent call last): File "manage.py", line 10, in main from django.core.management import execute_from_command_line File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\management\__init__.py", line 14, in <module> from django.core.management.base import ( File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\management\base.py", line 11, in <module> from django.core import checks File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\checks\__init__.py", line 8, in <module> import django.core.checks.caches # NOQA isort:skip File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\checks\caches.py", line 2, in <module> from django.core.cache import DEFAULT_CACHE_ALIAS File "C:\Users\never\envmon\airquality\django-venv\lib\site-packages\django\core\cache\__init__.py", line 15, in <module> from asgiref.local import Local ModuleNotFoundError: No module named 'asgiref' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 16, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? The virtual environment is activated. I tried setting up the PYTHONPATH in my environment variables with no success. I am using … -
Getting MultiValueDictKeyError on Django while trying to receiving a stripe hook
I am getting a django.utils.datastructures.MultiValueDictKeyError while trying to receive a stripe signal when a subscription's charge fails, Here is the traceback Traceback (most recent call last): File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/sentry_sdk/integrations/django/views.py", line 67, in sentry_wrapped_callback return callback(request, *args, **kwargs) File "/usr/lib/python3.7/contextlib.py", line 74, in inner return func(*args, **kwds) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/zebra/views.py", line 38, in webhooks request_data = json.loads(request.POST["request_data"]) File "/home/aditya/dev/cn/pmx_env/lib/python3.7/site-packages/django/utils/datastructures.py", line 80, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'request_data' [13/Nov/2021 09:36:29] "POST /zebra/webhooks/ HTTP/1.1" 500 121292 I am using django 2.2 Python 3.7.12 Thanks in advance for any solutions and suggestions. -
How to send user IP address from ListView to template?
i'm working on a blog project using django.I need to send User IP address from my class PostListView (which inheritance ListView class) to template, how can i do this ????? This is my signals.py from django.contrib.auth.signals import user_logged_in from django.contrib.auth.models import User from django.dispatch import receiver @receiver(user_logged_in,sender=User) def login_success(sender,request,user,**kwargs): print("____________________________") print("log in") ip = request.META.get('REMOTE_ADDR') print(" ip: ",ip) request.session['ip'] = ip I think i need to change in views.py, so what i need to add/change.... views.py class PostListView(ListView): model = Post template_name = 'blog/home.html' context_object_name = 'posts' ordering = ['-date_posted'] paginate_by = 5 def get_context_data(self,request, **kwargs): ip = request.session.get('ip',0) context = super().get_context_data(**kwargs) context['ip'] = ip return context Template <p>ip{{ip}}</p> I got a error from views.py -
How to get the param PK in django restframework permission?
I have this permission in Django that look like this: class PermissionName(BasePermission): def has_object_permission(self, request, view, obj): if request.method in SAFE_METHODS: return True #I want to extract the pk or id params in here. return False Can anybody help me get the params of request I tried using self.kwargs["pk"], request.POST['pk'] but they all return saying object has no attribute. -
ImproperlyConfigured: The included URLconf
I am trying to have all access all courses in my courses.urls but when i trying running my server, i am getting this error message. ImproperlyConfigured: The included URLconf '<module 'courses.urls' from 'C:\Users\USER\Desktop\jtalk_project\jtalks_institute\courses\urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Here is my code def course_list(request, category_slug=None): category = None categories = Category.objects.all() courses = Courses.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) courses = Courses.filter(category=category) return render(request,'courses/content/list.html', {'category': category, 'categories': categories, 'courses': courses}) def course_detail(request, id, slug): course = get_object_or_404(Courses, id=id, slug=slug, available=True) return render(request, 'courses/content/detail.html', {'course': course}) here is the code for my url project directory urlpatterns = [ path('admin/', admin.site.urls), path('', include('jtalks.urls')), path('signup/', user_signup, name='signup'), path('blog/', include('blog.urls', namespace='blog')), path('course/', include('courses.urls', namespace='course')), ] What could be the problem ? -
sessions in django not updating
i'm a beginner webdeveloper, and i have an issue. i'm building an e-commerce website following this tutorial on youtube. everthing was going fine until i was trying to access the session data through the session key onthe django shell. it was returning an empty dictionary even tho it's meant to return the product id and the price. the codes are down below the view from django.shortcuts import render from django.http import JsonResponse from django.shortcuts import get_object_or_404 from store.models import Product from .cart import Cart # Create your views here. def cart_summary(request): return render(request, 'store/cart/summary.html') def cart_add(request): cart = Cart(request) if request.POST.get('action') == 'post': product_id = int(request.POST.get('productid')) product_qty = int(request.POST.get('productqty')) product = get_object_or_404(Product, id=product_id) cart.add(product=product, qty=product_qty) response = JsonResponse({'test':'data'}) return response the cart.py class Cart(): def __init__(self, request): self.session = request.session cart = self.session.get('skey') if 'skey' not in request.session: cart = self.session['skey']= {} self.cart = cart def add(self, product, qty): product_id = product.id if product_id not in self.cart: self.cart[product_id]= {'price': str(product.price), 'qty':int(qty)} self.session.modified = True the script <script> $(document).on('click', '#add-button', function(e){ e.preventDefault(); console.log($('#select option:selected').text()) $.ajax({ type:'POST', url:'{% url "cart:cart_add" %}', data:{ productid: $('#add-button').val(), csrfmiddlewaretoken:"{% csrf_token %}", action: 'post' }, success: function (json){ }, error: function (xhr, errmsg, err){} }) }) </script> -
Using prefetch_related and aggregations to avoid n+1 issue with Django database queries for model with time series data
I am trying to avoid an obscene amount of database queries in a Django app. In the app I am monotoring a number of suggestions (model: Suggestion) that can be voted for (model: Vote). The Vote model does not store each individual vote. Instead the total number of votes for a suggestion are stored at regular intervals. A suggestion of "Better ice cream" could have "10 votes at 8:10", "12 votes at 8:20", "25 votes at 8:30", etc. I have created a very ineffecient loop with some major n+1 issues to calculate the number of new votes per day per suggestion. I am looking for a more efficient (probably single) queryset than the current ones for the same functionality. I know that I should probably create some kind of annotation by dates of votes on "suggestions" in views.py and then annotate that by my aggregate function that calculates the number of votes on each day, but I cannot figure out how to actually chain this together. Here's my current working but very inefficient code: models.py: class Suggestion(models.Model): unique_id = models.CharField(max_length=10, unique=True) title = models.CharField(max_length=500) suggested_date = models.DateField() class Vote(models.Model): suggestion = models.ForeignKey('Suggestion', on_delete=models.CASCADE) timestamp = models.DateTimeField() votes = models.IntegerField() … -
Not getting Django paypal IPN handshake
I am trying to implement Django- PayPal in my project , now it has been 3 days , I am still stuck on this , I don't understand how we perform IPN handshake, I am receiving a signal from PayPal after payment but what is the next step after this , really frustrated there are no clear docs about this process help needed , thanks in advance def show_me_the_money(sender, **kwargs): ipn_obj = sender if ipn_obj.payment_status == ST_PP_COMPLETED: verify_url = settings.VERIFY_URL_TEST print ('content-type: text/plain') print () print('SIgnal form paypal') param_str = sys.stdin.readline().strip() print(param_str) params = urllib.parse.parse_qsl(param_str) params.append(('cmd', '_notify-validate')) print(params) headers = {'content-type': 'application/x-www-form-urlencoded', 'user-agent': 'Python-IPN-Verification-Script'} r = requests.post(verify_url, params=params, headers=headers, verify=True) r.raise_for_status() print(r) # WARNING ! # Check that the receiver email is the same we previously # set on the `business` field. (The user could tamper with # that fields on the payment form before it goes to PayPal) if ipn_obj.receiver_email != settings.PAYPAL_RECEIVER_EMAIL: # Not a valid payment print('reciever mail is diff') print(ipn_obj.receiver_email) # ALSO: for the same reason, you need to check the amount # received, `custom` etc. are all what you expect or what # is allowed. # Undertake some action depending upon `ipn_obj`. if ipn_obj.custom == "premium_plan": … -
phone verification in django session or cookie for security purpose
i am trying to validate a user phone number in my website using twilio and django. but for some reason i am really concern about security risk.So my question is: What is the best to use cookie or session ?(i want to code validation to expire after 5 minutes) Will my code below will need some improvement for security reason ? views.py @login_required def show_phone_verification(request): form = NumberForm() if request.method == 'POST': form = NumberForm(request.POST) if form.is_valid(): request.session['number'] = form.cleaned_data.get('telephone') request.session['code'] = generate_code() return redirect('send_verify_code') return render(request,request.session['is_mobile']+'profile/phone_show.html',{'form':form}) @login_required def send_verify_code(request): form = CodeForm(request.POST or None) code = request.session.get('code',None) number_verify = request.session.get('number',None) if number_verify and code: if not request.POST: send_sms(number_verify,code) if form.is_valid(): del request.session['code'] del request.session['number'] number = form.cleaned_data.get('number') if number == code: obj, created = Phone.objects.update_or_create( user=request.user,is_verified=True, defaults={'phone': number_verify},) messages.success(request,'Your Number Has been verified.') return redirect('news') else: messages.success(request,'Your Number Has not been verified.Tried again.') return redirect('show_phone_verification') return render(request,request.session['is_mobile']+'profile/verify_code.html',{'form':form}) else: messages.success(request,'Access Refused') return redirect('news') Thanks. -
Add url to a field in TabularInline in Django admin
How can I make links from fields for TabularInline? For now I implement this (source: https://stackoverflow.com/a/10011307/9112151): class Post(models.Model): title = models.CharField(max_lenght=100) author = models.ForeignKey('User', on_delete=models.CASCADE) def add_link_field(target_model = None, field = '', link_text = unicode): def add_link(cls): reverse_name = target_model or cls.model.__name__.lower() def link(self, instance): app_name = instance._meta.app_label reverse_path = "admin:%s_%s_change" % (app_name, reverse_name) link_obj = getattr(instance, field, None) or instance url = reverse(reverse_path, args = (link_obj.id,)) return mark_safe("<a href='%s'>%s</a>" % (url, link_text(link_obj))) link.allow_tags = True link.short_description = reverse_name + ' link' cls.link = link cls.readonly_fields = list(getattr(cls, 'readonly_fields', [])) + ['link'] return cls return add_link @add_link_field('author') class PostInline(admin.TabularInline): model = Post Maybe there is built-in decision? -
django formset option value set to none
Gratings Developer, While working with Django I encounter a problem. Django formset give option value to none. <select name="form-1-model" id="id_form-1-model"> <option value="">---------</option> <option value="None" selected>option_1</option> <option value="None">option_2</option> models.py class orderlist(models.Model): # product_list.objects.a date=models.DateField(auto_created=timezone.now(),auto_now_add=True) sr=models.CharField(max_length=50) dealer=models.CharField(max_length=50,default=False) shopno=models.IntegerField() model=models.ForeignKey(product_list,blank=True,on_delete=models.CASCADE) quantity=models.IntegerField(default=None) def __str__(self): return self.model -
Django Celery IntegrityError
I want to create a progress bar for my project. I have a class and this class has some functions. Especially, one of them takes a long time (def download_all) and this is my main reason for wanting to create a progress bar. I successfully set up celery, celery-progress, etc. and they work all fine. My problem is this: I want to integrate the progress bar to download_all function. I It gives an error: IntegrityError at /o.../k... NOT NULL constraint failed: django_celery_results_taskresult.task_id How can I solve it? functions.py class myClass(): def __init__(self, n_user, n_password, n_url, n_port, db_password, username): ... self.download_all(n_user, n_password, n_url, n_port, db_password) ... @shared_task(bind=True, name="my_add") def download_all(n_user, n_password, n_url, n_port, db_password) ... len_scans = len(scans) progress_recorder = ProgressRecorder(self) for s in scans: i = 0 progress_recorder.set_progress(i + 1, len_scans) i += 1 views.py def setup_wizard(request): ... functions.Zafiyet(setup.n_username, setup.n_password, setup.n_url, setup.n_port, setup.db_password, username=request.user.username) traceback Environment: Request Method: POST Request URL: http://127.0.0.1:8000/operasyonmerkezi/konfigurasyon Django Version: 3.2.7 Python Version: 3.9.6 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard', 'accounts', 'logs', 'crispy_forms', 'django_apscheduler', 'easy_timezones', 'django_celery_results', 'celery_progress'] 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'] Traceback (most recent call last): File "C:\Users\edeni\Desktop\hawkdragon\myvenv\lib\site-packages\django\db\models\query.py", line 581, in get_or_create return self.get(**kwargs), False File "C:\Users\edeni\Desktop\hawkdragon\myvenv\lib\site-packages\django\db\models\query.py", line … -
Error zincrby() got multiple values for argument 'amount'
r.zincrby(name=self.get_product_key(product_id), amount=1, value=with_id) The func where the error occurs. I dont know why amoun get multiple values if I pass all arguments by their names. Code of func zincrby: def zincrby(self, name, amount, value): "Increment the score of ``value`` in sorted set ``name`` by ``amount``" return self.execute_command('ZINCRBY', name, amount, value) Func get_product_key return string Code from the book Django 2 in exapmles: def products_bought(self, products): product_ids = [p.id for p in products] for product_id in product_ids: for with_id in product_ids: # Take products bought with this if product_id != with_id: # Increase their rating r.zincrby(self.get_product_key(product_id),with_id,amount=1) If not difficult, you can explain what each zincrby function argument is responsible for.I understand that after performing this function, I will have a rating for each product with the most frequently purchased products with this product. The code itself is from the recommendation service. -
Pass request.user parameter to modelformset_factory form
So I've a formset tied to a model and one of the fields in that is ForeignKey. models.py class Squad(models.Model): rid = models.AutoField(primary_key=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return self.team.tname forms.py class SquadForm(ModelForm): class Meta: model = Squad def __init__(self, logged_user, user, *args, **kwargs): super(SquadForm, self).__init__(*args, **kwargs) self.fields['team'] = forms.ModelChoiceField(queryset=Team.rows.get_my_teams(user=logged_user), empty_label="None") As you can see, the __init__ function is expecting an extra parameter logged_user which I'm hoping to pass via the views.py file. But if I do the following: views.py def choose_teams(request): teamformset = modelformset_factory(Squad, extra=2, form=SquadForm(request.user)) form = teamformset(queryset=Squad.objects.none()) return render(request, 'foo.html', {'form':form}) I'm trying to pass the logged in user as a parameter on line 2 but this is resulting in the following message: Field 'id' expected a number but got 'SquadForm' Not sure what I'm missing here. But if I remove the parameter from line 2: teamformset = modelformset_factory(Squad, extra=series.team_number, form=SquadForm) it starts working (of course, I no longer expect the user in the forms.py file and remove it too) but shows all the data and not filtered one. -
Django using PostgreSQL - duplicated indexes
I'm using Django over PostgreSQL, and I'm having trouble understanding how to use indices correctly to achieve the best performance. This is an example Model: class SomeObject(BaseAggModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) element = models.ForeignKey(Element, on_delete=models.PROTECT, db_index=True) city = models.ForeignKey(City, on_delete=models.PROTECT, db_index=True) date_created = models.DateTimeField(null=True) class Meta: unique_together = ('element', 'city', 'date_created') indexes = [ models.Index(fields=['city ', 'element']) ] My questions are regarding how to change the indices to have as few indices as possible but maintain the best performance possible. Since I have the unique_together, and element is the first entity in that index. Does it necessarily mean that I can change the element field to have db_index=False since I already have a combined index to this field? Since I have the index over city and element together, and city is the first entity in this index. Does it necessarily mean I can change the city field to have db_index=False since I probably don't need a dedicated index for it? Alternatively (instead of doing the previous changes mentioned), since I have the unique_together and also the Index. If I will reorder the unique_together to be over (city, element, date_created), will it make the index over (city, element) redundant and … -
Set a limit for forms with the same value Django
So what I want to do is to set a limit of forms with the same value. There are different activities from a foreign model to which students can apply. I have name(naam), student number(studentnummer), activity(activiteit) and class(klas), and I want to set a limit of 10 forms with the same activity (max of people who can do the same activity) and a limit of 1 for student number (so students can only apply for one activity). models.py class Klas(models.Model): klas = models.CharField(max_length=8) def __str__(self): return f"{self.klas}" class Activiteit(models.Model): titel = CharField(max_length=64) docent = CharField(max_length=32) icon = models.ImageField() uitleg = models.TextField() def __str__(self): return f"{self.id}:{self.titel}:{self.docent}" class Aanmelden(models.Model): naam = CharField(max_length=32) studentnummer = IntegerField() klas = ForeignKey(Klas, on_delete=models.CASCADE, default=None, blank=True) activiteit = ForeignKey(Activiteit, on_delete=models.CASCADE, default=None, blank=True) def __str__(self): return f"{self.id}:{self.naam}:{self.studentnummer}" views.py def home(request): activiteiten = Activiteit.objects.all() form = AanmeldenForm() if request.method == 'POST': form = AanmeldenForm(request.POST) if form.is_valid(): form.save() return render(request, 'home.html', { 'activiteiten': activiteiten, 'form':form, }) forms.py class AanmeldenForm(forms.ModelForm): class Meta: model = Aanmelden fields = ( 'naam','studentnummer','klas','activiteit' ) If you know how to solve this or have a better idea of doing this kind of system please let me know. Thanks in advance!! -
User model and User auth (Django and mysql)
I am new to py web dev. I am using django and mysql for my web app. My app works but i am not able to maintain the login session. after each query on main page it redirect me to login page. The reason for that is im not using the django User auth system instead i wrote my own auth code inside ```view.py ``` def login(request): if request.method == "POST": form = Studentlogin(request.POST) if form.is_valid(): email = form.cleaned_data.get('email') password = form.cleaned_data.get('password') try: currstudent = students.objects.get(email=email, password=password) expense = sublist.objects.all() return render (request, 'subscrap/main.html', {'student': currstudent, 'sublist': expense }) except: messages.success(request, 'Error, either Email or Password is not correct') pass else: form = Studentlogin() return render(request, 'subscrap/login.html', {'form': form}) the login data is only accessible inside the login function and I have to call it every time to render and see an updated main.html. I searched on the web and the clue I got was that it might be because my user model aka(class students) is not actually built like a user model. I am a newbie to the py syntax and web dev on it and confused about how to implement Django user auth and save my info in … -
DJANGO Passing markdown into template
I have attempted to pass a markdown text into the html template. I have also disabled autoescaping within the html template but there is still an error when attempting to render the html template page. Could the safe filter not be working? views.py content = util.get_entry(title) if content: return render(request, "encyclopedia/entry_page.html", { "title": title, "entry": markdown.markdown(content) }) else: return render(request, 'encyclopedia/404.html', status=404) entry_page.html {% block title %} {{ title }} {% endblock %} {% block body %} {{ entry|safe }} <br> <a href="{% url 'edit_page' title=entry %}">Click here to edit the page.</a> {% endblock %} -
What is the best topic to research in M Tech for a programming lover [closed]
What is the best topic to research in M Tech for a programming lover. I love to code. Angular, Django, Python etc. I do enjoy coding. But now I am stuck in M tech and I have to do a research, and I am having a very hard time to select the topic. Help! -
How to populate a dropdown from another dropdown's selected value in Django
I have 2 models, one model is of the users and another of videos. user_id is acting as a foreign key for the videos model. I have created 2 dropdowns using the select/option tags. models.py class Users(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Videos(models.Model): user = models.ForeignKey(Users,on_delete=CASCADE) def __str__(self): return self.user.name I have populated the first dropdown by retrieving all the users from the DB and sending them to the template in views.py. What I want is, as soon as I select one of the users in the first dropdown all the videos corresponding to that particular user should appear as options in the second dropdown. <div class="mb-3"> <label class="py-1" for="Select_participant">Select Participant:</label> <select name = "selected_user" class="form-select" required aria-label="select example"> {% for user in users %} <option value="{{user.id}}">{{user.name}}</option> {% endfor %} </select> </div> <div class="mb-3"> <label class="py-1" for="URL">Select Video:</label> <select class="form-select" required aria-label="select example"> <option value="/path">video1</option> </select> </div> I am not able to figure out to achieve this. I was thinking like first sending the value of the selected user to the backend, and then filtering the videos w.r.t that particular user and then again rendering the template, but it will become much complex. Are there any easy … -
Django related objects reference remove(obj, bulk=False)
I've tried to use related manager remove() method with bulk=False but no success.Can anyone tell me what happened and where is mistake ? Thanks. In order to use remove(obj, bulk=False) I created models like Then I tried method itself in interactive shell like bellow: I've created musician object created album object with Foreign key to musician object but I didn't save it I called related manager on musician object to remove album from relation with option bulk=False => I expected that this will call save on my album object and than remove foreign key relation but nothing happened, album wasn't saved nor relation on musician was removed. I expected the final call to album to give me <Album: First album None> and album to be saved in data base but it didn't happen. The same procedure implemented on add(obj, bulk=False) yield expected results add(album2, bulk=False) saved my alabum2 and added reference to musician object