Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I get a serializer with an instance as a Foreign key?
How do I get a serializer with an instance as a Foreign key? Here is my model and serializer: class ChargeSchedule(models.Model): vehicle = models.OneToOneField(Vehicle, on_delete=models.PROTECT, related_name='vehicle_charge_schedule') max = models.FloatField() min = models.FloatField() class ChargeScheduleSerializer(serializers.ModelSerializer): class Meta: model = ChargeSchedule fields = '__all__' When I try to validate the serializer I get an error saying 'This field must be unique': class ChargeScheduleViewSet(ModelViewSet): model = ChargeSchedule serializer_class = ChargeScheduleSerializer def create(self, request, *args, **kwargs): # request.data = {'min': 10, 'max': 100} vehicle = request.user.vehicle request.data['vehicle'] = vehicle.id serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) # FAILS HERE, {ValidationError}{'vehicle': [ErrorDetail(string='This field must be unique.', code='unique')]} How can I validate this serializer using the Vehicle instance? -
mod_wsgi shared library is over 1MB using pyenv
I work in an AWS lightsail server with a LAMP self-contained installation stack and I want to host a second web-app in django. Tried to install mod_wsgi to a pyenv virtual environment (3.8.3 and 3.8-dev, both with shared libraries installed) using export APXS=/opt/USER/apache2/bin/apxs pip install mod_wsgi (tried with and w/o wheel) but the module mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so that created is over 1MB in size. -rwxrwxr-x 1 USER USER 1157792 Jun 21 20:15 mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so ldd gives: ldd mod_wsgi-py38.cpython-38-x86_64-linux-gnu.so linux-vdso.so.1 => (0x00007ffc3e198000) libpython3.8.so.1.0 => /home/USER/.pyenv/versions/3.8-dev/lib/libpython3.8.so.1.0 (0x00007fce67120000) libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007fce66f03000) libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fce66b39000) libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007fce66935000) libutil.so.1 => /lib/x86_64-linux-gnu/libutil.so.1 (0x00007fce66732000) libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fce66429000) /lib64/ld-linux-x86-64.so.2 (0x00007fce678f0000) According the manual https://modwsgi.readthedocs.io/en/develop/user-guides/installation-issues.html#lack-of-python-shared-library, that should be a problem for my server's memory performance. Is there something else that I could do in order to get a ~250KB in size module as the docs describe it? -
Django basic ModelForm not showing choices
Using Django tutorial, I built a basic ModelForm with choice fields: One field (Shirt size) - is not showing choices Second field - not showing at all I can't find the reason, anywhere I checked it seems like I'm doing things right, but obviously I'm not. Thank you. The Result Form views.py def person(request): if request.method == 'POST': form = forms.PersonForm(request.POST) if form.is_valid(): return HttpResponseRedirect('/thanks/') else: form = forms.PersonForm() return render(request, 'development/form_template.html', {'form': form}) forms.py class PersonForm(ModelForm): class Meta: model = models.Person fields = '__all__' models.py class Person(models.Model): SHIRT_SIZES = ( ('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ) name = models.CharField(max_length=60, default='Anonymous', help_text='Type your name.') shirt_size = models.CharField(max_length=1, choices=SHIRT_SIZES) medal_type = models.TextChoices('MedalType', 'GOLD SILVER BRONZE') form_template.html {% extends 'development/development_template.html' %} {% block content %} <div class="container"> <form action="/your-name/" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Submit"> </form> </div> {% endblock content %} -
Error (1062, "Duplicate entry '4' for key 'user_id'") on django loaddata
I just deleted my localhost database due to export my production website database and then import it to my lcoal db I used this command to dump db: ./manage.py dumpdata --exclude contenttypes --exclude auth.permission --exclude sessions --indent 2 > dump.json and then on my localhost: ./manage.py loaddata dump.json but I get error: Traceback (most recent call last): File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/db/backends/mysql/base.py", line 74, in execute return self.cursor.execute(query, args) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 209, in execute res = self._query(query) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/MySQLdb/cursors.py", line 315, in _query db.query(q) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/MySQLdb/connections.py", line 239, in query _mysql.connection.query(self, query) MySQLdb._exceptions.IntegrityError: (1062, "Duplicate entry '1' for key 'user_id'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 21, in <module> main() File "./manage.py", line 17, in main execute_from_command_line(sys.argv) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 72, in handle self.loaddata(fixture_labels) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 114, in loaddata self.load_label(fixture_label) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/management/commands/loaddata.py", line 181, in load_label obj.save(using=self.using) File "/home/mehdi/python/projects/FollowBotWebsite/v1.2.2/venv/lib/python3.8/site-packages/django/core/serializers/base.py", line 223, in save models.Model.save_base(self.object, using=using, raw=True, **kwargs) … -
TypeError: User() got an unexpected keyword argument 'is_staff' when using CustomUser
I am Creating a Custom User using AbstractBaseUser, but anytime I try to create a superuser, it says TypeError: User() got an unexpected keyword argument 'is_staff' user=self._create_user(email, password, True, True, **extra_fields) File "C:\Users\user1\django\customuserproject\users\models.py", line 24, in _create_user How do I solve this problem? I have checked other StackOverflow posts on this issue, but they didn't help me. I haven't tried with a regular user yet (I need a superuser to create a regular user), but I am sure it would be the same thing My models.py: class UserManager(BaseUserManager): def _create_user(self, email, password, is_staff, is_superuser, **extra_fields): if not email: raise ValueError('Users must have an email address') now = timezone.now() email = self.normalize_email(email) user = self.model( email=email, is_staff=is_staff, is_active=True, is_superuser=is_superuser, last_login=now, date_joined=now, **extra_fields ) #user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, **extra_fields): """ Creates and saves a User with the given email and password. """ return self._create_user(email, password, False, False, **extra_fields) def create_staffuser(self, email, password, **extra_fields): """ Creates and saves a staff user with the given email and password. """ user=self._create_user(email, password, True, False, **extra_fields) user.save(using=self._db) return user def create_superuser(self, email, password, **extra_fields): """ Creates and saves a superuser with the given email and password. """ user=self._create_user(email, password, True, True, **extra_fields) … -
How to start a single background task when django server boots up?
I need to run a long running background task when the Django server is started. This task needs to run in an endless loop, or restarted at set intervals. I was looking at Threading, multi processing, django-background-tasks. The problem with django-background-tasks is that if I just declare my task in tasks.py, it inserts a new task each time the server is restarted. So after a while, I have hundreds of tasks running, while I only need a single one. The problem with Threads and multi processing, is that these tasks are not triggered at all, unless I do import tasks in views.py. In that case, they get triggered all the time, for example, python3 manage.py makemigrations triggers the task. I only want to run the task when the server is started. How can I achieve this? This is what I have now. This keeps inserting new tasks each time I restart the server, resulting in hundreds of parallel tasks. tasks.py REPEAT = 60*15 @background() def process_transactions(): ... process_transactions(repeat=REPEAT) -
Django looking for template that doesn't exist
I made some major changes to my site and now when I click a specific link, it tries to go to a page that doesn't exist (rightfully so) but I can't find any reference to that non-existent page in my code so I can't direct it properly. views.py from django.shortcuts import render from .models import BakingPost from django.views import generic def index(request): num_posts = BakingPost.objects.all().count() context = { 'num_posts': num_posts, } return render(request, 'food_blog/index.html', context=context) class BakingListView(generic.ListView): model = BakingPost # paginate_by = 10 class BakingDetailView(generic.DetailView): model = BakingPost urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('bakes/', views.BakingListView.as_view(), name='bakes'), path('bake/<int:pk>/', views.BakingDetailView.as_view(), name='bake_detail'), # path('post/new/', views.post_new, name='post_new'), # path('post/<int:pk>/edit/', views.post_edit, name='post_edit'), ] navbar.html <nav> <div id="div_navbar"> <ul class="ul_navbar"> <li class="li_navbar"> <a class="a_navbar" href="{% url 'index' %}">Home</a> </li> <li class="li_navbar"> <a class="a_navbar" href="{% url 'bakes' %}">Baking List</a> </li> </ul> </div> </nav> bake_list.html {% extends 'food_blog/base.html' %} {% block content %} <h1>Baking List</h1> {% if bake_list %} <ul> {% for bake in bake_list %} <li> <a href="{{ bake.get_absolute_url }}">{{ bake.title }}</a> ({{bake.author}}) </li> {% endfor %} </ul> {% else %} <p>Nothing in the oven</p> {% endif %} {% endblock %} When I click on "Baking … -
A URL of a Hyperlinked Model Serializer returns '{"detail": "not found."} for a model with custom PK
class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) website = models.URLField(max_length=30, null=True, blank=True) class ProfileViewSet(viewsets.ModelViewSet): lookup_field = 'user' serializer_class = ProfileSerializer queryset = Retailer.objects.all() class ProfileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Profile fields = ['website', 'user', 'url'] extra_kwargs = { 'url': {'view_name': 'profile-detail', 'lookup_field': 'user'}, 'user': {'lookup_field': 'username', 'view_name': 'user-detail'} } The code above lists all profiles and their URL's in JSON format. However, when a URL is clicked, it returns '{"detail": "not found."} instead of showing the details of the profile. Any idea? Thanks! Django version: 3.0.4 Django Rest Framework version: 3.11.0 -
python timer decorator with outputting classname
I am creating a little helper tool. It is a timer decorator (not so special) for measuring the execution times of any method. It prints the calculated execution time on the console with useful informations. def timer(func): """@timer decorator""" from functools import wraps from time import time def concat_args(*args, **kwargs): for arg in args: yield str(arg) for key, value in kwargs.items(): yield str(key) + '=' + str(value) @wraps(func) # sets return meta to func meta def wrapper(*args, **kwargs): start = time() ret = func(*args, **kwargs) dur = format((time() - start) * 1000, ".2f") print('{}{}({}) -> {}ms.'.format( func.__module__ + '.' if func.__module__ else '', func.__name__, ', '.join(concat_args(*args, **kwargs)), dur )) return ret return wrapper This gives me the modelname, and the functionname like that: user.models.get_matches(demo) -> 24.09ms. I want to have the class name in the output, too: user.models.User.get_matches(demo) -> 24.09ms. How can I get the class name of the function ('func') from inside the wrapper? Edit: Great thanks to Hao Li. Here is the finished version: def timer(func): """@timer decorator""" from functools import wraps from time import time def concat_args(*args, **kwargs): for arg in args: yield str(arg) for key, value in kwargs.items(): yield str(key) + '=' + str(value) @wraps(func) # … -
How to transform a list of dictionaries in Django view to return it as JSON?
I am calling the Giphy API using another wrapper API which returns a list of dictionaries. I am having hard times to transform the data to return it to AJAX. The data is returned as InlineResponse200 with three properties. According to the docu the dict consists of strings mainly. def get_gifs(request): # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = 'NGSKWrBqtIq1rFU1Ka11D879Y1u4Igia' # Search term q = request.POST.get('query') # Query parameters limit = 2 offset = 0 rating = 'g' lang = 'en' fmt = 'json' try: # Search Endpoint api_response = api_instance.gifs_search_get(api_key, q, limit=limit, offset=offset, rating=rating, lang=lang, fmt=fmt) pprint(api_response) except ApiException as e: print("Exception when calling DefaultApi->gifs_search_get: %s\n" % e) response = api_response.data JsonResponse(response) return render(request, response) # Returns: TypeError: Object of type Gif is not JSON serializable [...] response = api_response.data return render(request, response) # Returns: TypeError: join() argument must be str or bytes, not 'Gif' [...] response = api_response.data serialized_obj = serializers.serialize('json', response) return render(request, serialized_obj) # Returns: AttributeError: 'Gif' object has no attribute '_meta' [...] response = api_response.data[0] serialized_obj = serializers.serialize('json', response) return render(request, serialized_obj) # TypeError: 'Gif' object is not iterable Going nuts.. -
Display fields based on previous dropdown
On Django site have model "Worksheet" and it has several types (for instance Driver/Cook/Housekeeper) When adding WS 1st step is choise field called "Worksheet type" and regarding the choosed type display related fields Flow: Add worksheet Form show dropdown list called "Choose worksheet type" (Driver for example), click next Form display fields specified for driver (e.g driving experience and vehicle type) I thought it is simple but a long time cant find the solution I have a lot of experience with different cms e.g Drupal/Joomla/Wordpress but I'm new in Django and I'll be very grateful if you provide your answer in details Thks!!! -
Bookmark Implementation methods in Django
I am trying to add a bookmarking system to my website however, I am kinda stuck on how to implement this: My approach following the link: https://evileg.com/en/post/244/ is class BookmarkBase(models.Model): class Meta: abstract = True user = models.ForeignKey(Profile,on_delete=models.CASCADE, verbose_name="User") def __str__(self): return self.user.username class BookmarkPost(BookmarkBase): class Meta: db_table = "bookmark_post" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey(Post,on_delete=models.CASCADE, verbose_name="Post") class BookmarkBlog(BookmarkBase): class Meta: db_table = "bookmark_blog" date = models.DateTimeField(auto_now_add=True) obj = models.ForeignKey(Blog,on_delete=models.CASCADE, verbose_name="Blog") However, I was also wondering if the approach of creating a many to many relationships inside my user model with each object is also correct or not: so I will have : class Profile(AbstractUser): ''' Custome fields ''' bookmark_blog = models.ManyToManyField(Blog, blank=True, related_name='b_blogs') bookmark_post = models.ManyToManyField(Post, blank=True, related_name='b_posts') -
Field 'id' expected a number but got <QueryDict: >error in django
I have this form: class addMeal(forms.Form): name = forms.CharField( max_length=40, widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'}) ) foods = forms.ModelMultipleChoiceField( queryset=Food.objects.none(), widget=forms.SelectMultiple(attrs={'class':'form-control'}) ) def save(self,request): data = self.cleaned_data meal = Meals(name=data['name'],user=request.user,foods=data['foods']) meal.save() def __init__(self, user=None,*args, **kwargs, ): super().__init__(*args, **kwargs) if user is not None: self.fields['foods'].queryset = Food.objects.filter(user=user) class Meta: model = Meals and this view: @login_required def addmeal(request): if request.method == 'POST': form = addMeal(request.POST) if form.is_valid(): form.save(request) return redirect('food:index') else: form = addMeal(user=request.user) return render(request,'addmeal.html',{'form':form}) when i fill out form and press submit django give me error(Field 'id' expected a number but got <QueryDict: {'csrfmiddlewaretoken': ['C2B8y3kLCa5IQ0S5Mvk7Tw0NTU4pNlYicppWlsIL1LCrcc8AuCQzjJkqWNUot4z6'], 'name': ['شام'], 'foods': ['1']}>.). what should i do to fix it? -
TypeError: join() argument must be str or bytes, not 'InlineResponse200' - How to return API data via Django view to AJAX?
I am calling an async AJAX function to trigger a view which itself requests API data. Everything works fine and the API data is returned properly. But then the view function crashes with the following error. I use this wrapper for the API requests. I assume something is messy with my return method in the view. Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\finsphere\finsphere\blog\views.py", line 229, in get_gifs return render(request, api_response) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loader.py", line 15, in get_template return engine.get_template(template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\backends\django.py", line 34, in get_template return Template(self.engine.get_template(template_name), self) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 143, in get_template template, origin = self.find_template(template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\engine.py", line 125, in find_template template = loader.get_template(name, skip=skip) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\base.py", line 18, in get_template for origin in self.get_template_sources(template_name): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\loaders\filesystem.py", line 36, in get_template_sources name = safe_join(template_dir, template_name) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\_os.py", line 17, in safe_join final_path = abspath(join(base, *paths)) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\ntpath.py", line 109, in join genericpath._check_arg_types('join', path, *paths) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\genericpath.py", … -
Django modelformset with customized model initialization
I have a model in django with a foreign keya to another modela as follows: TAG: user=ForeignKey() name=CharField() shop=ForeignKey() It is being used to assign a tag to a given user and chosen shop. For this purpose, shop field is being filtered based on the user instance. Now I need to create a modelformset that will allow me to store bunch of different tags per user. What I am looking for is a way to initialize such formset with a shop field filtered out. Any ideas are very welcome! Thanks -
NoReverseMatch at /v2/search/SARS_CoV_2/GID1716
I am developing a django application in which I am trying to send a value of the variable to the backend on click of a button through javascript. javascript code: $(document).on("click", "#filter", function (e) { IUPredscorethreshold = 0.4 $("#ksNetwork").empty(); ksInteractionNetwork('{% url "camkinetv2:newinteractors_intnet" tab1.caMKipedia_Id IUPredscorethreshold %}'); }); urls.py path( "dataJson/newinteractors_intnet/<str:geneId>/<str:IUPredscorethreshold>", views.newinteractors_intnet, name="newinteractors_intnet", ), views.py @csrf_exempt def newinteractors_intnet(request, geneId, IUPredscorethreshold): print("IUPredscorethreshold:" + IUPredscorethreshold) . . . . . some computation graphData = {"nodes": uniquenodesdata, "links": linksdata} response = JsonResponse(graphData) return response when I execute this code i am getting following error: NoReverseMatch at /v2/search/SARS_CoV_2/GID1716 Reverse for 'newinteractors_intnet' with arguments '('GID1716', '')' not found. 1 pattern(s) tried: ['v2/dataJson/newinteractors_intnet/(?P<geneId>[^/]+)/(?P<IUPredscorethreshold>[^/]+)$'] Exception Value: Reverse for 'newinteractors_intnet' with arguments '('GID1716', '')' not found. 1 pattern(s) tried: ['v2/dataJson/newinteractors_intnet/(?P<geneId>[^/]+)/(?P<IUPredscorethreshold>[^/]+)$'] what am I doing wrong? how can I solve this issue. I am still at learning stage of django and I am not able to figure out how to solve this error. -
when I execute the python manage.py runserver, CMD throws AttributeError:
I am new to Django! So I built a simple blog application using python/Django, MySQL as the back end using the XAMPP control panel. It was running as expected on http://localhost:8000. However, at the end of project when I added a Button functionality & restarted(python manage.py runserver) the server using the CMD. The CMD threw: AttributeError: module 'posts.views' has no attribute 'details'. Your help wold be appreciated! -Attached is the project on GitHub. urls.py file: from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^details/(?P<id>\d+)/$', views.details, name='details') ] views.py file: from django.shortcuts import render from django.http import HttpResponse from .models import Posts # Create your views here. def index(request): # return HttpResponse('HELLO FROM POSTS') posts = Posts.objects.all()[:10] context = { 'title': 'Latest Posts', 'posts': posts } return render(request, 'posts/index.html', context) def details(request, id): post = Posts.object.get(id=id) context = { 'post': post } return render(request, 'posts/details.html', context) details.py file: {% extends 'posts/layout.html' %} {% block content%} <h3 class="center-align red lighten-3">{{post.title}}</h3> <div class = "card"> <div class="card-content"> {{post.body}} </div> <div class="card-action"> {{post.created_at}} </div> </div> <a href="/posts" class="btn">Go Back</a> {% endblock %} Error stacktrace: (py1) C:\Users\Ajmal .M\Google Drive\GitHub\Projects\djangoproject>python manage.py runserver Watching for file changes with StatReloader Performing system … -
The system cannot find the path specified: error returned when changing field in admin page Django
Hi guys I was just following this tutorial (https://realpython.com/get-started-with-django-1/) to integrate a projects application for my Django portfolio-site project. Everything was going well with the set up until I tried to log in to admin page of Django to add more objects to my Project model in the database. After I click add, it return me an error page and it says like this: Error return page [1]: https://i.stack.imgur.com/co1Cy.png Traceback Traceback (most recent call last): File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\username\anaconda3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 607, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\sites.py", line 231, in inner return view(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1638, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1522, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\username\anaconda3\lib\site-packages\django\contrib\admin\options.py", line 1555, in _changeform_view ModelForm = self.get_form(request, obj, change=not add) … -
Django saving data to wrong fields
When I create an object in Django it saves the data to the wrong fields. When I make the following postman request: The return serialized data is correct. But the data saved to the db is not which looks like: The first two fields are correct but the rest are not. It saves the price as the rating, the weight_unit as the price, the user id as the weight and the rating as the user_is. View class CoffeeViewSet(viewsets.ViewSet): def create(self, request): serializer = CoffeeSerializer(data=request.data) if serializer.is_valid(): c = Coffee.objects.create( company = serializer.validated_data.get('company'), rating = serializer.validated_data.get('rating'), weight = serializer.validated_data.get('weight'), weight_unit = serializer.validated_data.get('weight_unit'), blend = serializer.validated_data.get('blend'), price = serializer.validated_data.get('price'), user = request.user ) print(c) return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.data, status=status.HTTP_401_BAD_REQUEST) Serializer class CoffeeSerializer(serializers.ModelSerializer): class Meta: model = Coffee fields = ['company', 'blend', 'rating', 'price', 'weight_unit', 'weight'] also when I print validated_data is correct so my assumption is something with how the object is saved is not correct but I can not figure out. validated data OrderedDict([('company', 'Stumptown'), ('blend', 'Hair Bender'), ('rating', 7), ('price', Decimal('16.00')), ('weight_unit', 'OZ'), ('weight', Decimal('12.00'))]) What is going on here? -
How to call an API endpoint async via Django view
I want to make an async API request to get gifs from the Giphy API. The user triggers the AJAX call and therefor the related view by clicking the submit button. I then want to populate the DOM with the returned GIFs. Right now when I click the submit button, the page reloads and nothing happens. I don't even see the print within the view function. Where do I mess up? Does it even make sense to set up a view for this or just call the API within the AJAX directly? html <script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script> <form> <label for="search">Search</label> <input placeholder="Search gif" id="search" type="search" name="q" action="{% url 'get_gifs' %}"/> <button type="submit" id="btnSearch">Go</button> </form> urls.py from blog.views import get_gifs urlpatterns = [ # Gyphy Search path('get_gifs', get_gifs, name='get_gifs'), ] Ajax (function($) { $('#btnSearch').on('click', function() { var query = $('#search').text(); e.preventDefault(); $.ajax({ type: 'get', async: true, url: '/get_gifs/', data: { 'query': query, 'csrfmiddlewaretoken': window.CSRF_TOKEN // from blog.html }, success: function(data) { console.log(data); }, error: function(xhr, status, error) { // shit happens friends! } }); }); }(jQuery)); Views.py def get_gifs(request, query): print('fired') # create an instance of the API class api_instance = giphy_client.DefaultApi() # API Key api_key = … -
CSS not working on django password form field
I downloaded a css template from the web. I was able to link everything to my Django code execpt for the password fields and button styling. What step am I missing missing? I have read the Django documentatin and I am using the attr metthod to add css attributes to my django form fields. In my python code their seems to be a missing form attribute for password fields when implementing css. #My Forms.py code class CreateUserForm(UserCreationForm): class Meta: model = User fields = [ 'username', 'email', 'password1', 'password2'] #applying form css rules where the item is a call to the css name or form attribute widgets={ 'username': forms.TextInput(attrs={'class':'un', 'type':'text', 'align':'center', 'placeholder':'UserName'}), 'email':forms.TextInput(attrs={'class':'un', 'type':'text', 'align':'center', 'placeholder':'Email'}), 'password1':forms.PasswordInput(attrs={'class':'pass', 'type':'text', 'align':'center', 'placeholder':'password'}), 'password2': forms.PasswordInput(attrs={'class':'pass', 'type':'password', 'align':'center', 'placeholder':'password'}), } #My View function def signup(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() return redirect('login') context = {'form': form} return render(request, "testingapp/signup.html", context) #My css code body { background-color: #F3EBF6; font-family: 'Ubuntu', sans-serif; } .main { background-color: #FFFFFF; width: 400px; height: 400px; margin: 7em auto; border-radius: 1.5em; box-shadow: 0px 11px 35px 2px rgba(0, 0, 0, 0.14); } .sign { padding-top: 40px; color: #8C55AA; font-family: 'Ubuntu', sans-serif; font-weight: bold; font-size: … -
Ajax request returns `Page not found (404)` result
I know what that error means. I need your help to see my code, what I am doing wrong. I want to create an add to wishlist button, here is the tag: <a href="{% url 'listing:wishlist' %}" id="wishlistbtn" data-slug='{{ list.slug }}'>Add to wishlist</a> urls.py path('wishlist/', wishlist, name='wishlist'), Ajax code in template: $(document).on('click', '#wishlistbtn', function (e) { let el = $(this); $.ajax({ type: 'GET', url: "/wishlist/", data: { title_slug: el.attr("data-slug"), }, success: function () { alert('added to wishlist'); } }) }) and here is the view: def wishlist(request): slug = request.GET.get('title_slug') obj = get_object_or_404(Listing, slug=slug) profile = Profile.objects.all().filter(user=request.user).first() profile.wishlist.add(obj) return HttpResponse('true') Kindly help me find the error and solve it. -
use request in form class in django
I have a form just like this: class addMeal(forms.Form): name = forms.CharField(max_length=40,widget=forms.TextInput(attrs={'class':'form-control','placeholder':'نام وعده'})) foods = forms.ModelMultipleChoiceField(queryset=Food.objects.filter(user=1),widget=forms.SelectMultiple(attrs={'class':'form-control'})) class Meta: model = Meals i need write a queryset to get user id with request(see the queryset=Food.objects.filter(user=1) ) what should i do to fix it? -
How does the code use the regex to match the info in the URL here?
class FourDigitYearConverter: regex = '[0-9]{4}' def to_python(self, value): return int(value) def to_url(self, value): return '%04d' % value from django.urls import path, register_converter from . import converters, views register_converter(converters.FourDigitYearConverter, 'yyyy') urlpatterns = [ path('articles/2003/', views.special_case_2003), path('articles/<yyyy:year>/', views.year_archive), ... ] How does the regex variable is used to match the year info in the URL? It is just a class variable. It is from Django docs so I think it must work somehow. Anybody knows how this snippet works? Thanks in advance! -
Django session variable gets deleted when back button is clicked
I am new to django. I want a page (lets say page X) to be accessible by the user only once (that too by a redirect). So what I did is used session variables to do this: This is the view for the page from where I want to redirect the user to X - def MainPageView(request): //Some code which doesn't use or modify session variables request.session['seen_status'] = False redirect ("url_of_X_%d" % some_int) This is the view of X - def Status(request,id): if request.session['seen_status'] == False: //some code which shows the page content request.session['seen_status] = True return render(page) //page contains a button 'A' to go to the next page else: //page to display if user has already seen the page. This works fine if I go to X and refresh (that is, the else block gets executed). But, if the user goes to the next page by clicking the button 'A' and comes back using the back button of the browser, he can see the page again! I tried to debug this by using print statements, that is by printing request.session['seen_status'] but I get an error: Not Found: /favicon.ico Further, on clicking the back button, I don't get anything like: …