Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to unapply migrations or remove table programmatically? using schema_editor in migration file
I want to unapply migration file 1.py and apply 2.py and 3.py. How can I programmatically do it? Like using schema_editior in 2.py or in 1.py def remove_tables_from_1(apps, schema_editor): *function to remove* migrations.RunPython(remove_tables_from_1), -
Instance error Django Test models.py AttributeError: 'NoneType' object has no attribute
I am performing a Django test case for models.py file the models.py file looks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id = models.PositiveIntegerField(null=True, blank=True) # Af team user to whom farm is assigned. previous_crop_ids = ListTextField(base_field=models.IntegerField(), null=True, blank=True, size=None) sr_assignee_id = models.PositiveIntegerField(null=True, blank=True) lgd_state_id = models.PositiveIntegerField(null=True, blank=True) district_code = models.PositiveIntegerField(null=True, blank=True) sub_district_code = models.PositiveIntegerField(null=True, blank=True) village_code = models.PositiveIntegerField(null=True, blank=True) farm_network_code = models.CharField(max_length=12, null=True, blank=True) … -
ImportError: cannot import name 'render_to_response' from 'django.shortcuts' - Django 3.2 Python 3.8
I am getting this error Traceback (most recent call last): File "/usr/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/usr/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/core/management/__init__.py", line 375, in execute autoreload.check_errors(django.setup)() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/apps/registry.py", line 122, in populate app_config.ready() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/contrib/admin/apps.py", line 27, in ready self.module.autodiscover() File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/contrib/admin/__init__.py", line 24, in autodiscover autodiscover_modules('admin', register_to=site) File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 671, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 848, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/home/kritik/empereon_django3.2/lib/python3.8/site-packages/djcelery/admin.py", line 11, in <module> from django.shortcuts import render_to_response ImportError: cannot import name 'render_to_response' from 'django.shortcuts' (/home/kritik/empereon_django3.2/lib/python3.8/site-packages/django/shortcuts.py) I got this when I upgraded Django from 2.2 to 3.2 My python version is 3.8. I am not using render_to_response anywhere in my code is it related … -
django.db.utils.OperationalError: (1074, "Column length too big for column 'value' (max = 16383); use BLOB or TEXT instead")
I am trying to host my website using FileZilla and PuTTY. For that, I have added the code in FileZilla remote site and I have created a database named jobs using following commands in PuTTY app. sudo mysql -u root #For Maria DB CREATE DATABASE jobs; GRANT ALL PRIVILEGES ON jobs.*TO 'hello'@'localhost'; flush privileges; exit Then python3 manage.py makemigrations command is executed and after that when I executed the python3 manage.py migrate command I got an error like this. django.db.utils.OperationalError: (1074, "Column length too big for column 'value' (max = 16383); use BLOB or TEXT instead") Can anyone suggest a solution to solve this issue? -
django graphene, arguments raise Unknow argument error for ObjectType
I have a arguements in mutation like class Arguments: id = graphene.String() detail = DetailType() Here DetailType is DjangoObjectType in my mutation function def mutation(parent, info, id, detail) I want to take value like this where detail is dictionary But Its giving me error like Unknown arguement detail What is the issue here ? Am I not allowed to create arguments from ObjectType ? -
Filtering Forms in Django
I am making a small project to rate salesmen. I have regions and each region has its salesmen. So, if region "blahblah" is selected, form should show salesmen choices which are related to that region. I have found some answers via stackoverflow, but it still shows all salesmen, regardless of their regions. My model is this: class Region(models.Model): name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) def __str__(self): return self.name class Salesman(models.Model): region = models.ForeignKey(Region, related_name='region', on_delete=models.CASCADE) name = models.CharField(max_length=40) surname = models.CharField(max_length=40) def __str__(self): return self.name class Rating(models.Model): RATING_CHOICES = [(i, str(i)) for i in range(1,6)] salesman = models.ForeignKey(Salesman, related_name='salesman', on_delete=models.CASCADE) phone = models.CharField(max_length=15, blank=True) rating = models.IntegerField(choices=RATING_CHOICES, blank=False) sent_time = models.DateTimeField(auto_now_add=True) def __str__(self): return self.phone I found modified __init__ method for my forms.py: class RateAddForm(forms.ModelForm): class Meta: model = Rating def __init__(self, region_id=None, **kwargs): super(RateAddForm, self).__init__(**kwargs) if region_id: self.fields['salesman'].queryset = Salesman.objects.filter(region=region_id) And also my views.py is this: def report_add(request, region_id): if request.method == 'POST': print(region_id) form = RateAddForm(request.POST, region_id=region_id) if form.is_valid(): message = "Thanks!" form.save() return HttpResponse(message) else: print("Something went wrong!") form = RateAddForm() else: form = RateAddForm(request.POST) return render(request, 'account/report.html', {'form': form}) It still shows me all salesmen on my database, even if i choose a region. How … -
Django rest framework Serializer returns null value even if there's object exist
when i hit the detail view or list view, it returns null each time. but i have 300+ address object in my database. The code attached here. Model: class Address(BaseModel): order = models.ForeignKey(Order, related_name='addresses', on_delete=models.CASCADE, null=True, blank=True) first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) house = models.CharField(max_length=200) optional = models.CharField(max_length=200) city = models.CharField(max_length=200) state = models.CharField(max_length=200) postal_code = models.CharField(max_length=200) email = models.CharField(max_length=200) phone_number = models.CharField(max_length=200) address_type = models.PositiveIntegerField(choices=AddressType.choices(), default=0) Serializer class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__' View class AddressDetailApiView(generics.RetrieveAPIView): queryset = Address.objects.all() serializer_class = AddressSerializer lookup_field = 'pk' Error TypeError at /api/v1/address-detail/293 'NoneType' object is not iterable N.B.: Object with ID 293 exist in my database. List view also return all the object but address all the object as null. -
How do I save django rest authorization token in db cache?
I am using 'rest_framework.authentication.TokenAuthentication', I am not allowed to use any other Token library. Is there a way to instruct Django to save an access token to db cache? Also, is there a command or library that will allow me to call for a new key to be generated? I have configured my backend cache as follows and would like Tokens saved here... CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'TOKEN_cache_table', 'TIMEOUT': 600, #=10 minutes in second 'OPTIONS': { 'MAX_ENTRIES': 5 } } } -
how to filter data in different models in django?
my models class Player(TimeStampedModel): name = models.CharField(max_length=200) email = models.CharField(max_length=200) email_verified = models.BooleanField(default=False, blank=True) phone = models.CharField(max_length=200) phone_verified = models.BooleanField(default=False, blank=True) company_id = models.ImageField(upload_to=get_file_path_id_card, null=True, max_length=255) company_id_verified = models.BooleanField(default=False, blank=True) team = models.ForeignKey(Team, related_name='player', on_delete=models.DO_NOTHING) def __str__(self): return self.name this is my model , how to filter data in multiple model? -
I keep getting "false" in my response body, even when the request is successful
My function in my viewset ... def create(self, request): context = {'request':request} serializer = StorySerializer(data=request.data, context=context) if serializer.is_valid(): story = serializer.create(request) if story: return Response(status==HTTP_201_CREATED) else: return Response(status==HTTP_400_BAD_REQUEST) Screenshot of the response a screenshot of my api response -
Heroku error H10 and fwd, my site won't function and I'm unable to determine what actions to take to correct the problem
I just uploaded sync'd my working GitHub repository to Heroku, and when I load the page, I get the "appplication error" page. This is a Django/Python project for school. Here's a bit of the error codes. I've removed my static IP address. 2022-01-20T00:13:48.472109+00:00 app[api]: Starting process with command bash by user studio42dotcom@gmail.com 2022-01-20T00:14:26.576915+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=seitopic.herokuapp.com request_id=731ed097-3b1f-431b-b3bf-04e731125046 fwd="xxx.xxx.xxx.xxx" dyno= connect= service= status=503 bytes= protocol=https 2022-01-20T00:14:30.006905+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/admin" host=seitopic.herokuapp.com request_id=4029aa01-b304-49d0-ae48-8f5b656a9bc2 fwd="xxx.xxx.xxx.xxx" dyno= connect= service= status=503 bytes= protocol=https About the only thing I can think of that is different was adding in the django-cors-headers, but I don't see how that could be causing issues. The project runs fine locally using python3 manage.py runserver and that doesn't generate errors. The instructors are stumped but said all should be working. I'm not sure what other information you need but I should be able to provide it relatively quickly. -
How to add "-" in django rest_framework Serializer class variables?
I am writing a rest_framework Serializer class for basic validations class ValidateSerializer(serializers.Serializer): client_name = serializers.CharField(allow_blank=False, trim_whitespace=True) and my request data contains "-" in the keys, so I need something like this class ValidateSerializer(serializers.Serializer): # Like the below class variable? I know it is not possible with python variable declaration. client-name = serializers.CharField(allow_blank=False, trim_whitespace=True) I've checked the rest_framework CharField to find out any kwargs that allow me to accept data like client_name = serializers.CharField(name='client-name') So, is it possible to accept - in the Serializer class variables from request data? -
Images in react not displaying
I'm using django and react to build an application. There are some images in react public folder which are being used in different pages. The rest images are coming from django. Both images (images from react and django) were displaying on the browser until I combined react and django and started serving react index.html page from django (using react build folder in django). Immediately I did that the images within react public folder stopped displaying in the browser. The only images I see are those from the API. settings.py BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'frontend/build') ], ... STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'media',), os.path.join(BASE_DIR, 'frontend/build/static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index.html')), path('api/blog/', include('blog.urls')), ... ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) Is there anything I can do to get the images to display? -
How do I export my django model into custom csv?
I have a Django app in which I maintain products for a webshop. Since many products have multiple variations and working in Excel is not optimal, I thought Python could help me and make the work easier. However, for the import into my store system I need a CSV file and here comes my problem. I have a model with five fields where two are multiple fields (django-multiselectfield). SIZES = (('16', 'Size 16'), ('17', 'Size 17'), ('18', 'Size 18'), ('19', 'Size 19'), ('20', 'Size 20')) COLORS = (('white', 'White'), ('black', 'Black'), ('blue', 'Blue'), ('red', 'Red'), ('yellow', 'Yellow')) class Items(models.Model): name = models.CharField(_('Name'), max_length=254, null=True, blank=True, default='',) sku = models.CharField(_('SKU'), max_length=254, null=True, blank=True, default='',) size = MultiSelectField(_('Size'), choices=SIZES) color = MultiSelectField(_('Color'), choices=COLORS) price = models.DecimalField(_('Price'), max_digits=7, decimal_places=2) I created two products to demonstrate my needs In my CSV file, for example, I need a new line for each size and color so that the variation is created correctly in the webshop software. So my CSV would have to look like this: "type","sku","attribute 1 name","attribute 1 value","attribute 2 name","attribute 2 value" "variable","abc01921","size","16","color","white,black,blue" "variation","abc01921_white_16","size","16","color","white" "variation","abc01921_black_16","size","16","color","black" "variation","abc01921_blue_16","size","16","color","blue" "variable","abc01831","size","16,17","color","black,blue" "variation","abc01831_black_16","size","16","color","black" "variation","abc01831_blue_16","size","16","color","blue" "variation","abc01831_black_17","size","17","color","black" "variation","abc01831_blue_17","size","17","color","blue" How do I best implement this successfully? How can I check if … -
Django Rest Framework Ordering on a SerializerMethodField with pagination
How could i sort data based on nested custom serializer method: here is my serializer: class MyModelSerizalier(serializers.ModelSerializer): monthly_price = serializers.SerializerMethodField() class Meta: model = MyModel def get_monthly_price(self, instance): # ... do some calcs with instance # and values that is not related with MyModel installments = [{"due_date": "some_date", "value": 10}] total_price = sum([x["value"] for x in installments]) return {"installments": installments, "total_price": total_price} on my view i have: class MyModelViewSet(viewsets.ModelViewSet): queryset = MyModel.objects.all() serializer_class = MyModelSerializer http_method_names = ['get'] filterset_class = MyModelFilterSet pagination_class = StandardResultsSetPagination # tryed to use same logic for joins but didn't work ordering = ('monthly_price__total_price', '-monthly_price__total_price') ordering_fields = ('monthly_price__total_price', '-monthly_price__total_price') def get_queryset(self): self.queryset also tried this suggestion here but as i'm using pagination, could get the entire response.data to manually sort. any help will be appreciated -
Deploy django project with apache
/etc/apache2/sites-available/000-default.conf <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /home/myuser/project ErrorLog /home/myuser/error.log CustomLog /home/myuser/access.log combined Alias /media/ /home/myuser/project/cdn/cdn_medias/ Alias /static/ /home/myuser/project/cdn/cdn_assets/ <Directory /home/myuser/project/cdn/cdn_assets> Require all granted </Directory> <Directory /home/myuser/project/cdn/cdn_medias> Require all granted </Directory> <Directory /home/myuser/project/project> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/myuser/project> Require all granted </Directory> WSGIDaemonProcess project python-path=/home/myuser/project python-home=/home/myuser/myvirualenv/lib/python3.8/site-packages/ WSGIProcessGroup project WSGIScriptAlias / /home/myuser/project/project/wsgi.py </VirtualHost> and /home/myuser# ls access.log project myvirualenv error.log mysql.cnf Why I can not see website on example.com/project or example.com? -
How do I pass a django auth token to view or serializer?
I am trying to work with a Token provided by 'rest_framework.authentication.TokenAuthentication', I would like to either work with the token from the view or from the serializer. What method do I use to make a token viewable inside of my application? Here is what i have tried only the current user returns. The 'auth' key returns none. def get(self, request, format=None): content = { 'auth': str(request.auth), 'user': str(request.user), } return Response(content) -
"Type 'manage.py help ' for help on a specific subcommand" - Error solving python with IIS
I'm trying to run a django project with IIS on Windows server, I've already modified handler mapings and FastCGI Settings -> image statusIt should be running at this point. There's any error but the page is not running. (even withouth /manage.py is the same legend) Legend: "Type 'manage.py help ' for help on a specific subcommand. Available subcommands: [auth]changepasswordcreatesuperuser [channels]runworker [contenttypes]remove_stale_contenttypes [django]checkcompilemessagescreatecachetabledbshelldiffsettingsdumpdataflushinspectdbloaddatamakemessagesmakemigrationsmigratesendtestemailshellshowmigrationssqlflushsqlmigratesqlsequenceresetsquashmigrationsstartappstartprojecttesttestserver [sessions]clearsessions [staticfiles]collectstaticfindstaticrunserver " Any ideas? Thank you -
How to allow CORS from chrome extension origin on django after set white list to all?
I'm trying to re-add CSRF token protection to an API made with Django and deployed to heroku. Local tests with the CSRFToken verification allowed worked fine before I uploaded the web app to heroku but now that I'm in the final tests is not working unless I add the csrf_exempt decorator to the the Django view. I obtained the following error with Django 3.1.7: Referer checking failed - no Referer I was using Django 4.0 on heroku and I decided to try with 3.1.7 version because I tought it could resolve my problem since in this question I understood that this was because in previously Django versions CSRF domain was not checked: Forbidden (403) CSRF verification failed. Request aborted. Reason given for failure: Origin checking failed does not match any trusted origins and I already tried to allow all origins this way (I already use django-cors-headers library): In settings.py: CSRF_TRUSTED_ORIGINS = ['*'] CORS_ALLOW_ALL_ORIGINS = True CORS_ALLOW_CREDENTIALS = True All of this with the same error: 2022-01-19T23:01:08.715032+00:00 heroku[router]: at=info method=POST path="/smoke/add/" host=my-app.herokuapp.com request_id=b1342451-1a4b-4a0c-9993-ba1e86f0f969 fwd="187.168.154.155" dyno=web.1 connect=0ms service=19ms status=403 bytes=3009 protocol=https 2022-01-19T23:01:08.714194+00:00 app[web.1]: Forbidden (Origin checking failed - chrome-extension://nfbjppodghgcapmokljafeckhkmbcogd does not match any trusted origins.) I don't understand what this is happening … -
Site matching query does not exist. Django/Heroku
My site appears to deploy correctly on heroku, I can access the main page fine but when I try to login or signup (which directs to a new page) I get the following error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 69, in view return self.dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/views/decorators/debug.py", line 90, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 146, in dispatch return super(LoginView, self).dispatch(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 74, in dispatch response = super(RedirectAuthenticatedUserMixin, self).dispatch( File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/base.py", line 101, in dispatch return handler(request, *args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 90, in get response = super(AjaxCapableProcessFormViewMixin, self).get( File "/app/.heroku/python/lib/python3.9/site-packages/django/views/generic/edit.py", line 135, in get return self.render_to_response(self.get_context_data()) File "/app/.heroku/python/lib/python3.9/site-packages/allauth/account/views.py", line 177, in get_context_data site = get_current_site(self.request) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/shortcuts.py", line 13, in get_current_site return Site.objects.get_current(request) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/models.py", line 58, in get_current return self._get_site_by_id(site_id) File "/app/.heroku/python/lib/python3.9/site-packages/django/contrib/sites/models.py", line 30, in _get_site_by_id site = self.get(pk=site_id) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/app/.heroku/python/lib/python3.9/site-packages/django/db/models/query.py", line 439, in get raise self.model.DoesNotExist( Exception Type: DoesNotExist at /accounts/login/ Exception Value: Site matching query does … -
Using subdomains for redirection only (Special for Django)
Suppose that my domain is example.com I want to set subdomains such as blog.example.com, contact.example.com ... In my use case: The subdomains will never have unique content. They will always redirected to determined URLs. Assume that, --> Site objects were created for them. (using The “sites” framework) site_1 : example.com site_2 : contact.example.com site_3 : blog.example.com ... --> Then, Redirects are handling with The Redirects app. Example Redirects Goals: >>> redirect_1 = Redirect.objects.create( ... site_id=1, ... old_path='/contact-us/', ... new_path='/contact/', ... ) >>> redirect_2 = Redirect.objects.create( ... site_id=2, ... old_path='/', ... new_path='https://example.com/contact/', ... ) >>> redirect_3 = Redirect.objects.create( ... site_id=3, ... old_path='/first-blog/', ... new_path='https://example.com/blog/first-blog/', ... ) My questions - Can The sites framework and The redirects app be used this way with subdomains? - If possible, how should subdomains be configured for this use case? Note: Assume that there is no configuration related to subdomains in the project and that what is wanted to be done is prefer to done by Django side as much as possible. -
Django: Reverse for 'update-gig' with arguments '('',)' not found. 1 pattern(s) tried: ['freelance/gig/(?P<gig_category_slug>[
I want to put a url in the update button it not working out rather throwig an error update.html <a href="{% url 'freelance:update-gig' gig.gig_category_slug %}"> Update </a> views.py @login_required def update_gig(request, gig_category_slug): user = request.user gig = get_object_or_404(Gigs, slug=gig_category_slug) freelancer = Freelancers.objects.get(user=request.user) if request.method == "POST": form = CreateGig(request.POST, request.FILES, instance=gig) if form.is_valid(): new_form = form.save(commit=False) new_form.user = request.user new_form.creator = freelancer new_form.slug = slugify(new_form.title) new_form.save() messages.success(request, f'Gig Updated Successfully!') return redirect('freelance:gig-details', slug=gig_category_slug) else: form = CreateGig(instance=gig) context = { 'form': form } return render(request, 'freelance/create.html', context) -
Django channels - unable to subscribe to groups
I'm attempting to send consumers.py information to display on the client end outside of consumers.py. I've referenced Send message using Django Channels from outside Consumer class this previous question, but the sub process .group_send or .group_add don't seem to exist, so I feel it's possible I'm missing something very easy. Consumers.py from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class WSConsumer(WebsocketConsumer): def connect(self): async_to_sync(self.channel_layer.group_add)("appDel", self.channel_name) self.accept() self.render() appAlarm.py def appFunc(csvUpload): #csvUpload=pd.read_csv(request.FILES['filename']) csvFile = pd.DataFrame(csvUpload) colUsernames = csvFile.usernames print(colUsernames) channel_layer = get_channel_layer() for user in colUsernames: req = r.get('https://reqres.in/api/users/2') print(req) t = req.json() data = t['data']['email'] print(user + " " + data) message = user + " " + data async_to_sync(channel_layer.group_send)( 'appDel', {'type': 'render', 'message': message} ) It's throwing this error: async_to_sync(channel_layer.group_send)( AttributeError: 'NoneType' object has no attribute 'group_send' and will throw the same error for group_add when stripping it back more to figure out what's going on, but per the documentation HERE I feel like this should be working. -
How to serve a subdomain and the domain on a single django-cms?
Is is possible to serve a subdomain and the main domain on the same django-cms instance ? For example: how to serve the following submains and the main domain on the same Django-CMS instance ? abc.mydomain.com xyz.mydomain.com www.mydomain.com If so, what are needed to be done in Apache httpd.conf and Django-CMS ? Thank you in advance. -
Sending dictionary as Django model attribute
Is there any possibility to send some keyword: argument into django model attribute (one attribute)? I tried to use models.TextField for that but there must be better solution. from django.db import models class Newsletter(models.Model): start_datetime = models.DateTimeField() text = models.TextField(blank=True) filter = models.TextField() end_datetime = models.DateTimeField()