Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Always image cannot be sent normally What is wrong in my code?
Always image cannot be sent normally. I wrote in views.py def photo(request): d = { 'photos': Post.objects.all(), } return render(request, 'registration/accounts/profile.html', d) def upload_save(request): form = UserImageForm(request.POST, request.FILES) if request.method == "POST" and form.is_valid(): data = form.save(commit=False) data.user = request.user data.save() return render(request, 'registration/photo.html') else: return render(request, 'registration/profile.html') in profile.html <main> <div> <img class="absolute-fill"> <div class="container" id="photoform"> <form action="/accounts/upload_save/" method="POST" enctype="multipart/form-data" role="form"> {% csrf_token %} <div class="input-group"> <label> <input id="file1" type="file" name="image1" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file2" type="file" name="image2" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="input-group"> <label> <input id="file3" type="file" name="image3" accept="image/*" style="display: none"> </label> <input type="text" class="form-control" readonly=""> </div> <div class="form-group"> <input type="hidden" value="{{ p_id }}" name="p_id" class="form-control"> </div> <input id="send" type="submit" value="SEND" class="form-control"> </form> </div> </div> </div> </main> in forms.py class UserImageForm(forms.ModelForm): image = forms.ImageField() class Meta: model = ImageAndUser fields = ('image',) n my system,I can send 3 images at most each one time, so there are 3 blocks.Now always program goes into else statement in upload_save method, I really cannot understand why always form.is_valid() is valid.When I send only 1 image, same thing happens.So the number of image does not cause the error. … -
Is it possible to use django-filter OrderingFilter with function based views?
I'm trying to create an order by dropdown in a template that will order a queryset by fields of my model. Picture of ordering menu I'm going for I understand how to use the django-filter package to filter by model but I can't find any documentation on how to use the OrderingFilter without using class based views. I already have tons of function based views so I'm not looking to switch to class based views right now. Here is my code so far views.py def homepage(request): course_review_list = CourseReview.objects.all() course_review_filter = CourseReviewFilter(request.GET, queryset=course_review_list) return render(request, 'homepage.html', { 'course_review_filter':course_review_filter}) filters.py from course.models import CourseReview import django_filters from django_filters import OrderingFilter class CourseReviewFilter(django_filters.FilterSet): class Meta: model = CourseReview exclude = ['courseDepartment','courseNumber', 'reviewId','instructorId', 'courseReviewTagId', 'review', 'reviewDate' ] o = OrderingFilter( # tuple-mapping retains order fields=( ('courseDepartment', 'Course Department'), ('rating', 'rating '), ), ) homepage.html <form method="get"> {{ course_review_filter.form.as_p }} <button type="submit">Search</button> </form> <ul> {% for course_review in course_review_filter.qs %} <li>{{ course_review.courseDepartment }} - {{ course_review.rating }}</li> {% endfor %} </ul> -
Can't login users with specific permissions
I'm creating a school, kinda, and I created a group called Instructors. Instructors are users with permission to create courses. They have all permissions of the courses application except those of the Subject model). Whenever I try logging into the courses creation page with an instructor, I get the login page over and over again. It's only the superuser that can login successfully. Instructors just get the login page over and over again. Here are my files: models.py from django.db import models from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from .fields import OrderField class Subject(models.Model): title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) class Meta: ordering = ('title',) def __str__(self): return self.title class Course(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='courses_created') subject = models.ForeignKey(Subject, on_delete=models.CASCADE, related_name='courses') title = models.CharField(max_length=200) slug = models.SlugField(max_length=200, unique=True) overview = models.TextField() created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ('-created',) def __str__(self): return self.title class Module(models.Model): course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='modules') title = models.CharField(max_length=200) description = models.TextField(blank=True) order = OrderField(blank=True, for_fields=['course']) class Meta: ordering = ['order'] def __str__(self): return '{}. {}'.format(self.order, self.title) class Content(models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='contents') content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to={ 'model__in':('text', 'video', 'image', 'file') }) object_id = models.PositiveIntegerField() item = … -
How to use GPS location in Django REST API?
I am making a REST API with Django for a restaurant search app. I need to get a list of restaurants within a distance of X meters from my location. I am not sure how to store this on my database (I am using PostgreSQL) and how to retrieve this list. I searched online some options and I found PostGIS as an extension to Postgres that can be used in Django, but I still want to listen to some of your recommendations. Thank you -
Can't display image on browser with django rest framework
I've a problem similar to this SO post, but none of its answers helped me to solve my issue. Here we are : I'm able to save an image on the server but not able to get Image from API image hyperlink. My files : model.py class Summary(models.Model): question_text = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) cover_image = models.ImageField(upload_to='cover_image/', max_length=255) userProfileSummary = models.ManyToManyField(UserProfile, through='UserProfileSummary') def __str__(self): return self.question_text views.py class Summary(models.Model): question_text = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) cover_image = models.ImageField(upload_to='cover_image/', max_length=255) userProfileSummary = models.ManyToManyField(UserProfile, through='UserProfileSummary') def __str__(self): return self.question_text serializer.py class SummarySerializer(serializers.ModelSerializer): """A serializer for summary item""" cover_image = serializers.ImageField(max_length=None, use_url=True) class Meta: model = models.Summary exclude = ('userProfileSummary',) settings.py STATIC_URL = '/static/' STATICFILES_DIRS =( os.path.join(BASE_DIR, 'static'), '/static', ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') urls.py from django.urls import path, include from rest_framework.routers import DefaultRouter from django.conf.urls.static import static from django.conf import settings from . import views router = DefaultRouter() router.register('Hello-viewset', views.HelloViewSet, base_name='hello-viewset') urlpatterns= [ path('hello-view/', views.HelloApiView.as_view()), path('UserProfileSummary/<int:id>/', views.UserProfileSummaryViewSet.as_view()), path('', include(router.urls)) ]+static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) App structure : - myproject/ - cover_image/ - media/ - myproject_api/ - models.py - serializers.py - ... - myproject/ - settings.py - ... I can Make a Request For POST successfully & It show correct image link but … -
django-channels Connecting websocket to channel
How do I connect the Websocket client to the Django channel? I created a basic handler and a the router: from channels.routing import route def ws_message(message): print(message["text"]) channel_routing = [ route("websocket.receive", ws_message), ] But when I try to connect a websocket client: import websocket ws = websocket.WebSocket() ws.connect("ws://127.0.0.1/") it throws the following error: Handshake status 200 -
How to get rid of superfluous slashes in url in django
I have an issue with extra slashes in the url in django. I have url subdomain.domain.com/, but subdomain.domain.com//// shows the same page. I need that people, who entering subdomain.domain.com////, are redirected to subdomain.domain.com/ or receive 404. This is the way how I define the url in urls.py: urlpatterns = [ url(r'^$', views.home, name='home'),] -
Django JSON Response to HTML Page Not Working
I have a Django project where I am trying to get AJAX working. I can't seem to send the JSON response to the HTML page. When I check the chrome console the JSON data is not returned only parses the HTML. This is my Views.py where I have the cart logic defined: def cart_home(request): cart_obj, new_obj = Cart.objects.new_or_get(request) return render(request, "carts/carts.html", {"cart": cart_obj}) def cart_update(request): print("Hello") product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Product is gone") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added = False else: cart_obj.products.add(product_obj) added = True request.session['cart_items'] = cart_obj.products.count() if request.is_ajax(): print("Ajax request") json_data = { "added": added, "removed": not added, } return JsonResponse(json_data) return redirect("cart:home") This is javascript for the Ajax: <script> $(document).ready(function(){ var productForm = $(".form-product-ajax") productForm.submit(function(event){ event.preventDefault(); console.log("Form is not sending") var thisForm = $(this) var actionEndpoint; thisForm.attr("action"); var httpMethod; thisForm.attr("method"); var formData; thisForm.serialize(); $.ajax({ url: actionEndpoint, method: httpMethod, data: formData, success: function(data){ console.log("success") console.log(data) console.log(data.added) console.log(data.removed) console.log("Added", data.added) console.log("Removed", data.removed) var submitSpan = thisForm.find(".submit-span") if (data.added){ submitSpan.html("<button>Remove</button>") } else { submitspan.html("<button>Add to Basket</button>") } }, error: function(errorData){ console.log("error") console.log(errorData) } }) }) }) </script> -
model_unpickle() takes exactly 3 arguments (1 given)
I'm facing this error bellow with celery 3.1.25 and 4.1.0, this happen if I set serializing with pickle (I know is a problem with security) but I use a library that needs this kind of serialization to work with files, anyone have solved this problem?. Will add my freeze at the bottom of the question. Thank you Can't decode message body: DecodeError(TypeError('model_unpickle() takes exactly 3 arguments (1 given)', , (('data_importer', 'FileHistory'),)),) [type:u'application/x-python-serialize' encoding:u'binary' headers:{u'origin': u'gen29@f6876eb537fc', u'lang': u'py', u'task': u'data_importer_task', u'group': None, u'root_id': u'655b3b91-b48e-41c3-a893-ab7b5bdfdf79', u'expires': None, u'retries': 0, u'timelimit': [3600, None], u'argsrepr': u'()', u'eta': None, u'parent_id': None, u'id': u'655b3b91-b48e-41c3-a893-ab7b5bdfdf79', u'kwargsrepr': u"{'source': , 'importer': , 'file': , 'owner': >, 'subproject': , 'action': 'u'}"}] body: '\x80\x02)}q\x01(U\x06sourceq\x02cdjango.db.models.base\nmodel_unpickle\nq\x03U\rdata_importerq\x04U\x0bFileHistoryq\x05\x86\x85Rq\x06}q\x07(U\x06statusq\x08K\x01U\x0bfile_uploadq\tXI\x00\x00\x00upload_history/map_su/2018/02/02/7bee4c1c-751c-44df-a318-d527916148f5.xlsU\x0fcontent_type_idq\nK\x17U\x0f_django_versionq\x0bU\x061.11.9U\ncreated_atq\x0ccdatetime\ndatetime\nq\rU\n\x07\xe2\x02\x02\x16\x188\x00\r\xd7cpytz\n_UTC\nq\x0e)Rq\x0f\x86Rq\x10U\x06_stateq\x11cdjango.db.models.base\nModelState\nq\x12)\x81q\x13}q\x14(U\x06addingq\x15\x89U\x02dbq\x16U\x07defaultq\x17ubU\nupdated_atq\x18h\rU\n\x07\xe2\x02\x02\x16\x188\x00\r\xf4h\x0f\x86Rq\x19U\tobject_idq\x1aNU\x07is_taskq\x1bK\x00U\x13_content_type_cacheh\x03U\x0ccontenttypesq\x1cU\x0bContentTypeq\x1d\x86\x85Rq\x1e}q\x1f(h\x0bU\x061.11.9U\x05modelq X... (220389b) Traceback (most recent call last): File "/usr/local/lib/python2.7/dist-packages/kombu/messaging.py", line 592, in _receive_callback decoded = None if on_m else message.decode() File "/usr/local/lib/python2.7/dist-packages/kombu/message.py", line 142, in decode self.content_encoding, accept=self.accept) File "/usr/local/lib/python2.7/dist-packages/kombu/serialization.py", line 184, in loads return decode(data) File "/usr/lib/python2.7/contextlib.py", line 35, in __exit__ self.gen.throw(type, value, traceback) File "/usr/local/lib/python2.7/dist-packages/kombu/serialization.py", line 59, in _reraise_errors reraise(wrapper, wrapper(exc), sys.exc_info()[2]) File "/usr/local/lib/python2.7/dist-packages/kombu/serialization.py", line 55, in _reraise_errors yield File "/usr/local/lib/python2.7/dist-packages/kombu/serialization.py", line 184, in loads return decode(data) File "/usr/local/lib/python2.7/dist-packages/kombu/serialization.py", line 64, in pickle_loads return load(BytesIO(s)) DecodeError: ('model_unpickle() takes exactly 3 arguments (1 given)', , (('data_importer', … -
Circular model references
I am not quite sure about the best/idiomatic way to approach the following: I have a model called BlogPost and a model called BlogPostContent. BlogPost has a field called CurrentContent which references a related record in the BlogPostContent table. BlogPostContent has a foreign key field called Post referencing its related BlogPost. When a blog is modified, a new BlogPostContent record is created, and the BlogPost is updated such that its CurrentContent field references the newest BlogPostContent. I do this so it is possible to provide a way to rollback and specify any BlogPostContent record to use the CurrentContent It is possible for the CurrentContent to reference ANY of the BlogPostContent records related to it. If I were to model this in code, it would be: class BlogPostContent { //Content } class BlogPost { BlogPostContent currentPost; List<BlogPostContent> contentHistory; } -
Adding to userform in django before saving in database
Im sure this was working and now it's not. Anyone know what could be up? its failing at the new_user = form.save(commit=False) class Signup(View): def get(self, request): return render(request, 'accounts/signup.html') def post(self, request): form = UserCreationForm(request.POST) new_user = form.save(commit=False) email=new_user.cleaned_data.get('email') new_user.username=email if new_user.is_valid(): new_user.save() username = new_user.cleaned_data.get('username') raw_password = new_user.cleaned_data.get('password') user = authenticate(username=username, password=raw_password) login(request, user) return redirect('/accounts/home/') -
Filter on checkbox as well as the filter.py items using Django Filters
I have my filters working correctly, but I want to also filter on a checkbox that's in my result set, is this possible? My filter.py is the following: class UserFilter(django_filters.FilterSet): class Meta: model = Employee fields = ['employeeusername', 'employeefirstname', 'employeelastname', 'statusid', 'positiondesc'] My search form is the following: <form method="get"> <div class="well"> <h4 style="margin-top: 0">Filter</h4> <div class="row"> <div class="form-group col-sm-4 col-md-4"> <label/> 3-4 User ID {% render_field filter.form.employeeusername class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> First Name {% render_field filter.form.employeefirstname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Last Name {% render_field filter.form.employeelastname class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Status {% render_field filter.form.statusid class="form-control" %} </div> <div class="form-group col-sm-4 col-md-4"> <label/> Title {% render_field filter.form.positiondesc class="form-control" %} </div> </div> <button type="submit" class="btn btn-primary"> <span class="glyphicon glyphicon-search"></span> Search </button> </div> </form> In my result set I have the following: <table class="table table-bordered"> <thead> <tr> <th>User name</th> <th>First name</th> <th>Last name</th> <th>Title</th> <th>Status</th> <th></th> </tr> </thead> <tbody> {% for user in filter.qs %} <tr> <td>{{ user.employeeusername }}</td> <td>{{ user.employeefirstname }}</td> <td>{{ user.employeelastname }}</td> <td>{{ user.positiondesc }}</td> <td>{{ user.statusid }}</td> <td><input type="checkbox" name="usercheck" />&nbsp;</td> </tr> {% empty %} <tr> <td colspan="5">No data</td> </tr> {% endfor %} </tbody> </table> What I … -
Named groups with slashes in Django URLs
I have a set of following URLs defined: GET /data/(?P<tag>[^/]+)$ POST /data/(?P<tag>[^/]+)/action_1$ POST /data/(?P<tag>[^/]+)/action_2$ ... I would like to know whether it is possible to use tags containing slashes? E.g., when I try to get the data for the tag a/b/c, I always obtain 404 errors. Although I quote tags before forming actual URLs (i.e. /data/a%2Fb%2Fc for the previous case), the obtained URLs still do not match (though a%2Fb%2Fc should match [^/]+), because it looks like Django performs implicit unquoting, which is undesired. How can I overcome this problem without changing the URL forming scheme? -
Issue migrating DB from Local to Heroku Django
I've been working on a Django application and have recently run into a few issues pushing updates and migrating DB settings from Local to Heroku. I followed these steps: I added a few columns to my app model. Then ran python manage.py makemigrations then python manage.py migrate. I then committed these updates via github. Then I ran git push heroku master w/ Heroku CLI Then I entered heroku run python manage.py migrate Unfortunately, this did not migrate the appropriate updates I made to the DB settings in my local dev environment. The error message I received is "Column x does not exist in X-app". I ended up reverting back to my previous settings in model.py temporarily, but I would like to eventually add new columns to my database. At this point, I'm trying to assess what the best solution is to the problem. I've reviewed several other Stack Overflow questions, but haven't found one that's worked for me yet. What's odd is that I was able to migrate successfully in previous Heroku deployments. Any tips anyone has would be extremely appreciated. For reference, I'm using Python 3.6.2 and Django 1.11 -
Django .count() on ManyToMany has become very slow
I have a Django project that consists of a scraper of our inventory, run on the server as a cronjob every few hours, and the Django Admin page - which we use to view / access all items. We have about 30 items that are indexed. So each 'Scraping Operation' consists of about 30 individual 'Search Operations' each of which get around 500 results per run. Now, this description is a bit confusing, so I've included the models below. class ScrapingOperation(models.Model): date_started = models.DateTimeField(default=timezone.now, editable=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) round = models.IntegerField(default=-1) trusted = models.BooleanField(default=True) class Search(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) date_started = models.DateTimeField(default=timezone.now, editable=True) date_completed = models.DateTimeField(blank=True, null=True) completed = models.BooleanField(default=False) round = models.IntegerField(default=1) scraping_operation = models.ForeignKey(ScrapingOperation, on_delete=models.CASCADE, related_name='searches') trusted = models.BooleanField(default=True) def total_ads(self): return self.ads.count() class Ad(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE, related_name='ads') title = models.CharField(max_length=500) price = models.DecimalField(max_digits=8, decimal_places=2, null=True) first_seen = models.DateTimeField(default=timezone.now, editable=True) last_seen = models.DateTimeField(default=timezone.now, editable=True) def __str__(self): return self.title Now here is the problem we've run into. On the admin pages for both the Search model and the SeachOperation model we would like to see the amount of ads scraped for that particular object (represented as a number) This works fine four … -
Does graphene-django dynamically create an API documentation?
I'm considering using GraphQL with a Django backend service but I couldn't find much information regarding the API documentation. I need some solution to dynamically generate the documentation, perhaps like npm's graphql-docs with a result similar to GitHub's API docs. Is it feasible to accomplish with graphene-django? If not, what's a good alternative for a python environment? -
Django Admin display foreign key value
I'm trying to display the foreign key value itself in the Django Admin Panel. admins.py: class CateogoriesAdmin(admin.ModelAdmin): list_display = ('category_name',) class CateogoriesItemAdmin(admin.ModelAdmin): list_display = ('category_name', 'item_name', 'item_description',) Models.py: class Category(models.Model): category_name = models.CharField(max_length=50) class CategoryItems(models.Model): category_name = = models.ForeignKey(Categories, related_name='categoriesfk', on_delete=models.PROTECT) item_name = models.CharField(max_length=50) item_description = models.CharField(max_length=100) With the above, I just get Categories Object (1) as value, I want to display the actual value in the Django admin panel not object (1), e.g. if there is a category called "Bicycle", it should display Bicycle. -
Django: Can you create a relationship with an auto-generated through table?
My code looks something like this: from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Dish(models.Model): name = models.CharField(max_length=200) class Meal(models.Model): name = models.CharField(max_length=200) dishes = models.ManyToManyField(Dish) The many-to-many dishes field will result in a database table called 'myapp_meal_dishes' being created that includes id, meal_id, and dish_id fields. I would like to add a MealDishEater model that connects with that auto-generated table: class MealDishEater(models.Model): meal_dish = models.ForeignKey(MealDishes, on_delete=models.CASCADE) eater = models.ForeignKey(User, on_delete=models.PROTECT) ate_meal = models.BooleanField(default=False) Of course, that doesn't work, because MealDishes is not defined. Is there a way to do this or do I have to create my own through table? -
Heroku Django app: ECONNRESET: read ECONNRESET
I'm getting the below error when trying to run the command heroku run python manage.py migrate from the terminal. ECONNRESET: read ECONNRESET I followed the link in the heroku docs to check if there was a firewall issue, but I had a successful telnet connection. I haven't been able to find any other examples of anyone running into this issue unless they are having a proxy/firewall issue but according to the telnet test it doesn't seem like I have a problem right? I've also tried testing any other heroku run command I can think of and I get the same result. -
Django: issue with relationships between tables
I am creating an enrolment page for a website using Django. I have three tables: the default User table, a Profile table (to capture additional info) and a Subscription table. I have setup the Profile table as follows: class Profile(models.Model): user_id = models.ForeignKey(User, on_delete=models.CASCADE) profile_id = models.AutoField(primary_key=True) I have setup the Subscription table as follows: class Subscription(models.Model): subscription_no = models.AutoField(primary_key=True) user_id = models.ForeignKey(User, on_delete=models.CASCADE) profile_id = models.ForeignKey(Profile, on_delete=models.CASCADE) When a new user enrols, I create a new Profile and Subscription object for that user in views.py: #Create a new Profile object for the User user_profile = Profile() lookup_user = User.objects.get(username=username) lookup_user_id = lookup_user.pk user_profile.user_id = User.objects.get(pk=lookup_user_id) #Create a new Subscription object for the User user_subscription = Subscription() user_subscription.user_id = User.objects.get(pk=lookup_user_id) lookup_profile = Profile.objects.get(user_id=user_profile.user_id) lookup_profile_id = lookup_profile.pk user_subscription.profile_id = Profile.objects.get(pk=lookup_profile_id) Everything works okay, except I am worried that I am establishing the relationship between the tables in an incorrect manner. When I add the User, Profile and Subscription tables to the Django Admin app, the following appears for each new user profile: The following appears for a Subscription object created for a new User: And finally, if I open up a Subscription object, for example, the relationship field (which should be … -
Cannot multiply values from IntegerFields in django
I am confused regarding how to multiply the values of two IntegerFields in django. I am relatively new to django so I might be missing something fairly obvious. My code gives me the following exception: "ValueError at /multiplication/multiplied The view multiplication.views.post didn't return an HttpResponse object. It returned None instead. Request Method: POST" Here is the code from my views.py: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from django import forms from multiplication.forms import HomeForm template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) form = myForm() def get(request): return render(request,template_name1,{'form': form} ) def multiply_two_integers(x,y): return x*y def post(request): if (form.is_valid()): x = request.POST('quantity1') y = request.POST('quantity2') product = multiply_two_integers(x, y) return render(request, template_name2, {'form': form, 'product': product }) Template 1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:post' %}" method = "post"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <!--<button type="submit"> Multiply </button>--> <h1>{{product}}</h1> </form> Template 2: <h1>{{product}}</h1> -
Django Channels 2.0 channel_layers not communicating
So I've been migrating my server that was using Django Channels 1.x -> 2.x+ The original design would send a task to celery using getAFTreeTask.delay(message.reply_channel.name) and by having access to the channel_name it could haply reply asynchronously from celery import task from channels import Channel @task def getAFTreeTask(channel_name): tree = Request().cache_af_tree() Channel(channel_name).send({ "text": json.dumps({ "channel": "AF_INIT", "payload": tree }) }) Now I've migrated my server to Channels 2.x+ for various reasons. According to the docs class Consumer(JsonWebsocketConsumer): def connect(self): print("Client Connected: ", self.channel_name) self.accept() def receive_json(self, content, **kwargs): print(content) parse_request(self.channel_name, content) def disconnect(self, content): print(content) def chat_message(self, event): print("Entered reply channel") print(event) A consumer set out like this should receive request via the channel layer providing I use the right channel_name, now the consumer works as a send-receive websocket correctly if the response has access to self.send_json() or self.send() for the other generic consumers, so I'm assuming all my settings are correct, my problem is when I try to use the channel layer to send something, like this (according to https://channels.readthedocs.io/en/latest/topics/channel_layers.html#single-channels) from channels.layers import get_channel_layer from asgiref.sync import AsyncToSync def parse_request(channel_name, content): print("parsed ", channel_name, content) channel_layer = get_channel_layer() AsyncToSync(channel_layer.send)(channel_name, { "type": "chat.message", "text": "Hello there!", }) I get 2018-02-02 … -
I need to do something like form.save(commit=False) in my model in Django
I have a model that needs to include the ID in another field when its created... see below: id = models.AutoField(primary_key=True) ticket_number = models.CharField(max_length=200, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True) ... def save(self, *args, **kwargs): shortname = self.brand.shortname super(Job, self).save(*args, **kwargs) self.ticket_number = shortname.upper() + '-' + str(self.id) super(Job, self).save(*args, **kwargs) It works, which is good, and creates a unique ticket number. I'm new to Django, but I know enough that I feel like saving a post twice is inefficient. Is there something like .save(commit=False) for Models? I'd like to only save it once per save. -
Django - How do you get the corresponding model object in a for loop in html?
I am trying to create a simple django website where any user can rate and create posts. As displayed in this django tutorial (https://docs.djangoproject.com/en/1.7/topics/templates/), you can display all the model objects in html using a for loop. In my case, each object is going to be displayed with a Like and a Dislike button, so people can rate the post. My problem is: How do I know which object belongs to which like/dislike button so that the corresponding model field can be changed for that particular object? Thank You for answers! models.py from django.db import models # Create your models here. class Post(models.Model): post_text = models.CharField(max_length=500) pub_date = models.DateTimeField("date published") likes = models.IntegerField(default=0) dislikes = models.IntegerField(default=0) def __str__(self): return self.post_text index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AllPosts</title> </head> <body> {% if post_list %} <ul> {% for post in post_list %} <li>{{post.post_text}}</li> <p>This post has {{post.likes}} likes and {{post.dislikes}} dislikes.</p> <br>Leave a <button type="button" method="LIKE">Like</button> or a <button type="button" method="DISLIKE">Dislike</button>!</p> {% endfor %} </ul> <h2>If you want to create a post yourself, <a href="{% url 'create' %}">click here.</a></h2> {% else %} <h1>There are no posts yet...</h1> {% endif %} </body> </html> views.py from django.http import HttpResponse from django.template import … -
Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/admin
I create a project using Django called PROJECT_2.when I try the website with the URL admin "http://127.0.0.1:8000/admin" it gives me this error 'Page not found (404)'.I have no clue what the error could be as this is occurring right at the beginning before I even start code. PROJECT_2/urls.py from django.conf.urls import url from django.contrib import admin urlpatterns = [ url(r'^admin/', admin.site.urls), ] settings.py import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.9/howto/deployment/checklist/ # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'PROJECT_2.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'PROJECT_2.wsgi.application' # Database # https://docs.djangoproject.com/en/1.9/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password- validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, …