Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - What is wrong with my view function?
In this function, the script can't get past the second if statement. def save_data(request): if request.method == 'POST': if request.POST.get('id')\ and request.POST.get('id1')\ and request.POST.get('id2'): try: print('if2') data=Flow() data.id = request.POST.get('id') data.id1 = request.POST.get('id1') data.id2 = request.POST.get('id2') data.save() except Exception as e: print(e) My question is pretty simple, why might this be happening? If you'd like to see more code please let me know in the comments. -
Login with limited IP addresses
I have written a custom authentication that allows only certain IP addresses to login. Below is my code: def get_client_ip(request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip def authenticate(self, request, username=None, password=None): # do something I am trying to write a test for it. Although, seems like my solution has an empty request. Here's my code: def test_login(self): # create user .... .... # pass a custom HTTP_X_FORWARDED_FOR client = Client(HTTP_X_FORWARDED_FOR='127.0.0.1') response = client.login(username='username', password='password') assert response.status_code == 200 This throws an error AttributeError: 'NoneType' object has no attribute 'META' So, perhaps my request in the fuction somehows is None. How can I fix this ? Thanks in advance! -
Data from one table not writing to another table
I have User table which contains registered user. I have created Enter table which has to record info about when user went through turnstile by using rfid tag. Model has been created, code been written but it doesn't work and not writing data to table. Last row in Written code file should write data to database, but now it doesn't. Thanks in advance! models.py from django.db import models class Department(models.Model): class Meta: verbose_name_plural = 'Отделы' department_name = models.CharField(verbose_name='Отдел', max_length=40, editable=True, unique=True) def __str__(self) -> str: return self.department_name class User(models.Model): class Meta: verbose_name_plural = 'Участники' first_name = models.CharField(verbose_name='Имя', max_length=40) last_name = models.CharField(verbose_name='Фамилия', max_length=40) rfid_mark = models.CharField(verbose_name='RFID', max_length=8, editable=True, unique=True) department = models.ForeignKey(Department, on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True, editable=False) def __str__(self) -> str: return self.first_name + ' ' + self.last_name class Enter(models.Model): class Meta: verbose_name_plural = 'Проход' user = models.ForeignKey(User, verbose_name='Пользователь', on_delete=models.CASCADE) datetime = models.DateTimeField(auto_now=True, verbose_name='Время', editable=False, null=True, blank=True) enter_status = models.BooleanField(editable=False, verbose_name='Статус входа') turnstile_id = models.CharField(verbose_name='id Терминала', max_length=50) def __str__(self) -> str: return self.user + ' ' + self.enter_status Written code class Actions: def gives_access_if_registered(self): connection = database.connects_to_database() cur = connection.cursor() while True: ser.write(request_for_read) scanned_rfid = ser.readline().hex()[12:20] cur.execute("SELECT * FROM passage_user WHERE rfid_mark=?", (scanned_rfid,)) all_database_rows = cur.fetchall() for data in all_database_rows: name … -
threaded websocket in django and kubernetes
I have a model for which I take some data from another website using a websocket and send a request to another website and save the result to database. what I'm doing right now is in my appconfig's ready I create the websockets for all my model's instances in database and store them in a global dictionary where i can access the thread for each model instance using it's PK. I have two questions: As my website gets bigger, with each model having its own thread would that cause me a problem having more than 10,000 threads for example? If I want to scale the application using kubernetes for example would I get into a problem? Because with each instance of my application, threads will spawn and they all try to do the same thing while I only want it to be done once. Also the code doesn't look so pretty this way so I assume there must be other ways of doing this in django which would also be scalable, so I appreciate any suggestion. -
Dual behavior for Class Based View
Let's say that we model university programs, which are divided in tracks. A track belongs to a program. So: class Program(models.Model): name = models.CharField(max_length=30) class Track(models.Model): name = models.CharField(max_length=30) program = models.ForeignKey(Program, on_delete=models.CASCADE, related_name='tracks') I'd like to allow the creation of a track, with the possibility of specifying the program it belongs to, so I can use: class TrackCreateView(CreateView): model = Track fields = ['name', 'program'] But from the program details, I want to allow the creation of a track for that specific program, so I came up with: class ProgramTrackCreateView(CreateView): model = Track fields = ['name'] def form_valid(self, form): form.instance.program_id = self.kwargs['pk'] return super().form_valid(form) In the urls.py, a pk parameter is provided, so this will populate the program_id correctly. Is there any way to merge these two views into a single one, e.g. passing a parameter to the .to_view() method, or something similar? Because I need to change the list of fields to be displayed before the form is created and I need to know if I need to override program_id or not. -
Django : pass session information to next template & view
I'm trying to build a little website where users can set up tournaments and then invite players for their tournaments. These are my Tournament and Invite models: class Tournament(models.Model): tourney_name = models.CharField(max_length=200, null=False, blank=False) event = models.ForeignKey(NewsArticle, on_delete=models.DO_NOTHING, related_name='tourneys') host_user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) # player_count_limit = models.PositiveIntegerField(validators=[MaxValueValidator(100)]) player_join_deadline = models.DateField() fantasy_team_size = models.PositiveIntegerField(validators=[MinValueValidator(5),MaxValueValidator(15)]) created_dt = models.DateTimeField(auto_now_add=True) last_modified_dt = models.DateTimeField(auto_now=True) def __str__(self): return self.tourney_name def get_absolute_url(self): return reverse('home') class Invite(models.Model): name = models.CharField(max_length=200, blank=True, null=True) email = models.CharField(max_length=320, null=False, blank=False, validators=[EmailValidator],) invited_by = models.ForeignKey(get_user_model(), on_delete=models.DO_NOTHING) invited_for = models.ForeignKey(Tournament, on_delete=models.DO_NOTHING) created_dt = models.DateTimeField(auto_now_add=True) def __str__(self): return self.email def get_absolute_url(self): return reverse('home') And then these are my Views: class MakeTourneyView(CreateView): template_name = 'make_tourney.html' model = Tournament form_class = MakeTourneyForm def form_valid(self, form): form.instance.host_user = self.request.user form.save() return super(MakeTourneyView, self).form_valid(form) def get_success_url(self): return reverse('invite_players') #return reverse('invite_players', kwargs={'tourney_id': self.object.id}) def update_session(self): tourneyobj = self.get_object() self.request.session['tourney_id'] = tourneyobj.id return self.request.session['tourney_id'] class InvitePlayersView(CreateView): template_name = 'invite_players.html' model = Invite form_class = InvitePlayerForm def form_valid(self, form): tourney_id = self.request.session['tourney_id'] form.instance.invited_for = Tournament.objects.filter(id=tourney_id).get() form.instance.invited_by = self.request.user form.save() return super(InvitePlayersView, self).form_valid(form) I'm doing something wrong because the tourney_id is not being set on form.instance.invited_for ; instead when I click submit I get Django error saying "KeyError at /tourney/inviteplayers/ 'tourney_id'" Any … -
Django ContentType for relation to many models
I am working on model which is suppose to have relation to many different models, but one instance should have relation to only one of those models. Like Model Response which should store response body parsed on fields but this response can be from different sites which have different set of fields. Searching through SO i find that using django GenericRelation is good approach, so I tried it as below: class Response(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() service_data = GenericForeignKey("content_type", "object_id") class ServiceOne(models.Model): field1 = models.CharField(...) class ServiceTwo(models.Model): field2 = models.CharField(...) With those models I want to do something like this: s1 = ServiceOne.objects.create(field1="Foo") s2 = ServiceTwo.objects.create(field1="Bar") r1 = Response.objects.create(service_data=s1) r2 = Response.objects.create(service_data=s2) but it is throwing django.db.utils.IntegrityError: null value in column "content_type_id" violates not-null constraint. Solutions like "Add null=True" (as here Django Make ContentType Not Required) are not what I expect since I want this relation to be, not to get rid of error itself. According to https://docs.djangoproject.com/en/3.2/ref/contrib/contenttypes/ it should work just fine but I assume I miss something. I tried adding this to ServiceOne and ServiceTwo response = GenericRelation( Response, content_type_field='content_type_fk', object_id_field='object_primary_key', ) and model_type = ContentType.objects.get( app_label='actual_app_label', model="serviceone" ) s1 = ServiceOne.objects.create(field1="Foo") r1 = Response.objects.create( … -
django-cors-headers not working: No 'Access-Control-Allow-Origin' header is present on the requested resource
Full error: Access to XMLHttpRequest at 'https://[redacted]/api/get_match_urls/' from origin 'https://trello.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. I am making an API call from an extension while at trello.com I have corsheaders in my INSTALLED_APPS. I have 'corsheaders.middleware.CorsMiddleware' in my middleware as high up as possible. And I have CORS_ORIGIN_ALLOW_ALL set to True. Yes I've tried the alternate alias CORS_ALLOW_ALL_ORIGINS and it still didn't work. Anyone have any ideas? -
Category cant be empty issue in Django rest framework
I have a product add post API. I am sending all the data that is required but I got the above error every time. I am not sure what is the issue. "Category cant be empty" But I am sending the data. class Variants(models.Model): product_id = models.CharField(max_length=70, default='OAXWRTZ_12C',blank=True) price = models.DecimalField(decimal_places=2, max_digits=20,default=500) size = models.CharField(max_length=50, choices=SIZE, default='not applicable',blank=True,null=True) color = models.CharField(max_length=70, default="not applicable",blank=True,null=True) variant_image = models.ImageField(upload_to="products/images", blank=True,null=True) thumbnail = ImageSpecField(source='variant_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) quantity = models.IntegerField(default=10,blank=True,null=True) # available quantity of given product variant_availability = models.CharField(max_length=70, choices=AVAILABILITY, default='available') class Meta: verbose_name_plural = "Variants" def __str__(self): return self.product_id #Product Model class Product(models.Model): merchant = models.ForeignKey(Seller,on_delete=models.CASCADE,blank=True,null=True) category = models.ManyToManyField(Category, blank=False) sub_category = models.ForeignKey(Subcategory, on_delete=models.CASCADE,blank=True,null=True) brand = models.ForeignKey(Brand, on_delete=models.CASCADE) collection = models.ForeignKey(Collection, on_delete=models.CASCADE) featured = models.BooleanField(default=False) # is product featured? best_seller = models.BooleanField(default=False) top_rated = models.BooleanField(default=False) tags = TaggableManager(blank=True) # tags mechanism name = models.CharField(max_length=150,unique=True) main_product_image = models.ImageField(upload_to="products/images", null=True, blank=True) thumbnail = ImageSpecField(source='main_product_image', processors=[ResizeToFill(100, 50)], format='JPEG', options={'quality': 60}) slug = models.SlugField(max_length=200,blank=True) description = RichTextField(blank=True) #picture = models.ImageField(upload_to="products/images", null=True, blank=True) picture = models.ManyToManyField(ImageBucket,null=True,blank=True,verbose_name="Add extra 3 images") rating = models.IntegerField(choices=((1, 1), (2, 2), (3, 3), (4, 4), (5, 5)) ) availability = models.CharField(max_length=70, choices=AVAILABILITY, default='in_stock') warranty = models.CharField(max_length=100, choices=WARRANTY, default='no_warranty') services = models.CharField(max_length=100, choices=SERVICES, … -
How to send scheduled mail in django?
I'm a complete beginner to Django, I want to send a reminder mail to the user to update the record 1st of every January and July. I have tried cron jobs, but I cannot implement it since it will work only on Linux. I tried scheduler in python since we are using while True...loop always runs and my website server itself not starting. Please help me to send scheduled mail using Django if you have any other approach. Thanks!!! -
cropper.js not displaying anything on Django website
I am following this tutorial on how to get cropper.js working with Django but it does not seem to work for me. https://medium.com/geekculture/implement-cropping-feature-on-your-website-in-under-10-min-cropper-js-46b90d860748 Here is the source code of said tutorial: https://github.com/RG2021/mysite I configured the settings, have the URLs right. Here is my code: views.py @login_required def edit(request): if request.method == 'POST': user_form = CustomUserChangeForm(instance=request.user, data=request.POST) profile_form = ProfileEditForm( instance=request.user.profile, data=request.POST, files=request.FILES) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, 'Profile updated successfully') else: messages.error(request, 'Error updating your profile') else: user_form = CustomUserChangeForm(instance=request.user) profile_form = ProfileEditForm(instance=request.user.profile) posts = Profile.objects.all() return render(request, 'account/edit.html', {'user_form': user_form, 'profile_form': profile_form}) edit.html < script > // image-box is the id of the div element that will store our cropping image preview const imagebox = document.getElementById('image-box') // crop-btn is the id of button that will trigger the event of change original file with cropped file. const crop_btn = document.getElementById('crop-btn') // id_image is the id of the input tag where we will upload the image const input = document.getElementById('id_image') // When user uploads the image this event will get triggered input.addEventListener('change', () => { // Getting image file object from the input variable const img_data = input.files[0] // createObjectURL() static method creates a DOMString containing a URL representing … -
django-plotly-dash how to integrate 3 different dash files
Earlier was using dash server with a base.py which runs dash app server to run the files which was combined using dashboard.py which renders data from files A and B which has data and responsive UI. Now trying to move it to django using django-plotly-dash. Could someone help one this. File Structure: base.py - dash app server dashboard.py - from base imports app, from a imports a_tab (which contains a dataframe) from b imports b_tab (which contains a dataframe) runs server both a.py and b.py --- from base imports app Have setup everything with django-plotly-dash but the data is not populating by clicking UI. -
Python - overlap time period business hours [closed]
I try to find the best way to solve this problem: I'am coding a scheduler for machine job. I will have a postgres table with all day of a year. Every row has different columns with start and ends of shift work. For example: day 17/01/21 - start_time_work1 00:00 - end_time_work1 20:00 - start_time_close1 20:00 - end_time_close1 00:00 day 18/01/21 - start_time_work1 00:00 - end_time_work1 04:00 - start_time_close1 04:00 - end_time_close1 06:00 - start_time_work2 06:00 - end_time_work2 12:00 - start_time_close2 12:00 - end_time_clos22 00:00 There may usually be several shifts on the same day. The purpose is to create a function that allows me, by entering a work start date and a work duration, to know, considering only the work periods, when this work will end. For my example: 17/01/21 18/01/21 Work Closed Work Closed Work Closed |----------------------------|----------|----------|---------|----------|---------------| 00:00 20:00 00:00 04:00 06:00 12:00 00:00 Input: |--------------------------------| 01:00 (22hous) 23:00 Output |-------------------------------------------| 01:00 (26hous) 03:00 Input: |---------------------------------------| 01:00 (24hous) 01:00 Output |-------------------------------------------------------------| 01:00 (30hous) 07:00 -
Python categories not updating?
I am currently making a blog but I recently added a dropdown menu for my website. From that point onwards when I add a new category it does not update. Instead it says this page does not exist when it should have. add_category.html file {% extends 'base.html' %} {% block title %}Create a New Blog Category!{% endblock %} {% block content %} {% if user.is_authenticated %} <h1>Add Category</h1> <br/><br/> <div class="form-group"> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button class="btn btn-secondary">Add Category</button> </div> {% else %} You are not allowed here! (and you know it...) {% endif %} {% endblock %} categories.html file {% extends 'base.html' %} {% block content %} {% if category_posts %} <h1>{{ cats }}</h1> <ul> {% for post in category_posts %} <li><a href="{% url 'article-detail' post.pk %}">{{post.title}}</a> - {{post.author.first_name}} {{post.author.last_name}} - {{ post.post_date }} <small> {% if user.is_authenticated %} - <a href="{% url 'update_post' post.pk %}">(Edit)</a> <a href="{% url 'delete_post' post.pk %}">(Delete)</a> {% endif %} </small><br/> {{post.body|slice:":200"| safe }}</li> {% endfor %} </ul> {% else %} <h2>Sorry this page does not exist...</h2> {% endif %} {% endblock %} urls.py file from django.urls import path #from . import views from .views import HomeView, ArticleDetailView, AddPostView, UpdatePostView, … -
How to make complex searches in django ? Use views or models?
I want to create a Job search page on my Django Application. I'm now wondering what the best practice is on how to develop this. Would it be better to do al the filtering in my views? Or should I do all the filtering in the models? -
FileNotFoundError with matplotlib and apscheduler
My goal is to download data from a website, plot a graph, save it, and display it on a webpage. I am using Django 3.2, Python 3.9.5, pandas and matplotlib. When I just had the below code in my views, everything worked and the graph displayed correctly: r = requests.get(url_lab) #url_lab defined elsewhere, not relevant z = zipfile.ZipFile(io.BytesIO(r.content)) if file_lab in z.namelist(): #file_lab defined elsewhere, not relevant df_lab = pd.read_csv(z.open(file_lab), dtype={'a': str, 'b': str, 'c': float}, usecols=col_list, parse_dates=['Period'], \ encoding = "ISO-8859-1", engine='python') df_lab.set_index('Period', inplace=True, drop=True) df_lab = df_lab.sort_index().loc['2015-03-03':] x = df_lab.index[df_lab.Series_reference == "HLFQ.S1A1S"] y = df_lab.Data_value[df_lab.Series_reference == "HLFQ.S1A1S"] fig = plt.plot(x, y) plt.savefig('static/images/lab-empl-lev.png') However, I don't want this code to run every time I run the server, and in fact it's important that the data gets updated at a specific time every day. So I need to use some kind of task scheduler, and decided on apscheduler. So, following a tutorial, I made a new folder, containing an empty __init__.py, fetch.py with the previous code in it and updater.py: fetch.py: def get_lab_data(): r = requests.get(url_lab) z = zipfile.ZipFile(io.BytesIO(r.content)) if file_lab in z.namelist(): df_lab = pd.read_csv(z.open(file_lab), dtype={'a': str, 'b': str, 'c': float}, usecols=col_list, parse_dates=['Period'], \ encoding = "ISO-8859-1", engine='python') df_lab.set_index('Period', … -
how to make a field which gets shown if another field reached a specific value in django
So lets say in django models, we have a ForeignKey model named info_type, the user In django admin can select height or weight, Now, my question is what can we do so when info_type == weight a field get shown named weight and when the info_type is equivalent to height, a field gets shown named height I found no clue for doing such thing, how can I make that possible? -
Django Ajax request seems to be calling incorrect view
I am trying to set up the inventory section of my page, I have created a new view definition that handles updating the database with the value set by the user. However I keep getting errors from the main page view. I believe I'm only call the updateInventory view def. Error: Internal Server Error: /magic/sets/update-inventory/ Traceback (most recent call last): File "...\card_crate_admin_venv_v2\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "...\card_crate_admin_venv_v2\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "...\card_crate_admin_venv_v2\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "...\website\magic\views.py", line 33, in setsIndividualPage setName = Set.objects.filter(code=setCode.upper()).values_list('name', flat=True).get() File "...\card_crate_admin_venv_v2\lib\site-packages\django\db\models\query.py", line 437, in get self.model._meta.object_name magic.models.Set.DoesNotExist: Set matching query does not exist. urls.py path('sets/<str:setCode>/', setsIndividualPage), path('sets/<str:setCode>/sets-individual-data/', SetsIndividualData.as_view(), name='sets-individual-data'), path('sets/update-inventory/', updateInventory, name='updateInventory'), view.py # ====================== # Sets Individual Page # ====================== @login_required() def setsIndividualPage(request, setCode): setName = Set.objects.filter(code=setCode.upper()).values_list('name', flat=True).get() return render(request, "magic/sets-individual.html", {'setCode': setCode, 'setName': setName}) def updateInventory(request): current_user = request.user if request.POST['card_type'] == 'standard': Inventory.objects.update_or_create( user_id = current_user.id, card_id = request.POST['id'], defaults = { 'standard': request.POST['value'] } ) elif request.POST['card_type'] == 'foil': Inventory.objects.update_or_create( user_id=current_user.id, card_id=request.POST['id'], defaults={ 'foil': request.POST['value'] } ) javascript.js function updateCard(e) { if (e.getAttribute('type') == 'number'){ if (e.value < 0) e.value = 0; if (e.value > … -
Why is my user manager not creating superuser?
So I tried to make a superuser in my terminal with createsuperuser and it created a user successfully only that it wasn't a superuser because when I tried to login it gave me this error but when I tried to create another superuser with the same email it tells me the email is already taken Account.models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager # Create your models class AccountManager(BaseUserManager): def create_user(self, email, username, password=None): if not email: raise ValueError("user must have an email") cemail = self.normalize_email(email) user = self.model(email=cemail, username=username) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password): if not email: raise ValueError('user must have an email') user = self.create_user(email, username, password) user.is_admin = True user.save(using=self._db) return user class Account(AbstractBaseUser): email = models.EmailField(unique=True, max_length=255) username = models.CharField(max_length=255) is_active = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] objects = AccountManager() def __str__(self): return self.email @property def is_staff(self): return self.is_admin @property def is_superuser(self): return self.is_admin -
Django: unable to save a value in models
I am currently working on a CS50 Web development SQL, Models, and Migrations and following what the tutorial says to do , yet I found that I am not able to duplicate the result at some points. I have created a new class in models.py named Airport. class Airport(models.Model): code = models.CharField(max_length=3) city = models.CharField(max_length=64) def __str__(self): return f"{self.city} ({self.code})" When I try to use the f = Airport(code="NY", city="New York") f.save() function to save it, the following error occurs django.db.utils.OperationalError: no such table: flights_airport I have checked some solutions from the internet, the first one is to do the migration again. Yet, when I do python manage.py makemigrations it says No changes detected when I do python manage.py migrate, it shows a long error message with django.db.utils.IntegrityError: The row in table 'flights_flight' with primary key '1' has an invalid foreign key: flights_flight.origin_id contains a value 'new york' that does not have a corresponding value in flights_airport.id I have also tried to delete all the data with Airport.objects.all().delete() It again shows the following error code django.db.utils.OperationalError: no such table: flights_airport I am stuck in a point that I cant do migration nor can I start it again. I'd like to … -
What does kwargs={'pk': self.pk} do in get_absolute_url method?
I've finished a Django tutorial a few days ago and I've started to recap the functionalities in my application. In my models.py I've stumbled upon a method and the kwargs thing it's not that clearly to me. What is the logic behind this, can you explain to me what it does? Thank you. models.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class Creation(models.Model): title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='creation_posts') def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:detail', kwargs={'pk': self.pk}) def total_likes(self): return self.likes.count() What does kwargs={'pk':self.pk}) do exactly? Thank you -
Page Not Found after adding user in Group ( While Redirecting )
I am building a Simple Group App in which users can ask admin for permission for join. First they have to send a join request to join the Group then a admin will accept it. BUT when user is clicking on join_the_accept then user is successfully adding BUT after click on join_the_accept then it is keep showing Page Not Found (404) models.py class Group(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) title = models.ForeignKey(max_length=30,default='') members = models.ManyToManyField(User,related_name='group_member',blank=True) class GroupRequest(models.Model): group = models.ForeignKey(Group,on_delete=models.CASCADE) request_sender = models.ForeignKey(User, on_delete=models.CASCADE) views.py def accept_it(request,pk): group_request = get_object_or_404(GroupRequest, pk=pk) group_request.group.members.add(group_request.request_sender) group_request.members.add(sent_request.request_sender) return redirect('DetailGroup',pk=pk) #Redirecting Here def DetailGroup(request,pk): data = Group.objects.get(pk=pk) request_message = data.groupjoinrequest_set.order_by('-date_sent').exclude(request_sender=request.user) context = {'data':data} return render(request,'Group_detail.html', context) Group_detail.html {% for requests in group_requests %} {{ requests.request_sender }}<a href="{% url 'accept_it' requests.id %}">Accept it</a> {% endfor %} What i have tried :- I have also tried by putting group_id instead of pk like this :- ('DetailGroup',pk=group_id) BUT it is showing the same error. I have also renamed the instances in url but still showing the error. User is saving fine BUT it is not redirecting in the Group. I have no idea what is wrong with it, Any help would be Appreciated. Thank You in Advance. -
django session key during session
I am looking for the session key that should be the same from the time when the user logs in until he logs out. I am communicating with another api that requires such key. I tried using csrf token but this one is different per request. Also, I have tried using session storage and again it is different one. I see that in the django_sessions there is a session_key that is created during the login, but I dont know how to assosiate it with a user, it has only session_key, session_data and the expire date. def user_login(request): if request.method == 'POST': response = None form = LoginForm() username = request.POST.get("username") password = request.POST.get("password") cookie = request.COOKIES['csrftoken'] user = authenticate(username=username, password=password) # logger.info(f"Session key [Login] --> {request.session}") # logger.info(f"Session key [Login] --> {request.session.session_key}") # request.session.create() # logger.info(f"Session key [Login] --> {request.session.session_key}") if user is not None: logger.info(f"Cookie [Login] --> {cookie}") response = loginApi( username, password, 'demo', cookie) if response["status"] == 200: login(request, user) logger.info("User logged in") return redirect('home') else: logger.info(f"Request Response [Log in] --> {response}") else: logger.error(f"User failed [Log in] --> {response.text}") else: form = LoginForm() return render(request, 'users/login.html', {'form': form}) -
How can I properly send images (and text) from React to Django API using fetch?
My django API views is setup as follows; class AddProductToStorageAPIView(APIView): parser_classes = [MultiPartParser, FormParser] def post(self, request, format=None): print(request.data) #I want to know what data is coming in for now return Response({"details": "all done successfully"}, status=200) When I make a POST request from postman (with formdata), the data request.data returns: <QueryDict: {'title': ['Something'], 'description': ['some description'], 'price': ['600'], 'category': ['A'], 'Images': [<InMemoryUploadedFile: img-transparent_bg.jpg (image/jpeg)>]}> However, when I try to make a POST request from the react side. Things got so messed up. First here is my code in react side: const handleSubmit = (e) =>{ e.preventDefault(); var headers = new Headers(); headers.append("Content-Type", "multipart/form-data"); headers.append("X-CSRFToken", csrftoken) var formdata = new FormData(); formdata.append("title", state.title); formdata.append("description", state.description); formdata.append("price", state.price); formdata.append("category", state.category); for (var i = fileinput.current.files.length - 1; i >= 0; i--) { formdata.append("Images", fileinput.current.files[0], fileinput.current.files[0].name); }//because the file input has 'multiple'='true' (i.e multiple files can be added) var requestOptions = { method: 'POST', headers: headers, body: formdata, redirect: 'follow' }; fetch("http://127.0.0.1:8000/api/v1/plus/product/", requestOptions) .then(response => response.text()) .then(result => console.log(result)) .catch(error => console.log('error', error)); } On submit however, I get 400 bad request error saying multipart form parse error - invalid boundary in multipart:None and I don't have a clue what that means. Then, … -
INVALID_PATCH_PATH error while using patch/updating the interval unit in PayPal plan update API
I used the details in body as [ { "op": "replace", "path": "/billing_cycles/frequency/interval_unit", "value": "MONTH" } ] I get the output as follows { "name": "INVALID_REQUEST", "message": "Request is not well-formed, syntactically incorrect, or violates schema.", "debug_id": "7e77554e0bd6d", "details": [ { "field": "/0/path", "value": "/billing_cycles/frequency/interval_unit", "location": "body", "issue": "INVALID_PATCH_PATH", "description": "The specified field cannot be patched." } ], "links": [ { "href": "https://developer.paypal.com/docs/api/v1/billing/subscriptions#INVALID_REQUEST", "rel": "information_link", "method": "GET" } ] } what is the correct body data to pass to update the interval_unit of the PayPal plan data.