Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
The use of ForeingKey on django when I create an object is also creating an object from the foreignkey model
I have a function on the main app of the website i'm working on that creates a User - the model name is "Usuario" (different from the default User model that django provides). The model is: class Usuario(models.Model): email = models.CharField(max_length=250) data_cadastro = models.DateTimeField(default=now) telefone = models.CharField(validators=[phone_regex], max_length=17, blank=True) # validators deve ser uma lista renda = models.DecimalField(default=0,max_digits=14,decimal_places=2) longitude = models.DecimalField(default=0,max_digits=20,decimal_places=12) latitude = models.DecimalField(default=0,max_digits=20,decimal_places=12) (the names of the fields are in Portuguese) This model is connected to a different one in another app by a simple foreing key (usuario). The other model is: from core.models import Usuario class Simulacao(Usuario): usuario = models.ForeignKey(Usuario, related_name="Usuario_contas", on_delete=models.CASCADE) data_simulacao = models.DateTimeField(default=now, verbose_name="Data simulação") tem_conta = models.BooleanField(default=False) class Meta: verbose_name = 'Simulação' verbose_name_plural = 'Simulações' def __str__(self): return self.nome def __unicode__(self): return self.nome The function where I create the "Simulacao" object is this one: from .models import Simulacao, Tipo_Pessoa from core.models import Usuario from django.utils.timezone import now def cadastro_simulacao(form, email): nova_simulacao = Simulacao.objects.create(usuario = Usuario.objects.get(email = email), tem_conta=form['tem_conta']) usuario.Usuario_contas_set.add(nova_simulacao) usuario.save() All i've done is based on the Django documentation: https://docs.djangoproject.com/pt-br/2.1/topics/db/examples/many_to_one/ I have also tried the function like that: from .models import Simulacao, Tipo_Pessoa from core.models import Usuario from django.utils.timezone import now def cadastro_simulacao(form, email): nova_simulacao … -
Django - override __str__ method for a single queryset
I have my User model, and overrode the __str__ method as such: def get_django_user_full_name(self): return self.get_full_name() User.add_to_class("__str__", get_django_user_full_name) Now the issue: I have a specific dropdown menu where I want it to display the users in a different manner, namely: def get_user_name_last_first_email(self): return self.last_name + ', ' + self.first_name + ', ' + self.email User.add_to_class("last_first_email", get_user_name_last_first_email) The specific dropdown menu form field is: assignee = forms.ModelMultipleChoiceField(queryset=User.objects.filter(groups__name='actor').order_by('last_name'), required=False) However, this dropdown menu, as it should, displays in the default "first_name last_name" way. I cannot figure out a way to force it to instead display the names as "last_name, first_name, email' in the dropdown menu - using the custom property I built or not. The only way I found to override it is to use values_list() but that either only returns one field (if flat=True) or returns all 3, but as an ugly tuple. tl;dr How do I customize the display (i.e. the __str__ method) of a single queryset? -
django.db.utils.ProgrammingError: relation "django_content_type" does not exist
I've a project that I've built up slowly on my PC and it is working fine. I'm just trying to put it onto a server and I'm getting this error: django.db.utils.ProgrammingError: relation "django_content_type" does not exist I cannot work out the issue and the posts on Stackoverflow suggest deleted migrations and recreating them, which I done but have the same issue. If you could guide me as to what I should be looking for I would be grateful. Here's my traceback: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/base.py", line 288, in run_from_argv self.execute(*args, **cmd_options) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/base.py", line 332, in execute self.check() File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/base.py", line 364, in check include_deployment_checks=include_deployment_checks, File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/commands/migrate.py", line 58, in _run_checks issues.extend(super()._run_checks(**kwargs)) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/management/base.py", line 351, in _run_checks return checks.run_checks(**kwargs) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/checks/registry.py", line 73, in run_checks new_errors = check(app_configs=app_configs) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 40, in check_url_namespaces_unique all_namespaces = _load_all_namespaces(resolver) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/core/checks/urls.py", line 57, in _load_all_namespaces url_patterns = getattr(resolver, 'url_patterns', []) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/utils/functional.py", line 36, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/urls/resolvers.py", line 540, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/var/www/jobsite/env/lib/python3.5/site-packages/django/utils/functional.py", line 36, in … -
Django join tables with ORM and conditional Where clause
I have 3 tables to join; Personnels,Machines and Locations. I want to join these tables and add where clause to end of the ORM query if request body includes filtering data. Here is my raw query (I want to write this query in django ORM) and sample if condition for where clause; query = '''select * from "Sales" as "SL" INNER JOIN "Personnels" as "PL" ON ("SL"."PersonnelId" = "PL"."user_id") INNER JOIN "Machines" as "MC" ON ("SL"."MachineId" = "MC"."id") INNER JOIN "Locations" as "LC" ON ("SL"."LocationId" = "LC"."id") ''' if request.method=='POST': if request.data['personnel_name'] and request.data['personnel_name'] is not None: personnel_name = request.data['personnel_name'] condition = '''WHERE "PL"."name" = '{0}' '''.format(personnel_name) query = query+condition As it is seen, there are lots of quotes (if I don't write,postgresql makes some trouble) and code is not clean. My question is, how can I write this query with using django ORM? As you see, I want to add where conditions dynamically. How can I achieve that? -
Cannot query "ABC": Must be "Image" instance
I came across an error message within the model.py. I would appreciate if you guys could give me some assistance on this; the following are parts of the model.py: class WorkJob(models.Model): id = models.AutoField(primary_key=True) share = models.ForeignKey(FShare, on_delete=models.PROTECT) aftId = models.ForeignKey(AftId, null=True, blank=True, on_delete=models.PROTECT) history = HistoricalRecords() class Image(models.Model): id = models.AutoField(primary_key=True) imagingJob = models.OneToOneField(WorkJob, on_delete=models.PROTECT) md5 = models.CharField(max_length=32, null=True, blank=True) originalCopy = models.ForeignKey(Disc, related_name='originalCopy', null=True, blank=True, on_delete=models.PROTECT) workingCopy = models.ForeignKey(Disc, related_name='workingCopy', null=True, blank=True, on_delete=models.PROTECT) history = HistoricalRecords() class Copy(models.Model): id = models.AutoField(primary_key=True) image = models.ForeignKey(Image, on_delete=models.PROTECT) disc = models.ForeignKey(Disc, on_delete=models.PROTECT, related_name='copy') history = HistoricalRecords() def aftId(self): return self.image.imagingJob.aftId.aft the next class is the one that I have problems. class TFI(models.Model): id = models.AutoField(primary_key=True) createDate = models.DateTimeField(auto_now_add=True, null=True) status = models.IntegerField(choices=STATUS_OPTIONS, default=0) history = HistoricalRecords() def check_third(self): if self.status == 5: im = 0 third_imajob = WorkJob.objects.filter(share=self.share) for ima in third_imajob: if Copy.objects.filter(image__exact=ima.aftId).exists(): # some code blablabla else: break The line that the error message says that it is problematic is: if Copy.objects.filter(image__exact=ima.aftId).exists(): I am not certain why is it saying that the instance must be with Image. The line clearly is extracting from class Copy and WorkJob. I did see that that the Copy.image has a foreignkey reference to … -
getting data from pre-populated formset
i'm working on little project where i used the modelfomset_factory ,everything is working just fine, i just want that to use the images url passed to the formset to display it on my template so the user can know which image he wants to change. views.py def ProductUpdate(request, pk): product = Product.objects.get(pk=pk) formset_i = modelformset_factory(ImageModel,fields=('Image',), extra=0) if request.method == 'POST': formset=formset_i(request.POST,request.FILES) productForm = updateProduct(request.POST) if productForm.is_valid() and formset.is_valid(): product.Name=productForm.cleaned_data['Name'] product.Price=productForm.cleaned_data['Price'] product.Description=productForm.cleaned_data['Description'] product.Type=productForm.cleaned_data['Type'] product.save() formset.save() return redirect(reverse('my_products')) else: messages.error(request, ('Please correct the error below.')) else: image=ImageModel.objects.filter(product=product) formset=formset_i(queryset=image) productForm = updateProduct(instance=product) return render(request, 'store/product_update.html', {'form': productForm, 'product': product,'form2':formset}, ) product_update.html <form method="post" action="{% url 'product_update' product.pk %}" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} {{ form2.management_form }} {% for fr in form2 %} <img src="{{ fr.Image.url }}" style="width:150px;height:150px" > {{ fr.as_p }} {% endfor %} <button type="submit" class="btn btn-primary">Ajouter</button> </form> the image won't display i think i'm not doing it wright -
Assign Permission in User Role Django
I want to create HR Role and assign role into user. But when I assign to user and I check the User permissions of the user that I assigned, It doesn't the correct permissions that I wish. role.py from rolepermissions.roles import AbstractUserRole class Hr(AbstractUserRole): available_permissions = { 'Can add candidate rank': True, 'Can change candidate rank': True, 'Can delete candidate rank': True, 'Can view candidate rank': True, } model.py from django.db import models class CandidateRank(models.Model): """docstring forCandidate_History_Education.""" candidate = models.CharField(max_length=50, blank=True, null=True) count = models.CharField(max_length=50, blank=True, null=True) def __int__(self): return self.candidate The Chosen user permissions that show like this... auth | user | Can add candidate rank auth | user | Can change candidate rank auth | user | Can delete candidate rank auth | user | Can view candidate rank So I don't want, I want like this *** rank | candidate rank | Can add candidate rank rank | candidate rank | Can change candidate rank rank | candidate rank | Can delete candidate rank rank | candidate rank | Can view candidate rank -
django generic view: detail in category
I use a generic view to list my categories. I would also like to display the title of each items belonging to these categories. I understand the principle of ListView and DetailView but what about some details in lists ? Here are my different files: Models.py class categories(models.Model): name = models.CharField(max_length=50,unique=True) slug = models.SlugField(max_length=100,unique=True) def __str__(self): return self.name class details(models.Model): title = models.CharField(max_length=100) author = models.CharField(max_length=42) category = models.ForeignKey('categories', on_delete=models.CASCADE) def __str__(self): return self.title Views.py class IndexView(generic.ListView): model = categories context_object_name = "list_categories" template_name='show/index.html' Urls.py urlpatterns = [ path('', views.IndexView.as_view(), name='index'), ] Index.html {% load static %} <p>These is a list of categories</p> {% for category in list_categories %} <div class="article"> <h3>{{ category.name }}</h3> {% for title in category.detail %} <p> {{title}} </p> {% endfor %} </div> {% endfor %} -
Django Admin changeform_view methosdont' permit open edit data
In my django project i whant add a table with last data insert above any add/edit form, so in my admin.py i write: class t_proj_routeAdmin(admin.ModelAdmin): def changeform_view(self, request, obj_id=None, form_url='', extra_context=None): l_mod = t_proj_route.objects.latest('id') extra_context = { 'lmod': l_mod, } return super(t_proj_routeAdmin, self).changeform_view(request, extra_context=extra_context) then in my template use the data for add a table. All done if i open an ADD page,, but whe i try to modify an already present record django redirect me ever on a new ADD, and i am unable to open edit page with data selected. How can i use this technique for manage ADD and EDIT record? Thanks in advance -
Assign a separate html page to each user in django admin
I have 15 users in my django model and they are displayed on an html page by using the html code: {% for user in users %} <h3>{{ user.get_full_name }}</h3> {% endfor %} I want for each user to have a different html page. I would like for the name of the user to be a hyperlink and when you click on the link, it will go to the html page of that user's page. views.py: def user1(request): if request.method =='POST': if form.is_valid(): form.save() return redirect('user1') else: return render(request, 'accounts/user1.html') def user2(request): if request.method =='POST': if form.is_valid(): form.save() return redirect('user2') else: return render(request, 'accounts/user2.html') How do I connect each user in the "for users" with their own html page. Since I am not writing out every user manually and adding a tag, I am confused on how to give each user a separate html page using this format. -
Is there a limitation on running db query in imported function in django tests?
I am using function in views to query db (postgresql), calculate values and return list of lists. When I call it from views.py I get what is expected. When I call it from test.py I get empty list (not error, not None). To investigate I have created list of lists in views function manually and it was returned just fine (so there is no issue with import or length of returned value). It seems that if I call function imported from views that makes a db query and it is called from TestCase object then the db query is not done. Why? from django.test import TestCase from <my app>.views import calc import datetime from pytz import timezone class CalcTestCase(TestCase): maxDiff = None def test_calc_image(self): start_time = datetime.datetime(2018, 9, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') ) finish_time = datetime.datetime(2018, 10, 1, 0, 0, 0, 0, tzinfo=timezone('UTC') ) instance_type = "test" output = calc(instance_type, start_time, finish_time) test_output = [[test, values, in],[list, of, lists]] self.assertEqual(output, test_output) -
format_suffix_patterns error in django 2.1 and python 3.6.5
I'm upgrading from Django==1.11 to Django==2.1 and i can't solve this error. This line of code: urlpatterns = format_suffix_patterns(urlpatterns, allowed=['api', 'json', 'xml']) show this error: AttributeError: 'list' object has no attribute 'regex' Thanks in advance. -
Add form choices as options in a select tag html
I'm in my final project and I'm a little bit lost on what I'm doing now. I'm developping a website and I need to insert some choices into a html select tag, I mean, that choices must be options of this select tag. I'm trying it, but the dropdown doesn't appear as it should, and, when I try to submit my form, it gives me an error. I wish you could help me, I'm becoming crazy. Here I leave my code, feel free to ask anything you want forms.py class FormCancion(forms.ModelForm): NOTAS_CHOICES=(('35','Acoustic Bass Drum'),('36','Bass Drum 1'),('37','Side Stick'),('38','Acoustic Snare'),('39','Hand Clap'), ('40','Electric Snare'),('41','Low Floor Tom'),('42','Closed Hi Hat'),('43','High Floor Tom'),('44','Pedal Hi-Hat'), ('45','Low Tom'),('46','Open Hi-Hat'),('47','Low-Mid Tom'),('48','Hi-Mid Tom'),('49','Crash Cymbal 1'),('50','High Tom'), ('51','Ride Cymbal 1'),('52','Chinese Cymbal'),('53','Ride Bell'),('54','Tambourine'),('55','Splash Cymbal'), ('56','Cowbell'),('57','Crash Cymbal 2'),('58','Vibraslap'),('59','Ride Cymbal 2'),('60','Hi Bongo'),('61','Low Bongo'), ('62','Mute Hi Conga'),('63','Open Hi Conga'),('64','Low Conga'),('65','High Timbale'),('66','Low Timbale'),('67','High Agogo'), ('68','Low Agogo'),('69','Cabasa'),('70','Maracas'),('71','Short Whistle'),('72','Long Whistle'),('73','Short Guiro'), ('74','Long Guiro'),('75','Claves'),('76','Hi Wood Block'),('77','Low Wood Block'),('78','Mute Cuica'),('79','Open Cuica'), ('80','Mute Triangle'),('81','Open Triangle')) nota_pad_gris = forms.ChoiceField(choices=NOTAS_CHOICES, widget=forms.Select()) views.py: def crearCancion(request): cancion=Cancion() if request.method=="POST": formulario=FormCancion(request.POST,request.FILES,instance=cancion) if formulario.is_valid(): formulario.save() return HttpResponseRedirect('/ListadoCanciones/') else: formulario=FormCancion() context={'formulario':formulario} return render(request,"nuevaCancion.html",context) .html: <br><br><br> <div class="container"> <form id='formulario' method='post' {% if formulario.is_multipart %} enctype="multipart/form-data" {% endif %} action=''> {% csrf_token %} <center> <label for="nota_pad_gris">Nota del pad Gris:</label> … -
Organizing templates in a django project
I am trying to use the "app-specific" approach to organizing various django apps. For example: - app2 - __init__.py - urls.py - views.py -templates/ - app2 - __init__.py - urls.py - views.py -templates/ - manage.py - settings.py One issue I'm having with this though is where to put the base templates that everything inherits from? For example, at the top of all my templates I have {% includes "base.html" %}, but if I'm doing the above I don't see how I could do this in a logical fashion. -
def() defined in a class are not executed
I defined a class that has a get method. When the user sends a request with the get method, the method fetches the data from the database, and then makes some changes and sends it to the user. However, I tried it. When the user initiates a get request, only the following two lines of code are executed queryset = Product.objects.all() serializer_class = ProductSerializer and the get method is not executed. ## urls.py router.register(r'getList', ProductListViewset) ## views.py class ProductListViewset(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer def get(self, request, format=None): serializer = ProductSerializer data = serializer.data username = data.get('user_name') user = User.objects.get(username__exact=username) new_data = { 'id': data.get('id'), 'user_name': data.get('user_name'), 'user_image_URL': user.get('user_image_URL'), 'c_time': data.get('c_time'), 'goods_price': data.get('goods_price'), 'title': data.get('title'), 'description': data.get('description') } return Response(new_data, 200) -
How to access a field with reverse name = '+' in Django?
How do you define the reverse relation from another object to this one with a '+' as it's related name? class FeaturedContentPage(Page): featured_page = models.ForeignKey( 'wagtailcore.Page', null=True, blank=True, on_delete=models.SET_NULL, related_name='+', ) -
render Django HTML tag using JavaScript
I have installed in my project django-contib-comments and I have an HTML that displays the list of comments and also displays the form to enter a new one. I now want to use Ajax to submit the form without a page refresh and on success to add the submitted comment to the list. I have done most of the work, but I'm sure there must be an easier way to achieve this. my question is if there is a way for me to render a Django HTML tag within a javascript something like this: document.getElementById("comments").innerHTML = {% render_comment_list for obj %} so far this is the code I have done: 1) I don't want to change anything in the django-contrib-comments project (i am avoiding to override methods. 2) I used the standard tags in django-contrib-comments to render a list of comments. {% render_comment_list for obj %} 3) Created a JavaScript that handles the submit of the form and then creates a new entry in the list. function submit_comments(event) { event.stopPropagation(); $.ajax({ type: $('#comment_form').attr('method'), url: $('#comment_form').attr('action'), data: $('#comment_form').serialize(), cache: false, dataType: "html", success: function (html, textStatus) { var comment_count_btn = document.getElementById('comment-text-vertical-btn'); if (comment_count_btn != null) { if (!isNaN(parseInt(comment_count_btn.innerHTML))) { comment_count_btn.innerHTML = … -
Django translate the user permissions
Hello is it possible to translate the user permissions This is in bulgarian but there is still cam add/can change can anyone help please I found it in the db.json can i override it somehow? There is in the db.json -
Django username/password and api key JWT authentications
I have some requirements where I need to be able to authenticate the user either with username/password or with an api_key and return a JWT token for both cases. My approach with the username/password: if request.data['email'] and request.data['password']: try: user = User.objects.get(email=request.data['email']) except User.DoesNotExist: return Response({'Error': "Invalid username."}, status=status.HTTP_400_BAD_REQUEST) if user: if user.check_password(request.data['password']): payload = jwt_payload_handler(user) token = jwt_encode_handler(payload) exp = datetime.now() + api_settings.JWT_EXPIRATION_DELTA return Response({'token': token, 'exp': format(exp, 'U')}, status=status.HTTP_200_OK) else: return Response({'Error': "Invalid password."}, status=status.HTTP_400_BAD_REQUEST) where jwt_payload_handler is implemented as: def jwt_payload_handler(user): payload = { "id": user.id, "date": get_user_join_date(user), "username": user.username, } return payload One of my questions is doesn't the keyword username need to be in the payload for the token to be a valid one? What would a good approach be in the case of the api_key considering the key is not related to a user? Should i create a default user that will be used in the payload given the api_key provided was correct? Any suggestions? -
Django 2 ModelFormSet not submitting new entries
I have a very simple Django grocery list app that I am using to learn the framework, and I'm using a modelformset to display/edit/add items in the list. The problem I am having is that when I attempt to POST changes to the formset, it fails the .is_valid() condition. formset.errors response is [{'id': ['This field is required.']}, {}], but all documentation/web lore says to not mess with the autogenerated id field, so I'm not sure why it is not working/why the ID field is not being generated. models.py from django.db import models # Create your models here. class Grocery(models.Model): itemName = models.CharField(max_length=64) itemQuantity = models.IntegerField() itemChecked = models.BooleanField(default = False, blank = False, null = False) forms.py from django.forms import ModelForm from .models import Grocery class GroceryForm(ModelForm): class Meta: model = Grocery fields = ['itemName', 'itemQuantity', 'itemChecked'] views.py from django.shortcuts import render from django.forms import modelformset_factory from .models import Grocery from .forms import GroceryForm def index(request): GroceryFormSet = modelformset_factory(Grocery, form=GroceryForm, can_order=True, can_delete=True, ) formset = GroceryFormSet(request.POST or None) if request.method == 'POST': print(formset.errors) if formset.is_valid(): formset.save() context = { 'formset': formset, } return render(request, "Lister/index.html", context) index.html <form method="post" action=""> {% csrf_token %} {{ formset.management_form }} <table> <tr> <th>Grocery Thing</th> … -
How do I access forms in a form_list in the done method in formwizard?
from views.py def done(self, form_list, **kwargs): user = self.request.user resumes = form_list[0] resumes.user = user resumes.save() return HttpResponseRedirect(reverse('resumes:my-resumes')) from forms.py class ResumeForm(ModelForm): class Meta: model = Resume fields = ['name', ] from models.py class Resume(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True, editable=False) updated_at = models.DateTimeField(auto_now=True) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.name Hi, I'm trying to configure the done method in my Wizard view (extends SessionWizardView). I want to access the first form in the form_list but this throws an error? What am I doing wrong? I'm trying to insert user into a model before saving it (resume requires a user foreign key). Any help would be much appreciated. Thanks! -
Django Nested Query in Template
Loan Model: class Loan(models.Model): user = models.ForeignKey(Member, blank=True, null=True, on_delete=models.CASCADE) amount = models.PositiveIntegerField(blank=False, null=False) Loan Pay Model: class LoanPay(models.Model): loan = models.ForeignKey(Loan, blank=True, null=True, on_delete=models.CASCADE) amount = models.PositiveIntegerField(blank=False, null=False) want to show data like the image table How to make nested loop in template or any better idea in views -
Why is my posted param not returning in my response?
I have a form that sends params correctly. I can see the values are being posted to my endpoint. However, one of the values keeps coming back "null" on my response. The value in question is for my "Litter" model. I suspect the back-end code is broken somehow (since i see the form is sending the values via my developer tools network tab) But I don't know where the flaw is. This used to be working .... until my back-end guy decided to rewrite everything...now I've been stuck trying to rewire my front-end to Mr, professors new back-end. But I digress. I won't even mention how Mr. Know-it-all handed off to me a back-end without checking if the new api endpoints actually worked (hint: they did not) You can see inside posting values for my form in my front-end file AddCat.vue in my method onSubmitted... onSubmitted() { axios.post(`/api/v1/cats/`, { name: this.name, gender: this.gender, cat_type: this.cat_type, litter: {name: this.litter, notes: this.notes}, weight: this.weight, birthday: this.birthday, weight_unit: this.weight_unit }) .then(response => { console.log("onSubmitted called:"); console.log(response); response.status === 201 ? this.showSuccess = true : this.showDanger = true; // this.profilePic = true; }) .catch(error => { console.log(error); this.showDanger = true; }) Below are the … -
i have facing this kind of error when i have add new app and register that app in setting url.py show error
when i have add one app and register in admin url that kind of error showing Traceback (most recent call last): File "C:\Python\Python36\lib\site-packages\django\utils\autoreload.py", line 227, in wrapper fn(*args, **kwargs) File "C:\Python\Python36\lib\site-packages\django\core\management\commands\runserver.py", line 125, in inner_run self.check(display_num_errors=True) File "C:\Python\Python36\lib\site-packages\django\core\management\base.py", line 359, in check include_deployment_checks=include_deployment_checks, File "C:\Python\Python36\lib\site-packages\django\core\management\base.py", line 346, in _run_checks return checks.run_checks(**kwargs) File "C:\Python\Python36\lib\site-packages\django\core\checks\registry.py", line 81, in run_checks new_errors = check(app_configs=app_configs) File "C:\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 16, in check_url_config return check_resolver(resolver) File "C:\Python\Python36\lib\site-packages\django\core\checks\urls.py", line 26, in check_resolver return check_method() File "C:\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 254, in check for pattern in self.url_patterns: File "C:\Python\Python36\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 405, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Python\Python36\lib\site-packages\django\utils\functional.py", line 35, in get res = instance.dict[self.name] = self.func(instance) File "C:\Python\Python36\lib\site-packages\django\urls\resolvers.py", line 398, in urlconf_module return import_module(self.urlconf_name) File "C:\Python\Python36\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 994, in _gcd_import File "", line 971, in _find_and_load File "", line 955, in _find_and_load_unlocked File "", line 665, in _load_unlocked File "", line 678, in exec_module File "", line 219, in _call_with_frames_removed File "E:\utttam_project\utaam_ecom\utaam_ecom\urls.py", line 22, in url(r'$/',include('store.urls')), File "C:\Python\Python36\lib\site-packages\django\conf\urls__init__.py", line 50, in include urlconf_module = import_module(urlconf_module) File "C:\Python\Python36\lib\importlib__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", … -
Django. Get choices from another model columns
I have two django apps: -App1 --models.py --views.py --etc.py -App2 --models.py In App1: #models.py class Table1(models.Model): field1 = models.IntegerField(default=20) field2 = models.IntegerField(default=20) etc.... In App2 I want to give users a choice selecting one of the fields in the model above, so: #models.py app2 from App1 import models as app1model choices = app1model.Table1._meta.get_fields(include_parents=False) class Table2(model.Model): select = models.Charfield(max_length=1, choices=choices) This results in a circular import error, how can I avoid this? Should I rethink the approach to the problem??