Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does one save Django objects to models dynamically using functions?
I have several models that inherited an abstract model. With Django Rest Framework, I'm creating a custom action. I'm trying to save models based off an argument provided when utilizing the function: def mover_func(blobs, noteModel, commentModel): myself = blobs.get_object() U1(author=myself.author, title=myself.title, summary=myself.summary).save() class P1ViewSet(viewsets.ModelViewSet): queryset = PNote1.objects.all() serializer_class = PNote1Serializer @action(detail=True, methods=['get']) def pnote_move_to_unote(self, request, pk): mover_func(self, blah1, blah2) return Response({'status', 'Done'}) U1 is one of the models inheriting the abstract model. Later on, other viewsets such as P2ViewSets, P3, etc. are included, I need to save them to the models U2, U3, etc. There's more unrelated stuff than that, but I just wanted to minimize it for readability. I was thinking of adding an argument to mover_func like mover_func(self, blah1, blah2, U1) U1 being the model that should be creating and saving the object, but my recollection of previous experiences in Django 2.2 tells me that won't work... Again, something helpful is that the attributes author, title, and summary are the same across U1-->UInfinite (if you forgot that these models inherited from the same abstract model). -
Problem sending information between Django template and views using AJAX call
I used an ajax post request to send some variable from my javascript front end to my python back end. Once it was received by the back end, I want to modify these values and send them back to display on the front end. I need to do this all without refreshing the page. With my existing code, returning the values to the front end gives me a 'null' or '[object object]' response instead of the actual string/json. I believe the formatting of the variables I'm passing is incorrect, but it's too complicated for me to understand what exactly I'm doing wrong or need to fix. This is the javascript ajax POST request in my template. I would like the success fuction to display the new data using alert. $.post({ headers: { "X-CSRFToken": '{{csrf_token}}' }, url: `http://www.joedelistraty.com/user/applications/1/normalize`, data: {arr}, dataType: "json", contentType : "application/json", success: function(norm_data) { var norm_data = norm_data.toString(); alert( norm_data ); } }); This is my Django URLs code to receive the request: path('applications/1/normalize', views.normalize, name="normalize") This is the python view to retrieve the code and send it back to the javascript file: from django.http import JsonResponse def normalize(request,*argv,**kwargs): norm_data = request.POST.get(*argv, 'true') return JsonResponse(norm_data, safe = … -
"No module named 'settings' error when trying to use Django OAUTH toolkit models
I want to access the models that are used by Django OAUTH Toolkit so I can periodically delete old tokens from the database. I thought I'd just import them: # this module will periodically delete rows from the table from oauth2_provider.models import AbstractAccessToken old_access_tokens = AbstractAccessToken.objects.all() print(old_access_tokens) I tried testing this but I receive the error: Traceback (most recent call last): File ".\db_cleanup.py", line 3, in <module> from oauth2_provider.models import AbstractAccessToken File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\models.py", line 12, in <module> from .generators import generate_client_id, generate_client_secret File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\generators.py", line 4, in <module> from .settings import oauth2_settings File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\oauth2_provider\settings.py", line 24, in <module> USER_SETTINGS = getattr(settings, "OAUTH2_PROVIDER", None) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 57, in __getattr__ self._setup(name) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 44, in _setup self._wrapped = Settings(settings_module) File "C:\Users\User\.virtualenvs\gsm-django\lib\site-packages\django\conf\__init__.py", line 107, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\User\.virtualenvs\gsm-django\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'settings' Do I need to be referencing the settings file somewhere where I'm currently not? -
KeyError at /admin/login/ 'request'
What could be the cause of this issue? I have looked at similar questions and most of the answers recommended are things I have already configured in my settings file. When I try login to the admin section. This error shows up KeyError at /admin/login/ 'request' the request context processor here is already part of the configuration here is my TEMPLATE configuration { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ str(APPS_DIR.path('templates')), ], 'OPTIONS': { 'debug': DEBUG, 'loaders': [ 'django.template.loaders.filesystem.Loader', 'django.template.loaders.app_directories.Loader', ], 'context_processors': [ 'django.template.context_processors.request', 'django.template.context_processors.debug', 'django.contrib.auth.context_processors.auth', 'django.template.context_processors.i18n', 'django.template.context_processors.media', 'django.template.context_processors.static', 'django.template.context_processors.tz', 'django.contrib.messages.context_processors.messages', ], }, }, ] middleware MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] AUTH BACKENDS AUTHENTICATION_BACKENDS = [ 'allauth.account.auth_backends.AuthenticationBackend', 'django.contrib.auth.backends.ModelBackend', ] Django 1.11 PS: I am using djangorestframework as well, any ideas if it's somehow affecting this? -
How to correctly query Tags from the database and display the result in templates in DJANGO
I am trying to query Tags (Django taggit) associated to objects IDs and display the result to the templates. For some reason it returns NONE when I try to debug it with PDB. So far I have tried multiple way to debug it still the console return NONE when I try to query the ```tag`` from the page. models.py from taggit.managers import TaggableManager class Post(models.Model): STATUS_CHOICES = ( ('draft', 'draft'), ('published', 'published') ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete='models.CASCADE', related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') objects = models.Manager() published = PublishedManager() tags = TaggableManager() class Meta: ordering = ('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('core:post_detail', args=[self.publish.year, self.publish.month, self.publish.day, self.slug]) from django.urls import path, include from . import views app_name = 'core' urlpatterns = [ path('', views.post_list, name='post_list'), path('tag/<slug:tag/>', views.post_list, name='post_list_by_tag'),path('<int:year>/<int:month>/<int:day>/<slug:post>/', views.post_detail, name='post_detail'), path('<int:post_id>/share/', views.post_share, name='post_share') ] views.py from taggit.models import Tag def post_list(request, tag_slug=None): """ List of Posts and Tags. """ page_posts = Post.published.all() # Tags tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) page_posts = page_posts.filter(tags__in=[tag]) paginator = Paginator(page_posts, 2) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: … -
How to properly config html code to replace confirm button in Sweet Alert 2?
I'm currently on a crucial step on my Sweet Alert program. I need to replace the default submit and cancel buttons by some inside-html buttons (the form is being rendered through ajax), but I cannot find any reference on how to properly get the submited information or close the alert. My form html code: <div class="card"> <div class="card-header card-header-icon" data-background-color="orange"> <i class="large material-icons">cloud_upload</i> </div> <br> <div class="card-content"> <form {% if modal_title_id %} id="{{ modal_title_id }}"{% endif %} class="form-{{ style|default:'stacked' }} {{ class }} create-form" method="{{ method|default:'post' }}" {% if action %} action="{{ action }}"{% endif %} enctype="multipart/form-data"> {% if not method == "get" %}{% csrf_token %}{% endif %} {% if title %}<h5><i class="icon-sitemap icon-large"></i>{{ title }}</h5>{% endif %} {% include 'dashboard/partials/form_fields.html' %} </form> <div class="row"> <button type="button" class="btn btn-secondary" id="closeSwal">{% trans 'Close' %}</button> <button type="submit" class="btn btn-primary" id="PostSwal">{% trans 'Upload File' %}</button> </div> </div> </div> My button html code: <p> <button type="button" class="btn btn-primary upload-file-js" data-url="{% url 'crm:customer:lead_upload' %}"> <span class="glyphicon glyphicon-plus"></span> Importar Leads </button> <button type="button" class="btn btn-primary js-import-client"> <span class="glyphicon glyphicon-plus"></span> Importar Clientes </button> </p> and my js code is: $('.upload-file-js').click(function() { var uploadUrl = $(this).attr('data-url') $.ajax({ url: uploadUrl, type: 'get', dataType: 'json', success: function (data) { Swal.fire({ … -
How To Load Fonts In Django
I have a project I am working on in django and i am trying to load locally installed fonts with the .tff extensions but they dont seem to be working. My css code is @font-face { font-family: 'JandaAppleCobbler'; src: url('../fonts/JandaAppleCobbler.tff') format("truetype"), local('JandaAppleCobbler'); } My directory structure is --static |--css | |--main.css | |--fonts |--JandaAppleCobbler.tff -
Why don't see data from multiple select in admin page?
I wrote a multi-select form for the admin page. The data saved, but for some reason it is don't show in field as selected. What could be the problem? Django 1.9 class ConditionAdminForm(forms.ModelForm): """docstring for ConditionAdminForm.""" REGISTRATION_CHOICES= ( ('Any', _('Any')), ('Constant', _('Constant')), ('Temporary', _('Temporary')), ) registration = forms.MultipleChoiceField(choices = REGISTRATION_CHOICES, label=_("registration form")) def clean_registration(self): registration = self.cleaned_data['registration'] if not registration: raise forms.ValidationError("...") registration = ', '.join(registration) return registration class Meta: model = Condition fields = '__all__' class ConditionInlineAdmin(admin.StackedInline): model = Condition form = ConditionAdminForm field "регистрация" -
No matching object on query during save() override on model - DoesNotExist error thrown
I'm overriding my Model save() to check and see if there is a Consumer (related object) that already exists with the email entered. When a Consumer does exist with a matching Email, the code executes as expected and associates the Case to the correct Consumer. However, if there is not an existing Consumer that exists with a matching Email, I'm receiving the error: "DoesNotExist: Consumer matching query does not exist." I've tried adjusting the save() method, however to me it looks correct (obviously, could be wrong here). Models.py class Case(models.Model): ... def save(self,*args,**kwargs): if Consumer.objects.get(email__iexact=self.email): self.consumer = Consumer.objects.get(email__iexact=self.email) else: consumer = Consumer(first_name=self.first_name,last_name=self.last_name,email=self.email) consumer.save() return super().save(*args,**kwargs) The expected results is to create a new Consumer object in the case that the Email entered on the Case does not match an already existing Consumer's email. Instead, it throws this error. -
How to highlight and get informations from elasticsearch-dsl search in django?
I'm using django-elasticsearch-dsl. I have already index datas and set up some queries on them. Here is an example of query in my views : q = HemisticheDocument.search().query(operation, field="value") Then after I have : listHem = [hit for hit in q[:q.count()] I have results. When operation is "match", I have no problem because it is an exact term that I am looking for. However, when I use "fuzzy" as my operation, I would like to know if it possible for any hit : To highlight or extract the term (which may not be the exact one) that has been found in the hit. To get the score of it. I would put them in a dictionary for other uses. Thank you in advance. Hope the question is clear enough. -
How to take into consideration objects with null foreign keys?
Image I have two models: class Category(models.Model): name = models.CharField(max_length=1024) def __str__(self): return self.name class Card(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) now i want to get number of cards in categories: cards_by_categories = Card.objects.filter( user_id=request.user.id).values('categories__name').annotate( num_per_cat=Count('categories__name') ) And I get (please consider that i have many Cards without categories): [ { "categories__name": null, "num_per_cat": 0 <-- do not want 0 here, why 0? }, { "categories__name": "alol", "num_per_cat": 2 }, { "categories__name": "category_name1", "num_per_cat": 3 } ] However, I want the amount of cards with null categories to be not null, but actual number of cards without categories. I know I can query like Cards.objects.filter(categories=None), but how to combine that? -
ERROR: Failed building wheel for mysqlclient
I'm unable to 'pip install mysqlclient', and every attempt returns the error: 'ERROR: Failed building wheel for mysqlclient'. For context, I'm running on macOS Mojave 10.14.5. The rest of this post assumes that both 'python==3.6' and 'virtualenv' are already downloaded. In addition, x-code command line tools are already installed (not that I think that matters). The steps to this are (from command line): 'virtualenv ~/venv' Output: Using base prefix '/usr/local/Cellar/python/3.6.5_1/Frameworks/Python.framework/Versions/3.6' New python executable in /Users/usr1/venv/bin/python3.6 Also creating executable in /Users/usr1/venv/bin/python Installing setuptools, pip, wheel...done." 'source ~/venv/bin/activate' 'pip install mysqlclient' So far, I've viewed and attempted everything on: Failed building wheel for mysqlclient "Failed building wheel for psycopg2" - MacOSX using virtualenv and pip Failed building wheel for mysql-python Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/f4/f1/3bb6f64ca7a429729413e6556b7ba5976df06019a5245a43d36032f1061e/mysqlclient-1.4.2.post1.tar.gz Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error ERROR: Complete output from command /Users/usr1/venv/bin/python3.6 -u -c 'import setuptools, tokenize;file='"'"'/private/var/folders/2j/1qt0_7q96lxbxl2w5kx8r1zr0000gn/T/pip-install-4uobjq_4/mysqlclient/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/2j/1qt0_7q96lxbxl2w5kx8r1zr0000gn/T/pip-wheel-ehvuw9uv --python-tag cp36: ERROR: running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.13-x86_64-3.6 creating build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/compat.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.13-x86_64-3.6/MySQLdb copying MySQLdb/times.py … -
How to use purchased UI Theme with Django
I'm working with Django framework and I've recently purchased a dashboard Theme in order to give to my application a nice front end. My idea is to use styles, components, fonts and everything else provided in the Theme through in Django's templates. The product that I bought is called architectui-html-pro-theme. According to documentation provided the template is powered by jQuery, Bootstrap4 & Webpack The installation process of the Theme consist of: 1) Download files 2) Run npm install 3) and then start the application thought npm run start After all that, what i got is a nice Demo of the Theme running on http://localhost:8081 Great... But none further informations is provided regarding how to make the Theme works in My Django application. It's looks like the Theme installed a lot of dependencies (node_modules directory ) so I think to make it work in my Django project it is not just a matter of copy and paste the full directory in some "static" folder and just make reference some main.css style file in my "base.html" file. I have already asked the provider but no answer so far. This is the file structure of the Theme: .babelrc .gitignore architectui-html-pro <dir> node_modules <dir> … -
How do I properly set up Django-Rest-Tracking, so I can log usage
I am not sure how to use drt. I've read through the documentation multiple times and I am not understanding it. So far what I have is from rest_framework_tracking.mixins import LoggingMixin in my polls\views.py app and then from rest_framework import generics from rest_framework.response import Response from rest_framework_tracking.mixins import LoggingMixin class LoggingView(LoggingMixin, generics.GenericAPIView): def get(self, request): return Response('with logging') In my api\views.py app, nothing is changing on the logs page on the admin site, and I am not sure what is wrong, or where to go from here. -
django theader for consume rabbitmq queue error
i new in microservices pattern and i have a django app that contains a view sending a message and a consumption in node js calling a message processes and returns to a django application. This entire communication process is done by rabbitmq. when an http request arrives at a certain endpoint the application django sends a message in a queue this process is working to consume the answer I thought about launching a theader that consumes the answer queue. I can launch theader but the client (django) closes the connection with rabbitmq my app ready from django.apps import AppConfig from rpc.rpc_queues import RcpOrder class SaleConfig(AppConfig): name = 'sale' def ready(self): r = RcpOrder() r.daemon = True r.start() my rpc interface class RpcInterface(Thread): host = None queue = None def __init__(self): #cria conexao TCP self.connection = pika.BlockingConnection( pika.URLParameters(self.host) ) #cria um canal virtual que server para o envio e consumo de mensagens self.channel = self.connection.channel() #declara a queue criando se for necessario result = self.channel.queue_declare(queue='', exclusive=True) self.callback_queue = result.method.queue super().__init__() def on_response(self, ch, method, props, body): #verifica se a mensagem foi para este consumer if self.corr_id == props.correlation_id: self.response = body def call(self, body): self.response = None #cria um id unico … -
returning related field in template
I have the following classes, I can get the related objects through this {{plantpart.fraction_id.fraction}} going up the models, but I want to go the other way. I know I need a related_name to avoid the _set ending and it needs to be in a nested for loop. So how do I correct the following: {% for f in fractions %} {% for pp in plantparts%} {{pp.plantparts.fraction}} {% endfor %} {% endfor %} class Fraction(models.Model): fraction_id = models.AutoField(primary_key=True) composition_id = models.ForeignKey(Composition, db_column='composition_id', on_delete = models.PROTECT) fraction = models.CharField(max_length=20, choices = FRACTIONS) class PlantPart(models.Model): plantpart_id = models.AutoField(primary_key=True) fraction_id = models.ForeignKey(Fraction, db_column='fraction_id', on_delete = models.PROTECT, related_name='plantparts') taxon_id = models.ForeignKey(Taxon, db_column='taxon_id', on_delete = models.PROTECT, related_name='plant_taxon', blank=True, null=True) part = models.CharField(max_length=100) weight = models.DecimalField(max_digits=10, decimal_places=3) quantity = models.DecimalField(max_digits=10, decimal_places=3) p.s. I know I don't need to use an id, but this connects to an existing database. -
Are Django models tightly coupled with databases?
Are Django Models tightly coupled with databases? I want to create a web application using Django framework, but I don't want to use any database. By this, I mean that my data is stored in the network file system and I have already written python functions to read/write data from/to the file system. How can I go about creating such an application using Django? -
Django: 'editorial' is not a registered namespace
I'm getting the error of 'editorial' is not a registered namespace I've found this similar question: Django - is not a registered namespace But I'm currently using it's solution (to use a namespace in the project url file) and still getting the error. Proyect urls.py: """el_comercio_app URL Configuration""" from django.contrib import admin from django.urls import path, include urlpatterns = [ path("", include("editorial.urls", namespace='editorial')), ] editorial urls.py: from django.urls import path from editorial import views from django.contrib import admin app_name = 'editorial' urlpatterns = [ path('admin', admin.site.urls), path("", views.today_editorial, name="today_editorial") ] The error happens when running a test: coverage run manage.py test editorial -v 2 # models test class EditorialTest(TestCase): def create_editorial(self, title="only a test", body="yes, this is only a test"): return Editorial.objects.create(title=title, body=body, url="https://www.google.com", image = "https://img.elcomercio.pe/files/article_content_ec_fotos/uploads/2019/06/19/5d0ae893b3287.jpeg", date=timezone.now()) def test_today_editorial_view(self): url = reverse("editorial:today_editorial") resp = self.client.get(url) self.assertEqual(resp.status_code, 200) -
Google App Engine Standard can not find/execute Gunicorn
I have a project with a Django backend and an Angular frontend. I've deployed them as two services into Google App Engine Standard and the deploy is successful. However, when I try to access the backend url this-backend.appspot.com, i get /bin/sh: 1: exec: gunicorn: not found I have gunicorn in my requirements file: gunicorn==19.9.0 I also have defined the entrypoint: runtime: python37 service: default entrypoint: gunicorn -b :$PORT thisapp.wsgi handlers: - url: /static static_dir: static - url: /.* secure: always redirect_http_response_code: 301 script: auto But still get the same error. I looked into all the same issues on the Stackoverflow, and they were either because of the requirements or the entrypoint which I've defined both of them. Even when I go to the Stackdriver I can see the gunicorn folders inside the app engine:/: gunicorn gunicorn-19.9.0.dist-info This is the backend cloudbuild.yaml file: steps: - name: 'python:3.7' entrypoint: python3 args: ['-m', 'pip', 'install', '-t', '.', '-r', 'requirements.txt'] - name: 'python:3.7' entrypoint: python3 args: ['./manage.py', 'collectstatic', '--noinput'] - name: 'gcr.io/cloud-builders/gcloud' args: ['app', 'deploy', '--version=prod'] I'd really appreciate it if anyone has any solutions or recommendations as I've looked into almost all the same issues on the Internet. Thanks, James -
how get pk in get_absolute_url recursively
By using inlineformset I've created a createview, all is working very well but, I need to redirect the user to the created author detail view. How can I get the author id using the get_absolute_url in the model Book? I will explain in the following code what I've made. Firstly, I have two models with a relationship, Author and Book. class Author(models.Model): description = models.CharField("Description", max_length=150) author = models.ForeignKey( "Book", verbose_name=_("Book"), on_delete=models.PROTECT ) class Meta: verbose_name = _("Author") verbose_name_plural = _("Authors") class Book(models.Model): name = models.CharField("Book Name", max_length=150) class Meta: verbose_name = _("Book") verbose_name_plural = _("Books") def get_absolute_url(self): return reverse('author-detail', args=(need author pk here,)) Here, I have the formset. AuthorFormSet = forms.inlineformset_factory( Book, Author, form=AuthorForm, fields = ['description'], extra=2 ) And here I have my view. class BookAuthorCreateView(CreateView): model = Book fields = ['name'] template_name = "core/formset.html" def get_context_data(self, **kwargs): data = super( BookAuthorCreateView, self).get_context_data(**kwargs ) if self.request.POST: data['formset'] = AuthorFormSet(self.request.POST) else: data['formset'] = AuthorFormSet() return data def form_valid(self, form, *args): context = self.get_context_data() authors = context['formset'] with transaction.atomic(): self.object = form.save() if authors.is_valid(): authors.instance = self.object authors.save() return super(BookAuthorCreateView, self).form_valid(form) Thanks for your time. -
How to get all data from a loop using a django form?
I created a table from a loop. And in my table I make editions. And after editing the data, I will want to retrieve all the data in a dictionary. Here is my tablemplate: <form action="{% url 'Note_Update' %}" name="get_note" id="get_note" method="get"> <table border="1" class="stripe row-border order-column" style="width:100%"> <tr> <th>user</th> <th>point</th> </tr> <tbody id="table"> {% for a in team %} <tr scope="row"> <td class="text-center col-md-1">{{ a.user }}</td> <td class="text-center col-md-1">{{ a.point }}</td> </tr> {% endfor %} </tbody> </table> </form> here is my view or function: def Note_Update(request): get_note = request.GET.get('get_note') print(get_note) # get dictionary # example # {"A": "12" , "B": "18" , "C": "15"} return redirect('home') -
'NoneType' object has no attribute '__getitem__' Django , i got stuck when try to follow a tutorial
hello everyone im a student from indonesia, im following a video tutorial on how to make a website spesifically about digital marketplace, so theres a part when i try to make 'a auto generated thumbnail' feature, from high resolution picture that we upload, but the end i got this kind of error, that made me stuck to do my Project firstly im using django version 1.8.6, and python ver 2.7.10 heres my models.py from django.conf import settings from django.core.urlresolvers import reverse from django.db import models from django.db.models.signals import pre_save, post_save #signal from django.utils.text import slugify #signal from django.core.files.storage import FileSystemStorage def download_media_location(instance, filename): return "%s/%s" %(instance.slug,filename) class Produk(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL) managers = models.ManyToManyField(settings.AUTH_USER_MODEL, related_name="managers_produk", blank=True) media = models.ImageField( blank=True, null=True, upload_to=download_media_location, storage=FileSystemStorage(location=settings.PROTECTED_ROOT)#memindahkan dr media ke protected ) judul = models.CharField(max_length=30) slug = models.SlugField(blank=True, unique=True) deskripsi = models.TextField() harga = models.DecimalField(max_digits=100, decimal_places=2, default=1000.0) harga_sale = models.DecimalField(max_digits=100, decimal_places=2, default=1000.0, null=True, blank=True) #bisa di kosongin def __unicode__(self):#menampilkan list di admin berdasarkan judul return self.judul def get_absolute_url(self):#absolute url redirect success url ke slug path view_name = "produk:detail_slug" return reverse(view_name, kwargs={"slug":self.slug}) def get_download(self): view_name = "produk:download_slug" url = reverse(view_name, kwargs={"slug":self.slug}) return url def create_slug(instance, new_slug=None): slug = slugify(instance.judul) if new_slug is not None: slug=new_slug … -
Django urlpatterns - NoReverseMatch at... Reverse for '' with no arguments not found
I am building a modal form in Django that would allow the user to edit the details of an existing record. Specifically, in the paper_detail.html, there is a button that the user can click on, which would then load the specific paper in a modal form via ajax. Once the paper is loaded into the modal form, the user can edit it. When I go to http://127.0.0.1:8000/paper/796134/, I ran into the following error: NoReverseMatch at /paper/796134/ Reverse for 'edit_paper' with no arguments not found. 1 pattern(s) tried: ['search/edit/(?P<pk>\\d+)/$'] This is very puzzling to me because I expect it to go to paper_detail. urls.py: urlpatterns = [ path('paper/<int:pk>/', views.paper_detail, name='paper_detail'), url('', views.load_paper, name='load_paper'), url(r'^edit/(?P<pk>\d+)/$', views.edit_paper, name='edit_paper'), path('', views.HomePageView.as_view(), name='home'), ] What I found is that if I remove the (?P<pk>\d+) from the edit_paper pattern, the page loads fine. (i.e. http://127.0.0.1:8000/paper/796134/ loads correctly if url(r'^edit/(?P<pk>\d+)/$', views.edit_paper, name='edit_paper'), becomes url(r'^edit/$', views.edit_paper, name='edit_paper'), This would be problem solved but I believe I actually need to have (?P<pk>\d+) in the edit_paper pattern. This is because I need to pass the pk of the paper back to the edit_paper function by including {{object.pk}} as a parameter in form action. Please advise what is the best course … -
Django call_command before loading fixtures in tests
Is it possible to call_command() before loading the fixtures in TestCase? This code doesn't work - fixtures can't be loaded because the groups do not exist yet. class UserAPITestCase(APITestCase): fixtures = [ 'user/fixtures/user.json', ] def _fixture_setup(self): call_command('create_groups') super()._fixture_setup() -
Python - Django OperationalError no such table even though --run-syncdb
I cannot create new table (the 4th one called Vote) in my models. I have tried every solutions under: Django: OperationalError No Such Table including the --run-syncdb option during my migration execution. My migration process is: python manage.py makemigrations eathere python manage.py migrate --run-syncdb py manage.py runserver It executes successfully, however the table is not created. I check it by these commands: from django.db import connection tables = connection.introspection.table_names() seen_models = connection.introspection.installed_models(tables) And when I try to refer it on the admin site (after successfull registration of the model), it throws OperationalError No Such Table eathere_vote Could you please help me what could be the cause of the issue? My code is: from django.contrib.auth.models import AbstractUser, Group from django.db import models class CustomUser(AbstractUser): def full_name(self): return self.first_name + self.last_name class FoodProvider(models.Model): id = models.CharField(max_length=200, primary_key=True) description = models.CharField(max_length=200, default=None, blank=True, null=True) def __str__(self): return str(self.id) + " (" + str(self.description) + ")" class EatingOpportunity(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) food_provider = models.ForeignKey(FoodProvider, on_delete=models.CASCADE) class Meta: managed = False unique_together = (('group', 'food_provider'),) class Vote(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) food_provider = models.ForeignKey(FoodProvider, on_delete=models.CASCADE) vote_date = models.DateTimeField('vote date') class Meta: managed = False unique_together = (('user', 'group', 'food_provider', 'vote_date'),) …