Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django cms not updating the page type
I am trying to create the Page Type and use it in the pages, and I can create it and use it in the pages at the time of creating the pages. But after the creation of the Page, I cant update the Page Type. -
Celery task and python function debug together
I have a Test class in the SampleFIle.py file that looks like this: Class Test: def m1(): import ipdb; ipdb.set_trace(); # Some logic In the same file I have a celery task that looks like this: @shared_task() def m1_task(): from celery.contrib import rdb rdb.set_trace() # some logic But The rdb break after the function returns. It doesn't go and checks what m1() contains. How can I debug both celery tasks and related functions for a better understanding of coding flow? -
I need has_perm() example for AbstractBaseUser in django
I have a Custom User Model, and I need to give permissions to users with certain roles (fields in user model) but I couldn't find any examples on the internet, so I'm asking for examples from anybody who has done this before. Here's my Abstract user model for reference: class User(AbstractBaseUser, PermissionsMixin): class RoleChoices(models.TextChoices): admin = 'Admin', _('Admin') cashier = 'Cashier', _('Cashier') waiter = 'Waiter', _('Waiter') courier = 'Courier', _('Courier') customer = 'Customer', _('Customer') username = models.CharField(_('username'), unique=True, max_length=100) name = models.CharField(_('name'), max_length=100) surname = models.CharField(_('surname'), max_length=100) phone_number = models.CharField(_('phone_number'), max_length=100, null=True, default='Invalid Phone Number') role = models.CharField(max_length=50, choices=RoleChoices.choices, default=RoleChoices.customer) active = models.BooleanField(default=True) date_joined = models.DateTimeField(auto_now_add=True) USERNAME_FIELD = 'username' REQUIRED_FIELDS = ['name', 'surname'] class Meta: ordering = ['date_joined', ] def __str__(self): return self.username def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True @property def is_active(self): return self.active objects = CustomUserManager() Thanks in advance, and Please excuse any grammatical errors. -
Error Apollo Client local resolver handling has been disabled and 400 Bad Request
I use GraphQl to access and set JWT token into Authorization Header, but it issues 2 errors, i have done every thing but I cannot resolve and fix it. const client = new ApolloClient({ uri: "http://localhost:8000/graphql/", fetchOptions : { credentials: "include" }, request: operation => { const token = localStorage.getItem('authToken') || ""; operation.setContext({ headers: { Authorization: `JWT ${token}` } }); }, clientState : { defaults: { isLoggedIn: !!localStorage.getItem('authToken') } } }); Dev tools warning that: Found @client directives in a query but no ApolloClient resolvers were specified. This means ApolloClient local resolver handling has been disabled, and @client directives will be passed through to your link chain. POST http://localhost:8000/graphql/ 400 (Bad Request) -
Why {{ form }} represents a form instance in template file?
According to django official doc, All you need to do to get your form into a template is to place the form instance into the template context. So if your form is called form in the context, {{ form }} will render its <label> and <input> elements appropriately. Where is the form instance named/defined as form for template context in django source code? and How can I change the name to something else {{ my_form }} for example ? -
Django - Get urls of all images that reference a Post?
I have this model where a Post can have many Photos. I'm trying to retrieve all posts, including ImageField url attribute (according to Django docs FileField and ImageField have a url attribute). So I'd like to ideally return all the urls of the images associated with the post (ideally in order of created). model.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = models.ManyToManyField(HashTag) class Photo(AbstractBaseModel): created = models.DateTimeField('Created at', auto_now_add=True) post_id = models.ForeignKey(Post, on_delete=models.CASCADE) image = models.ImageField(upload_to=directory_path) view.py def get(self, request): data = Post.objects.order_by('created').values('body', 'goal_id__description', 'created', 'creator_id__username', replies=Count('replypost'), cheers=Count('cheerpost'), image_urls='photo__image_url') return Response(list(data), status=status.HTTP_200_OK) -
how to use django Serializer to update an instance
in Django PUT method, I want to update an instance: sv= SV.objects.get(pk=pk) serializer = SVSerializer(sv, data=request.data) if serializer.is_valid(): Here, in request.data, I just want to pass some of the variable of SV. But as some fields missing, the is_vaild will be false. What I want is, just update the fields in request.data, for the other ones, keep the value in sv. How could I do that? -
Django filter model based on max date
I have a model Drugs with following entries : id location num date country 1 UC ABC 2021-03-26 ZAF 2 UC DEF 2021-03-26 ZAF # line to retrieve with filter 3 UC ABC 2021-09-06 ZAF # line to retrieve with filter I want to select record based on max date for a combinaison loc - num - date for example, in the test case above, I want to only return the laste 2 records as id 3 is more recent than id 1 -
Model form data not showing up in database. Form not saving data
The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly. ps. I've connected my database, ran migrations and created a superuser as well but still nothing. models.py from django.db import models Media_Choices = ( ("TV", "TV"), ("Radio", "Radio"), ("Youtube", "Youtube"), ("Podcast", "Podcast"), ) class Appear(models.Model): Show = models.CharField(max_length=100) Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices) Episode = models.IntegerField() Date = models.DateField(max_length=100) Time = models.TimeField(auto_now=False, auto_now_add=False) Producer = models.CharField(max_length=100) Producer_Email = models.EmailField(max_length=254) def __unicode__(self): return self.Show + ' ' + self.Producer_Email forms.py from django import forms from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Appear class AppsForm(ModelForm): class Meta: model = Appear fields = '__all__' views.py from django.shortcuts import redirect, render from django.http import HttpResponse from .forms import AppsForm from .models import Appear def AppS(request): if request == 'POST': form = AppsForm(request.POST) if form.is_valid(): Apps = form.save(Commit=False) Apps.save() … -
Rendering multiple views and documents based on user settings
I am currently creating a settings menu to figure out what "type" of trial balance a user would like to pull and whether they would want to preview it , print it to pdf or print it to excel My code looks like this... Views.py: def home(request): return render(request , 'main/home.html') def KyletrbSettings(request): if request.GET.get('Excel'): return redirect('main/pdf-trialbalance.html') if request.GET.get('PDF'): return redirect('main/pdf-trialbalance.html') if request.GET.get('Preview'): return redirect('main/Kyletrb.html') def Kyletrb(request): all = 'SELECT Master_Sub_Account , cAccountTypeDescription , Debit , Credit FROM [Kyle].[dbo].[PostGL] AS genLedger'\ ' Inner JOIN [Kyle].[dbo].[Accounts] '\ 'on Accounts.AccountLink = genLedger.AccountLink '\ 'Inner JOIN [Kyle].[dbo].[_etblGLAccountTypes] as AccountTypes '\ 'on Accounts.iAccountType = AccountTypes.idGLAccountType'\ ' WHERE genLedger.AccountLink not in (161,162,163,164,165,166,167,168,122)' cursor = cnxn.cursor(); cursor.execute(all); xAll = cursor.fetchall() cursor.close() xAll_l = [] for row in xAll: rdict = {} rdict["Description"] = row[0] rdict["Account"] = row[1] rdict["Debit"] = row[2] rdict["Credit"] = row[3] xAll_l.append(rdict) creditTotal = ' Select ROUND(SUM(Credit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(creditTotal); xCreditTotal = cursor.fetchone() debitTotal = ' Select ROUND(SUM(Debit) , 2) FROM [Kyle].[dbo].[PostGL] ' cursor = cnxn.cursor(); cursor.execute(debitTotal); xDebitTotal = cursor.fetchone() return render(request , 'main/Kyletrb.html' , {"xAlls":xAll_l , 'xCreditTotal':xCreditTotal , 'xDebitTotal':xDebitTotal}) def printToPdf(request): response = HttpResponse(content_type= 'application/pdf') response['Content-Disposition']= 'attachment; filename=TrialBalance' + \ str(datetime.now()) + '.pdf' response['Content-Transfer-Encoding'] = 'binary' all … -
Django - how to match URL pattern regex with additional parameters?
I have the following endpoint at my urls.py url(r'^stream/(?P<pk>[0-9a-f-]+)$', App_Views.stream, name='stream'), That would mean that the endpoint would look like this on call: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156 Now I'm adding some extra parameters to the URL before calling it, so that it looks like this: http://localhost/stream/5409caac-fc9c-42b8-90af-058eff65a156?st=zD3H0cHJrbcUAHZPNbPGyg&e=1630915404 Now to my actual question, how does the regex at urls.py has to look like in order to accept the second URL example? Already dealing with this since 2 days and was not able to find a solution. Thanks in advance -
How to retrieve the .count in a django template through ManyToManyField
I have some models, which are connected via manytomany or foreignkey. I would like to get a .count value for tutor.students.lessons.type and display the number of lessons online or class based. I have tried to pass in tuttype= tutorObj.students.get(type="CLASS") through the views which does not get the required result and have been trying out {{tutorobj.students.type.ONLINE.get}} {{tutorobj.students.get(type=ONLINE)}} in the templates with no luck also models.py class Tutor(models.Model): name = models.CharField(max_length=200, null=True, blank=True) students = models.ManyToManyField('Student', blank=True) lessons = models.ManyToManyField('Lesson', blank=True) lesson_reviews = models.ManyToManyField('LessonNote', blank=True) created = models.DateTimeField(auto_now_add=True) id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) def __str__(self): return self.name class Student(models.Model): GENDER_CHOICES = ( ('M', 'Male',), ('F', 'Female',) ) TYPE_CHOICES = ( ('CLASS', 'Class',), ('ONLINE', 'Online',) ) YEAR_CHOICES = ( ('K1', 'Kindergarten 1',), ('K2', 'Kindergarten 2',), ('K3', 'Kindergarten 3',), ('P1', 'Primary 1',), ('P2', 'Primary 2',), ('P3', 'Primary 3',), ('P4', 'Primary 4',), ('P5', 'Primary 5',), ('P6', 'Primary 6',), ('M1', 'Mathayom 1',), ('M2', 'Mathayom 2',), ('M3', 'Mathayom 3',), ('M4', 'Mathayom 4',), ('M5', 'Mathayom 5',), ('M6', 'Mathayom 6',), ('C', 'College',), ('U', 'University',), ('A', 'Adult',), ) taught_by = models.ForeignKey(Tutor, on_delete=models.SET_NULL, null=True, editable=False) name = models.CharField(max_length=200, null=True, blank=True) school_year = models.CharField(max_length=2, choices=YEAR_CHOICES, null=True, blank=True) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=True, blank=True) type = models.CharField(max_length=7, choices=TYPE_CHOICES, null=True, blank=True) hours_weekly = … -
How to connect Google Sheets with PostgreSQL database in a server?
So I have a server with a Django backend using PostgreSQL, but now I need to connect the database to this Google sheet to add on to the current database. How do I do this? I did some research and installed the KIPbees addon in Google Sheets. However, I do not know what the hostname for the database should be. -
how does django class based view cycle go around?
got request a worker initialize a class based view instance returns a response and destroies the view instance or view instance is initialized when server starts up workers wait in queue to get response and returns a response from view instance view instance lives forever I suddenly came to realize that i've been using Django for several years and still don't know how it works so.. which one is it? Thanks -
Django - How to properly receive multi-image upload via POST?
I have this view.py and models.py files below that supposed to support uploading multiple images. I have tests that work and do generate images, but the images are attached to the POST request as a ByteIO format. I'd like this endpoint to receive a POST request from a React Native front-end containing an image and I don't know if it'll be in ByteIO format. I tried sending an image in byte format by doing with open('./media/test.png', 'rb') as f: image = f.read() But it turns the QueryDict that is request.data into an immutable dict for some reason. As you can see below that's an issue as I do change it. Is the way I've implemented it correct for receiving multiple image uploads from React Native? view.py class PostView(APIView): def post(self, request): post_body = request.data['body'] hash_tags_list = extract_hashtags(post_body) hash_tags = [HashTag.objects.get_or_create( hash_tag=ht)[0].hash_tag for ht in hash_tags_list] request.data['hash_tags'] = hash_tags serializer = PostSerializer(data=request.data) if serializer.is_valid(): try: post_obj = serializer.save() if 'images' in request.FILES.keys(): for img in request.FILES.getlist('images'): Photo.objects.create(post_id=post_obj, image=img) except django.db.utils.InternalError as e: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) models.py class Post(AbstractBaseModel): creator_id = models.ForeignKey( User, on_delete=models.CASCADE, related_name="post_creator_id") goal_id = models.ForeignKey(Goal, on_delete=models.CASCADE) body = models.CharField(max_length=511, validators=[MinLengthValidator(5)]) hash_tags = … -
How to upload image/media file from React to Django API?
I am able to save the data without the image field. I am new to react so don't know pretty much about this type of problems. What is the problem with the image field?? this isn't showing me any error just my image data is not saving. I am sharing all my code it will be really helpful if you guys help me out. #models.py class Test(models.Model): full_name = models.TextField(max_length=200, blank=True, null=True) image = models.ImageField(null=True, blank=True) address = models.TextField(max_length=200, blank=True, null=True) def __str__(self): return str(self.id) #views.py @api_view(['POST']) def add(request): data = request.data test = Test.objects.create( full_name = data['full_name'], address = data['address'], ) serializer = TestSerializer(test, many=False) return Response(serializer.data) #this is screen for react page import React from 'react'; class Test extends React.Component{ constructor(){ super(); this.state={ full_name:'', image: '', address:'' } this.changeHandler=this.changeHandler.bind(this); this.submitForm=this.submitForm.bind(this); } // Input Change Handler changeHandler(event){ this.setState({ [event.target.name]:event.target.value }); } // Submit Form submitForm(){ fetch('http://127.0.0.1:8000/api/orders/test',{ method:'POST', body:JSON.stringify(this.state), headers:{ 'Content-type': 'application/json; charset=UTF-8', }, }) .then(response=>response.json()) .then((data)=>console.log(data)); this.setState({ full_name:'', image: '', address:'' }); } render(){ return ( <table className="table table-bordered"> <tbody> <tr> <th>Full Name</th> <td> <input value={this.state.full_name} name="full_name" onChange={this.changeHandler} type="text" className="form-control" /> </td> </tr> <tr> <th>Voucher</th> <td> <input value={this.state.image} name="image" onChange={this.changeHandler} type="file" className="form-control" /> </td> </tr> <tr> <th>Address</th> <td> <input … -
why the user is not logged in after registration in django
views.py ( after registration it is not logged in , can anyone help me to solve why this is happening there after successfully creating user but not logged in by user. User creates table in data base successfully and register consider all the required added def login_view(request): if request.method == "POST": # Attempt to sign user in email = request.POST["email"] password = request.POST["password"] user = authenticate(request, username=email, password=password) # Check if authentication successful if user is not None: login(request, user) return redirect('home') else: return render(request, "login.html", { "message": "Invalid email or password." }) else: return render(request, "login.html") models.py ( consider all required install or added ) class User(AbstractUser): G = [ ('Female', 'Female'), ('Male', 'Male'), ('Others', 'Others'), ] address = models.TextField(max_length=50 ,default='' ,null=True,blank=True) phone = models.CharField(max_length=15 ) email = models.EmailField(max_length=100 ,default='') password = models.CharField(max_length=500) Gender = models.CharField(max_length=150,choices=G ,default='',null=True,blank=True) def __str__(self): return self.email def register(self): self.save() @staticmethod def get_customer_by_email(email): try: return User.objects.get(email=email) except: return False def isExists(self): if User.objects.filter(email = self.email): return True return False is_staff = models.BooleanField(('Staff status'),default=True,) is_active = models.BooleanField(('Active'),default=True,) login.html ( where user can logged but not working ) <div class="loginContainer"> {% if message %} <div><i>{{ message }}</i></div> {% endif %} <div class="login__form"> <h2>Login</h2> <form action="{% url 'login' … -
django.db.utils.ProgrammingError: relation "Industry" does not exist // LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR
enter image description here enter image description here django.db.utils.ProgrammingError: relation "Industry" does not exist LINE 1: SELECT "Industry"."id", "Industry"."Name" FROM "Industry" OR... -
How can I display data stored in a Django model using CSS styles?
I have a for loop to display an image, title and description from a Django model, and it works good. but I want the title and description to be displayed as overlay on the image. Is there any way to do that? This code displays the data: <div class="tz-gallery"> <div class="row"> {% for service in services %} <div class="col-sm-6 col-md-4"> <h6 class="text-center">{{service.title}}</h6> <a class="lightbox" href="{{service.image.url}}"> <img src="{{service.image.url}}" alt="Park"> </a> <p>{{service.content}}</p> </div> {% endfor %} </div> </div> And I want the service.title and service.image.url to be displayed with this css style while the for loop iterates .tz-gallery .lightbox:after { position: absolute; top: 0; left: 0; width: 100%; height: 100%; opacity: 0; background-color: rgba(46, 132, 206, 0.7); content: ''; transition: 0.4s; } .tz-gallery .lightbox:hover:after, .tz-gallery .lightbox:hover:before { opacity: 1; } How could I do that? -
Django Models Design: Solo-Player OR Team with players in Game
I'm designing a Django based webinterface for a game which can be played eiter solo OR as a team. A game is based on points; First party to reach set number of points wins. For later statistics and displaying, points have a timestamp. My Problem: How can I have either two Players OR two Teams in one Game? My Models look like this at the moment: from django.db import models # Create your models here. class Player(models.Model): slug = models.SlugField(unique=True) # will be autogenerated when inserting new Instance name = models.CharField(max_length=100) wins = models.IntegerField() losses = models.IntegerField() picture = models.ImageField(upload_to='images/player_pics') # games_played = wins + losses def __str__(self): return self.name class Team(models.Model): slug = models.SlugField(unique=True) name = models.CharField(max_length=100) players = models.ManyToManyField(Player) wins = models.IntegerField() # from here on seems redundant to Player class losses = models.IntegerField() picture = models.ImageField(upload_to='images/team_pics') # games_played = wins + losses def __str__(self): return self.name class Point(models.Model): val = models.IntegerField() timestamp = models.DateTimeField() class Game(models.Model): slug = models.SlugField(unique=True) timestamp = models.DateTimeField() players = models.ManyToManyField(Player) # here should be either Team or Player points = models.ManyToManyField(Point) My Idea was to implement another class like GameParty which can be either a Player or a Team but the same … -
How to not trigger `m2m_changed` signal when updating many to many relationship in Django?
The Use Case In my case, I have two signals that are listening on two 2 m2m fields, each of those fields are in different models. The problem happens when one signal is triggered, it triggers the other signal and vice versa, which will result in a recursive loop which will never ends. I need a convenient way to run one signal without triggering the second signal. Understand More If you are curious to know how this case could happen: I have two models which I need to make them mutually synced; if I updated the m2m field in the one model, I need those changes to be reflected on another m2m field in another model and vice versa. -
Unable to restore DB after Database change to Postgres (Django)
I have migrated from SQLite to Postgres, but now I am unable to restore my data on Postgres, i am using Django db-backup package, it is giving me this error on dbrestore command Traceback (most recent call last): File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 22, in <module> main() File "C:\Users\atifs\Documents\food_deliveryapp\fooddelivery\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\management\commands\dbrestore.py", line 53, in handle self._restore_backup() File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\management\commands\dbrestore.py", line 94, in _restore_backup self.connector.restore_dump(input_file) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\base.py", line 92, in restore_dump result = self._restore_dump(dump) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\postgresql.py", line 56, in _restore_dump stdout, stderr = self.run_command(cmd, stdin=dump, env=self.restore_env) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\postgresql.py", line 21, in run_command return super(PgDumpConnector, self).run_command(*args, **kwargs) File "C:\Users\atifs\Documents\food_deliveryapp\virtual-env\lib\site-packages\dbbackup\db\base.py", line 150, in run_command raise exceptions.CommandConnectorError( dbbackup.db.exceptions.CommandConnectorError: Error running: psql --host=localhost --port=5432 --username=postgres --no-password --set ON_ERROR_STOP=on --single-transaction postgres ERROR: syntax error at or near "AUTOINCREMENT" LINE 1: ...S "auth_group" ("id" integer NOT NULL PRIMARY KEY AUTOINCREM... -
AttributeError: 'function' object has no attribute 'as_view' | Django
Don't know why this error occur. ERROR Watching for file changes with StatReloader Performing system checks... Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Qasim Iftikhar\anaconda3\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\Qasim Iftikhar\anaconda3\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\management\base.py", line 419, in check all_issues = checks.run_checks( File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config return check_resolver(resolver) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver return check_method() File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 412, in check for pattern in self.url_patterns: File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Qasim Iftikhar\anaconda3\lib\site-packages\django\urls\resolvers.py", line 591, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Qasim Iftikhar\anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 783, in exec_module … -
Jquery CurrentLink Detector with wildcard support for django?
I have a snippet which words good on html files, as it check filename and compare url to make menu active ! It also works on web framework like django, but the problem is that it doesnt support sub urls, Menu changes active, when i go to "example.com/profile" But it doesnt gets active when i go to "example.com/profile/another/123" How to make this snippet which can support wildcard urls' I need it to make active irrespective to what comes after the /profile CurrentLink = function(){ var _link = '.nk-menu-link, .menu-link, .nav-link', _currentURL = window.location.href, fileName = _currentURL.substring(0, (_currentURL.indexOf("#") == -1) ? _currentURL.length : _currentURL.indexOf("#")), fileName = fileName.substring(0, (fileName.indexOf("?") == -1) ? fileName.length : fileName.indexOf("?")); $(_link).each(function() { var self = $(this), _self_link = self.attr('href'); if (fileName.match(_self_link)) { self.closest("li").addClass('active current-page').parents().closest("li").addClass("active current-page"); self.closest("li").children('.nk-menu-sub').css('display','block'); self.parents().closest("li").children('.nk-menu-sub').css('display','block'); } else { self.closest("li").removeClass('active current-page').parents().closest("li:not(.current-page)").removeClass("active"); } }); }; This is the snippet ! Am asking this for django -
How to unpack OrderedDict in python?
serializers.py def create(self, validated_data): choice_validated_data = validated_data.pop('choices') print("jdsfd this from vdata sdjfdsjf", validated_data) question = Question.objects.create(**validated_data) for each in choice_validated_data: choice = Choice.objects.create(text=each, question=question) choice.save() return question Output i want... { "title": "Added from admin", "choices": [ { "id": 144, "text": "asdf1" }, { "id": 145, "text": "asdf2" } ] } Can anyone help me out to fix this issue, I am facing it from almost 5 days. Please can anyone fix the code.