Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to include the start date and end date while filtering in django
views.py if request.method == "POST": from_date = request.POST.get("from_date") f_date = datetime.datetime.strptime(from_date,'%Y-%m-%d') print(f_date) to_date = request.POST.get("to_date") t_date = datetime.datetime.strptime(to_date, '%Y-%m-%d') print(t_date) check_box_status = request.POST.get("new_records", None) print(check_box_status) drop_down_status = request.POST.get("field") print(drop_down_status) if check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) The following code get_records_by_date = Scrapper.objects.filter(start_time__range=(f_date, t_date)) is unable to include the t_date. Is there any solution to include the t_date. -
Object created in view isn't rendering in template
I'm creating a new object in a view through an external function. This is the code: def index(request): sousei = suii_scratch(SOUSEI_URL) s_jikan = sousei[0] s_suii = sousei[1] sousei_obj = Sousei.objects.create(jikan=s_jikan, suii=s_suii) #print(sousei_obj) context = { sousei_obj : 'sousei', } return render(request, 'index.html', context) The external function is returning two values, that are being catched in s_jikan and s_suii variables. These variables are then used to create a new object (the model has only this two fields). If I uncomment the print statement, I get printed the __str__ method of the model with the newly obtained data from the external function. Also, if I check the admin, the new record in the database is beign saved correctly. Until here seems everything is working fine, but when passing the created object to the template I can't get it rendered. This is template code: {% if sousei %} <p>{{sousei.jikan}}</p> <p>{{sousei.suii}}</p> {% else %} <p>No data.</p> {% endif %} But I keep getting there is no data. What am I missing? -
How to create a class that can handle request data
I will have a input data that look like this (will be POST by postman) { "COMMAND_ID":"56789", "CARRIER_ID":"HF2202109W061", "CURR_GRP":"", "CURR_DEV":"", "CURR_LOC":"FAKE1-1", "DEST_GRP":"", "DEST_DEV":"", "DEST_LOC":"FAKE2-1", "MOVE_PRIORITY":"50" } and my views.py look like this class PalletMoveAPI(APIView): authentication_classes = [SessionAuthentication , BasicAuthentication] permission_classes = [IsAuthenticated,] def post(self,request,format=None,*args,**kwargs): try: inputdata = request.data testdata= { "DATAID":"", "CommandID":inputdata["COMMAND_ID"], "Priority":inputdata["MOVE_PRIORITY"], "Replace":0, "VehicleID":"", "CarrierID1":inputdata["CARRIER_ID"], "WCount1":inputdata["WAFER_QTY"], "SourcePort1":inputdata["CURR_LOC"], "DestPort1":inputdata["DEST_LOC"], "CarrierID2":"", "WCount2":"", "SourcePort2":"", "DestPort2":"" } pallet_move = requests.post('http://10.13.10.43:10000/api/command/send',json= testdata) if pallet_move.status_code in [HTTPStatus.OK,HTTPStatus.CREATED]: event = Post_successed() return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) except Exception as e: event = Error(str(e)) return JsonResponse({"code":event.code,"detail":event.description},status=event.status,safe=False) how can i create a class or function to handle to include the request part. like i wan to make that part reusable. a class that can take in request data and then return as the 'testdata' format shown above -
DRF CreateModelMixin with additional fields
I'm using GenericAPIView with the CreateModelMixin to create a model instance. I need my serializer to add additional fields that aren't defined by the user. My Serializer.create method is already set up for this, but I don't know how to pass fields through to the CreateModelMixin.create method. Here's a minimal version of what I have: class Foo(mixins.CreateModelMixin, generics.GenericAPIView): permission_classes = [IsAuthenticated] def get_serializer_class(self): return FooSerializer def post(self, request): return self.create( request, requester=request.user # Additional field ) This doesn't work - the requester field isn't passed to FooSerializer.save, so FooSerializer throws an error when it attempts to access requester in FooSerializer.create. Before, I was using APIView and calling the serializer directly, so I could simply: serializer = FooSerializer(data=request.data) if serializer.is_valid(): foo = serializer.save(requester=request.user) Is there any way to achieve this with the GenericAPIView? I want to embrace DRF's DRY-ness and avoid calling serializers in every endpoint method. -
Why do I keep getting 403 error in Django after using csrftoken in Ajax POST call?
I am doing an Ajax POST request to get news articles. I have put a csrftoken in the headers, but I still keep getting a 403 error. I have looked online and have tried many solutions, but I keep getting a 403 error. Why is this? $('#search-articles').on('submit', function(event) { event.preventDefault(); document.getElementById("loading").style.display = "block"; document.getElementById("search-bar").style.display = "none"; document.getElementById("articles").style.display = "none"; function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = jQuery.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } $.ajax({ url: "{% url 'stocks_sites:get_news_articles' %}", type: "POST", data: { "q": document.getElementById("search-articles").value, csrfmiddlewaretoken:$("input[name=csrfmiddlewaretoken]").val() }, headers: { "X-CSRFToken": getCookie("csrftoken"), // don't forget to include the 'getCookie' function }, success: function(response) { document.getElementById("loading").style.display = "none"; document.getElementById("search-bar").style.display = "block"; document.getElementById("articles").style.display = "block"; $("#search-bar").html(response[0]); $("#articles").html(response[1]); } }) }) -
Django, pandas, excel: uploading files, parsing them with pandas in Django
I have a big command-line script for parsing data in Excel (with pandas) and I want to wrap it with Django. I've tried both uploading files thru request.FILES and pandas, but get stuck on uploading file and, for example, saving it (not necessarily but just to check the upload for now). Haven't had any problems with other apps on Django which didn't require uploading and parsing anything external and thought that would be much easier..:) I've also tried Redirecting, doesn't really work, the only redirect which is actually happening is action in the form tag.. Here are the code snippets: views.py: def uploads(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): excel_file = request.FILES['document'] excel_file.save() return render(request, 'index.html') else: form = DocumentForm() return render(request, 'index.html', {'form': form}) models.py class Document(models.Model): document = models.FileField(upload_to="files/") forms.py: class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('document', ) index.html: <form action="{% url 'reports'%}" method="post" enctype="multipart/form-data" > {% csrf_token %} <span> Upload .xlsx file <input type="file" name="document" /> </span> <button type="submit"> SUBMIT </button> </form> -
How to use objects.create to add a file field from dataframe.to_csv?
I have used this code to try to add a dataframe.to_csv to a django db FileField, but it only works when I dont specify its path, so anyone know how to overcome this, I must specify its path and name it. Thats my code df = pd.DataFrame(profile_names, columns=['username', 'followers', 'tweets', 'hashtags', 'MostRecent']) Scrape.objects.create( user=request.user.profile, name=keyword, csvfile=df.to_csv(f'./static/assets_new/CSV/{request.user} - {keyword}.csv') ) Im trying to add a csv file to django db filefield, but nothing gets added instead -
Django query working locally but not in production
I have created a query in django that I am passing in an ID and receiving and object back from my model. On my local machine it works as expected. When I am trying to use it in my staging environment it is not returning any data but I have confirmed that the data exists in my database and have printed out all of the requests to make sure I am passing the information properly. When printing out my query I receive "<SoftDeletableQuerySet []>" in my AWS logs. I've tried logging everything, I've confirmed that the data exists. I've recreated everything so that it is the same in production as it is in my local environment. At this point I am not sure how to troubleshoot this anymore. code below for reference class GetStripeCustomer(rest_framework.generics.ListCreateAPIView): permission_classes = () serializer_class = serializers.StripeSerializer def get_queryset(self, *args, **kwargs): print('getting user stripe info', self) print('self.request', self.request) print('self.request.user', self.request.user) print('user_id', self.request.user.id) # print('user_id', self,request.user['id']) user = models.Stripe.objects.all().filter(user_id=self.request.user.id) print('user', user) for customer in user: print('customer', customer) # if (self.request.user.id == None): print('this should have the user', models.Stripe.objects.all().filter(user_id=self.request.user.id)) # return models.Stripe.objects.all() # else: return models.Stripe.objects.all().filter(user_id=self.request.user.id) -
AttributeError: 'function' object has no attribute 'split_contents'
im trying to set swagger in my django restAPI by this guide: https://krakensystems.co/blog/2017/swagger-integration-with-django-rest-framework but i get an error : `AttributeError: 'function' object has no attribute 'split_contents' can anyone help me? in my pycharm the import is not beeing used so idk how that make sense from rest_framework.documentation import include_docs_urls schema_view = get_swagger_view(title="Swagger Docs") url(r'^docs/', schema_view) try install swagger -
Django file structure with react
I am new to Django and react. I am following the guide below and I have run into an issue. I think my file structure is the issue. The Guide I am following The file structure in the guide is ├── manage.py ├── mysite │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp <----- a normal Django app │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── assets <----- our front-end project source │ ├── javascript │ └── styles ├── static <----- our front-end project outputs (and other Django static files) │ ├── css │ ├── images │ └── js └── templates <----- our Django template files └── myapp and my file structure is: |myproject ├── manage.py ├── .gitignore ├── package-lock.json ├── package.json ├── webpack.config.js │ ├── node_modules │ ├── ..... ├── myproject │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── myapp │ ├── __init__.py │ ├── models.py │ ├── urls.py │ └── views.py ├── js │ ├── index.js ├── static │ ├── css │ ├── images │ ├── js | ├── index-bundle.js └── templates ├── myapp ├── hello_webpack.html I have followed the guide step by … -
Django How to call a function inside template with credential arguments?
I have a function which gets all email addresses from a mail server. Currently I have 3 variables stored in my .env file (host, email and password) for each mail server (I have 3 different) and then writing the function FOR EACH MAILSERVER. On the template, I have 3 buttons that get emails from the 3 mail servers, each button different function. This was done in testing but now I'd like to have the 3 buttons in my Django template to call just ONE function with different credentials (stored on my .env file). Is there any way to call one function with different parameters from my django template? -
Django Custom Commands: Will writing to SQLite DB with a custom command while the server is running fail due to File Lock?
I would like to keep the django server running as I call some custom commands that will read / write to the sqlite DB. However I'm nervous that this may conflict due to the main server locking the database file. Is this cause for concern ? I can't use PostgreSQL or MySQL. I tried this and it didn't throw any errors, however I would like to know if this is something that can occur. -
Why is Django test cases checking actual DB and raising IntegrityError instead of just running in-memory?
When I run my tests with the DB empty (the actual application DB), everything goes fine. But when the DB has data, Django raises an IntegrityError for basically every test. The stact trace looks like the following (but for every test): ====================================================================== ERROR: test_api_get_detail (core.projects.tests.test_project_api.ProjectConfidentialPrivateAPITests) Getting confidential object via API (GET) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 299, in _setup_and_call self._post_teardown() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 1199, in _post_teardown self._fixture_teardown() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/test/testcases.py", line 1461, in _fixture_teardown connections[db_name].check_constraints() File "/Users/ramonkcom/Desktop/management/management-backend/venv/lib/python3.10/site-packages/django/db/backends/sqlite3/base.py", line 383, in check_constraints raise IntegrityError( django.db.utils.IntegrityError: The row in table 'custom_fields_customfield' with primary key '1' has an invalid foreign key: custom_fields_customfield.definition_id contains a value '1' that does not have a corresponding value in custom_fields_customfielddefinition.id. At first I thought this was a problem with my fixtures. But they work just fine to set up the application basic data. The DB seems to be the key issue: if it has data, the tests crash, if it's empty, the tests work. The most weird part is that the error being raised doesn't match with reality, and by that I mean: the CustomFieldDefinition object with pk=1 exists in the DB. Anyway, it shouldn't matter, since I expect Django to build an in-memory DB … -
Django: Force create index on ForeignKey fields when db's `supports_foreign_keys=False`
I'm trying to use Django (v4.1.3) with Planet Scale's DB which is MySQL compliant with the relevent exception of not supporting foreign keys. For this, they provide a Django DB driver which subs class the MySQL DB feature class from django.db.backends.mysql.features import \ DatabaseFeatures as MysqlBaseDatabaseFeatures class DatabaseFeatures(MysqlBaseDatabaseFeatures): supports_foreign_keys = False Given this, when I generate migrations and apply them on my local MySQL server, I don't see any foreign keys being created as expected. However, I also don't see keys being created but I still want the keys. For example with the MySQL driver, when I run SHOW CREATE app_user_groups (from django.contrib.auth package) I see the following key: CREATE TABLE `auth_group_permissions` ( ... KEY `auth_group_permissio_permission_id_84c5c92e_fk_auth_perm` (`permission_id`), ) But with the Planet Scale driver (supports_foreign_keys = False), Django doesn't create an key/index. I know in my models, I can explicitly define keys but I don't find this ideal. In addition, I don't have control over models from other Django apps like django.contrib.auth and many other 3rd party ones. What can I do to make Django create keys on django.db.models.ForeignKey despite support for foreign keys being off. -
Understanding permissions in Django
I trying to understand permissions in Django. In the points below I wrote what I was able to find on this issue and how I understand it. Maybe someone will be able to tell me if I am thinking correctly or if it works in a different way. I will be grateful for additional articles on this topic. Thanks! 1. APIView with built-in permissions Django has some built-in permissions that we can use in APIView through permission_classes. class OrderView(APIView): permission_classes = [permissions.IsAuthenticated] We can add the following built-in permissions to permission_classes, because they don’t have has_object_permission: AllowAny, IsAuthenticated, IsAuthenticatedOrReadOnly, IsAdminUser, DjangoModelPermissions, DjangoModelPermissionsOrAnonReadOnly 2. APIView with custom permissions Let’s say that we want to use the custom permission from the point 1 in APIView. Can we use permission_classes in that case? class OrderView(APIView): permission_classes = [permissions.IsAuthenticatedAndOwner] I don’t know which object will be sent to has_object_permission and how to do it. Is it a good way? def has_object_permission(self, request, view, obj): # <-- obj return obj.user == request.user 3. APIView with check_permissions and check_object_permissions. I am a little confused about the methods. If I understood correctly these methods are used to call has_permission and has_object_permission from APIView? Is there a different … -
Django: Using F expression of an IntegerField to annotate a DateField
I have a model like this: class RentDue(models.Model): balance = DecimalField() day_due = IntegerField() # e.g. 1-5, representing the 1st through 5th of the month I want to be able to annotate a queryset using the integer from day_due to create a new attribute rent_due_date so that I can filter on the next month's due date like this: from datetime import date, timedelta # create RentDue instances -- one due on the 1st another on the 3rd rent_due_first = RentDue.objects.create(day_due=1) rent_due_third = RentDue.objects.create(day_due=3) # query for all RentDue on the 1st or earlier RentDue.objects.annotate( rent_due_date=date(2022, 12, F('day_due')) ).filter( rent_due_date__lte=date(2022, 12, 1) ) # -> returns [rent_due_first] # query for all RentDue on the 3rd or earlier RentDue.objects.annotate( rent_due_date=date(2022, 12, F('day_due')) ).filter( rent_due_date__lte=date(2022, 12, 3) ) # -> returns [rent_due_first, rent_due_third] However, passing in the F expression to date raises TypeError: an integer is required (got type F) I've tried using ExpressionWrapper as laid out in this answer as well as TruncDate but I'm getting some weird errors I don't quite get. A possible solution would be to annotate the entire queryset with DateField of next_month (hard-coded to date(2022, 12, 1) and then being able to use that in an F … -
How to display a list of children objects on detail view for Django Admin?
I have two models: Setting and SettingsGroup. When someone clicks on a specific SettingsGroup in the Django Admin and the edit/detail page appears I'd like for the child Setting objects to be displayed but as a list not a form. I know that Django has InlineModelAdmin but this displays the children as editable forms. My concern isn't with the child objects being editable from the parent object but rather the amount of space it consumes. I'd rather have a list with either a link to the appropriate child record or that changes a particular object to be inline editable. Here is my Setting model: class Setting(models.Model): key = models.CharField(max_length=255, blank=False) value = models.TextField(blank=True) group = models.ForeignKey('SettingsGroup', blank=True, on_delete=models.SET_NULL, null=True) def __str__(self): return str(self.key) And the SettingsGroup model: class SettingsGroup(models.Model): name = models.CharField(max_length=255) description = models.TextField(blank=True) def __str__(self): return str(self.name) The method I don't want to use (or need to find a different way to use) is InlineModelAdmin which appears in my admin.py currently as: class SettingsGroupInline(admin.StackedInlin): model = Setting fk_name = 'group' @admin.register(SettingsGroup) class SettingsGroupAdmin(admin.ModelAdmin): inlines = [ SettingGroupsInline, ] Here is an example of how I'd like it to work: There is a MySettings object, an instance of the … -
Docker nginx service can't communicate with Django service and returning Bad Request 400
My nginx Docker container can't seem to communicate with my Django WSGI app container. It works locally but when I deploy it to Linode I get Bad Request (400) Project Structure Project ─ Dockerfile ─ docker-compose.yml ─ entrypoint.sh └── app ── wsgi.py ── settings.py ── urls.py ── <other django apps> └── nginx ── Dockerfile ── nginx.conf docker-compose.yml: version: '3.3' services: web: build: context: . dockerfile: Dockerfile command: gunicorn app.wsgi:application --bind 0.0.0.0:8000 expose: - 8000 env_file: - ./.env depends_on: - db db: image: postgres:12.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - ./.env.db nginx: build: ./nginx volumes: - static_volume:/var/www/app/staticfiles - media_volume:/var/www/app/mediafiles ports: - 80:80 depends_on: - web volumes: postgres_data: nginx/Dockerfile FROM nginx:1.17.4-alpine RUN rm /etc/nginx/conf.d/default.conf COPY nginx.conf /etc/nginx/conf.d nginx/nginx.conf upstream polls_django { server web:8000; } server { listen 80; location / { proxy_pass http://polls_django; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } Clues: Locally: I can visit my app at localhost just fine. However, I noticed that I will get Bad Request (400) when trying to visit 0.0.0.0. Linode: When I visit the IP address of my Linode I get Bad Request (400). Looking at my nginx container's error logs, something I noticed is this entry: 2022/11/28 01:08:51 [info] 7#7: *2 client … -
Query unique values inside django forloop
I have a query where I should avoid double entry of the same question. In fact, I would like to get only unique values but, I am using the distinct() django function which isn't working. I have these models: class QuestionTopic(models.Model): name = models.CharField(max_length=255) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) exam_questions_num = models.IntegerField(null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.name class Meta: ordering = ('created_at',) class Question(models.Model): id = models.CharField(max_length=7, unique=True, primary_key=True, editable=False) question_subject = models.ForeignKey( QuestionSubject, on_delete=models.CASCADE) text = tinymce_models.HTMLField() mark = models.IntegerField(default=1) is_published = models.BooleanField(default=True) question_bank_id = models.CharField(max_length=255, blank=True, null=True) question_topic = models.ForeignKey( QuestionTopic, on_delete=models.CASCADE, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) and the query is: subject = QuestionSubject.objects.get(id=request.POST.get('subject')) question_topics = QuestionTopic.objects.filter( question_subject=subject) questions_list = [] for topic in question_topics: for q in range(topic.exam_questions_num): question = Question.objects.filter( question_subject=subject, question_topic=topic).values_list( 'id', flat=True).order_by('?').distinct().first() questions_list.append(question) What I would like to achieve is to have all different questions for each different topic inside questions_list. Which I am not achieving at the moment being the distinct used inside a loop. -
Hubspot api client does not work for existing django project but works for new Django project
In my existing Django project I added a function called test as following: ... import hubspot from hubspot.crm.contacts import ApiException, PublicObjectSearchRequest, SimplePublicObjectInput ... ... def test(email): client = hubspot.Client.create(access_token=<access_token>) public_object_search_request = PublicObjectSearchRequest(filter_groups=[{"filters": [{ "value": email, "propertyName": "email", "operator": "EQ" }]}]) try: api_response = client.crm.contacts.search_api.do_search( public_object_search_request=public_object_search_request) pprint(api_response) except ApiException as e: print("Exception when calling search_api->do_search: %s\n" % e Running sudo python3 manage.py runserver gives me error saying no such module 'hubspot.crm'. So I commented everything in test except client line as following: ... import hubspot ... ... def test(email): client = hubspot.Client.create(access_token=<access_token>) This time I get error module 'hubspot' has no attribute 'Client'. I then created new Django project (on same system) and had same test function (the first snippet) and ran django server, this time it worked without errors. Why is Django not seeing hubspot module for existing project? I have also tried to do this using venv and same results were seen. I am using: Python 3.10.6 hubspot-api-client=7.0.0 https://pypi.org/project/hubspot-api-client/ -
Django - Sending post request using a nested serializer with many to many relationship. Getting a [400 error code] "This field may not be null] error"
I'm fairly new to Django and I'm trying to make a POST request with nested objects. This is the data that I'm sending: { "id":null, "deleted":false, "publishedOn":2022-11-28, "decoratedThumbnail":"https"://i.ytimg.com/vi/a2lC4V479hQ/maxresdefault.jpg, "rawThumbnail":"https"://i.ytimg.com/vi/a2lC4V479hQ/maxresdefault.jpg, "videoUrl":"https"://www.youtube.com/watch?v=cl60ToTvG8w, "title":"Video with tags", "duration":120, "visibility":1, "tags":[ { "id":null, "videoId":null, "videoTagId":42 } ] } Here's a brief diagram of the relationship of these objects on the database I want to create a video and pass in an array of nested data so that I can create multiple tags that can be associated to a video in a many to many relationship. Because of that, the 'id' field of the video will be null and the 'videoId' inside of the tag object will also be null when the data is being sent. However I keep getting a 400 (Bad request) error saying {tags: [{videoId: [This field may not be null.]}]} I'm trying to override the create method inside VideoManageSerializer so that I can extract the tags and after creating the video I can use that video to create those tags. I don't think I'm even getting to the create method part inside VideoManageSerializer as the video is not created on the database. I've been stuck on this issue for a few days. … -
AttributeError at /social-auth/complete/google-oauth2/ 'Request' object has no attribute 'login'
I had written a REST API service on python using django rest framework to which I wanted to attach authentication from authorizations using OAuth2 (Google). I used to social django lib, however when I was starting my service locally and putting my credentials in google form to auth I keep getting this error (look at image)... The point where the error began auth = request.login in /messenger/venv/lib/python3.8/site-packages/requests/sessions.py, line 479, in prepare_request. It was weird, but I solved my problem! -
How to write a correct test (pytest) for RegisterView is failing (the View is working correctly)
I managed to create a View for registering user in django. And it works. The user added manually through form (post) is showing in the database. I am currently trying to write test for this view and it's failing. I keep getting; AttributeError: 'User' object has no attribute 'items' tests.py # test for Register View @pytest.mark.django_db def test_012_register_view_post(client, new_user): url = reverse('register') response = client.post(url, new_user) assert response.status_code == 302 assert response.url == reverse('login') User.objects.get(**new_user) conftest.py (tested 2 different fixtures) - both return the same result (AttributeError) @pytest.fixture def users(): lst = [] for user in range(10): user_name = 'User_' + str(user) lst.append(User.objects.create(username=user_name)) return lst @pytest.fixture def new_user(): username = 'User@test.pl' email = 'User@test.pl' first_name = 'User' last_name = 'Test' x = User.objects.create(username=username, email=email, first_name=first_name, last_name=last_name) x.save() return x view.py class RegisterView(View): def get(self, request): form = RegisterForm() return render(request, 'register.html', {'form': form}) def post(self, request): form = RegisterForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] password = form.cleaned_data['password1'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] u = User() u.username = email u.email = email u.first_name = first_name u.last_name = last_name u.set_password(password) u.save() return redirect('/login') return render(request, 'form.html', {'form': form}) form.py class RegisterForm(forms.ModelForm): first_name = forms.CharField(max_length=128, widget=forms.TextInput(attrs={'class': 'form-group', 'placeholder': 'Imię'}), label='') last_name = … -
Python Django: deleting an object
I'm looking to delete an object in Django, but none of the other Stack Overflow questions fix mine. I looked at this one, but it doesn't seem to be working. My delete object code (in the views file) looks like this: @login_required def delete_entry(request, entry_id): """Delete an existing entry.""" if request.method != 'POST': # No data submitted; create a blank form. form = TopicForm() else: # POST data submitted; process data. form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.delete(commit=False) ### code to delete object new_topic.owner = request.user new_topic.save() return redirect('learning_logs:topics') # Display a blank or invalid form. context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) And in URLs.py: path('delete_entry/<int:entry_id>', views.delete_entry, name='delete_entry'), I would like to use a Bootstrap4 button (inside a modal) to delete the entry, (so without any redirects to another confirmation page). Image. Unfortunately, this isn't working. I'm just getting a server error saying that NoReverseMatch at /delete_entry/6. Could someone tell me what this means? Thanks, Ben -
How to whitelist only specific domain in Google OAuth2
I was making a registration portal using in Django 4 using Google OAuth2 and need to register people only with a specific domain like abc@akgec.ac.in but I'm not able to figure out how to do it. I'm using social-auth-app-django for setting up Google OAuth Authentication. Can anyone help me? I have tried using SOCIAL_AUTH_GoogleOAuth2_WHITELISTED_DOMAINS = ['akgec.ac.in'] but it's not working too.