Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX POST Data does not appear to be hitting Django Rest Framework API Endpoint
I am trying to build a feature with AJAX and DRF whereby a user can follow another user. However when I initiate it, the POSTed data does not appear to be hitting the DRF endpoint so I am getting no errors beyond: {user: ["This field is required."], following_user: ["This field is required."]} following_user: ["This field is required."] user: ["This field is required."] Here is my js function: const followUser = function(followedUser){ var pathArray = window.location.pathname.split('/'); var currentUser = pathArray[1]; console.log("Following" + " " + followedUser); $.ajax({ type: 'POST', url: '/api/userconnections/', data: { csrfmiddlewaretoken: document.querySelector('input[name="csrfmiddlewaretoken"]').value, 'current_user': currentUser, 'followed_user': followedUser }, success: function(data) { alert('Successfully Followed') } }); } Here is my serializer: class UserConnectionListSerializer(serializers.ModelSerializer): user = serializers.StringRelatedField() following_user = serializers.StringRelatedField() class Meta: model = UserConnections fields = ['user','following_user'] class UserConnectionSerializer(serializers.ModelSerializer): class Meta: model = UserConnections fields = '__all__' And here is the views function: class UserConnectionsViewSet(viewsets.ModelViewSet): serializer_class = serializers.UserConnectionListSerializer queryset = UserConnections.objects.all() def get_serializer_class(self): """IF this is a form post, use the basic serializer that deals with id (primary key) otherwise give the more sophisticated version that deals with actual username""" if self.request.method == 'POST': return serializers.UserConnectionSerializer return self.serializer_class def follow_user(request): if request.method == "POST": data = {'user': request.DATA.get('current_user'), 'following_user': request.DATA.get('followed_user')} … -
django many to many query
I'm attempting to create an application that would help me store old music. These are my models. class ArtistGenre(models.Model): genre_name = models.CharField('Genre', max_length=20) def __str__(self): return self.genre_name def get_absolute_url(self): return reverse('genre_detail', kwargs={'pk': self.pk}) class ArtistTrait(models.Model): trait_name = models.CharField('Trait', max_length=20) def __str__(self): return self.trait_name def get_absolute_url(self): return reverse('trait_detail', kwargs={'pk': self.pk}) class Artist(models.Model): stage_name = models.CharField('Stage Name', max_length=255) real_name = models.CharField('Birth Name', max_length=255, blank=True) artist_genre = models.ForeignKey(ArtistGenre, on_delete=models.CASCADE) artist_trait = models.ManyToManyField(ArtistTrait) def __str__(self): return self.stage_name def get_absolute_url(self): return reverse('profile_artist', kwargs={'pk': self.pk}) My hang-up is properly querying the ArtistGenre and ArtistTrait models in order to create clickable links that would list all artists in a Genre or with a particular Trait. Do I have to create Many To Many fields in the Trait and Genre models that link to the artists or is there a way for me to query the it currently? Thank You! -
face recognition using django, opencv, and flutter
Hi I am new in django and python, right now I would like to develop face recognition. There are so many resources to access live camera webcam to do face recognition, but here I would like to access live camera from flutter and connect it with the django as backend. Is it possible to do that ? So far, I have been following this article to do face recognition in live webcam https://www.mygreatlearning.com/blog/face-recognition/ and I still don't know how to make connection between django and flutter video_capture = cv2.VideoCapture(0) while True: ret, frame = video_capture.read() gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(60, 60), flags=cv2.CASCADE_SCALE_IMAGE) rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) encodings = face_recognition.face_encodings(rgb) names = [] for encoding in encodings: matches = face_recognition.compare_faces(data["encodings"], encoding) name = "Unknown" if True in matches: matchedIdxs = [i for (i, b) in enumerate(matches) if b] counts = {} for i in matchedIdxs: name = data["names"][i] counts[name] = counts.get(name, 0) + 1 name = max(counts, key=counts.get) names.append(name) for ((x, y, w, h), name) in zip(faces, names): cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2) cv2.putText(frame, name, (x, y), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 2) cv2.imshow("Frame", frame) if cv2.waitKey(1) & … -
Get value from django field and change it dynamically
I have created two models with two fields which are quantity and quantity_given, so I want to change the value of quantity field by adding the value of quantity + quantity given. For example if quantity = 4 and quantity_given = 8 therefore the new value of quantity field will be 12. Here are the source code for my models class Stock(models.Model): `name = models.CharField(max_length=30)` def __str__(self): return self.name class Medicine(models.Model): stock = models.ForeignKey(Stock, on_delete=models.CASCADE) name = models.CharField(max_length=30) quantity = models.IntegerField() def __str__(self): return self.name class MedicineGiven(models.Model): medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE) quantity_given = models.IntegerField() -
NOT NULL constraint failed: jobs_job.created_by_id IntegrityError at /jobs/add/
I am trying to enable the user to be able to add job and after filling the form i got that error. Here is my code: models.py from django.db import models from django.contrib.auth.models import User class Job(models.Model): title = models.CharField(max_length=255) short_description = models.TextField() long_description = models.TextField(blank=True, null=True) created_by = models.ForeignKey(User, related_name='jobs', on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) changed_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .forms import AddJobForm from .models import Job def job_detail(request, job_id): job = Job.objects.get(pk=job_id) return render(request, 'jobs/job_detail.html', {'job': job}) @login_required def add_job(request): if request.method == 'POST': form = AddJobForm(request.POST) if form.is_valid(): job = form.save(commit=True) job.created_by = request.user job.save() return redirect('dashboard') else: form = AddJobForm() return render(request, 'jobs/add_job.html', {'form': form}) forms.py from django import forms from .models import Job class AddJobForm(forms.ModelForm): class Meta: model = Job fields = ['title','short_description','long_description'] What do i need to do to solve this error? I have try to remove the commit=True, from views.py and I have try to remove sqlite3 and do the migrations again. -
Django Rest Framework cannot add extra fields
I am new to Django. And I trying to work along with django-rest-framework (DRF from now on) to create an API so I can consume it from a React frontend. I am getting currently: AttributeError: Got AttributeError when attempting to get a value for field answers_set on serializer QuestionSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Question instance. Original exception text was: 'Question' object has no attribute 'answers_set'. But I have followed this question to add extra fields and this one to dig into that error. Still getting the same error. So, I have two models: Question class Question(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=250) description = models.CharField(max_length=1000) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=False, auto_now_add=True) Answer class Answer(models.Model): id = models.AutoField(primary_key=True) answer = models.CharField(max_length=1000) question = models.ForeignKey(Question, on_delete=models.CASCADE, default=None) created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now=False, auto_now_add=True) updated_at = models.DateTimeField(auto_now=False, auto_now_add=True) So I have two serializers: AnswerSerializer class AnswerSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ['answer', 'created_by', 'updated_at'] QuestionSerializer class QuestionSerializer(serializers.ModelSerializer): answers_set = AnswerSerializer(many=True) class Meta: model = Question fields = [ 'id', 'title', 'description', 'answers_set', 'created_by', 'created_at', 'updated_at', ] I guess this is the … -
Updating django form without prompting the user to enter their ID
So i'm working on job application portal. the logic is as follows : Applicant ---> Applies for ---> Job Models are (Job, User, Application) I used the User model from django and i extend it. Now the dilemma is when i render the ApplicationForm, because i have to update the foreign key and i want it to be updated automatically. Here is my code : Models.py class Job(models.Model): owner = models.ForeignKey(User,related_name='job_owner',on_delete=models.CASCADE) title = models.CharField(max_length=100) #location job_type = models.CharField(max_length=15,choices=JOB_TYPE) description= models.TextField(max_length=1000) published_at = models.DateTimeField(auto_now=True) vacancy = models.IntegerField(default=1) salary = models.IntegerField(default=0) experience = models.IntegerField(default=1) category = models.ForeignKey('Category',on_delete=models.CASCADE) icon = models.ImageField(upload_to ='job_icons/',default='job_icons/job.png') slug = models.SlugField(blank = True,null=True) class Application(models.Model): job = models.ForeignKey(Job, related_name="job_applied",on_delete=models.CASCADE) applicant = models.ForeignKey(User,related_name='job_applicant',on_delete=models.CASCADE) first_name= models.CharField(max_length=40) last_name= models.CharField(max_length=40) email = models.EmailField(max_length=60) website = models.URLField() cv = models.FileField(upload_to='application/') coverletter = models.TextField(max_length=550) application_date = models.DateTimeField(auto_now=True) def __str__(self): return self.last_name+"\t"+self.first_name Forms.py class JobApplication(ModelForm): class Meta: model = Application fields = ['first_name', 'last_name','email', 'website','cv','coverletter'] vews.py def job_detail(request,slug): job_specific = Job.objects.get(slug=slug) form = JobApplication(instance=request.user) if request.method == 'POST': form = JobApplication(request.POST,request.FILES) if form.is_valid(): my_form = form.save(commit=False) my_form.job = job_specific Application.applicant.user = request.user Application.job = job_specific my_form.save() context ={'job_specific':job_specific, 'form':form,} return render(request,"job/job_details.html",context) So once the user submit their application, i wanted to updated the fields that are … -
Creating a Reusable Chartjs Function
I have the following javascript Chartjs code which works well when I use it in a django template. However this template is for a dashboard and I need to recreate 7 of the same charts. As such, instead of recreating this code multiple times can I reconfigure it as a function of some kind and call it instead? var ctx_category_driving = document.getElementById('myChart_Category_Drving').getContext('2d'); var data = { // labels: ["Chocolate", "Vanilla", "Strawberry"], labels: {{ lbl_category_driving|safe }}, datasets: [ { label: "acceptable", // backgroundColor: "blue", data: {{ data_cat_driving_acceptable|safe }}, fill: true, // backgroundColor: "rgba(179,181,198,0.2)", backgroundColor: "#3cba9f", borderColor: "rgba(179,181,198,1)", pointBorderColor: "#fff", pointBackgroundColor: "rgba(179,181,198,1)", }, { label: "unacceptable", // backgroundColor: "red", data: {{ data_cat_driving_unacceptable|safe }}, fill: true, // backgroundColor: "rgba(255,99,132,0.2)", // backgroundColor: "rgba(216, 27, 96, 0.6)", backgroundColor: "rgba(216, 27, 96, 0.6)", borderColor: "rgba(255,99,132,1)", pointBorderColor: "#fff", pointBackgroundColor: "rgba(255,99,132,1)", pointBorderColor: "#fff", }, ] }; var myBarChart = new Chart(ctx_category_driving, { type: 'bar', data: data, options: { responsive: true, maintainAspectRatio: false, barValueSpacing: 20, scales: { yAxes: [{ ticks: { min: 0, } }] } } }); Once reconfigured how would I call it to make it reusable? Any help will be greatly appreciated as I am now learning Django and various web technologies. -
Django form fields
suppose I have one form like: RandonForm(forms.Form): field1 = forms.CharField(blablabla) field2 = forms.CharField(blablalba) And in my views I save this form: index(request): if request.method == 'POST': form = RandonForm(request.POST) form.save() return render(BLABLABLA, {"form": form}) how to return the form just with field1 filled -
Adding two factor authentication in Django/Django Rest
I know this topic has been widely discussed, but most of the examples are about two factor authentication in standard Django templates, while in my case i want to add two factor authentication to a project where Django is used as an API on the backend while the frontend is a native VueJS application. For eveything authentication related, i'm using the built-in Django session authentication, since both frontend and backend are deployed on the same server. My question is: how can i add two factor authentication (using google authenticator or yubikey) to a project where django is used as an API? Here is the problem: the easiest way to do this would be to let the user login from the frontend, and once the user is logged in from /accounts/login (built-in django authentication view), submit a form where the user has to input their code. The problem with this approach is that once the user is logged in Django will create a session, so request.user.is_authenticated will return True even though the user didn't submit the Two Factor code yet, so everything would depend on the frontend. I don't like this approach because i'm afraid that someone might find a way … -
Create with id and get nested structure does not work in django
I have spent already a couple of days researching about this issue in similar questions and I am not able to get a solution. This should be something simple, I have a model: model.py class Item(models.Model): """Class to represent an item...""" label = models.TextField(null=True) name = models.TextField() category = models.ForeignKey( "Category", on_delete=models.SET_NULL, null=True, default=DEFAULT_CATEGORY_ID) class Category(models.Model): """Class to represent the category of an Item. Like plants, bikes...""" name = models.TextField() description = models.TextField(null=True) view.py class ItemViewset(viewsets.ModelViewSet): # pylint: disable=too-many-ancestors """API Endpoint to return the list of items""" queryset = Item.objects.all() serializer_class = ItemSerializer serializer.py class ItemSerializer(serializers.ModelSerializer): """Serializer for Item.""" category = CategorySerializer(read_only=True) class Meta: # pylint: disable=too-few-public-methods """Class to represent metadata of the object.""" model = Item fields = [ 'id', 'label', 'name', 'category'] read_only_fields = ['id'] # def to_representation(self, instance): # ret = super().to_representation(instance) # ret['category'] = CategorySerializer(instance.category).data # return ret def create(self, request): # Look up objects by arbitrary attributes. # You can check here if your students are participating # the classes and have taken the subjects they sign up for. category = get_object_or_404(Category(), id=request.data.get('category')) serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(category=category) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) If I have the line category = CategorySerializer(read_only=True) commented the … -
Django dumpdata doesn't work with emoji in CharField or TextField
I have a model: class BlogPost(models.Model): description = models.TextField() I created a model instance and assigned it a description with an emoji: >>> BlogPost.objects.create(description='🙂') I run py manage.py dumpdata > data.json and it returns this error: CommandError: Unable to serialize database: 'charmap' codec can't encode character '\U0001f642' in position 1: character maps to <undefined> Exception ignored in: <generator object cursor_iter at 0x0000022F87CCC890> Traceback (most recent call last): File "C:\Users\zackp\.virtualenvs\django_wagtail_emoji_test-aUFzZHWp\lib\site-packages\django\db\models\sql\compiler.py", line 1609, in cursor_iter cursor.close() sqlite3.ProgrammingError: Cannot operate on a closed database. If I just run python manage.py dumpdata, it returns the output (in the command line) as expected. I'm runnning latest version of Django and Python 3.9.2. How do you make it to where you can export from an sqlite3 database to a .json file without that weird error? -
django project takes to base url on refresh?
Below is my web app project in django code it runs fine but when I refresh my page it takes me to the base url rather it should keep me on same page where I reloaded it. I tried to figure it out for quite some time now but is something not clicking to me. TIA. it should not take me to base url because this makes it very hard to share page with others. url.py from django.conf.urls import url from . import views urlpatterns = [ url( r'^new$', view=views.new_ui, name='product.new.ui'), url( r'^new/api/.*', view=views.new_api, name='product.new.api'), url(r'^uploader$', view=views.product_uploader_ui, name='product.uploader.ui'), url( r'^uploader/api/.*', view=views.product_uploader_api, name='product.uploader.api'), ] view.py @user_passes_test(lambda u: u.is_superuser) def product_uploader_ui(request): client = boto3.client('s3') BUCKET = 'tt' FILE_TO_READ = 'index.html' content_object = client.get_object(Bucket=BUCKET, Key=FILE_TO_READ) file_content = content_object['Body'].read().decode('utf-8') return render(request, 'product_uploader_ui.html', { "html" : file_content }) @login_required @user_passes_test(lambda u: u.is_superuser) def new_ui(request): client = boto3.client('s3') BUCKET = 'tt' FILE_TO_READ = '2/index.html' content_object = client.get_object(Bucket=BUCKET, Key=FILE_TO_READ) file_content = content_object['Body'].read().decode('utf-8') return render(request, 'new_ui.html', { "html" : file_content }) @csrf_exempt @user_passes_test(lambda u: True if stage == "local" else u.is_superuser) def new_api(request): # helpers method = request.method route = request.path.replace('/admin/product/new/api', '') print('new_api_audit_log', request.user, method, route) # a whitelist of allowed apis for new_ui to use if method … -
How to set up torsocks with postgresql
Hi When I try to run my Python program The program runs well with torsocks But when the program needs to connect to the database (postgresql) Gives an error and can not How to configure the tor so that our program can find the database? I use the postgresql Photo of Error: It does not matter if my program is a Django or I use a sqlalchemy Cannot find database at all -
How to show UTC time in local timezone in Django view?
I use UTC in my Django app and I want to display the time for my local timezone; 'Europe/Stockholm'. I just can't get this simple thing to work so I must be doing something wrong. I just can't figure out what it is... This is what I have in my settings.py: TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True And this is how I get the date that is passed to my template: my_time = datetime.datetime.utcnow() And finally this is what i have in my template file: {% load tz ‰} {% timezone 'Europe/Stockholm' %}{{ my_time|time }}{% endtimezone %} But whatever timezone I use in {% timezone ... %} the date always read the same 20:31, and the local time should in fact be 22:31. Thankful for any help with this! -
Basic Django urls (home : name not defined)
I'm getting the error : File "E:\2- Formations\1-Programmation\3- PYTHON\1- DASH\1- Apprentissage\dashsite\dashsite\urls.py", line 23, in <module> path('',include(home.urls)), NameError: name 'home' is not defined When I try to runserver / migrate. I'm sucepting a wrong setting cause it should work : My folders organisation Settings.py code which should alowwed my to use the home. : from pathlib import Path from django import apps BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'home.apps.HomeConfig', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'dashsite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'dashsite.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.1/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.1/howto/static-files/ STATIC_URL = '/static/' Project : urls.py (dir dashsite): from … -
Cannot have a SlugRelatedField to a FileField in a DRF Serializer?
I have a Model w/ a foreign-key relationship to another Model w/ a FileField. I am unable to serialize the 1st model using a serializer w/ a SlugRelatedField to the file of the 2nd model. Here is some code: models.py: class Foo(models.Model): name = models.CharField(max_length=100) bar = models.ForeignKey(Bar, blank=True, null=True) class Bar(models.Model): file = models.FileField(blank=True, null=True, upload_to="some_path") serializers.py: class FooSerializer(serializers.ModelSerializer): class Meta: model = Foo fields = ("name", "bar") bar = serializers.SlugRelatedField(read_only=True, slug_field="file") But when I try to serialize an instance of Foo I get the following sort of error: UnicodeDecodeError at /api/foo/1/ 'utf-8' codec can't decode byte 0xb5 in position 1: invalid start byte Any suggestions? -
Django: Move columns, fields from Child Model to Parent Model?
I currently have a Parent model and a few Child model classes that descend from it. Something like this: class ParentClass(django.db.models.Model) , class ChildClassA(ParentClass) , class ChildClassB(ParentClass) There are several fields that only exist currently on one of the child classes that I would like to exist on all of the child classes. Let's call those fields FieldX, FieldY, and FieldZ. One way I could handle this is by copying FieldX, FieldY, FieldZ to all of the child models. Which isn't a bad solution but is kind of annoying. Is there a good way to move the column/field to the ParentClass? Originally I was going to do it with three migration files: the first migration file would add the columns to the parent class, the second migration file would copy data over, the third would remove the columns from ChildClassA. However, that didn't work. Because Django is smart enough to detect that I was trying to add the same field name to the Parent Class that already exists on one of the Child classes. It raised a n exception for that: django.core.exceptions.FieldError: Local field 'FieldX' in class 'ChildClassA' clashes with field of the same name from base class 'ParentClass'. Instead … -
Django rest_framework returning Server error 500 on UnsupportedMediaType
New to Django REST. My API is supposed to work with JSON content-type. However, when I send a POST body of Content-type text, the API raises UnsupportedMediaType exception as expected, But the response contains 500 Server error instead of 415 Unsupported Media type. -
Django Inline Formset Field Required/Not Required Setting in View
How do I change a field of a inline formset from not required to required in the view? For example, for a form, it would be form.fields['field name'].required = True How do I replicate this setting for an inline formset? I tried formset.fields['field name'].required = True, but was given the error, 'formset' object has no attribute fields. -
How to use django selenium testing in GitHub actions?
I am creating a Django project and I have created a test case that inherits from django.test.LiveSeverTestCase (so it uses selenium): from django.test import LiveServerTestCase from selenium.webdriver.chrome.webdriver import WebDriver class FrontEndTestCase(LiveServerTestCase): @classmethod def setUpClass(cls): super().setUpClass() cls.selenium = WebDriver() cls.selenium.implicitly_wait(10) # Get the URL cls.selenium.get('http://127.0.0.1:8000/vota/') # Add CSRFToken cls.selenium.add_cookie({'name': 'csrftoken', 'value': '1cY4Yb3SljOqj9tUndW1YlIokNOD8tNc2MSU5iKNvsZW8co9WoOOCVGd5RFzxD8P'}) # Define page sections cls.choose_comps = cls.selenium.find_element_by_id('choose-comps') cls.poll = cls.selenium.find_element_by_id('poll-container') cls.end_table = cls.selenium.find_element_by_id('table-container') cls.navs = cls.selenium.find_elements_by_class_name('nav-link') @classmethod def tearDownClass(cls): cls.selenium.quit() super().tearDownClass() The tests are irrelevant to my problem, so I won't include them for the sake of longness. As you probably realize, for this test case to work, I have to start the server with python manage.py runserver. The problem here is that I want to use all these tests in GitHub Actions, and so far, I have, until creating this testcase. Since I have to start the server first, I made a new step in the job. But this step never ends since the server will always be listening for further requests. I also have to install somehow a chromedriver, a step I don't know how to do. Here is my ci.yml file: name: Testing on: push jobs: test_vote: runs-on: ubuntu-latest services: postgres: image: postgres:10.8 env: POSTGRES_USER: postgres … -
cant save ManyToMany field in django?
i have ManytoMany Field but everytime i save data in forms all data saved except this field (ManyToManyField) this is my views.py @login_required() def post_update(request,id): post = get_object_or_404(Post,id=id) form = PostForm(request.POST or None,request.FILES or None,instance=post ) if request.method == 'POST': if form.is_valid(): instance =form.save(commit=False) instance.user = request.user instance.save() form.save_m2m() messages.success(request, "You successfully updated the post") return redirect(reverse("home:post",kwargs={"id":post.id})) context={"form":form} return render(request,"post_update.html",context) and this is the Error: Internal Server Error: /post/update/4/ Traceback (most recent call last): File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "G:\Web Development\Back End\JustDjango\Build any blog with Django\Blog\blog\BlogApp\views.py", line 111, in post_update form.save_m2m() File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\forms\models.py", line 443, in _save_m2m f.save_form_data(self.instance, cleaned_data[f.name]) File "C:\Users\abdal\AppData\Local\Programs\Python\Python38-32\lib\site-packages\taggit\managers.py", line 543, in save_form_data getattr(instance, self.name).set(*value) TypeError: set() argument after * must be an iterable, not NoneType -
Django - create ForeignKey reference based on existing value in referenced model
models.py: class Thread(models.Model): title = models.CharField(max_length=400) discussion = models.URLField(max_length=250, unique=True, blank=True, null=True) ... class Comment(models.Model): thread = models.ForeignKey('Thread', null=True, on_delete=models.SET_NULL) thread_name = models.CharField(max_length=100) thread_link = models.URLField(max_length=250) ... addcomments.py: .... clean_comments = list(zip(thread_name, thread_link)) for thread_name, thread_link in clean_comments: # if thread_link exists in Thread model Comment.object.create( thread=???, thread_name=thread_name, thread_link=thread_link) # if not exists Comment.object.create( thread=Null, thread_name=thread_name, thread_link=thread_link) I want to create Comment object with ForeignKey referencing Thread object if the value of thread_link (Comment model) exists in Thread model (thread_link == discussion). If thread_link != discussion i want ForeignKey to be set to None. I'm thinking about for thread_name, thread_link in clean_comments: filtered = Thread.objects.filter(discussion=thread_link) if filtered: Comment.object.create( thread=???, thread_name=thread_name, thread_link=thread_link) else: Comment.object.create( thread=None, thread_name=thread_name, thread_link=thread_link) -
My views.py is returning null from django admin object
I would really appreciate some help on this because I'm completely stuck. I've started up a simple django app (trying to make an instagram clone). However, when I try to display the post objects (which I created in the django admin page) nothing is displayed in index.html, so I tried printing out the objects in the views.py and it's returning to me an empty query set. I don't quite understand what I'm doing wrong and why I can't access the objects? When I print out the username I am able to get that, but then nothing for both post and stream objects. Please I'm so stuck any advice would be appreciated. views.py from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.template import loader from django.http import HttpResponse # Create your views here. from post.models import post, stream @login_required # we are getting all of the string objects that are created for the user def index(request): user = request.user print(user) posts = stream.objects.filter(user=user) print(posts) group_ids = [] #then looping through and getting post id to a list for posted in posts: group_ids.append(posted.post_id) print(group_ids) #then filtering them so that you can display it in the index #selecting a specific post by … -
why am I receiving this error == Reverse for 'download_done' not found. 'download_done' is not a valid view function or pattern name
I'm trying to create a youtube downloader but when I'm trying to download it gives this error "Reverse for 'download_done' not found. 'download_done' is not a valid view function or pattern name." I have compared the app name and its corresponding, I have also checked the HTML file it looks okay please help me...its urgent views.py from django.shortcuts import render from pytube import YouTube import os # Create your views here. def youtubedownloader(request): return render(request, 'youtube_downloader.html') def download(request): global url url = request.GET.get('url') yt = YouTube(url) video = [] video = yt.streams.filter(progressive=True).all() embed_link = url.replace("watch?v=", "embed/") Title = yt.title context = {'video': video, 'embed': embed_link, 'title': Title} return render(request, 'download.html', context) def download_done(request, resolution): global url homedir = os.path.expanduser("~") dirs = homedir + '/Downloads' if request.method == "POST": YouTube(url).streams.get_by_resolution(resolution).download(dirs) return render(request, 'download_done.html') else: return render(request, 'errorrrr.html') urls.py from django.contrib import admin from django.urls import path from .views import youtubedownloader, download, download_done app_name = 'yt_downloader' urlpatterns = [ path('youtube_downloader/', youtubedownloader, name='youtube downloader'), path('youtube_downloader/download/', download, name='download video'), path('download/<resolution>/', download_done, name='download done') ] download.html {% extends 'base.html' %} {% block content %} <div class="container"> <h1> Title : {{title}} </h1> <div class=" mt-5 embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src={{embed}} allowfullscreen></iframe> </div> <table class="table"> <thead class="thead-light"> …