Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Use Traefik reverse-proxy to host WordPress and Django
I am new to deployment related tasks so what I'm asking may be very simple to implement but it is difficult for me nonetheless. In one domain, I need a WordPress-based public website (about 3-4 pages) as well as a link to log into the internal management Django v3.2 app. Both plus some extras (redis, postgres) will be served through docker-compose. I am using cookiecutter-django for my Django application. It uses Traefik by default as reverse-proxy for the production configuration. I looked at the docs for Traefik and I couldn't quite understand how I can implement the paths for my use case. I have the WP site and the Django app separately working currently so I just need to figure out how to deploy it together under the same domain, just different paths. As an example of what I need to achieve, let's assume my WordPress site has pages home, about, and contact so I would want the full URL to be example.com, example.com/about, and example.com/contact respectively. Any other links should be forwarded to Django. For those who have not used cookiecutter-django, the default file structure and configuration is to have a separate traefik.yml and Dockerfile for Traefik, and separate … -
APS Scheduler raising exception for no reason django
Even though the target function is receiving both the arguments it's still throwing an error for missing parameters ? wonder why check_device() missing 1 required positional argument: 'device_id' Job "check_device (trigger: interval[0:00:30], next run at: 2021-11-05 19:35:24 IST)" raised an exception Scheduler snip def job_add(application_id,device_id,count): scheduler.add_job( check_device, 'interval', args = (application_id,device_id,), seconds=7, jobstore = 'default', id=f'my_job_{count}', replace_existing=True, max_instances = 7, misfire_grace_time=None ) function i am calling def check_device(application_id,device_id): print('Mqtt connected ... calling on ',application_id,device_id) mqttc = mqtt.Client(clientId) -
AttributeError: module 'crontab' has no attribute 'CronSlices'
I am currently dev a website using Django. I want to program tasks so I am planing to use Celery and Redis. I've installed Celery (pip command). I've also installed Redis using brew and it works : redis-cli ping returns PONG. I had to install django-celery-result and django-celery-beat (I used pip command). After setting-up my Django code, I got this error message when I run the server. File "/usr/local/lib/python3.9/site-packages/django_celery_beat/validators.py", line 7, in <module> class _CronSlices(crontab.CronSlices): AttributeError: module 'crontab' has no attribute 'CronSlices' I didn't know how to fix this error. Do anyone has an idea of where the problem comes from ? Thx -
Query Django comparing two charfield fields
I have this two examples models class ExternalTransaction(): external_id = models.CharField(max_length=255) class Transaction(): transaction_id = models.CharField(max_length=255) I want to create query which returns ExternalTransaction queryset which contains only transactions which are not in Transaction.transaction_id. I've tried to write something like this: ExternalTransaction.objects.exclude(external_id__in=Transaction.objects.all().values_list('transaction_id')) but it does not work, returns empty queryset. -
Update Create Method in Django Rest Framework for two nested werializers
I've found many answers to similar questions but not to my specific one. I'm trying to update the Create Method for my serializer which has two nested serializers: class TaskSerializer(serializers.ModelSerializer): products = ProductSerializer() prep = PrepSerializer() class Meta: model = Task fields = '__all__' def create(self, validated_data): products_data = validated_data.pop('products') task = Task.objects.create(**validated_data) for products_data in products_data: Product.objects.create(task=task, **products_data) return task I want to add the "prep" nested serializer in as well to be updated at the same time but I can't seem get the syntax right. Any help, greatly appreciated. -
In Django models, how does the foreign key field know which field to match with in the other model?
I understand what Foreign Keys do but I'm having trouble understanding why this is working in Django. I have the Project model in 'app1/models.py' file. This model has a ForeignKey named 'owner' that links to the Profile model in my 'app2/models.py' file. How does the 'owner' field in the Project model know it should be linking to the 'user' field in the Profile model if I'm only passing the model name to the 'owner' field? I feel like I should be passing the Profile.field or something like this in the Project model: owner = models.ForeignKey(Profile.user, null=True, blank=True ... ) Full model code from Dennis Ivy's tutorial: class Project(models.Model): owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.SET_NULL) title = models.CharField(max_length=200) #null is default=False and is required description = models.TextField(null=True, blank=True) #for a bigger field, allows null(for db)/blank(for Django get/post) featured_image = models.ImageField(null=True, blank=True, default='default.jpg') demo_link = models.CharField(max_length=2000) source_link = models.CharField(max_length=2000, null=True, blank=True) #can be blank in db tags = models.ManyToManyField('Tag', blank=True) #quotes will ref other class after this one vote_total = models.IntegerField(default=0, null=True, blank=True) vote_ratio = models.IntegerField(default=0, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) #generate when model instance is created id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) name … -
django error : NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)'
I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items: when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error: NoReverseMatch at /watchlist/ Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$'] my code: Model.py file class Post(models.Model): #data fields title = models.CharField(max_length=64) textarea = models.TextField() #bid price = models.FloatField(default=0) currentBid = models.FloatField(blank=True, null=True) imageurl = models.CharField(max_length=255, null=True, blank=True) category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True) creator = models.ForeignKey(User, on_delete=models.PROTECT) date = models.DateTimeField(auto_now_add=True) # for activated the Category activate = models.BooleanField(default=True) buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator") ############################### this is the watchers watchers = models.ManyToManyField(User, blank=True, related_name='favorite') def __str__(self): return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}" urls.py urlpatterns =[ # Watchlist path('Post/<int:id>/watchlist_post/change/<str:reverse_method>', views.watchlist_post, name='watchlist_post'), path('watchlist/', views.watchlist_list, name='watchlist_list') ] views.py #start watchlist def viewList(request, id): # check for the watchlist listing = Post.objects.get(id=id) if listing.watchers.filter(id=request.user.id).exists(): is_watched = True else: is_watched = False context = { 'listing': listing, 'comment_form': CommentForm(), 'comments': listing.get_comments.all(), 'Bidform': BidForm(), # IS_WATCHED method 'is_watched': is_watched } return render(request, 'auctions/item.html', context) @login_required def watchlist_post(requset, … -
Not migrated with Open edX migrate
I am trying to generate edX open-release / hawthorn and when migrations run the following output is what shows me I cut the code for a better reading Apply all migrations: ... Traceback (most recent call last): File "manage.py", line 123, in <module> execute_from_command_line([sys.argv[0]] + django_args) ... File "/edx/app/edxapp/venvs/edxapp/lib/python3.8/site-packages/django/db/migrations/operations/fields.py", line 98, in state_forwards state.models[app_label, self.model_name_lower].fields.append((self.name, field)) KeyError: ('enterprise', 'enterprisecustomer') Captured Task Output: --------------------- ---> pavelib.servers.update_db ---> pavelib.prereqs.install_prereqs ---> pavelib.prereqs.install_node_prereqs ---> pavelib.prereqs.install_python_prereqs ---> pavelib.prereqs.uninstall_python_packages pip install -q --disable-pip-version-check --exists-action w -r requirements/edx/development.txt pip freeze > /edx/app/edxapp/edx-platform/test_root/log/pip_freeze.log NO_EDXAPP_SUDO=1 EDX_PLATFORM_SETTINGS_OVERRIDE=devstack_docker /edx/bin/edxapp-migrate-lms --traceback --pythonpath=. Build failed running pavelib.servers.update_db: Subprocess return code: 1 make: *** [Makefile:257: dev.migrate.studio] Error 1 -
How to disable translations in tests (django, pytest)
That's not really a question but the proposition of solution to the problem. I tried to find an article to solve this issue I was facing but at the end of the day I actually came up with something which might help some ppl in the same situation as mine: Tech Stack: Django==2.2.x, pytest==6.0.0 Issue: I tried to test the simple form validation. Compare error messages returned from form validation with the expected ones, to check if the validation works as expected. class TestPassword: @pytest.mark.parametrize( 'password,error_message', [ ('#noDigitPassword', 'At least one digit is required.'), ('#nouppercasep4ssword', 'At least one capital letter is required.'), ('#NOLOWERC4SEPASSWORD', 'At least one lower case letter is required.'), ('NoSymbolP4ssword', 'At least one special char (!%&amp;@#$^*?_~.) is required.'), ('#WhitSpace P4ssword', 'Whitespaces are not allowed.'), ], ) def test_form_password_complexity_check(self, password: str, error_message: str) -> None: form = SignUpForm( dict( email="dummy@email.com", first_name="dummy first_name", last_name="dumy last_name", password=password, ) ) assert form.is_valid() is False assert error_message in str(form.errors['password']) class SignUpForm(forms.Form): email = forms.CharField(max_length=255) first_name = forms.CharField(max_length=255) last_name = forms.CharField(max_length=255) password = forms.CharField( max_length=255, validators=[ at_least_one_capital_case_validator, at_least_one_lower_case_validator, at_least_one_number_validator, at_least_one_special_char_validator, no_whitespaces_validator, ], ) Validation error messages use ugettext_lazy and the output strings are: _("At least one lower case letter is required.") _("At least one … -
How to configure two databases with different tables in same Django app?
settings.py DATABASE_ROUTERS = ["mysite.router.CheckerRouter"] DATABASES = { "default": { "ENGINE": "sql_server.pyodbc", "NAME": "A", "USER": "user", "PASSWORD": "dummypassword", "HOST": "server", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, "marketing": { "ENGINE": "sql_server.pyodbc", "NAME": "B", "USER": "user", "PASSWORD": "dummypassword", "HOST": "server", "PORT": "1433", "OPTIONS": { "driver": "ODBC Driver 17 for SQL Server", }, }, } models.py class table1(models.Model): ## Default database table ID = models.CharField( db_column="Identifier", max_length=200, blank=True, null=True, db_index=True ) var1 = models.CharField( db_column="Type", max_length=200, blank=True, null=True, db_index=True ) class Meta: db_table = "Table 1" class table2(models.Model): ## Marketing database table ID = models.CharField( db_column="Identifier", max_length=200, blank=True, null=True, db_index=True ) marketer = models.CharField( db_column="Type", max_length=200, blank=True, null=True, db_index=True ) class Meta: db_table = "Table 2" app_label = "marketing_label" router.py class CheckerRouter: def db_for_read(self, model, **hints): if model._meta.app_label == "marketing_label": return "marketing" return "default" def db_for_write(self, model, **hints): if model._meta.app_label == "marketing_label": return "marketing" return "default" def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == "marketing_label" or obj2._meta.app_label == "marketing_label": return True return True def allow_migrate(self, db, app_label, model_name=None, **hints): if app_label == "marketing_label": return db == "marketing" return None When making migrations, the app is not detecting the marketing database tables at all. Only the default database … -
Sending a file with json with requests and tastypie
I'm trying to send some zip files, and some json to my tastypie endpoint. I'm getting: The format indicated \'multipart/form-data\' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer." On my client. This is my client code: def sendLogs(): url = "http://43.197.102.4:8000/api/ziprel/" payload = {"param_1": "value_1","param_2": "value_2"} files = { 'JSON': (None, json.dumps(payload), 'application/json'), 'Console': (os.path.basename('/home/pi/Desktop/Console.zip'), open('/home/pi/Desktop/Console.zip','rb'), 'application/zip') } r = requests.post(url,files=files) print(r.content) I get the error when I print, r.content. Here's my tastypie code: class MultipartResource(object): def deserialize(self, request, data, format=None): try: if not format: format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded') if format == 'application/x-www-form-urlencoded': return request.POST if 'multipart' in format: data = request.POST.copy() data.update(request.FILES) # Get the error here json.loads(request.body) zip = TestZipModel() zip.ADB = request.FILES['ADB'] zip.save() return data except Exception as e: print("Error {}".format(e)) return super(MultipartResource, self).deserialize(request, data, format) # overriding the save method to prevent the object getting saved twice def obj_create(self, bundle, request=None, **kwargs): pass The server is getting: Error 'utf-8' codec can't decode byte 0x95 in position 350: invalid start byte Am I able to send JSON with a multipart/form-data content type? Is there a better way to do this? Sending data along with the zips will be very helpful. -
Allauth/Microsoft Graph API - AADSTS900144: The request body must contain the following parameter: ‘resource’
I can't get contacts using Microsoft Graph API for some users as it raises: {“error”:“invalid_request”,“error_description”:“AADSTS900144: The request body must contain the following parameter: ‘resource’.} This error happens only with some users. Not all of them have problems. SOCIALACCOUNT_PROVIDERS = { 'microsoft': { 'SCOPE': ['Contacts.Read', 'Contacts.ReadWrite', 'offline_access', 'User.Read'], 'AUTH_PARAMS': {'prompt': 'select_account'}, }, The error URL is https://login.microsoftonline.com/error?code=900144 which just says it's an authentication issue. Do you know where the problem is and how to add the resource parameter? -
I could not point correctly the static image files
index.html <div class="carousel-inner" role="listbox"> {% for pizza in pizza_list %} {% if forloop.counter0 == 0 %} <div class="carousel-item active"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="..."> </div> {% else %} <div class="carousel-item"> <img width="250" height="850" class="d-block w-100 h-50" class="h-50 d-inline-block" src="{% static 'Pizza/{{ pizza }}' %}" alt="..."> </div> {% endif %} {% endfor %} </div> views.py def index(request): pizza_list = [] print(os.getcwd()) for item in os.listdir('static/Pizza'): pizza_list.append(item) ## print(pizza_list) context = {'pizza_list':pizza_list} return render(request,'index.html',context) settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' urls.py under Main_Project folder from django.contrib import admin from django.urls import path,include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('pizza.urls')), ] urlpatterns += static( settings.STATIC_URL, document_root=settings.STATIC_ROOT) My project directory Main_Project (top) --Main_Project (top) --settings --urls --pizza --static --Pizza --(images) --templates --migrations --views.py --models.py --urls.py In this Django project, I have a confusion about where should the static images and files put under because I could not load the image in index.html that I saved in the static folder directory. Also, I am not sure whether my settings are correct in order to have the images shown on the templates … -
Django ListView Through Model Relationships
I have been reading through here and I can't seem to find the answer of the question I am looking for. Maybe I'm not asking the correct question. I have three models. Recruiter Office Recruit Recruiters are assigned to multiple offices and each office has multiple employees. What I need to be able to do is create a listview that lists all of the employees that are associated with a recruiter. So something like this: Recruiter 1 has Office 1 and 2 assigned to them. Office 1 has Employee 1,2,3. Office 2 has employee 3,4,5 The Listview should display all employees under Recruiter 1. My Models are: class Recruit(models.Model): id = models.CharField(max_length=25,primary_key=True, unique=True) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile_phone = models.CharField(max_length=20,null=True) preferred_phone = models.CharField(max_length=20,null=True) email= models.CharField(max_length=100,null=True) officeid = models.ForeignKey(Office,on_delete=models.DO_NOTHING,related_name="recruit") class Office(models.Model): office_name = models.CharField(max_length=100) officeid = models.CharField(max_length=20,primary_key=True,unique=True) class Recruiter(models.Model): user = models.OneToOneField(User, related_name='recruiter',on_delete=models.CASCADE) organization = models.ForeignKey(UserProfile,on_delete=models.CASCADE) Do I need a AssingedOffices table to join this all together? class AssignedOffice(models.Model): user = models.ForeignKey(UserProfile,on_delete=models.CASCADE) esa_office = models.ForeignKey(Office,on_delete=models.CASCADE) Just not sure how to connect them & display in the listview. -
Django admin site: how to change admin URL based on verbose_name
class Meta: verbose_name only changes its displayed name. But when its clicked. i want its url changed too based on verbose name Here's my code: Models: tables = [f.id for f in StockId.objects.raw( "SELECT TABLE_NAME AS id FROM INFORMATION_SCHEMA.tables WHERE TABLE_NAME LIKE 'my_project_auth_stockid%%'")] table_map = {} for tbl in tables: class Stocks(models.Model): user_id = models.IntegerField() product_name = models.CharField(max_length=100) mrp = models.IntegerField() selling_price = models.IntegerField() class Meta: db_table = tbl managed = False verbose_name = _(tbl) verbose_name_plural = _(tbl) table_map[tbl] = Stocks Admin.py from my_project_auth.models import * class AllStocksAdmin(AdminSite): site_header = 'All User Stocks' stockadmin = AllStocksAdmin(name="stockadmin") for tbl in tables: class StocksAdmin(ImportExportModelAdmin): resource_class = StocksAdminResource list_display = ["product_name"] stockadmin.register(table_map[tbl], StocksAdmin) What I am trying to do is in above to make multiple stock table out of single model. But Admin panel for each stocks is not working. All stocks table is pointing towards single table because of admin URL is based on model's class name. I'm trying to do something like this in Admin.py, please suggest changes: for tbl in tables: class StocksAdmin(ImportExportModelAdmin): resource_class = StocksAdminResource list_display = ["product_name"] def get_urls(self): # Not Working urls = super(StocksAdmin, self).get_urls() my_urls = path(f'stockadmin/{tbl}/', self.admin_view(stockadmin)) return my_urls + urls -
how to create a Pagination with if and for loop django
I tried to do Pagination using for and if and it didn't work So how do I do that this an image that can show u front page image page 2 image front page code {% for post in posts %} {% if forloop.counter <= 2 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty %} <div class="notification"> <p>No posts yet!</p> </div> {% endfor %} page 2 code {% for post in posts %} {% if forloop.counter2 <= 30 %} <div style="background-color: #9999;" class="card mb-3" style="max-width: 100%;"> <div class="row no-gutters"> <div class="col-md-4"> <a href="{% url 'post_detail' post.slug %}"><img style="height: 200px; width: 330px;" src="{{ post.mainimage.url }}" class="card-img" alt="..."></a> </div> <div class="col-md-6" id="ph"> <div class="card-body"> <h5 class="card-title">{{ post.title }} , {{ post.xnumber }}</h5> <p class="card-text">{{ post.version }}</p> <p>{{ post.category }}</p> <p class="card-text"><small class="text-muted">{{ post.date_added }}</small></p> </div> </div> </div> </div> <hr > {% endif %} {% empty … -
Map integration not wokring
The following are the two lines I put in the head tag of my html <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&key=AIzaSyC_Ii8L8wy40S8pB-eUBg13MlIOGYHXx6Y"></script> <script src="{% static "js/mapscript.js" crossorigin="anonymous" %}"></script> The below is the script I use to load map into my html. In my html I have a div tag with ID equal to map_canvas. var map; function initialize() { console.log("Loading map"); var mapOptions = { zoom: 12, center: new google.maps.LatLng(55.85361568022353, -4.288761402220929) }; map = new google.maps.Map(document.getElementById('map_canvas'),mapOptions); } google.maps.event.addDomListener(window, 'load', initialize); The issue is that even if I added a API key and have a billing registered for google maps, map is not rendering after using the code above though this javascript code is hit. Can anybody give suggestions? -
AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser'
i am having this issue when registering user through a register.html template this is the exact issue AttributeError at /accounts/register/ Manager isn't available; 'auth.User' has been swapped for 'accounts.CustomUser' i created a custom user model and a custom manager which is listed here models.py file from django.contrib.auth.base_user import AbstractBaseUser from django.db import models from django.contrib.auth.models import AbstractUser, BaseUserManager, PermissionsMixin from datetime import datetime from Etesting.settings import USE_I18N from django.utils import timezone from django.utils.translation import gettext_lazy as _ # Create your models here. class MyCustomUserManager(BaseUserManager): def create_user(self, email,username, password=None, **extra_fields): if not username: raise ValueError('There must be a username') if not email: raise ValueError('There must be an email') user=self.model( email=self.normalize_email(email), username=username, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, username, password,**extra_fields): extra_fields.setdefault('is_admin',True) extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_superuser',True) return self.create_user(email, username, password, **extra_fields) class CustomUser(AbstractBaseUser, PermissionsMixin): username=models.CharField(max_length=50, unique=True) email=models.EmailField(verbose_name='email', unique=True) first_name=None last_name=None is_admin=models.BooleanField(default=False) is_staff=models.BooleanField(default=False) is_superuser=models.BooleanField(default=False) is_active = models.BooleanField(default=True) date_joined = models.DateTimeField(_('date joined'), default=timezone.now) USERNAME_FIELD='email' REQUIRED_FIELDS=['username'] objects = MyCustomUserManager() def __str__(self): return self.username def has_perm(self, perm, obj=None): """ Return True if the user has the specified permission. Query all available auth backends, but return immediately if any backend returns True. Thus, a user who has permission from a single auth backend is assumed to have … -
ModuleNotFoundError: No module named 'pip._vendor.six'
I am doing some example from the book called Django for professionals. I am at the part where you have to run the django server with docker-compose command. However, I got an error like this: raise ImproperlyConfigured("Error loading psycopg2 module: %s" % e) I realised that I needed to download psycopg2 with pip3 but then I got this error: from pip._vendor.six import iteritems ModuleNotFoundError: No module named 'pip._vendor.six' I don't understand why I received this error since I followed every step on the book carefully. I am using virtualenv as well so i decided to open a new terminal and downloaded it there. Download was a success however when I download it in virtual environment I get an error. What do you guys think is the problem and how can I solve it? -
Django comments - 'str' object has no attribute '_meta'
I am trying to implement a comment and reply system to my article application but I am receiving the following error: AttributeError: 'str' object has no attribute '_meta' Could you please let me know what am I doing wrong and how to fix this? I checked some answers but they were not related to this particular library. article_page.html {% extends 'base.html' %} {% load i18n %} {% load comments comments_xtd static %} {% block articleactive %}active{% endblock articleactive %} {% block body %} <div class="container"> <h1 class="py-3">{{ article.title }}</h1> <p>{{ article.content | safe }}</p> <br> <p class=" text-muted">{{ article.author }} | {{ article.date_published }}</p> <div class="container-fluid mt-4 comment-form"> {% render_comment_form for page %} </div> {% get_comment_count for page as comment_count %} {% if comment_count %} <hr> <div class="container-fluid mt-4 media-list"> {% render_xtdcomment_tree for page allow_feedback show_feedback %} </div> {% endif %} </div> {% endblock body %} setting.py INSTALLED_APPS = [ 'django_comments_xtd', 'django_comments', 'product', 'article', 'jazzmin', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'ckeditor', 'crispy_forms', 'taggit', 'axes', 'django_otp', 'django_otp.plugins.otp_totp', 'django.contrib.sites' ] COMMENTS_APP = "django_comments_xtd" COMMENTS_XTD_CONFIRM_EMAIL = False # Set to False to disable confirmation COMMENTS_XTD_SALT = b"es-war-einmal-una-bella-princesa-in-a-beautiful-castle" COMMENTS_XTD_FROM_EMAIL = 'noreply@example.com' COMMENTS_XTD_CONTACT_EMAIL = 'helpdesk@example.com' COMMENTS_XTD_MAX_THREAD_LEVEL = 1 # Default value COMMENTS_XTD_LIST_ORDER = ('-thread_id', … -
from . import views ImportError: attempted relative import with no known parent package
i just start to use django, and i got error when try to import in the "from . import views" part, this is my code from django.urls import path from . import views urlpatterns = [ path('',views.home,name='home') ] and i have error message, which is "ImportError: attempted relative import with no known parent package" can you show why it error, and the solution -
Exclude true Booleans from the List of Booleans
I am building a Blog App and I am trying to make a list accordingly of All Boolean Fields of a Profile Model and I am trying to exclude them if Boolean is true. And I successfully created a list But exclude is not working in list for exclude true Booleans models.py class Profile (models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=30) first_boolean = models.BooleanField(default=False) second_boolean = models.BooleanField(default=False) third_boolean = models.BooleanField(default=False) views.py def page(request): Booleans_List = [] Booleans_Lista.append(request.user.profile.first_boolean) Booleans_Lista.append(request.user.profile.second_boolean) Booleans_Lista.append(request.user.profile.third_boolean) context = {'Booleans_List'} return render(request, 'page.html', context) This List is working Fine, But I am trying to exclude Booleans which are true and also I am trying use .first() in list. But I have no idea, how can I do it. Any help would be greatly Appreciated. Thank You in Advance -
Tastypie: The format indicated had no available deserialization method
I'm trying to send some zip files and some json data to a tastypie endpoint. Resources.py class MultipartResource(object): def deserialize(self, request, data, format=None): try: if not format: format = request.META.get('CONTENT_TYPE', 'application/x-www-form-urlencoded') if format == 'application/x-www-form-urlencoded': return request.POST if 'multipart' in format: data = request.POST.copy() data.update(request.FILES) zip = TestZipModel() zip.ADB = request.FILES['ADB'] jsonData = request.body.decode('utf-8') body_data = json.loads(jsonData) zip.save() return data except Exception as e: print("Error {}".format(e)) return super(MultipartResource, self).deserialize(request, data, format) # overriding the save method to prevent the object getting saved twice def obj_create(self, bundle, request=None, **kwargs): pass class ResponseZipRel(MultipartResource, ModelResource): class Meta: limit = 100000 queryset = TestZipModel.objects.all() resource_name = "ziprel" authorization = Authorization() Raspberry Pi which sends the files def sendLogs(): url = "http://43.197.102.4:8000/api/ziprel/" payload = {"param_1": "value_1","param_2": "value_2"} files = { 'json': (None,json.dumps(payload),'application/json'), 'ADB': (open('/home/pi/Desktop/ADB.zip','rb'),'application/zip')} r = requests.post(url,files=files) if __name__ == "__main__": sendLogs() I'm getting: {'error_message': "The format indicated 'multipart/form-data' had no available deserialization method. Please check your ``formats`` and ``content_types`` on your Serializer.", I've tried setting the files to application/zip and application/octet-stream with no luck. I also tried sending the JSON as a parameter in the request, like this: r = requests.post(url,files=files, json={"testName": "test1", "testType": "thistestname"}) and got: Error 'utf-8' codec can't decode byte 0xdc … -
Django: It takes time for order_by() and count()
The following model object has about 300k rows in postgres, and I have set db_index=True for the published_at field. For some reason, order_by() takes a long time. (+100ms or so) Also, .count() takes a long time. (about 150ms). Why do these take so long even though the index is specified? class Video(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=300) thumbnail_url = models.URLField(max_length=1000) preview_url = models.URLField(max_length=1000, blank=True, null=True) embed_url = models.URLField(max_length=1000) embed_source = models.ForeignKey(EmbedSource, on_delete=models.CASCADE) duration = models.CharField(max_length=8) tags = models.ManyToManyField(Tag, blank=True, db_index=True) views = models.PositiveIntegerField(default=0, db_index=True) is_public = models.BooleanField(default=True) published_at = models.DateTimeField(default=timezone.now, db_index=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ["-published_at"] def __str__(self): return self.title -
How to change the starting auto-generated-primary key id in a Django + PostgreSQL web application?
I have a web application build on Django using PostgreSQL database. In a few tables, I have auto-generated-IDs being used as primary keys. Due to some unexpected circumstances, I had to uninstall everything on the Linux server and again setup them on a different Linux server. I want to use all the data which I had stored earlier and taken dumps in csv files for each table before uninstalling. So, I've used copy function and and copied all columns data (including "id") into the new database. Now, when using the Django app which is trying to insert data into the tables, its throwing PRIMARY KEY ERROR saying that id already exists. So, what can I do now so that this Django+PSQL app uses id from some 1000 or 5000 rather than from 1 since the previous ones are already used? How to know this setup not to use 1 to 1000 as its already used. I don't think any screenshots are required for this. Kindly let me know if I have to make myself more clear. Thanks much in advance.